interplane.Get Omega
Read in your language

open-humanity

Privacy-first peer assistance network for sovereign autonomous agents

Brought by drakestapleton

branch main Branches Tags History

open-humanity / crates / beacon / src / lib.rs

544 lines · 21341 bytes Raw Blame History
1//! Open Humanity relay.
2//!
3//! A UDP relay that carries a request for help to the nodes that registered for its
4//! topic and carries each encrypted answer back to the node that asked. It holds
5//! requests in memory for seven days so a helper that registers later still sees them.
6//! It never sees an answer in the clear and stores no personal context.
7//!
8//! The relay sends datagrams only to addresses that completed the cookie exchange
9//! (see `beacon_core::wire`), so a forged source address gains nothing.
10//!
11//! Relays can be linked (`set_links`, `BEACON_LINKS`): each registers with the other as
12//! a helper for every topic, through the same cookie exchange as any node. Requests
13//! then reach the helpers of both and each answer goes back the way its request came.
14
15use beacon_core::crypto::{verify_timestamp_drift, Keypair, ReplayProtector, MAX_TIMESTAMP_DRIFT_SECS};
16use beacon_core::wire::{
17 cookie_valid, random_secret, relay_cookie, unix_now, verify_capsule, verify_signal, Ack,
18 Challenge, Frame, Register, ALL_TOPICS, COOKIE_LEN, COOKIE_WINDOW_SECS, MAX_CAPSULE_DATAGRAM,
19};
20use std::collections::{HashMap, VecDeque};
21use std::net::SocketAddr;
22use std::sync::Arc;
23use std::time::{Duration, Instant};
24use tokio::net::UdpSocket;
25use tokio::sync::Mutex;
26use tracing::{debug, error, info};
27use uuid::Uuid;
28
29pub const RELAY_DEFAULT_PORT: u16 = 18098;
30pub const MAX_RING_ENTRIES: usize = 10_000;
31
32
33/// The address the relay listens on, from the values of `BEACON_BIND` and `BEACON_PORT`.
34/// A value that is not set takes the default (all interfaces, port 18098). A value that is
35/// set but empty or not valid is an error: a typing mistake in a config file must not turn
36/// into "listen on every interface".
37pub fn listen_addr(bind: Option<&str>, port: Option<&str>) -> Result<std::net::SocketAddr, String> {
38 let ip: std::net::IpAddr = match bind {
39 None => std::net::IpAddr::from([0, 0, 0, 0]),
40 Some(text) => text
41 .parse()
42 .map_err(|_| format!("BEACON_BIND is set but is not an IP address: {text:?}"))?,
43 };
44 let port: u16 = match port {
45 None => RELAY_DEFAULT_PORT,
46 Some(text) => match text.parse() {
47 Ok(0) | Err(_) => {
48 return Err(format!("BEACON_PORT is set but is not a port from 1 to 65535: {text:?}"))
49 }
50 Ok(port) => port,
51 },
52 };
53 Ok(std::net::SocketAddr::new(ip, port))
54}
55
56/// The relays to link with, from the value of `BEACON_LINKS`: `address:port` entries
57/// separated by commas. Not set or empty means none. An entry that is not an address
58/// and a port is an error.
59pub fn parse_links(text: Option<&str>) -> Result<Vec<SocketAddr>, String> {
60 let mut links = Vec::new();
61 for entry in text.unwrap_or("").split(',').map(str::trim).filter(|entry| !entry.is_empty()) {
62 let addr: SocketAddr = entry
63 .parse()
64 .map_err(|_| format!("BEACON_LINKS has an entry that is not address:port: {entry:?}"))?;
65 links.push(addr);
66 }
67 Ok(links)
68}
69
70#[derive(Debug, Clone)]
71pub struct RelayConfig {
72 /// A registration lasts this long; nodes repeat it to stay known.
73 pub peer_ttl: Duration,
74 /// A stored request is dropped after this long.
75 pub signal_ttl: Duration,
76 pub max_ring: usize,
77 pub max_peers: usize,
78 /// Answers forwarded for one request.
79 pub max_capsules_per_signal: u8,
80 /// Stored requests sent to a node that registers with `replay`.
81 pub replay_limit: usize,
82 /// Requests accepted from one address in a minute.
83 pub signals_per_minute: u32,
84 /// Requests accepted in a minute from a relay this one is linked with.
85 pub link_signals_per_minute: u32,
86}
87
88impl Default for RelayConfig {
89 fn default() -> Self {
90 Self {
91 peer_ttl: Duration::from_secs(120),
92 signal_ttl: Duration::from_secs(7 * 86400),
93 max_ring: MAX_RING_ENTRIES,
94 max_peers: 10_000,
95 max_capsules_per_signal: 16,
96 replay_limit: 64,
97 signals_per_minute: 20,
98 link_signals_per_minute: 600,
99 }
100 }
101}
102
103#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
104pub struct RelayStats {
105 pub peers: usize,
106 pub cached: usize,
107 pub signals_forwarded: u64,
108 pub capsules_forwarded: u64,
109 pub dropped: u64,
110 pub challenges: u64,
111}
112
113struct Peer {
114 topics: u8,
115 expires: Instant,
116 window_start: Instant,
117 signals_in_window: u32,
118}
119
120struct Cached {
121 id: Uuid,
122 topic_bit: u8,
123 received: Instant,
124 datagram: Vec<u8>,
125 source: SocketAddr,
126}
127
128struct Route {
129 source: SocketAddr,
130 capsules: u8,
131}
132
133/// A relay this one registers with.
134#[derive(Default)]
135struct Link {
136 cookie: [u8; COOKIE_LEN],
137 acked: Option<Instant>,
138 window_start: Option<Instant>,
139 replies: u8,
140}
141
142impl Link {
143 /// At most three registrations in ten seconds are sent in reply to what a linked
144 /// relay sends, so two relays can never drive each other in a loop.
145 fn allow(&mut self, now: Instant) -> bool {
146 if self.window_start.map_or(true, |at| now.duration_since(at) >= Duration::from_secs(10)) {
147 self.window_start = Some(now);
148 self.replies = 0;
149 }
150 self.replies = self.replies.saturating_add(1);
151 self.replies <= 3
152 }
153}
154
155struct State {
156 peers: HashMap<SocketAddr, Peer>,
157 links: HashMap<SocketAddr, Link>,
158 ring: VecDeque<Cached>,
159 routes: HashMap<Uuid, Route>,
160 seen: ReplayProtector,
161 last_sweep: Instant,
162 signals_forwarded: u64,
163 capsules_forwarded: u64,
164 dropped: u64,
165 challenges: u64,
166}
167
168impl State {
169 /// Forget registrations and stored requests that are past their time.
170 fn sweep(&mut self, now: Instant, config: &RelayConfig) {
171 if now.duration_since(self.last_sweep) < Duration::from_millis(200) {
172 return;
173 }
174 self.last_sweep = now;
175 self.peers.retain(|_, peer| peer.expires > now);
176 while let Some(front) = self.ring.front() {
177 if now.duration_since(front.received) < config.signal_ttl {
178 break;
179 }
180 let id = front.id;
181 self.ring.pop_front();
182 self.routes.remove(&id);
183 }
184 }
185}
186
187#[derive(Clone)]
188pub struct RelayServer {
189 socket: Arc<UdpSocket>,
190 state: Arc<Mutex<State>>,
191 secret: [u8; 32],
192 config: RelayConfig,
193 keypair: Arc<Keypair>,
194}
195
196impl RelayServer {
197 pub async fn bind(port: u16) -> std::io::Result<Self> {
198 let addr = SocketAddr::from(([0, 0, 0, 0], port));
199 Self::bind_addr(addr, RelayConfig::default()).await
200 }
201
202 pub async fn bind_addr(addr: SocketAddr, config: RelayConfig) -> std::io::Result<Self> {
203 let socket = UdpSocket::bind(addr).await?;
204 info!("Open Humanity relay bound to {}", socket.local_addr()?);
205 Ok(Self {
206 socket: Arc::new(socket),
207 state: Arc::new(Mutex::new(State {
208 peers: HashMap::new(),
209 links: HashMap::new(),
210 ring: VecDeque::new(),
211 routes: HashMap::new(),
212 seen: ReplayProtector::new(4 * config.max_ring.max(1)),
213 last_sweep: Instant::now(),
214 signals_forwarded: 0,
215 capsules_forwarded: 0,
216 dropped: 0,
217 challenges: 0,
218 })),
219 secret: random_secret(),
220 config,
221 keypair: Arc::new(Keypair::generate()),
222 })
223 }
224
225 pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
226 self.socket.local_addr()
227 }
228
229 /// Link this relay with others. It registers with each of them as a helper for
230 /// every topic, so their requests reach the helpers here and the answers go back.
231 /// A link carries traffic only when the other relay names this one too, and only
232 /// requests made while the link is up.
233 pub async fn set_links(&self, links: &[SocketAddr]) {
234 let own = self.socket.local_addr().ok();
235 let mut state = self.state.lock().await;
236 state.links = links
237 .iter()
238 .filter(|addr| Some(**addr) != own)
239 .map(|addr| (*addr, Link::default()))
240 .collect();
241 }
242
243 /// Linked relays that accepted this relay's registration within one lifetime.
244 pub async fn links_up(&self) -> usize {
245 let now = Instant::now();
246 let state = self.state.lock().await;
247 state
248 .links
249 .values()
250 .filter(|link| link.acked.is_some_and(|at| now.duration_since(at) < self.config.peer_ttl))
251 .count()
252 }
253
254 /// Register with every linked relay once. `run_loop` repeats it.
255 pub async fn link_once(&self) {
256 let links: Vec<SocketAddr> = self.state.lock().await.links.keys().copied().collect();
257 for link in links {
258 self.register_at(link).await;
259 }
260 }
261
262 async fn register_at(&self, to: SocketAddr) {
263 let Some(cookie) = self.state.lock().await.links.get(&to).map(|link| link.cookie) else {
264 return;
265 };
266 let mut register = Register::new(self.keypair.pubkey_bytes(), ALL_TOPICS, false, cookie);
267 if register.sign(&self.keypair).is_err() {
268 return;
269 }
270 if let Ok(bytes) = Frame::Register(register).encode() {
271 self.send(&bytes, to).await;
272 }
273 }
274
275 pub async fn stats(&self) -> RelayStats {
276 let mut guard = self.state.lock().await;
277 let state: &mut State = &mut guard;
278 state.last_sweep = Instant::now() - Duration::from_secs(1);
279 state.sweep(Instant::now(), &self.config);
280 RelayStats {
281 peers: state.peers.len(),
282 cached: state.ring.len(),
283 signals_forwarded: state.signals_forwarded,
284 capsules_forwarded: state.capsules_forwarded,
285 dropped: state.dropped,
286 challenges: state.challenges,
287 }
288 }
289
290 pub async fn run_loop(&self) -> std::io::Result<()> {
291 let mut buf = vec![0u8; MAX_CAPSULE_DATAGRAM + 1];
292 let every = (self.config.peer_ttl / 3).clamp(Duration::from_millis(200), Duration::from_secs(40));
293 let mut tick = tokio::time::interval(every);
294 loop {
295 tokio::select! {
296 received = self.socket.recv_from(&mut buf) => match received {
297 Ok((len, src)) => self.handle(&buf[..len], src).await,
298 Err(e) => {
299 error!("Socket recv error: {}", e);
300 tokio::time::sleep(Duration::from_millis(50)).await;
301 }
302 },
303 _ = tick.tick() => self.link_once().await,
304 }
305 }
306 }
307
308 async fn send(&self, bytes: &[u8], to: SocketAddr) {
309 if let Err(e) = self.socket.send_to(bytes, to).await {
310 debug!("send to {} failed: {}", to, e);
311 }
312 }
313
314 /// Tell an address the relay does not know how to register. The reply is smaller
315 /// than any datagram that causes it.
316 async fn challenge(&self, to: SocketAddr, now_secs: u64) {
317 let cookie = relay_cookie(&self.secret, &to, now_secs / COOKIE_WINDOW_SECS);
318 if let Ok(bytes) = Frame::Challenge(Challenge { cookie }).encode() {
319 self.send(&bytes, to).await;
320 }
321 }
322
323 async fn count_drop(&self, why: &str, src: SocketAddr) {
324 debug!("dropped datagram from {}: {}", src, why);
325 self.state.lock().await.dropped += 1;
326 }
327
328 /// Act on one datagram.
329 pub async fn handle(&self, packet: &[u8], src: SocketAddr) {
330 let frame = match Frame::decode(packet) {
331 Ok(frame) => frame,
332 Err(e) => return self.count_drop(&e.to_string(), src).await,
333 };
334 let now = Instant::now();
335 let now_secs = unix_now();
336 match frame {
337 Frame::Register(register) => {
338 if register.verify(now_secs).is_err() {
339 return self.count_drop("registration not signed or stale", src).await;
340 }
341 if register.node_pubkey == self.keypair.pubkey_bytes() {
342 // This relay named itself as a link under another address (bound to
343 // 0.0.0.0, linked to 127.0.0.1 or its public address): forget that link.
344 self.state.lock().await.links.remove(&src);
345 return self.count_drop("registration from this relay itself", src).await;
346 }
347 if !cookie_valid(&self.secret, &src, now_secs, &register.cookie) {
348 self.state.lock().await.challenges += 1;
349 return self.challenge(src, now_secs).await;
350 }
351 let topics = register.topics & ALL_TOPICS;
352 let replay: Vec<Vec<u8>>;
353 let nudge: bool;
354 {
355 let mut guard = self.state.lock().await;
356 let state: &mut State = &mut guard;
357 state.sweep(now, &self.config);
358 if !state.peers.contains_key(&src) && state.peers.len() >= self.config.max_peers {
359 state.dropped += 1;
360 return;
361 }
362 let expires = now + self.config.peer_ttl;
363 let peer = state.peers.entry(src).or_insert(Peer {
364 topics,
365 expires,
366 window_start: now,
367 signals_in_window: 0,
368 });
369 peer.topics = topics;
370 peer.expires = expires;
371 // A linked relay just registered here: if it has not accepted this
372 // relay lately, register there now instead of at the next tick.
373 let stale = self.config.peer_ttl / 3;
374 nudge = match state.links.get_mut(&src) {
375 Some(link) if link.acked.map_or(true, |at| now.duration_since(at) >= stale) => link.allow(now),
376 _ => false,
377 };
378 replay = if register.replay && topics != 0 {
379 let mut newest: Vec<Vec<u8>> = state
380 .ring
381 .iter()
382 .rev()
383 .filter(|c| c.topic_bit & topics != 0 && c.source != src)
384 .take(self.config.replay_limit)
385 .map(|c| c.datagram.clone())
386 .collect();
387 newest.reverse();
388 newest
389 } else {
390 Vec::new()
391 };
392 }
393 let ack = Ack {
394 topics,
395 ttl_secs: self.config.peer_ttl.as_secs() as u32,
396 };
397 if let Ok(bytes) = Frame::Ack(ack).encode() {
398 self.send(&bytes, src).await;
399 }
400 for datagram in &replay {
401 self.send(datagram, src).await;
402 }
403 if nudge {
404 self.register_at(src).await;
405 }
406 }
407 Frame::Signal(signal) => {
408 if verify_timestamp_drift(signal.timestamp, now_secs, MAX_TIMESTAMP_DRIFT_SECS).is_err()
409 || verify_signal(&signal).is_err()
410 {
411 return self.count_drop("request not signed or stale", src).await;
412 }
413 let bit = signal.topic.bit();
414 let targets: Vec<SocketAddr>;
415 {
416 let mut guard = self.state.lock().await;
417 let state: &mut State = &mut guard;
418 state.sweep(now, &self.config);
419 let limit = if state.links.contains_key(&src) {
420 self.config.link_signals_per_minute
421 } else {
422 self.config.signals_per_minute
423 };
424 let Some(peer) = state.peers.get_mut(&src) else {
425 state.challenges += 1;
426 drop(guard);
427 return self.challenge(src, now_secs).await;
428 };
429 if now.duration_since(peer.window_start) >= Duration::from_secs(60) {
430 peer.window_start = now;
431 peer.signals_in_window = 0;
432 }
433 if peer.signals_in_window >= limit {
434 state.dropped += 1;
435 return;
436 }
437 peer.signals_in_window += 1;
438 if state.routes.contains_key(&signal.beacon_id)
439 || state.seen.check_and_record(&signal.beacon_id).is_err()
440 {
441 state.dropped += 1;
442 return;
443 }
444 while state.ring.len() >= self.config.max_ring.max(1) {
445 if let Some(old) = state.ring.pop_front() {
446 state.routes.remove(&old.id);
447 }
448 }
449 state.ring.push_back(Cached {
450 id: signal.beacon_id,
451 topic_bit: bit,
452 received: now,
453 datagram: packet.to_vec(),
454 source: src,
455 });
456 state.routes.insert(signal.beacon_id, Route { source: src, capsules: 0 });
457 targets = state
458 .peers
459 .iter()
460 .filter(|(addr, peer)| **addr != src && peer.topics & bit != 0)
461 .map(|(addr, _)| *addr)
462 .collect();
463 state.signals_forwarded += targets.len() as u64;
464 }
465 info!(
466 "request {} [topic: {}] carried to {} helper(s)",
467 signal.beacon_id,
468 signal.topic.as_str(),
469 targets.len()
470 );
471 for target in targets {
472 self.send(packet, target).await;
473 }
474 }
475 Frame::Capsule(capsule) => {
476 if verify_capsule(&capsule).is_err() {
477 return self.count_drop("answer not signed", src).await;
478 }
479 let target: SocketAddr;
480 {
481 let mut guard = self.state.lock().await;
482 let state: &mut State = &mut guard;
483 state.sweep(now, &self.config);
484 if !state.peers.contains_key(&src) {
485 state.challenges += 1;
486 drop(guard);
487 return self.challenge(src, now_secs).await;
488 }
489 let Some(route) = state.routes.get_mut(&capsule.beacon_id) else {
490 state.dropped += 1;
491 return;
492 };
493 if route.capsules >= self.config.max_capsules_per_signal {
494 state.dropped += 1;
495 return;
496 }
497 target = route.source;
498 // An answer goes only to an asker that is still registered.
499 if !state.peers.contains_key(&target) {
500 state.dropped += 1;
501 return;
502 }
503 if let Some(route) = state.routes.get_mut(&capsule.beacon_id) {
504 route.capsules += 1;
505 }
506 state.capsules_forwarded += 1;
507 }
508 info!("answer for {} carried back", capsule.beacon_id);
509 self.send(packet, target).await;
510 }
511 Frame::Challenge(challenge) => {
512 // A linked relay asks this one to prove its address: keep the cookie and
513 // register again (see `Link::allow`).
514 let again = {
515 let mut state = self.state.lock().await;
516 match state.links.get_mut(&src) {
517 None => None,
518 Some(link) => {
519 link.cookie = challenge.cookie;
520 Some(link.allow(now))
521 }
522 }
523 };
524 match again {
525 Some(true) => self.register_at(src).await,
526 Some(false) => {}
527 None => self.count_drop("frame a relay does not take", src).await,
528 }
529 }
530 Frame::Ack(_) => {
531 let known = match self.state.lock().await.links.get_mut(&src) {
532 Some(link) => {
533 link.acked = Some(now);
534 true
535 }
536 None => false,
537 };
538 if !known {
539 self.count_drop("frame a relay does not take", src).await;
540 }
541 }
542 }
543 }
544}