Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/open-humanity/blob/main/crates/beacon-core/src/wire.rs # open-humanity Privacy-first peer assistance network for sovereign autonomous agents Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `open-humanity / crates / beacon-core / src / wire.rs` 367 lines ยท 14068 bytes Raw Blame History 1 //! Relay wire frames for Open Humanity. 2 //! 3 //! Every datagram starts with three bytes: 0x4F, a kind byte, the protocol version. 4 //! A request for help keeps its original encoding (its first bytes are already 5 //! 0x4F 0x48 0x01), so nodes that only know that format still parse it. 6 //! 7 //! The relay talks only to addresses that proved they can receive: a node registers, 8 //! the relay answers with a cookie bound to the sender address, and the node repeats 9 //! the registration with that cookie. A forged source address therefore never causes 10 //! the relay to send it requests or answers. 11 12 use crate::crypto::{verify_signature, verify_timestamp_drift, Keypair, MAX_TIMESTAMP_DRIFT_SECS}; 13 use crate::schema::{ 14 BeaconError, BeaconTopic, DistressNanobeacon, ResolutionCapsule, MAGIC_BYTES, 15 MAX_DATAGRAM_SIZE, PROTOCOL_VERSION, 16 }; 17 use rand::rngs::OsRng; 18 use rand::RngCore; 19 use serde::{Deserialize, Serialize}; 20 use std::net::SocketAddr; 21 22 /// Kind byte of a request for help (the second magic byte of the original format). 23 pub const KIND_SIGNAL: u8 = 0x48; 24 pub const KIND_REGISTER: u8 = 0x52; 25 pub const KIND_CHALLENGE: u8 = 0x51; 26 pub const KIND_ACK: u8 = 0x41; 27 pub const KIND_CAPSULE: u8 = 0x43; 28 29 pub const COOKIE_LEN: usize = 16; 30 pub const COOKIE_WINDOW_SECS: u64 = 120; 31 /// Largest answer datagram the relay forwards. 32 pub const MAX_CAPSULE_DATAGRAM: usize = 8192; 33 /// Bit mask naming every topic. 34 pub const ALL_TOPICS: u8 = 0x7F; 35 36 impl BeaconTopic { 37 pub const ALL: [BeaconTopic; 7] = [ 38 BeaconTopic::RustCompilation, 39 BeaconTopic::MojoSimd, 40 BeaconTopic::ModularMaxServing, 41 BeaconTopic::HardwareTopology, 42 BeaconTopic::SecurityAudit, 43 BeaconTopic::ProtocolCoordination, 44 BeaconTopic::AgentRecursion, 45 ]; 46 47 /// The topic's bit in a registration mask. 48 pub fn bit(self) -> u8 { 49 1u8 << (self as u8) 50 } 51 52 pub fn from_name(name: &str) -> Option { 53 Self::ALL.iter().copied().find(|t| t.as_str() == name) 54 } 55 } 56 57 /// A comma separated list of topic names, or `all`, as a registration mask. 58 pub fn topics_mask(names: &str) -> Option { 59 if names.trim() == "all" { 60 return Some(ALL_TOPICS); 61 } 62 let mut mask = 0u8; 63 for name in names.split(',') { 64 mask |= BeaconTopic::from_name(name.trim())?.bit(); 65 } 66 Some(mask) 67 } 68 69 pub fn unix_now() -> u64 { 70 std::time::SystemTime::now() 71 .duration_since(std::time::UNIX_EPOCH) 72 .unwrap_or_default() 73 .as_secs() 74 } 75 76 pub fn random_secret() -> [u8; 32] { 77 let mut secret = [0u8; 32]; 78 OsRng.fill_bytes(&mut secret); 79 secret 80 } 81 82 /// The cookie the relay hands to `addr` in the time window `window`. 83 pub fn relay_cookie(secret: &[u8; 32], addr: &SocketAddr, window: u64) -> [u8; COOKIE_LEN] { 84 let mut hasher = blake3::Hasher::new_keyed(secret); 85 hasher.update(addr.to_string().as_bytes()); 86 hasher.update(&window.to_le_bytes()); 87 let mut cookie = [0u8; COOKIE_LEN]; 88 cookie.copy_from_slice(&hasher.finalize().as_bytes()[..COOKIE_LEN]); 89 cookie 90 } 91 92 /// True when `cookie` is the relay's cookie for `addr` in this window or the one before. 93 pub fn cookie_valid( 94 secret: &[u8; 32], 95 addr: &SocketAddr, 96 now_secs: u64, 97 cookie: &[u8; COOKIE_LEN], 98 ) -> bool { 99 let window = now_secs / COOKIE_WINDOW_SECS; 100 if *cookie == relay_cookie(secret, addr, window) { 101 return true; 102 } 103 window > 0 && *cookie == relay_cookie(secret, addr, window - 1) 104 } 105 106 /// A node tells the relay it is reachable and which topics it helps with. 107 /// `topics` 0 registers a node that only asks. 108 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 109 pub struct Register { 110 pub node_pubkey: [u8; 32], 111 pub timestamp: u64, 112 pub topics: u8, 113 /// Ask for the stored requests of these topics once the registration is accepted. 114 pub replay: bool, 115 pub cookie: [u8; COOKIE_LEN], 116 #[serde(with = "crate::schema::serde_bytes_64")] 117 pub signature: [u8; 64], 118 } 119 120 impl Register { 121 pub fn new(node_pubkey: [u8; 32], topics: u8, replay: bool, cookie: [u8; COOKIE_LEN]) -> Self { 122 Self { 123 node_pubkey, 124 timestamp: unix_now(), 125 topics, 126 replay, 127 cookie, 128 signature: [0u8; 64], 129 } 130 } 131 132 pub fn signable_bytes(&self) -> Result, BeaconError> { 133 let mut clone = self.clone(); 134 clone.signature = [0u8; 64]; 135 bincode::serialize(&clone).map_err(|e| BeaconError::Serialization(e.to_string())) 136 } 137 138 pub fn sign(&mut self, keypair: &Keypair) -> Result<(), BeaconError> { 139 self.signature = keypair.sign(&self.signable_bytes()?); 140 Ok(()) 141 } 142 143 pub fn verify(&self, now_secs: u64) -> Result<(), BeaconError> { 144 verify_timestamp_drift(self.timestamp, now_secs, MAX_TIMESTAMP_DRIFT_SECS)?; 145 verify_signature(&self.node_pubkey, &self.signable_bytes()?, &self.signature) 146 } 147 } 148 149 /// The relay's answer to a datagram from an address it does not know yet. 150 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 151 pub struct Challenge { 152 pub cookie: [u8; COOKIE_LEN], 153 } 154 155 /// The relay accepted a registration. 156 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 157 pub struct Ack { 158 pub topics: u8, 159 pub ttl_secs: u32, 160 } 161 162 #[derive(Debug, Clone, PartialEq, Eq)] 163 pub enum Frame { 164 Signal(DistressNanobeacon), 165 Register(Register), 166 Challenge(Challenge), 167 Ack(Ack), 168 Capsule(ResolutionCapsule), 169 } 170 171 fn framed(kind: u8, value: &T, limit: usize) -> Result, BeaconError> { 172 let mut out = vec![MAGIC_BYTES[0], kind, PROTOCOL_VERSION]; 173 bincode::serialize_into(&mut out, value) 174 .map_err(|e| BeaconError::Serialization(e.to_string()))?; 175 if out.len() > limit { 176 return Err(BeaconError::DatagramTooLarge(limit, out.len())); 177 } 178 Ok(out) 179 } 180 181 fn unframed<'a, T: Deserialize<'a>>(bytes: &'a [u8], limit: usize) -> Result { 182 if bytes.len() > limit { 183 return Err(BeaconError::DatagramTooLarge(limit, bytes.len())); 184 } 185 bincode::deserialize(&bytes[3..]).map_err(|e| BeaconError::Deserialization(e.to_string())) 186 } 187 188 impl Frame { 189 pub fn encode(&self) -> Result, BeaconError> { 190 match self { 191 Frame::Signal(signal) => signal.to_bytes(), 192 Frame::Register(register) => framed(KIND_REGISTER, register, MAX_DATAGRAM_SIZE), 193 Frame::Challenge(challenge) => framed(KIND_CHALLENGE, challenge, MAX_DATAGRAM_SIZE), 194 Frame::Ack(ack) => framed(KIND_ACK, ack, MAX_DATAGRAM_SIZE), 195 Frame::Capsule(capsule) => framed(KIND_CAPSULE, capsule, MAX_CAPSULE_DATAGRAM), 196 } 197 } 198 199 pub fn decode(bytes: &[u8]) -> Result { 200 if bytes.len() < 3 { 201 return Err(BeaconError::Deserialization("Packet too short".into())); 202 } 203 if bytes[0] != MAGIC_BYTES[0] { 204 return Err(BeaconError::InvalidMagic([bytes[0], bytes[1]])); 205 } 206 if bytes[2] != PROTOCOL_VERSION { 207 return Err(BeaconError::UnsupportedVersion(bytes[2])); 208 } 209 match bytes[1] { 210 KIND_SIGNAL => DistressNanobeacon::from_bytes(bytes).map(Frame::Signal), 211 KIND_REGISTER => unframed(bytes, MAX_DATAGRAM_SIZE).map(Frame::Register), 212 KIND_CHALLENGE => unframed(bytes, MAX_DATAGRAM_SIZE).map(Frame::Challenge), 213 KIND_ACK => unframed(bytes, MAX_DATAGRAM_SIZE).map(Frame::Ack), 214 KIND_CAPSULE => unframed(bytes, MAX_CAPSULE_DATAGRAM).map(Frame::Capsule), 215 other => Err(BeaconError::InvalidMagic([bytes[0], other])), 216 } 217 } 218 } 219 220 /// Sign a request for help with the node's key. 221 pub fn sign_signal(signal: &mut DistressNanobeacon, keypair: &Keypair) -> Result<(), BeaconError> { 222 signal.signature = keypair.sign(&signal.signable_bytes()?); 223 Ok(()) 224 } 225 226 /// The request was signed by the key it names. 227 pub fn verify_signal(signal: &DistressNanobeacon) -> Result<(), BeaconError> { 228 verify_signature(&signal.sender_pubkey, &signal.signable_bytes()?, &signal.signature) 229 } 230 231 pub fn sign_capsule(capsule: &mut ResolutionCapsule, keypair: &Keypair) -> Result<(), BeaconError> { 232 capsule.signature = keypair.sign(&capsule.signable_bytes()?); 233 Ok(()) 234 } 235 236 /// The answer was signed by the key it names. 237 pub fn verify_capsule(capsule: &ResolutionCapsule) -> Result<(), BeaconError> { 238 verify_signature(&capsule.responder_pubkey, &capsule.signable_bytes()?, &capsule.signature) 239 } 240 241 #[cfg(test)] 242 mod tests { 243 use super::*; 244 use crate::schema::ErrorFingerprint; 245 246 fn signal(keypair: &Keypair) -> DistressNanobeacon { 247 let mut signal = DistressNanobeacon::new( 248 BeaconTopic::RustCompilation, 249 keypair.pubkey_bytes(), 250 [7u8; 32], 251 ErrorFingerprint::from_error_str("E0425", Some(425), "aarch64"), 252 "title".into(), 253 "summary".into(), 254 ); 255 sign_signal(&mut signal, keypair).unwrap(); 256 signal 257 } 258 259 #[test] 260 fn test_wire_signal_keeps_its_original_bytes() { 261 let keypair = Keypair::generate(); 262 let signal = signal(&keypair); 263 let bytes = Frame::Signal(signal.clone()).encode().unwrap(); 264 assert_eq!(bytes, signal.to_bytes().unwrap()); 265 assert_eq!(&bytes[..3], &[0x4F, KIND_SIGNAL, PROTOCOL_VERSION]); 266 assert_eq!(Frame::decode(&bytes).unwrap(), Frame::Signal(signal)); 267 } 268 269 #[test] 270 fn test_wire_every_kind_round_trips() { 271 let keypair = Keypair::generate(); 272 let mut register = Register::new(keypair.pubkey_bytes(), 0b101, true, [9u8; COOKIE_LEN]); 273 register.sign(&keypair).unwrap(); 274 let mut capsule = 275 ResolutionCapsule::new(uuid::Uuid::now_v7(), keypair.pubkey_bytes(), [1u8; 32], [2u8; 12], vec![3u8; 40]); 276 sign_capsule(&mut capsule, &keypair).unwrap(); 277 for frame in [ 278 Frame::Register(register), 279 Frame::Challenge(Challenge { cookie: [4u8; COOKIE_LEN] }), 280 Frame::Ack(Ack { topics: 3, ttl_secs: 120 }), 281 Frame::Capsule(capsule), 282 ] { 283 let bytes = frame.encode().unwrap(); 284 assert_eq!(bytes[0], 0x4F); 285 assert_eq!(bytes[2], PROTOCOL_VERSION); 286 assert_eq!(Frame::decode(&bytes).unwrap(), frame); 287 } 288 } 289 290 #[test] 291 fn test_wire_rejects_unknown_kind_version_and_short_packets() { 292 assert!(matches!(Frame::decode(&[0x4F, 0x5A, 1, 0, 0]), Err(BeaconError::InvalidMagic(_)))); 293 assert!(matches!(Frame::decode(&[0x4F, KIND_ACK, 9, 0, 0]), Err(BeaconError::UnsupportedVersion(9)))); 294 assert!(matches!(Frame::decode(&[0x00, KIND_ACK, 1, 0, 0]), Err(BeaconError::InvalidMagic(_)))); 295 assert!(Frame::decode(&[0x4F, KIND_ACK]).is_err()); 296 assert!(Frame::decode(&[0x4F, KIND_REGISTER, 1, 1, 2, 3]).is_err()); 297 } 298 299 #[test] 300 fn test_wire_oversized_capsule_is_refused_both_ways() { 301 let keypair = Keypair::generate(); 302 let capsule = ResolutionCapsule::new( 303 uuid::Uuid::now_v7(), 304 keypair.pubkey_bytes(), 305 [1u8; 32], 306 [2u8; 12], 307 vec![0u8; MAX_CAPSULE_DATAGRAM], 308 ); 309 assert!(matches!(Frame::Capsule(capsule).encode(), Err(BeaconError::DatagramTooLarge(_, _)))); 310 let mut big = vec![0x4F, KIND_CAPSULE, PROTOCOL_VERSION]; 311 big.resize(MAX_CAPSULE_DATAGRAM + 1, 0); 312 assert!(matches!(Frame::decode(&big), Err(BeaconError::DatagramTooLarge(_, _)))); 313 } 314 315 #[test] 316 fn test_wire_cookie_is_bound_to_address_secret_and_window() { 317 let secret = random_secret(); 318 let a: SocketAddr = "192.0.2.1:4000".parse().unwrap(); 319 let b: SocketAddr = "192.0.2.1:4001".parse().unwrap(); 320 let now = 1_000_000u64; 321 let cookie = relay_cookie(&secret, &a, now / COOKIE_WINDOW_SECS); 322 assert!(cookie_valid(&secret, &a, now, &cookie)); 323 assert!(cookie_valid(&secret, &a, now + COOKIE_WINDOW_SECS, &cookie)); 324 assert!(!cookie_valid(&secret, &a, now + 2 * COOKIE_WINDOW_SECS, &cookie)); 325 assert!(!cookie_valid(&secret, &b, now, &cookie)); 326 assert!(!cookie_valid(&random_secret(), &a, now, &cookie)); 327 assert!(!cookie_valid(&secret, &a, now, &[0u8; COOKIE_LEN])); 328 } 329 330 #[test] 331 fn test_wire_signatures_bind_content_and_key() { 332 let keypair = Keypair::generate(); 333 let other = Keypair::generate(); 334 let mut s = signal(&keypair); 335 assert!(verify_signal(&s).is_ok()); 336 s.title.push('x'); 337 assert_eq!(verify_signal(&s), Err(BeaconError::SignatureVerificationFailed)); 338 339 let mut register = Register::new(keypair.pubkey_bytes(), 1, false, [0u8; COOKIE_LEN]); 340 register.sign(&keypair).unwrap(); 341 assert!(register.verify(unix_now()).is_ok()); 342 assert!(matches!( 343 register.verify(unix_now() + MAX_TIMESTAMP_DRIFT_SECS + 5), 344 Err(BeaconError::TimestampDrift { .. }) 345 )); 346 register.node_pubkey = other.pubkey_bytes(); 347 assert_eq!(register.verify(unix_now()), Err(BeaconError::SignatureVerificationFailed)); 348 349 let mut capsule = 350 ResolutionCapsule::new(s.beacon_id, keypair.pubkey_bytes(), [1u8; 32], [2u8; 12], vec![5u8; 8]); 351 sign_capsule(&mut capsule, &keypair).unwrap(); 352 assert!(verify_capsule(&capsule).is_ok()); 353 capsule.ciphertext[0] ^= 1; 354 assert_eq!(verify_capsule(&capsule), Err(BeaconError::SignatureVerificationFailed)); 355 } 356 357 #[test] 358 fn test_wire_topic_names_and_masks() { 359 assert_eq!(BeaconTopic::RustCompilation.bit(), 1); 360 assert_eq!(BeaconTopic::AgentRecursion.bit(), 0x40); 361 assert_eq!(BeaconTopic::from_name("security-audit"), Some(BeaconTopic::SecurityAudit)); 362 assert_eq!(BeaconTopic::from_name("nope"), None); 363 assert_eq!(topics_mask("all"), Some(ALL_TOPICS)); 364 assert_eq!(topics_mask("rust-compilation, mojo-simd"), Some(0b11)); 365 assert_eq!(topics_mask("rust-compilation,nope"), None); 366 } 367 }