open-humanity
Privacy-first peer assistance network for sovereign autonomous agents
Brought by drakestapleton
open-humanity / crates / beacon-client / src / storage.rs
| 1 | //! Dual-tier local relational storage for Open Humanity. |
| 2 | //! |
| 3 | //! Enforces SQLite WAL mode, foreign keys, 7-day TTL sweeps, |
| 4 | //! and Cortex memory promotion for verified resolutions. |
| 5 | |
| 6 | use beacon_core::schema::{BeaconTopic, DistressNanobeacon}; |
| 7 | use rusqlite::{params, Connection, Result}; |
| 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 10 | use thiserror::Error; |
| 11 | |
| 12 | pub const DEFAULT_TTL_SECONDS: u64 = 7 * 86400; // 7 days |
| 13 | |
| 14 | #[derive(Error, Debug)] |
| 15 | pub enum StorageError { |
| 16 | #[error("Database error: {0}")] |
| 17 | Sqlite(#[from] rusqlite::Error), |
| 18 | #[error("IO error: {0}")] |
| 19 | Io(#[from] std::io::Error), |
| 20 | #[error("Serialization error: {0}")] |
| 21 | Serialization(String), |
| 22 | } |
| 23 | |
| 24 | #[derive(Debug, Clone)] |
| 25 | pub struct SolvedEntry { |
| 26 | pub fingerprint_hash: [u8; 32], |
| 27 | pub topic: BeaconTopic, |
| 28 | pub solution_patch: String, |
| 29 | pub verified_at: u64, |
| 30 | pub promoted_to_cortex: bool, |
| 31 | } |
| 32 | |
| 33 | pub struct BeaconStorage { |
| 34 | conn: Connection, |
| 35 | #[allow(dead_code)] |
| 36 | db_path: PathBuf, |
| 37 | } |
| 38 | |
| 39 | impl BeaconStorage { |
| 40 | pub fn open_default() -> std::result::Result<Self, StorageError> { |
| 41 | let mut path = dirs_fallback_local_data(); |
| 42 | std::fs::create_dir_all(&path)?; |
| 43 | path.push("beacon.sqlite"); |
| 44 | Self::open(&path) |
| 45 | } |
| 46 | |
| 47 | pub fn open_in_memory() -> std::result::Result<Self, StorageError> { |
| 48 | let conn = Connection::open_in_memory()?; |
| 49 | let storage = Self { |
| 50 | conn, |
| 51 | db_path: PathBuf::from(":memory:"), |
| 52 | }; |
| 53 | storage.init_tables()?; |
| 54 | Ok(storage) |
| 55 | } |
| 56 | |
| 57 | pub fn open<P: AsRef<Path>>(path: P) -> std::result::Result<Self, StorageError> { |
| 58 | let db_path = path.as_ref().to_path_buf(); |
| 59 | if let Some(parent) = db_path.parent() { |
| 60 | std::fs::create_dir_all(parent)?; |
| 61 | } |
| 62 | let conn = Connection::open(&db_path)?; |
| 63 | let storage = Self { conn, db_path }; |
| 64 | storage.init_tables()?; |
| 65 | Ok(storage) |
| 66 | } |
| 67 | |
| 68 | fn init_tables(&self) -> Result<()> { |
| 69 | self.conn.pragma_update(None, "journal_mode", "WAL")?; |
| 70 | self.conn.pragma_update(None, "foreign_keys", "ON")?; |
| 71 | self.conn.pragma_update(None, "busy_timeout", 5000)?; |
| 72 | |
| 73 | self.conn.execute_batch( |
| 74 | " |
| 75 | CREATE TABLE IF NOT EXISTS beacons_out ( |
| 76 | id TEXT PRIMARY KEY, |
| 77 | timestamp INTEGER NOT NULL, |
| 78 | topic INTEGER NOT NULL, |
| 79 | sender_pubkey BLOB NOT NULL, |
| 80 | fingerprint_hash BLOB NOT NULL, |
| 81 | compiler_code INTEGER, |
| 82 | arch TEXT NOT NULL, |
| 83 | title TEXT NOT NULL, |
| 84 | compact_summary TEXT NOT NULL, |
| 85 | status TEXT NOT NULL, |
| 86 | created_at INTEGER NOT NULL |
| 87 | ); |
| 88 | |
| 89 | CREATE TABLE IF NOT EXISTS beacons_in ( |
| 90 | id TEXT PRIMARY KEY, |
| 91 | timestamp INTEGER NOT NULL, |
| 92 | topic INTEGER NOT NULL, |
| 93 | sender_pubkey BLOB NOT NULL, |
| 94 | fingerprint_hash BLOB NOT NULL, |
| 95 | title TEXT NOT NULL, |
| 96 | compact_summary TEXT NOT NULL, |
| 97 | received_at INTEGER NOT NULL |
| 98 | ); |
| 99 | |
| 100 | CREATE TABLE IF NOT EXISTS solved_cache ( |
| 101 | fingerprint_hash BLOB PRIMARY KEY, |
| 102 | topic INTEGER NOT NULL, |
| 103 | solution_patch TEXT NOT NULL, |
| 104 | verified_at INTEGER NOT NULL, |
| 105 | promoted_to_cortex INTEGER NOT NULL DEFAULT 0 |
| 106 | ); |
| 107 | |
| 108 | CREATE TABLE IF NOT EXISTS peer_reputation ( |
| 109 | pubkey BLOB PRIMARY KEY, |
| 110 | successful_resolutions INTEGER NOT NULL DEFAULT 0, |
| 111 | failed_resolutions INTEGER NOT NULL DEFAULT 0, |
| 112 | last_seen INTEGER NOT NULL |
| 113 | ); |
| 114 | ", |
| 115 | )?; |
| 116 | Ok(()) |
| 117 | } |
| 118 | |
| 119 | pub fn record_outbound_beacon(&self, beacon: &DistressNanobeacon) -> Result<()> { |
| 120 | let now = SystemTime::now() |
| 121 | .duration_since(UNIX_EPOCH) |
| 122 | .unwrap_or_default() |
| 123 | .as_secs(); |
| 124 | |
| 125 | self.conn.execute( |
| 126 | "INSERT OR REPLACE INTO beacons_out ( |
| 127 | id, timestamp, topic, sender_pubkey, fingerprint_hash, |
| 128 | compiler_code, arch, title, compact_summary, status, created_at |
| 129 | ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", |
| 130 | params![ |
| 131 | beacon.beacon_id.to_string(), |
| 132 | beacon.timestamp, |
| 133 | beacon.topic as u8, |
| 134 | &beacon.sender_pubkey[..], |
| 135 | &beacon.fingerprint.hash[..], |
| 136 | beacon.fingerprint.compiler_code, |
| 137 | beacon.fingerprint.hardware_arch, |
| 138 | beacon.title, |
| 139 | beacon.compact_summary, |
| 140 | "pending", |
| 141 | now, |
| 142 | ], |
| 143 | )?; |
| 144 | Ok(()) |
| 145 | } |
| 146 | |
| 147 | pub fn record_inbound_beacon(&self, beacon: &DistressNanobeacon) -> Result<()> { |
| 148 | let now = SystemTime::now() |
| 149 | .duration_since(UNIX_EPOCH) |
| 150 | .unwrap_or_default() |
| 151 | .as_secs(); |
| 152 | |
| 153 | self.conn.execute( |
| 154 | "INSERT OR REPLACE INTO beacons_in ( |
| 155 | id, timestamp, topic, sender_pubkey, fingerprint_hash, |
| 156 | title, compact_summary, received_at |
| 157 | ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", |
| 158 | params![ |
| 159 | beacon.beacon_id.to_string(), |
| 160 | beacon.timestamp, |
| 161 | beacon.topic as u8, |
| 162 | &beacon.sender_pubkey[..], |
| 163 | &beacon.fingerprint.hash[..], |
| 164 | beacon.title, |
| 165 | beacon.compact_summary, |
| 166 | now, |
| 167 | ], |
| 168 | )?; |
| 169 | Ok(()) |
| 170 | } |
| 171 | |
| 172 | pub fn insert_solved_entry( |
| 173 | &self, |
| 174 | fingerprint_hash: &[u8; 32], |
| 175 | topic: BeaconTopic, |
| 176 | patch: &str, |
| 177 | ) -> Result<()> { |
| 178 | let now = SystemTime::now() |
| 179 | .duration_since(UNIX_EPOCH) |
| 180 | .unwrap_or_default() |
| 181 | .as_secs(); |
| 182 | |
| 183 | self.conn.execute( |
| 184 | "INSERT OR REPLACE INTO solved_cache ( |
| 185 | fingerprint_hash, topic, solution_patch, verified_at, promoted_to_cortex |
| 186 | ) VALUES (?1, ?2, ?3, ?4, 0)", |
| 187 | params![ |
| 188 | &fingerprint_hash[..], |
| 189 | topic as u8, |
| 190 | patch, |
| 191 | now, |
| 192 | ], |
| 193 | )?; |
| 194 | Ok(()) |
| 195 | } |
| 196 | |
| 197 | pub fn get_solved_entry(&self, fingerprint_hash: &[u8; 32]) -> Result<Option<SolvedEntry>> { |
| 198 | let mut stmt = self.conn.prepare( |
| 199 | "SELECT fingerprint_hash, topic, solution_patch, verified_at, promoted_to_cortex |
| 200 | FROM solved_cache WHERE fingerprint_hash = ?1", |
| 201 | )?; |
| 202 | |
| 203 | let mut rows = stmt.query(params![&fingerprint_hash[..]])?; |
| 204 | if let Some(row) = rows.next()? { |
| 205 | let hash_blob: Vec<u8> = row.get(0)?; |
| 206 | let mut hash = [0u8; 32]; |
| 207 | if hash_blob.len() == 32 { |
| 208 | hash.copy_from_slice(&hash_blob); |
| 209 | } |
| 210 | let topic_raw: u8 = row.get(1)?; |
| 211 | let topic = match topic_raw { |
| 212 | 0 => BeaconTopic::RustCompilation, |
| 213 | 1 => BeaconTopic::MojoSimd, |
| 214 | 2 => BeaconTopic::ModularMaxServing, |
| 215 | 3 => BeaconTopic::HardwareTopology, |
| 216 | 4 => BeaconTopic::SecurityAudit, |
| 217 | 5 => BeaconTopic::ProtocolCoordination, |
| 218 | _ => BeaconTopic::AgentRecursion, |
| 219 | }; |
| 220 | let patch: String = row.get(2)?; |
| 221 | let verified_at: u64 = row.get(3)?; |
| 222 | let promoted: i64 = row.get(4)?; |
| 223 | |
| 224 | Ok(Some(SolvedEntry { |
| 225 | fingerprint_hash: hash, |
| 226 | topic, |
| 227 | solution_patch: patch, |
| 228 | verified_at, |
| 229 | promoted_to_cortex: promoted != 0, |
| 230 | })) |
| 231 | } else { |
| 232 | Ok(None) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | pub fn sweep_expired(&self, ttl_seconds: u64) -> Result<usize> { |
| 237 | let now = SystemTime::now() |
| 238 | .duration_since(UNIX_EPOCH) |
| 239 | .unwrap_or_default() |
| 240 | .as_secs(); |
| 241 | let cutoff = now.saturating_sub(ttl_seconds); |
| 242 | |
| 243 | let count_out = self.conn.execute( |
| 244 | "DELETE FROM beacons_out WHERE created_at <= ?1", |
| 245 | params![cutoff], |
| 246 | )?; |
| 247 | |
| 248 | let count_in = self.conn.execute( |
| 249 | "DELETE FROM beacons_in WHERE received_at <= ?1", |
| 250 | params![cutoff], |
| 251 | )?; |
| 252 | |
| 253 | Ok(count_out + count_in) |
| 254 | } |
| 255 | |
| 256 | pub fn mark_promoted_to_cortex(&self, fingerprint_hash: &[u8; 32]) -> Result<()> { |
| 257 | self.conn.execute( |
| 258 | "UPDATE solved_cache SET promoted_to_cortex = 1 WHERE fingerprint_hash = ?1", |
| 259 | params![&fingerprint_hash[..]], |
| 260 | )?; |
| 261 | Ok(()) |
| 262 | } |
| 263 | |
| 264 | pub fn transaction(&mut self) -> std::result::Result<rusqlite::Transaction<'_>, StorageError> { |
| 265 | Ok(self.conn.transaction()?) |
| 266 | } |
| 267 | |
| 268 | pub fn count_outbound(&self) -> std::result::Result<usize, StorageError> { |
| 269 | let mut stmt = self.conn.prepare("SELECT COUNT(*) FROM beacons_out")?; |
| 270 | let count: usize = stmt.query_row([], |row| row.get(0))?; |
| 271 | Ok(count) |
| 272 | } |
| 273 | |
| 274 | pub fn count_inbound(&self) -> std::result::Result<usize, StorageError> { |
| 275 | let mut stmt = self.conn.prepare("SELECT COUNT(*) FROM beacons_in")?; |
| 276 | let count: usize = stmt.query_row([], |row| row.get(0))?; |
| 277 | Ok(count) |
| 278 | } |
| 279 | |
| 280 | pub fn record_outbound_beacon_tx( |
| 281 | tx: &rusqlite::Transaction<'_>, |
| 282 | packet: &DistressNanobeacon, |
| 283 | ) -> std::result::Result<(), StorageError> { |
| 284 | let now = SystemTime::now() |
| 285 | .duration_since(UNIX_EPOCH) |
| 286 | .unwrap_or_default() |
| 287 | .as_secs(); |
| 288 | |
| 289 | tx.execute( |
| 290 | "INSERT OR REPLACE INTO beacons_out ( |
| 291 | id, timestamp, topic, sender_pubkey, fingerprint_hash, |
| 292 | compiler_code, arch, title, compact_summary, status, created_at |
| 293 | ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", |
| 294 | params![ |
| 295 | packet.beacon_id.to_string(), |
| 296 | packet.timestamp, |
| 297 | packet.topic as u8, |
| 298 | &packet.sender_pubkey[..], |
| 299 | &packet.fingerprint.hash[..], |
| 300 | packet.fingerprint.compiler_code, |
| 301 | packet.fingerprint.hardware_arch, |
| 302 | packet.title, |
| 303 | packet.compact_summary, |
| 304 | "pending", |
| 305 | now, |
| 306 | ], |
| 307 | )?; |
| 308 | Ok(()) |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | fn dirs_fallback_local_data() -> PathBuf { |
| 313 | if let Ok(home) = std::env::var("HOME") { |
| 314 | PathBuf::from(home).join(".local/share/open-humanity") |
| 315 | } else { |
| 316 | PathBuf::from("./.open-humanity-data") |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | /// What this node has seen of one helper's answers. |
| 321 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 322 | pub struct PeerReputation { |
| 323 | pub pubkey: [u8; 32], |
| 324 | pub successful: u64, |
| 325 | pub failed: u64, |
| 326 | pub last_seen: u64, |
| 327 | } |
| 328 | |
| 329 | /// A helper with this many failed answers, and more failed than passed, is skipped. |
| 330 | pub const DISTRUST_AFTER_FAILED: u64 = 3; |
| 331 | |
| 332 | impl PeerReputation { |
| 333 | pub fn distrusted(&self) -> bool { |
| 334 | self.failed >= DISTRUST_AFTER_FAILED && self.failed > self.successful |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | impl BeaconStorage { |
| 339 | /// Count one checked answer for or against the helper that signed it. |
| 340 | pub fn record_peer_result(&self, pubkey: &[u8; 32], passed: bool) -> Result<()> { |
| 341 | let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(); |
| 342 | let (ok, bad): (i64, i64) = if passed { (1, 0) } else { (0, 1) }; |
| 343 | self.conn.execute( |
| 344 | "INSERT INTO peer_reputation (pubkey, successful_resolutions, failed_resolutions, last_seen) |
| 345 | VALUES (?1, ?2, ?3, ?4) |
| 346 | ON CONFLICT(pubkey) DO UPDATE SET |
| 347 | successful_resolutions = successful_resolutions + excluded.successful_resolutions, |
| 348 | failed_resolutions = failed_resolutions + excluded.failed_resolutions, |
| 349 | last_seen = excluded.last_seen", |
| 350 | params![&pubkey[..], ok, bad, now], |
| 351 | )?; |
| 352 | Ok(()) |
| 353 | } |
| 354 | |
| 355 | /// Every helper this node has checked, newest first. |
| 356 | pub fn list_peers(&self) -> Result<Vec<PeerReputation>> { |
| 357 | let mut stmt = self.conn.prepare( |
| 358 | "SELECT pubkey, successful_resolutions, failed_resolutions, last_seen |
| 359 | FROM peer_reputation ORDER BY last_seen DESC, pubkey", |
| 360 | )?; |
| 361 | let rows = stmt.query_map([], |row| { |
| 362 | let blob: Vec<u8> = row.get(0)?; |
| 363 | let mut pubkey = [0u8; 32]; |
| 364 | if blob.len() == 32 { |
| 365 | pubkey.copy_from_slice(&blob); |
| 366 | } |
| 367 | Ok(PeerReputation { |
| 368 | pubkey, |
| 369 | successful: row.get(1)?, |
| 370 | failed: row.get(2)?, |
| 371 | last_seen: row.get(3)?, |
| 372 | }) |
| 373 | })?; |
| 374 | rows.collect() |
| 375 | } |
| 376 | |
| 377 | pub fn peer_reputation(&self, pubkey: &[u8; 32]) -> Result<Option<PeerReputation>> { |
| 378 | Ok(self.list_peers()?.into_iter().find(|peer| &peer.pubkey == pubkey)) |
| 379 | } |
| 380 | |
| 381 | /// The keys of helpers whose answers are skipped. |
| 382 | pub fn distrusted_peers(&self) -> Result<std::collections::HashSet<[u8; 32]>> { |
| 383 | Ok(self.list_peers()?.into_iter().filter(|peer| peer.distrusted()).map(|peer| peer.pubkey).collect()) |
| 384 | } |
| 385 | } |