capsule_sdk/peering/delta.rs
1//! Determining the delta: what each side is missing.
2//!
3//! Before building an artifact the two devices must agree on what to move. Peering **reuses the
4//! sync-cursor model** rather than inventing a diff: each side offers the set of
5//! [addresses](capsule_core::crypto::hash::Hash32) it holds and its cursor, and the delta is
6//! the *complement*. "What changed" is already defined by the sync feed — peering borrows that
7//! definition wholesale. Because every address names an exact state, dedup is free: the
8//! complement already excludes anything the receiver holds.
9//!
10//! The addresses a sync offer carries are the **head record hashes** of the assets a device
11//! holds ([`record_hash`] of each chain's last record): an asset whose head the
12//! receiver already holds is what the complement leaves out, and a metadata edit that keeps the
13//! ciphertext still moves, because it changes the head.
14//!
15//! On the wire an offer is split into pages of at most [`OFFER_PAGE_CAP`] addresses, and each
16//! page is **padded to a size bucket** (a power of two of address slots, at least
17//! [`MIN_OFFER_BUCKET`]), so the encrypted channel's record sizes reveal only a coarse bucket of
18//! how much a device holds, and no single request can carry an unbounded offer. A whole offer is
19//! at most [`MAX_OFFER_PAGES`] pages.
20//!
21//! [`record_hash`]: capsule_core::crypto::provenance::ProvenanceRecord::record_hash
22
23use std::collections::BTreeSet;
24
25use capsule_core::backup::BackupAsset;
26use capsule_core::crypto::hash::Hash32;
27use capsule_core::crypto::provenance::ProvenanceRecord;
28
29use super::PeeringError;
30
31/// The most addresses one offer page carries — the per-request cap.
32pub const OFFER_PAGE_CAP: usize = 4096;
33
34/// The smallest size bucket, in address slots, a page is padded to.
35pub const MIN_OFFER_BUCKET: usize = 64;
36
37/// The most pages one offer is carried in, so a whole offer (at most
38/// `MAX_OFFER_PAGES * OFFER_PAGE_CAP` addresses) is bounded too, not only each page.
39pub const MAX_OFFER_PAGES: usize = 256;
40
41/// Bytes of a page header: the cursor (`u64`) then the real address count (`u32`), big-endian.
42const PAGE_HEADER: usize = 12;
43
44/// Bytes of one address slot.
45const SLOT: usize = 32;
46
47/// The largest encoded page: a full page padded to the cap's bucket.
48pub(crate) const MAX_OFFER_PAGE_BYTES: usize = PAGE_HEADER + OFFER_PAGE_CAP * SLOT;
49
50/// The bucket, in address slots, a page holding `count` addresses is padded to.
51#[must_use]
52pub fn offer_bucket(count: usize) -> usize {
53 count.max(MIN_OFFER_BUCKET).next_power_of_two()
54}
55
56/// One decoded offer page: the sender's cursor and the real addresses it carried.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct OfferPage {
59 /// The sender's sync-cursor high-water mark.
60 pub cursor: u64,
61 /// The real (unpadded) addresses on this page.
62 pub addresses: Vec<Hash32>,
63}
64
65/// One side's offer in the delta negotiation: the addresses it currently holds and its sync
66/// cursor high-water mark. The cursor is carried for parity with server sync (a peer only
67/// offers state it has itself reconciled up to); the set is what the complement is computed over.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Offer {
70 /// The head record hashes ([`head_address`]) of the assets this device holds.
71 pub addresses: BTreeSet<Hash32>,
72 /// This device's sync-cursor high-water mark.
73 pub cursor: u64,
74}
75
76impl Offer {
77 /// An offer over an explicit address set and cursor.
78 #[must_use]
79 pub fn new(addresses: BTreeSet<Hash32>, cursor: u64) -> Self {
80 Self { addresses, cursor }
81 }
82
83 /// Encode the offer as wire pages: at most [`OFFER_PAGE_CAP`] addresses each, every page
84 /// zero-padded to its [`offer_bucket`]. An empty offer is one empty, padded page.
85 #[must_use]
86 pub fn encode_pages(&self) -> Vec<Vec<u8>> {
87 let addresses: Vec<&Hash32> = self.addresses.iter().collect();
88 let mut chunks: Vec<&[&Hash32]> = addresses.chunks(OFFER_PAGE_CAP).collect();
89 if chunks.is_empty() {
90 chunks.push(&[]);
91 }
92 chunks
93 .into_iter()
94 .map(|chunk| {
95 let slots = offer_bucket(chunk.len());
96 let mut page = Vec::with_capacity(PAGE_HEADER + slots * SLOT);
97 page.extend_from_slice(&self.cursor.to_be_bytes());
98 // `chunk.len() <= OFFER_PAGE_CAP`, which fits a u32.
99 page.extend_from_slice(&(chunk.len() as u32).to_be_bytes());
100 for address in chunk {
101 page.extend_from_slice(&address.0);
102 }
103 page.resize(PAGE_HEADER + slots * SLOT, 0);
104 page
105 })
106 .collect()
107 }
108
109 /// Reassemble an offer from its decoded pages. Every page must carry the same cursor.
110 pub fn from_pages(pages: &[OfferPage]) -> Result<Self, PeeringError> {
111 let cursor = pages.first().map_or(0, |page| page.cursor);
112 if pages.iter().any(|page| page.cursor != cursor) {
113 return Err(PeeringError::Codec(
114 "offer pages disagree on the cursor".into(),
115 ));
116 }
117 let addresses = pages
118 .iter()
119 .flat_map(|page| page.addresses.iter().copied())
120 .collect();
121 Ok(Self { addresses, cursor })
122 }
123}
124
125/// Decode one wire offer page, refusing anything [`Offer::encode_pages`] would not produce: a
126/// size that is not a bucket, a bucket above the cap, a count above the bucket, or non-zero
127/// padding.
128pub fn decode_offer_page(bytes: &[u8]) -> Result<OfferPage, PeeringError> {
129 let codec = |what: &str| PeeringError::Codec(format!("offer page: {what}"));
130 let body = bytes
131 .get(PAGE_HEADER..)
132 .ok_or_else(|| codec("shorter than its header"))?;
133 if body.len() % SLOT != 0 {
134 return Err(codec("not a whole number of slots"));
135 }
136 let slots = body.len() / SLOT;
137 if slots > offer_bucket(OFFER_PAGE_CAP) || slots != offer_bucket(slots) {
138 return Err(codec("size is not an admitted bucket"));
139 }
140 let mut cursor = [0u8; 8];
141 cursor.copy_from_slice(&bytes[..8]);
142 let mut count = [0u8; 4];
143 count.copy_from_slice(&bytes[8..PAGE_HEADER]);
144 let count = u32::from_be_bytes(count) as usize;
145 if count > slots.min(OFFER_PAGE_CAP) {
146 return Err(codec("count exceeds the page"));
147 }
148 let (real, padding) = body.split_at(count * SLOT);
149 if padding.iter().any(|byte| *byte != 0) {
150 return Err(codec("non-zero padding"));
151 }
152 let addresses = real
153 .chunks_exact(SLOT)
154 .map(|slot| {
155 let mut address = [0u8; SLOT];
156 address.copy_from_slice(slot);
157 Hash32(address)
158 })
159 .collect();
160 Ok(OfferPage {
161 cursor: u64::from_be_bytes(cursor),
162 addresses,
163 })
164}
165
166/// The addresses `local` is **missing** relative to `remote` — the pull set the behind-device
167/// requests. This is `remote \ local`: everything the remote holds that we do not, which is
168/// exactly the set to transfer (content-addressing makes anything we already hold a no-op, so
169/// the complement doubles as dedup).
170#[must_use]
171pub fn missing_from(local: &Offer, remote: &Offer) -> BTreeSet<Hash32> {
172 remote
173 .addresses
174 .difference(&local.addresses)
175 .copied()
176 .collect()
177}
178
179/// The **symmetric difference** of two offers — every address exactly one side holds. Over two
180/// devices with overlapping-but-distinct content, this is the union of the two one-way pulls
181/// (`(a \ b) ∪ (b \ a)`): the total set of assets that must move for the pair to converge.
182#[must_use]
183pub fn symmetric_difference(a: &Offer, b: &Offer) -> BTreeSet<Hash32> {
184 a.addresses
185 .symmetric_difference(&b.addresses)
186 .copied()
187 .collect()
188}
189
190/// The address an asset is offered under: its chain's head record hash. `None` for an asset with
191/// no provenance, which no offer can name.
192#[must_use]
193pub fn head_address(asset: &BackupAsset) -> Option<Hash32> {
194 asset.provenance.last().map(ProvenanceRecord::record_hash)
195}
196
197/// Cut `assets` to the ones `receiver` is missing: [`missing_from`]`(receiver, ours)` over their
198/// [`head_address`]es. Returns what remains and how many the receiver's offer excluded. An asset
199/// with no head address is kept, since no offer can show the receiver holds it.
200#[must_use]
201pub fn cut_to_missing(assets: Vec<BackupAsset>, receiver: &Offer) -> (Vec<BackupAsset>, usize) {
202 let ours = Offer::new(assets.iter().filter_map(head_address).collect(), 0);
203 let missing = missing_from(receiver, &ours);
204 let before = assets.len();
205 let kept: Vec<BackupAsset> = assets
206 .into_iter()
207 .filter(|asset| head_address(asset).is_none_or(|head| missing.contains(&head)))
208 .collect();
209 let excluded = before - kept.len();
210 tracing::debug!(
211 offered = receiver.addresses.len(),
212 kept = kept.len(),
213 excluded,
214 "peering: delta cut from the receiver's offer"
215 );
216 (kept, excluded)
217}