1use crate::error::{Result, SyncError};
22use crate::log::{LogEntry, OpLog};
23use crate::protocol::{KeyRef, PAGE_BUDGET};
24use crate::rotation::KeyStatus;
25use serde::{Deserialize, Serialize};
26use std::borrow::Cow;
27use std::collections::BTreeMap;
28use weirdnet_keys::{Key32, Sealed, kdf};
29use zeroize::Zeroizing;
30
31pub const CHUNK_SUFFIX: &str = "#chunks";
33
34pub const VALUE_VERSION: u32 = 1;
36
37pub const CHUNK_MAX: usize = PAGE_BUDGET - 4 * 1024;
39
40pub fn chunk_type(typ: &str) -> String {
42 format!("{typ}{CHUNK_SUFFIX}")
43}
44
45pub fn is_chunk_type(typ: &str) -> bool {
46 typ.ends_with(CHUNK_SUFFIX)
47}
48
49pub fn base_type(typ: &str) -> Option<&str> {
51 typ.strip_suffix(CHUNK_SUFFIX)
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Limits {
57 pub inline_max: usize,
59 pub chunk_size: usize,
61 pub record_max: usize,
63 pub eager_chunks: bool,
66}
67
68impl Default for Limits {
69 fn default() -> Self {
70 Self { inline_max: 32 * 1024, chunk_size: 48 * 1024, record_max: 16 * 1024 * 1024, eager_chunks: true }
71 }
72}
73
74impl Limits {
75 pub fn check(&self) -> Result<()> {
76 let max_chunks = self.record_max.div_ceil(self.chunk_size.max(1));
77 if self.chunk_size < 1024 || self.chunk_size > CHUNK_MAX || self.inline_max > CHUNK_MAX || max_chunks * 32 > CHUNK_MAX {
78 return Err(SyncError::Protocol(format!(
79 "limits out of range: chunk_size 1 KiB..={CHUNK_MAX}, inline_max <= {CHUNK_MAX}, record_max / chunk_size * 32 <= {CHUNK_MAX}"
80 )));
81 }
82 Ok(())
83 }
84}
85
86#[derive(Debug, Clone, Default, PartialEq, Eq)]
88pub struct RecordOptions {
89 pub sealed: bool,
91 pub limits: Limits,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96pub struct Value {
97 pub v: u32,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub seal: Option<SealInfo>,
102 #[serde(default, skip_serializing_if = "Vec::is_empty", with = "crate::bytes")]
104 pub body: Vec<u8>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub blob: Option<Blob>,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112pub struct SealInfo {
113 pub epoch: u32,
114 pub key: String,
115 #[serde(with = "crate::bytes")]
116 pub nonce: Vec<u8>,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct Blob {
122 pub len: u64,
123 #[serde(with = "crate::bytes")]
124 pub hash: Vec<u8>,
125 #[serde(with = "crate::bytes")]
127 pub chunks: Vec<u8>,
128}
129
130impl Blob {
131 pub fn chunk_hashes(&self) -> impl Iterator<Item = &[u8]> {
132 self.chunks.chunks(32)
133 }
134
135 pub fn chunk_ids(&self) -> Vec<String> {
136 self.chunk_hashes().map(hex::encode).collect()
137 }
138}
139
140impl Value {
141 pub fn wire_size(&self) -> usize {
143 96 + self.body.len() + self.blob.as_ref().map_or(0, |b| 64 + b.chunks.len()) + self.seal.as_ref().map_or(0, |s| 64 + s.key.len())
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum RecordValue {
150 Ready(zeroize::Zeroizing<Vec<u8>>),
152 Pending { missing: Vec<String> },
154}
155
156impl RecordValue {
157 pub fn ready(self) -> Option<zeroize::Zeroizing<Vec<u8>>> {
158 match self {
159 RecordValue::Ready(v) => Some(v),
160 RecordValue::Pending { .. } => None,
161 }
162 }
163}
164
165pub type Chunk<'a> = ([u8; 32], &'a [u8]);
167
168pub fn split(payload: &[u8], chunk_size: usize) -> (Blob, Vec<Chunk<'_>>) {
170 let parts: Vec<Chunk<'_>> = payload.chunks(chunk_size.max(1)).map(|c| (*blake3::hash(c).as_bytes(), c)).collect();
171 let chunks = parts.iter().flat_map(|(h, _)| h.iter().copied()).collect();
172 (Blob { len: payload.len() as u64, hash: blake3::hash(payload).as_bytes().to_vec(), chunks }, parts)
173}
174
175pub fn assemble(log: &OpLog, typ: &str, blob: &Blob) -> Result<RecordValue> {
178 if !blob.chunks.len().is_multiple_of(32) || blob.hash.len() != 32 {
179 return Err(SyncError::Protocol("malformed blob".into()));
180 }
181 let ctyp = chunk_type(typ);
182 let mut missing = Vec::new();
183 let mut out = zeroize::Zeroizing::new(Vec::with_capacity(blob.len.min(64 * 1024 * 1024) as usize));
184 for h in blob.chunk_hashes() {
185 match log.chunk(&ctyp, h) {
186 Some(bytes) if missing.is_empty() => out.extend_from_slice(bytes),
187 Some(_) => {}
188 None => missing.push(hex::encode(h)),
189 }
190 }
191 if !missing.is_empty() {
192 missing.dedup();
193 return Ok(RecordValue::Pending { missing });
194 }
195 if out.len() as u64 != blob.len || blake3::hash(&out).as_bytes()[..] != blob.hash[..] {
196 return Err(SyncError::Protocol("blob does not match its hash".into()));
197 }
198 Ok(RecordValue::Ready(out))
199}
200
201pub(crate) fn payload(log: &OpLog, e: &LogEntry, v: &Value) -> Result<RecordValue> {
203 if v.v > VALUE_VERSION {
204 return Err(SyncError::Protocol(format!("value format {} is newer than {VALUE_VERSION}", v.v)));
205 }
206 match &v.blob {
207 Some(b) => assemble(log, &e.typ, b),
208 None => Ok(RecordValue::Ready(zeroize::Zeroizing::new(v.body.clone()))),
209 }
210}
211
212impl crate::net::SyncState {
213 pub fn configure(&mut self, typ: &str, opts: RecordOptions) -> Result<()> {
215 opts.limits.check()?;
216 if is_chunk_type(typ) {
217 return Err(SyncError::Protocol("chunk types are not configured directly".into()));
218 }
219 if !self.types.iter().any(|t| t == typ) {
220 self.types.push(typ.to_string());
221 }
222 self.records.insert(typ.to_string(), opts);
223 Ok(())
224 }
225
226 pub fn options(&self, typ: &str) -> RecordOptions {
228 self.records.get(typ).cloned().unwrap_or_default()
229 }
230
231 pub fn write(&mut self, now_ms: u64, typ: &str, record_id: &str, value: &[u8]) -> Result<u64> {
236 self.write_with_fallback(now_ms, typ, record_id, value, Vec::new())
237 }
238
239 pub fn write_with_fallback(&mut self, now_ms: u64, typ: &str, record_id: &str, value: &[u8], fallback: Vec<u8>) -> Result<u64> {
245 if is_chunk_type(typ) {
246 return Err(SyncError::Protocol("chunk types are written by the crate".into()));
247 }
248 let opts = self.options(typ);
249 let limits = &opts.limits;
250 if value.len() > limits.record_max {
251 return Err(SyncError::Protocol(format!("value of {} bytes is over record_max {}", value.len(), limits.record_max)));
252 }
253 if fallback.len() > limits.inline_max {
254 return Err(SyncError::Protocol("fallback is over inline_max".into()));
255 }
256 let (seal, payload) = self.seal_payload(&opts, typ, record_id, value)?;
257 if seal.is_none() && payload.len() <= limits.inline_max {
258 return Ok(self.local_op(now_ms, typ, record_id, payload.to_vec()));
259 }
260 let mut v = Value { v: VALUE_VERSION, seal, body: Vec::new(), blob: None };
261 if payload.len() <= limits.inline_max {
262 v.body = payload.to_vec();
263 } else {
264 let ctyp = chunk_type(typ);
265 let (blob, parts) = split(&payload, limits.chunk_size);
266 for (h, bytes) in parts {
267 if !self.log.has_own_chunk(&self.our_node, &ctyp, &h) {
268 self.local_op(now_ms, &ctyp, &hex::encode(h), bytes.to_vec());
269 }
270 }
271 v.blob = Some(blob);
272 }
273 let hlc = self.tick(now_ms);
274 Ok(self.log.append_value(self.our_node.clone(), hlc, typ, record_id, fallback, v).seq)
275 }
276
277 pub fn read(&self, e: &LogEntry) -> Result<RecordValue> {
281 let sealed_type = self.options(&e.typ).sealed;
282 let Some(v) = &e.value else {
283 if sealed_type {
284 return Err(SyncError::Protocol("unsealed entry in a sealed type".into()));
285 }
286 return Ok(RecordValue::Ready(zeroize::Zeroizing::new(e.op.clone())));
287 };
288 if sealed_type && v.seal.is_none() {
289 return Err(SyncError::Protocol("unsealed entry in a sealed type".into()));
290 }
291 match payload(&self.log, e, v)? {
292 RecordValue::Ready(p) => match &v.seal {
293 Some(s) => Ok(RecordValue::Ready(self.open_payload(s, e, &p)?)),
294 None => Ok(RecordValue::Ready(p)),
295 },
296 pending => Ok(pending),
297 }
298 }
299}
300
301pub fn record_key(epoch_key: &Key32, user_id: &str, typ: &str, record_id: &str, epoch: u32, id: &str) -> Result<Key32> {
304 let info = format!("weirdnet-sync/v1/record/{typ}/e{epoch}/k{id}/{record_id}");
305 Ok(kdf::hkdf(&epoch_key.0, Some(user_id.as_bytes()), info.as_bytes())?)
306}
307
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
310pub struct RecordRef<'a> {
311 pub typ: &'a str,
312 pub record_id: &'a str,
313 pub node: &'a str,
314}
315
316impl<'a> RecordRef<'a> {
317 pub fn of(e: &'a LogEntry) -> Self {
318 Self { typ: &e.typ, record_id: &e.record_id, node: &e.node_id.0 }
319 }
320}
321
322pub fn record_aad(r: &RecordRef<'_>, epoch: u32, id: &str) -> Vec<u8> {
325 format!("weirdnet-sync/v1/record|v{VALUE_VERSION}|{}|e{epoch}|k{id}|{}|{}", r.typ, r.node, r.record_id).into_bytes()
326}
327
328pub fn seal_record(epoch_key: &Key32, user_id: &str, r: &RecordRef<'_>, epoch: u32, id: &str, plain: &[u8]) -> Result<(SealInfo, Vec<u8>)> {
330 let key = record_key(epoch_key, user_id, r.typ, r.record_id, epoch, id)?;
331 let s = weirdnet_keys::seal(&key, plain, &record_aad(r, epoch, id))?;
332 let nonce = hex::decode(&s.nonce).map_err(|_| SyncError::Crypto("bad nonce".into()))?;
333 let ct = hex::decode(&s.ct).map_err(|_| SyncError::Crypto("bad ciphertext".into()))?;
334 Ok((SealInfo { epoch, key: id.to_string(), nonce }, ct))
335}
336
337pub fn open_record(epoch_key: &Key32, user_id: &str, r: &RecordRef<'_>, seal: &SealInfo, ct: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
339 let key = record_key(epoch_key, user_id, r.typ, r.record_id, seal.epoch, &seal.key)?;
340 let sealed = Sealed { nonce: hex::encode(&seal.nonce), ct: hex::encode(ct) };
341 Ok(weirdnet_keys::open(&key, &sealed, &record_aad(r, seal.epoch, &seal.key))?)
342}
343
344impl crate::net::SyncState {
345 fn seal_payload<'a>(&self, opts: &RecordOptions, typ: &str, record_id: &str, value: &'a [u8]) -> Result<(Option<SealInfo>, Cow<'a, [u8]>)> {
346 if !opts.sealed {
347 return Ok((None, Cow::Borrowed(value)));
348 }
349 if self.key_status() == KeyStatus::Revoked {
350 return Err(SyncError::Refused("revoked".into()));
351 }
352 let KeyRef { epoch, id: Some(id) } = self.current_key() else {
353 return Err(SyncError::Refused("no-epoch-key".into()));
355 };
356 let key = self.keys.get(&id).ok_or_else(|| SyncError::Refused("no-epoch-key".into()))?;
357 let (seal, ct) = seal_record(key, &self.user_id, &RecordRef { typ, record_id, node: &self.our_node.0 }, epoch, &id, value)?;
358 Ok((Some(seal), Cow::Owned(ct)))
359 }
360
361 fn open_payload(&self, s: &SealInfo, e: &LogEntry, ct: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
362 let key = self.keys.get(&s.key).ok_or_else(|| SyncError::Crypto("sealed under an epoch key this device does not hold".into()))?;
363 open_record(key, &self.user_id, &RecordRef::of(e), s, ct)
364 }
365
366 pub fn latest_entries(&self, typ: &str) -> Vec<&LogEntry> {
368 let mut latest: BTreeMap<&str, &LogEntry> = BTreeMap::new();
369 for e in self.log.iter().filter(|e| e.typ == typ) {
370 let slot = latest.entry(e.record_id.as_str()).or_insert(e);
371 if e.hlc.cmp_total(&slot.hlc).is_gt() {
372 *slot = e;
373 }
374 }
375 latest.into_values().collect()
376 }
377
378 pub fn reseal_stale(&mut self, now_ms: u64, typ: &str) -> Result<Vec<String>> {
385 if !self.options(typ).sealed {
386 return Ok(Vec::new());
387 }
388 let Some(head) = self.current_key().id else { return Err(SyncError::Refused("no-epoch-key".into())) };
389 let mut todo = Vec::new();
390 for e in self.latest_entries(typ) {
391 let Some(s) = e.value.as_ref().and_then(|v| v.seal.as_ref()) else { continue };
392 if s.key == head {
393 continue;
394 }
395 if let Ok(RecordValue::Ready(plain)) = self.read(e) {
396 todo.push((e.record_id.clone(), plain, e.op.clone()));
397 }
398 }
399 let mut done = Vec::new();
400 for (rid, plain, fallback) in todo {
401 self.write_with_fallback(now_ms, typ, &rid, &plain, fallback)?;
402 done.push(rid);
403 }
404 Ok(done)
405 }
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use crate::hlc::{Hlc, NodeId};
412 use crate::log::Page;
413 use crate::protocol::{decode, encode};
414
415 fn n(s: &str) -> NodeId {
416 NodeId::new(s)
417 }
418
419 fn entry(node: &str, seq: u64, typ: &str, rid: &str, op: Vec<u8>, value: Option<Value>) -> LogEntry {
420 LogEntry { node_id: n(node), seq, hlc: Hlc::new(seq, 0, n(node)), typ: typ.into(), record_id: rid.into(), op, value }
421 }
422
423 fn big(len: usize) -> Vec<u8> {
424 (0..len).map(|i| (i * 31 % 251) as u8).collect()
425 }
426
427 #[test]
428 fn a_split_value_reassembles_only_from_matching_chunks() {
429 let data = big(200_000);
430 let (blob, parts) = split(&data, 64 * 1024);
431 assert_eq!(blob.len, 200_000);
432 assert_eq!(parts.len(), 4);
433 assert_eq!(blob.chunk_ids().len(), 4);
434 let ctyp = chunk_type("notes");
435 let mut log = OpLog::new();
436 assert_eq!(assemble(&log, "notes", &blob).unwrap(), RecordValue::Pending { missing: blob.chunk_ids() });
438 let (h0, _) = parts[0];
440 let forged = entry("x", 1, &ctyp, &hex::encode(h0), vec![0u8; 10], None);
441 log.integrate(&Page { node_id: n("x"), from_seq: 1, to_seq: 1, ops: vec![forged] });
442 assert!(log.chunk(&ctyp, &h0).is_none());
443 let page: Vec<LogEntry> =
444 parts.iter().enumerate().map(|(i, (h, b))| entry("a", i as u64 + 1, &ctyp, &hex::encode(h), b.to_vec(), None)).collect();
445 log.integrate(&Page { node_id: n("a"), from_seq: 1, to_seq: 3, ops: page[..3].to_vec() });
446 assert_eq!(assemble(&log, "notes", &blob).unwrap(), RecordValue::Pending { missing: vec![hex::encode(parts[3].0)] });
447 log.integrate(&Page { node_id: n("a"), from_seq: 4, to_seq: 4, ops: page[3..].to_vec() });
448 assert_eq!(&assemble(&log, "notes", &blob).unwrap().ready().unwrap()[..], &data[..]);
449 let bad = Blob { hash: blake3::hash(b"other").as_bytes().to_vec(), ..blob.clone() };
451 assert!(assemble(&log, "notes", &bad).is_err());
452 let bad = Blob { len: 5, ..blob.clone() };
453 assert!(assemble(&log, "notes", &bad).is_err());
454 let bad = Blob { chunks: blob.chunks[..40].to_vec(), ..blob };
455 assert!(assemble(&log, "notes", &bad).is_err());
456 }
457
458 #[test]
459 fn entries_keep_the_0_3_wire_shape_and_old_peers_drop_the_value() {
460 #[derive(Serialize, Deserialize, PartialEq, Debug)]
461 struct EntryV03 {
462 node_id: NodeId,
463 seq: u64,
464 hlc: Hlc,
465 typ: String,
466 record_id: String,
467 #[serde(with = "crate::bytes")]
468 op: Vec<u8>,
469 }
470 let plain = entry("a", 1, "notes", "r", b"hi".to_vec(), None);
471 let old: EntryV03 = decode(&encode(&plain).unwrap()).unwrap();
472 assert_eq!(encode(&old).unwrap(), encode(&plain).unwrap(), "no value field on a plain entry");
473 let back: LogEntry = decode(&encode(&old).unwrap()).unwrap();
474 assert_eq!(back, plain);
475 let (blob, _) = split(&big(100_000), 32 * 1024);
477 let v = Value { v: VALUE_VERSION, seal: None, body: Vec::new(), blob: Some(blob) };
478 let rich = entry("a", 2, "notes", "r", b"preview".to_vec(), Some(v));
479 #[derive(Deserialize)]
480 struct PageV03 {
481 ops: Vec<EntryV03>,
482 }
483 let page = Page { node_id: n("a"), from_seq: 1, to_seq: 2, ops: vec![plain, rich] };
484 let old: PageV03 = decode(&encode(&page).unwrap()).unwrap();
485 assert_eq!(old.ops[1].op, b"preview");
486 assert_eq!(old.ops.len(), 2);
487 }
488
489 #[test]
490 fn a_newer_value_format_is_refused_not_misread() {
491 #[derive(Serialize)]
492 struct Future {
493 v: u32,
494 body: serde_bytes_like::B,
495 zstd: bool,
496 }
497 mod serde_bytes_like {
498 pub struct B(pub Vec<u8>);
499 impl serde::Serialize for B {
500 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
501 s.serialize_bytes(&self.0)
502 }
503 }
504 }
505 let v: Value = decode(&encode(&Future { v: 2, body: serde_bytes_like::B(b"x".to_vec()), zstd: true }).unwrap()).unwrap();
506 assert_eq!(v.v, 2, "unknown fields are skipped, the version is kept");
507 let e = entry("a", 1, "notes", "r", vec![], Some(v));
508 assert!(payload(&OpLog::new(), &e, e.value.as_ref().unwrap()).is_err());
509 }
510
511 #[test]
512 fn limits_stay_inside_a_page() {
513 assert!(Limits::default().check().is_ok());
514 assert!(Limits { chunk_size: CHUNK_MAX + 1, ..Default::default() }.check().is_err());
515 assert!(Limits { chunk_size: 512, ..Default::default() }.check().is_err());
516 assert!(Limits { inline_max: CHUNK_MAX + 1, ..Default::default() }.check().is_err());
517 assert!(Limits { record_max: usize::MAX / 2, ..Default::default() }.check().is_err());
518 assert!(Limits { chunk_size: 8 * 1024, record_max: 1024 * 1024, ..Default::default() }.check().is_ok());
519 }
520
521 #[test]
522 fn a_sealed_value_opens_only_for_its_record_writer_and_key() {
523 let k = Key32::random().unwrap();
524 let r = RecordRef { typ: "secrets", record_id: "mcp/github", node: "peer-a" };
525 let (seal, ct) = seal_record(&k, "user-1", &r, 2, "rot1", b"token").unwrap();
526 assert_eq!(&open_record(&k, "user-1", &r, &seal, &ct).unwrap()[..], b"token");
527 for other in [RecordRef { record_id: "mcp/other", ..r }, RecordRef { node: "peer-b", ..r }, RecordRef { typ: "notes", ..r }] {
528 assert!(open_record(&k, "user-1", &other, &seal, &ct).is_err(), "{other:?}");
529 }
530 assert!(open_record(&k, "user-2", &r, &seal, &ct).is_err());
531 assert!(open_record(&k, "user-1", &r, &SealInfo { key: "rot2".into(), ..seal.clone() }, &ct).is_err());
532 assert!(open_record(&k, "user-1", &r, &SealInfo { epoch: 3, ..seal.clone() }, &ct).is_err());
533 assert!(open_record(&Key32::random().unwrap(), "user-1", &r, &seal, &ct).is_err());
534 let mut bad = ct.clone();
535 bad[0] ^= 1;
536 assert!(open_record(&k, "user-1", &r, &seal, &bad).is_err());
537 }
538}