//! How the client reaches a relay. The library makes no network calls itself: an app gives it a //! [`Transport`] (HTTP in Amicitia, F22). [`MemoryTransport`] is a stand-in with the relay's rules, //! for tests and for running the client on a device without a relay. use std::collections::HashMap; use std::sync::{Arc, Mutex}; use tabellarius_protocol::{ blob_hash, CreateFile, CreateInvite, CreateMailbox, FileId, InviteId, MailboxId, PushEndpoint, Sha256Hash, Token, FILE_CHUNK_BYTES, }; /// Why the relay said no. Carries nothing of the request. #[derive(Debug, Clone, PartialEq, Eq)] pub enum TransportError { /// 404: unknown, wrong token, expired, or already claimed. NotFound, /// 409: the id is taken, or a file chunk is already there with other bytes. Conflict, /// 507: a quota is reached — the relay's, a mailbox's, or a file's (`PROTOCOL.md` §8). Full, /// Anything else: the network, a 5xx, a body that did not parse. Failed, } /// The relay's operations (`PROTOCOL.md` §8), one method each. pub trait Transport { fn create_mailbox(&self, req: &CreateMailbox) -> Result<(), TransportError>; fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError>; /// The waiting blobs, oldest first. fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result>, TransportError>; fn acknowledge( &self, id: &MailboxId, fetch: &Token, hash: &Sha256Hash, ) -> Result<(), TransportError>; fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError>; /// Block: the mailbox's post token becomes `new_hash`'s; the old one is refused from now on. fn rotate_post_token( &self, id: &MailboxId, fetch: &Token, new_hash: &Sha256Hash, ) -> Result<(), TransportError>; /// The KeyPackage, once. fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result, TransportError>; /// Where the relay wakes the mailbox's owner when a blob arrives (`Some`), or nowhere (`None`). /// `PROTOCOL.md` §6, `.agents/features/wake-up.md`. fn set_push( &self, id: &MailboxId, fetch: &Token, endpoint: Option<&PushEndpoint>, ) -> Result<(), TransportError>; /// `POST /v0/files` (`.agents/features/files.md` §2.3). fn create_file(&self, req: &CreateFile) -> Result<(), TransportError>; /// `PUT /v0/files/{id}/chunks/{index}` with the upload token. fn put_chunk( &self, id: &FileId, upload: &Token, index: u32, chunk: &[u8], ) -> Result<(), TransportError>; /// `GET /v0/files/{id}/chunks/{index}` with the fetch token. fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result, TransportError>; /// `DELETE /v0/files/{id}` with the upload token. fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError>; } /// A file as the relay keeps it: the two hashes, the chunk count, and the chunks by index. struct StoredFile { upload: Sha256Hash, fetch: Sha256Hash, chunks: u32, held: HashMap>, } #[derive(Default)] struct Boxes { mailboxes: HashMap>)>, invites: HashMap)>, push: HashMap, files: HashMap, } /// An in-memory relay with the same rules as the real one (no expiry: there is no clock here). /// Clone it to give two clients the same relay. #[derive(Clone, Default)] pub struct MemoryTransport(Arc>); impl MemoryTransport { fn boxes(&self) -> std::sync::MutexGuard<'_, Boxes> { self.0.lock().unwrap_or_else(|p| p.into_inner()) } /// How many blobs wait on the relay, in all mailboxes: what was not acknowledged. pub fn waiting_blobs(&self) -> usize { self.boxes() .mailboxes .values() .map(|(_, _, b)| b.len()) .sum() } /// The push endpoint a mailbox holds, if any. pub fn push_endpoint(&self, id: &MailboxId) -> Option { self.boxes().push.get(id).map(|e| e.as_str().to_string()) } /// How many chunks the relay holds, in all files. pub fn stored_chunks(&self) -> Vec> { self.boxes() .files .values() .flat_map(|f| f.held.values().cloned()) .collect() } /// Every byte the relay holds, for privacy tests: ids, hashes, blobs, KeyPackages, endpoints, /// files and their chunks. pub fn everything_stored(&self) -> Vec { let b = self.boxes(); let mut out = Vec::new(); for (id, (post, fetch, blobs)) in &b.mailboxes { out.extend_from_slice(id.as_bytes()); out.extend_from_slice(post.as_bytes()); out.extend_from_slice(fetch.as_bytes()); blobs.iter().for_each(|blob| out.extend_from_slice(blob)); } for (id, (hash, kp)) in &b.invites { out.extend_from_slice(id.as_bytes()); out.extend_from_slice(hash.as_bytes()); out.extend_from_slice(kp); } for (id, endpoint) in &b.push { out.extend_from_slice(id.as_bytes()); out.extend_from_slice(endpoint.as_str().as_bytes()); } for (id, f) in &b.files { out.extend_from_slice(id.as_bytes()); out.extend_from_slice(f.upload.as_bytes()); out.extend_from_slice(f.fetch.as_bytes()); f.held.values().for_each(|c| out.extend_from_slice(c)); } out } } impl Transport for MemoryTransport { fn create_mailbox(&self, req: &CreateMailbox) -> Result<(), TransportError> { let mut b = self.boxes(); if b.mailboxes.contains_key(&req.id) { return Err(TransportError::Conflict); } b.mailboxes.insert( req.id, (req.post_token_hash, req.fetch_token_hash, Vec::new()), ); Ok(()) } fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError> { match self.boxes().mailboxes.get_mut(id) { Some((hash, _, blobs)) if *hash == post.hash() => { blobs.push(blob.to_vec()); Ok(()) } _ => Err(TransportError::NotFound), } } fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result>, TransportError> { match self.boxes().mailboxes.get(id) { Some((_, hash, blobs)) if *hash == fetch.hash() => Ok(blobs.clone()), _ => Err(TransportError::NotFound), } } fn acknowledge( &self, id: &MailboxId, fetch: &Token, hash: &Sha256Hash, ) -> Result<(), TransportError> { match self.boxes().mailboxes.get_mut(id) { Some((_, f, blobs)) if *f == fetch.hash() => { let at = blobs .iter() .position(|b| blob_hash(b) == *hash) .ok_or(TransportError::NotFound)?; blobs.remove(at); Ok(()) } _ => Err(TransportError::NotFound), } } fn rotate_post_token( &self, id: &MailboxId, fetch: &Token, new_hash: &Sha256Hash, ) -> Result<(), TransportError> { match self.boxes().mailboxes.get_mut(id) { Some((post, f, _)) if *f == fetch.hash() => { *post = *new_hash; Ok(()) } _ => Err(TransportError::NotFound), } } fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> { let mut b = self.boxes(); if b.invites.contains_key(&req.id) { return Err(TransportError::Conflict); } b.invites .insert(req.id, (req.secret_hash, req.key_package.bytes().to_vec())); Ok(()) } fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result, TransportError> { let mut b = self.boxes(); match b.invites.get(id) { Some((hash, _)) if *hash == secret.hash() => b .invites .remove(id) .map(|(_, kp)| kp) .ok_or(TransportError::NotFound), _ => Err(TransportError::NotFound), } } fn set_push( &self, id: &MailboxId, fetch: &Token, endpoint: Option<&PushEndpoint>, ) -> Result<(), TransportError> { let mut b = self.boxes(); match b.mailboxes.get(id) { Some((_, f, _)) if *f == fetch.hash() => {} _ => return Err(TransportError::NotFound), } match endpoint { Some(e) => b.push.insert(*id, e.clone()), None => b.push.remove(id), }; Ok(()) } fn create_file(&self, req: &CreateFile) -> Result<(), TransportError> { let mut b = self.boxes(); if b.files.contains_key(&req.id) { return Err(TransportError::Conflict); } b.files.insert( req.id, StoredFile { upload: req.upload_token_hash, fetch: req.fetch_token_hash, chunks: req.chunks.get(), held: HashMap::new(), }, ); Ok(()) } fn put_chunk( &self, id: &FileId, upload: &Token, index: u32, chunk: &[u8], ) -> Result<(), TransportError> { if chunk.len() != FILE_CHUNK_BYTES { return Err(TransportError::Failed); } let mut b = self.boxes(); let f = match b.files.get_mut(id) { Some(f) if f.upload == upload.hash() => f, _ => return Err(TransportError::NotFound), }; if index >= f.chunks { return Err(TransportError::Full); } match f.held.get(&index) { Some(held) if held.as_slice() == chunk => Ok(()), Some(_) => Err(TransportError::Conflict), None => { f.held.insert(index, chunk.to_vec()); Ok(()) } } } fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result, TransportError> { match self.boxes().files.get(id) { Some(f) if f.fetch == fetch.hash() => { f.held.get(&index).cloned().ok_or(TransportError::NotFound) } _ => Err(TransportError::NotFound), } } fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError> { let mut b = self.boxes(); match b.files.get(id) { Some(f) if f.upload == upload.hash() => { b.files.remove(id); Ok(()) } _ => Err(TransportError::NotFound), } } }