Skip to main content

weirdnet_sync/
protocol.rs

1//! `weirdnet-sync/v1` messages and length-prefixed CBOR framing.
2//!
3//! After the authenticated channel is up, payloads that carry records, cursors or
4//! certificates are sealed under [`crate::sync_key`]. An [`Envelope`] carries the type and
5//! epoch in the clear so the receiver can pick the key; the body is sealed.
6use crate::error::{Result, SyncError};
7use crate::hlc::{Hlc, NodeId};
8use crate::log::{LogEntry, Page as LogPage};
9use crate::seal::{open_page, seal_page, sync_key};
10use serde::{Deserialize, Serialize};
11use weirdnet_keys::Sealed;
12use weirdnet_net::profile::{Profile, WEIRDNET};
13use weirdnet_net::user::NodeCert;
14use zeroize::Zeroizing;
15
16/// Request-response protocol id, same style as `/weirdnet/link/1`.
17pub const PROTOCOL: &str = "/weirdnet/sync/1";
18
19/// Largest sealed page (and the reply cap to set on a sync node). Still under weirdnet-net's 8 MiB default.
20pub const PAGE_MAX: usize = 256 * 1024;
21
22/// Identifier profile: `/weirdnet/sync/1` for request-response, otherwise [`WEIRDNET`].
23pub static SYNC_PROFILE: Profile = Profile { protocol: PROTOCOL, thread: "weirdnet-sync", ..WEIRDNET };
24
25/// Last seq applied from each node, as sent in Hello.
26pub type Cursors = Vec<(NodeId, u64)>;
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct Hello {
30    pub cert: NodeCert,
31    pub user_id: String,
32    pub epoch: u32,
33    pub types: Vec<String>,
34    pub our_cursors: Cursors,
35    pub our_hlc: Hlc,
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct HelloOk {
40    pub cert: NodeCert,
41    pub epoch: u32,
42    pub cursors: Cursors,
43    pub revocations: Vec<NodeCert>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct Refuse {
48    pub reason: String,
49}
50
51impl Refuse {
52    pub fn new(reason: &'static str) -> Self {
53        Self { reason: reason.into() }
54    }
55}
56
57pub type RefuseReason = Refuse;
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct Pull {
61    pub node_id: NodeId,
62    pub after_seq: u64,
63    pub typ: String,
64    pub limit: u32,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct Page {
69    pub typ: String,
70    pub page: LogPage,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub struct Ack {
75    pub node_id: NodeId,
76    pub last_seq: u64,
77}
78
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80pub struct RosterMsg {
81    pub certs: Vec<NodeCert>,
82    pub epoch: u32,
83}
84
85/// Application-level message, before sealing.
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87#[serde(tag = "kind", rename_all = "kebab-case")]
88pub enum Message {
89    Hello(Hello),
90    HelloOk(HelloOk),
91    Refuse(Refuse),
92    Pull(Pull),
93    Page(Page),
94    Ack(Ack),
95    Roster(RosterMsg),
96}
97
98/// What goes on the request-response wire: type and epoch in the clear, body sealed.
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
100pub struct Envelope {
101    pub typ: String,
102    pub epoch: u32,
103    pub sealed: Sealed,
104}
105
106impl Envelope {
107    pub fn seal(seed: &[u8], user_id: &str, typ: &str, epoch: u32, asking_peer: &str, msg: &Message) -> Result<Self> {
108        let key = sync_key(seed, user_id, typ, epoch)?;
109        let plain = encode(msg)?;
110        let sealed = seal_page(&key, typ, epoch, asking_peer, &plain)?;
111        Ok(Self { typ: typ.into(), epoch, sealed })
112    }
113
114    pub fn open(&self, seed: &[u8], user_id: &str, asking_peer: &str) -> Result<Message> {
115        let key = sync_key(seed, user_id, &self.typ, self.epoch)?;
116        let plain: Zeroizing<Vec<u8>> = open_page(&key, &self.typ, self.epoch, asking_peer, &self.sealed)?;
117        decode(&plain)
118    }
119}
120
121/// Length-prefixed CBOR (u32 big-endian length, then the item). For a raw stream;
122/// `Node::request` already frames [`Envelope`] as CBOR through libp2p.
123pub fn encode<T: Serialize>(v: &T) -> Result<Vec<u8>> {
124    cbor4ii::serde::to_vec(Vec::new(), v).map_err(|e| SyncError::Codec(e.to_string()))
125}
126
127pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T> {
128    cbor4ii::serde::from_slice(bytes).map_err(|e| SyncError::Codec(e.to_string()))
129}
130
131pub fn encode_framed<T: Serialize>(v: &T) -> Result<Vec<u8>> {
132    let body = encode(v)?;
133    if body.len() > u32::MAX as usize {
134        return Err(SyncError::Codec("frame too large".into()));
135    }
136    let mut out = Vec::with_capacity(4 + body.len());
137    out.extend_from_slice(&(body.len() as u32).to_be_bytes());
138    out.extend_from_slice(&body);
139    Ok(out)
140}
141
142pub fn decode_framed<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T> {
143    if bytes.len() < 4 {
144        return Err(SyncError::Codec("short frame".into()));
145    }
146    let n = u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize;
147    if bytes.len() != 4 + n {
148        return Err(SyncError::Codec(format!("frame length {n} does not match {}", bytes.len().saturating_sub(4))));
149    }
150    decode(&bytes[4..])
151}
152
153/// Build a `Page` message from a log page, dropping ops whose typ does not match (they
154/// stay in the log for a later pull of that type).
155pub fn page_for_type(typ: &str, page: LogPage) -> Page {
156    let ops: Vec<LogEntry> = page.ops.into_iter().filter(|e| e.typ == typ).collect();
157    let from_seq = ops.first().map(|e| e.seq).unwrap_or(page.from_seq);
158    let to_seq = ops.last().map(|e| e.seq).unwrap_or(page.to_seq);
159    Page { typ: typ.into(), page: LogPage { node_id: page.node_id, from_seq, to_seq, ops } }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use crate::hlc::Hlc;
166    use crate::roster::Roster;
167    use weirdnet_net::Keypair;
168    use weirdnet_net::user;
169
170    const SEED: [u8; 32] = *b"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
171
172    fn hello() -> (Message, String, Keypair) {
173        let u = Keypair::generate_ed25519();
174        let uid = user::user_id(&u.public());
175        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
176        let msg = Message::Hello(Hello {
177            cert,
178            user_id: uid.clone(),
179            epoch: 0,
180            types: vec!["bookmarks".into()],
181            our_cursors: vec![(NodeId::new("peer-a"), 3)],
182            our_hlc: Hlc::new(10, 0, NodeId::new("peer-a")),
183        });
184        (msg, uid, u)
185    }
186
187    #[test]
188    fn framed_cbor_round_trips_and_rejects_a_truncated_frame() {
189        let (msg, _, _) = hello();
190        let bytes = encode_framed(&msg).unwrap();
191        assert_eq!(u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize, bytes.len() - 4);
192        let back: Message = decode_framed(&bytes).unwrap();
193        assert_eq!(back, msg);
194        assert!(decode_framed::<Message>(&bytes[..3]).is_err());
195        assert!(decode_framed::<Message>(&bytes[..bytes.len() - 1]).is_err());
196    }
197
198    #[test]
199    fn a_sealed_hello_opens_for_the_same_seed_and_user_only() {
200        let (msg, uid, _) = hello();
201        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
202        let opened = env.open(&SEED, &uid, "peer-b").unwrap();
203        assert_eq!(opened, msg);
204        assert!(env.open(&SEED, "other-user", "peer-b").is_err());
205        assert!(env.open(&SEED, &uid, "peer-c").is_err());
206        assert!(Envelope { typ: "history".into(), ..env.clone() }.open(&SEED, &uid, "peer-b").is_err());
207    }
208}