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/spark-rsi-mv/blob/main/src/ledger/db.rs # spark-rsi-mv Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger 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 `spark-rsi-mv / src / ledger / db.rs` 580 lines ยท 22290 bytes Raw Blame History 1 use crate::evaluator::EvaluationReceipt; 2 use crate::ledger::blob::BlobStore; 3 use crate::ledger::merkle::{compute_merkle_root, MerkleCheckpoint}; 4 use crate::ledger::record::{BlockType, LedgerBlock, PromotionEvidencePayload}; 5 use crate::ledger::schema::init_schema; 6 use crate::supervisor::GenerationInfo; 7 use p256::ecdsa::{SigningKey, VerifyingKey}; 8 use rusqlite::{params, Connection}; 9 use serde::{Deserialize, Serialize}; 10 use std::path::{Path, PathBuf}; 11 use std::sync::{Arc, Mutex}; 12 13 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] 14 pub struct LedgerAuditReport { 15 pub total_blocks: u64, 16 pub total_blobs: u64, 17 pub latest_sequence: u64, 18 pub latest_block_hash: String, 19 pub merkle_root: String, 20 pub checkpoint_verified: bool, 21 pub signature_verified: bool, 22 pub chain_valid: bool, 23 pub audit_timestamp_utc: String, 24 /// Last sequence covered by the latest Merkle checkpoint; `None` when no checkpoint exists. 25 #[serde(default)] 26 pub checkpoint_sequence: Option, 27 /// Blocks after the latest checkpoint, or every block when there is none. Their hash links 28 /// are checked, but no checkpoint or signature covers them yet. 29 #[serde(default)] 30 pub blocks_after_checkpoint: u64, 31 } 32 33 impl LedgerAuditReport { 34 /// What this audit did not establish. Empty means the chain, the latest checkpoint over the 35 /// whole ledger and, when a key was given, its signature all verified. 36 pub fn unchecked(&self, key_given: bool) -> Vec { 37 let mut gaps = Vec::new(); 38 match self.checkpoint_sequence { 39 None => gaps.push("no Merkle checkpoint is stored".to_string()), 40 Some(seq) => { 41 if self.blocks_after_checkpoint > 0 { 42 gaps.push(format!( 43 "{} block(s) after checkpoint #{} are not covered by any checkpoint", 44 self.blocks_after_checkpoint, seq 45 )); 46 } 47 if !key_given { 48 gaps.push( 49 "the checkpoint signature was not checked (no verifying key)".to_string(), 50 ); 51 } 52 } 53 } 54 gaps 55 } 56 } 57 58 #[derive(Clone)] 59 pub struct ImprovementLedger { 60 conn: Arc>, 61 blob_store: BlobStore, 62 pub rsi_root: PathBuf, 63 } 64 65 impl ImprovementLedger { 66 pub fn open(rsi_root: &Path) -> Result { 67 std::fs::create_dir_all(rsi_root) 68 .map_err(|e| format!("Failed to create rsi_root dir {:?}: {}", rsi_root, e))?; 69 70 let db_path = rsi_root.join("ledger.db"); 71 let conn = Connection::open(&db_path) 72 .map_err(|e| format!("Failed to open SQLite database at {:?}: {}", db_path, e))?; 73 74 init_schema(&conn).map_err(|e| format!("Failed to initialize ledger schema: {}", e))?; 75 76 let blob_store = BlobStore::new(rsi_root)?; 77 let ledger = Self { 78 conn: Arc::new(Mutex::new(conn)), 79 blob_store, 80 rsi_root: rsi_root.to_path_buf(), 81 }; 82 83 // Initialize Genesis block if database is fresh 84 if ledger.latest_block()?.is_none() { 85 ledger.init_genesis()?; 86 } 87 88 Ok(ledger) 89 } 90 91 fn init_genesis(&self) -> Result { 92 let genesis_payload = serde_json::json!({ 93 "system": "spark-rsi", 94 "law": "Build the cage, build the measuring instruments, then give the animal a bigger brain.", 95 "standard": "Apache-2.0 WITH LLVM-exception" 96 }) 97 .to_string(); 98 99 let block = LedgerBlock::new( 100 0, 101 BlockType::Genesis, 102 chrono::Utc::now().to_rfc3339(), 103 LedgerBlock::GENESIS_PREV_HASH.to_string(), 104 genesis_payload, 105 Vec::new(), 106 ); 107 108 self.insert_block_internal(&block)?; 109 Ok(block) 110 } 111 112 fn insert_block_internal(&self, block: &LedgerBlock) -> Result<(), String> { 113 let conn = self.conn.lock().map_err(|e| e.to_string())?; 114 let blob_hashes_json = serde_json::to_string(&block.blob_hashes) 115 .map_err(|e| format!("Failed to serialize blob_hashes: {}", e))?; 116 117 conn.execute( 118 "INSERT INTO blocks ( 119 sequence, block_type, timestamp_utc, prev_block_hash, 120 payload_json, payload_digest, blob_hashes_json, block_hash 121 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", 122 params![ 123 block.sequence as i64, 124 block.block_type.to_string(), 125 block.timestamp_utc, 126 block.prev_block_hash, 127 block.payload_json, 128 block.payload_digest, 129 blob_hashes_json, 130 block.block_hash, 131 ], 132 ) 133 .map_err(|e| format!("Failed to insert block sequence {}: {}", block.sequence, e))?; 134 135 Ok(()) 136 } 137 138 pub fn latest_block(&self) -> Result, String> { 139 let conn = self.conn.lock().map_err(|e| e.to_string())?; 140 let mut stmt = conn 141 .prepare( 142 "SELECT sequence, block_type, timestamp_utc, prev_block_hash, 143 payload_json, payload_digest, blob_hashes_json, block_hash 144 FROM blocks ORDER BY sequence DESC LIMIT 1", 145 ) 146 .map_err(|e| e.to_string())?; 147 148 let mut rows = stmt.query([]).map_err(|e| e.to_string())?; 149 if let Some(row) = rows.next().map_err(|e| e.to_string())? { 150 let block = Self::row_to_block(row)?; 151 Ok(Some(block)) 152 } else { 153 Ok(None) 154 } 155 } 156 157 pub fn get_block(&self, sequence: u64) -> Result, String> { 158 let conn = self.conn.lock().map_err(|e| e.to_string())?; 159 let mut stmt = conn 160 .prepare( 161 "SELECT sequence, block_type, timestamp_utc, prev_block_hash, 162 payload_json, payload_digest, blob_hashes_json, block_hash 163 FROM blocks WHERE sequence = ?1 LIMIT 1", 164 ) 165 .map_err(|e| e.to_string())?; 166 167 let mut rows = stmt.query([sequence as i64]).map_err(|e| e.to_string())?; 168 if let Some(row) = rows.next().map_err(|e| e.to_string())? { 169 let block = Self::row_to_block(row)?; 170 Ok(Some(block)) 171 } else { 172 Ok(None) 173 } 174 } 175 176 pub fn get_block_by_hash(&self, block_hash: &str) -> Result, String> { 177 let conn = self.conn.lock().map_err(|e| e.to_string())?; 178 let mut stmt = conn 179 .prepare( 180 "SELECT sequence, block_type, timestamp_utc, prev_block_hash, 181 payload_json, payload_digest, blob_hashes_json, block_hash 182 FROM blocks WHERE block_hash = ?1 LIMIT 1", 183 ) 184 .map_err(|e| e.to_string())?; 185 186 let mut rows = stmt.query([block_hash]).map_err(|e| e.to_string())?; 187 if let Some(row) = rows.next().map_err(|e| e.to_string())? { 188 let block = Self::row_to_block(row)?; 189 Ok(Some(block)) 190 } else { 191 Ok(None) 192 } 193 } 194 195 pub fn all_blocks(&self) -> Result, String> { 196 let conn = self.conn.lock().map_err(|e| e.to_string())?; 197 let mut stmt = conn 198 .prepare( 199 "SELECT sequence, block_type, timestamp_utc, prev_block_hash, 200 payload_json, payload_digest, blob_hashes_json, block_hash 201 FROM blocks ORDER BY sequence ASC", 202 ) 203 .map_err(|e| e.to_string())?; 204 205 let rows = stmt 206 .query_map([], |row| { 207 let seq: i64 = row.get(0)?; 208 let bt_str: String = row.get(1)?; 209 let ts: String = row.get(2)?; 210 let prev_hash: String = row.get(3)?; 211 let payload_json: String = row.get(4)?; 212 let payload_digest: String = row.get(5)?; 213 let blob_hashes_json: String = row.get(6)?; 214 let block_hash: String = row.get(7)?; 215 216 let block_type = bt_str.parse::().unwrap_or(BlockType::Evaluation); 217 let blob_hashes: Vec = 218 serde_json::from_str(&blob_hashes_json).unwrap_or_default(); 219 220 Ok(LedgerBlock { 221 sequence: seq as u64, 222 block_type, 223 timestamp_utc: ts, 224 prev_block_hash: prev_hash, 225 payload_json, 226 payload_digest, 227 blob_hashes, 228 block_hash, 229 }) 230 }) 231 .map_err(|e| e.to_string())?; 232 233 let mut blocks = Vec::new(); 234 for r in rows { 235 blocks.push(r.map_err(|e| e.to_string())?); 236 } 237 Ok(blocks) 238 } 239 240 /// Every block hash in sequence order, and the last sequence, from one SELECT (one SQLite 241 /// read snapshot). Unlike `all_blocks`, payloads and blob lists are neither read nor parsed. 242 fn leaf_hashes(conn: &Connection) -> Result<(Vec, Option), String> { 243 let mut stmt = conn 244 .prepare("SELECT sequence, block_hash FROM blocks ORDER BY sequence ASC") 245 .map_err(|e| e.to_string())?; 246 let mut rows = stmt.query([]).map_err(|e| e.to_string())?; 247 let mut hashes = Vec::new(); 248 let mut last_sequence = None; 249 while let Some(row) = rows.next().map_err(|e| e.to_string())? { 250 let seq: i64 = row.get(0).map_err(|e| e.to_string())?; 251 hashes.push(row.get(1).map_err(|e| e.to_string())?); 252 last_sequence = Some(seq as u64); 253 } 254 Ok((hashes, last_sequence)) 255 } 256 257 fn row_to_block(row: &rusqlite::Row) -> Result { 258 let seq: i64 = row.get(0).map_err(|e| e.to_string())?; 259 let bt_str: String = row.get(1).map_err(|e| e.to_string())?; 260 let ts: String = row.get(2).map_err(|e| e.to_string())?; 261 let prev_hash: String = row.get(3).map_err(|e| e.to_string())?; 262 let payload_json: String = row.get(4).map_err(|e| e.to_string())?; 263 let payload_digest: String = row.get(5).map_err(|e| e.to_string())?; 264 let blob_hashes_json: String = row.get(6).map_err(|e| e.to_string())?; 265 let block_hash: String = row.get(7).map_err(|e| e.to_string())?; 266 267 let block_type = bt_str 268 .parse::() 269 .map_err(|e| format!("Failed to parse block_type: {}", e))?; 270 let blob_hashes: Vec = serde_json::from_str(&blob_hashes_json) 271 .map_err(|e| format!("Failed to parse blob_hashes_json: {}", e))?; 272 273 Ok(LedgerBlock { 274 sequence: seq as u64, 275 block_type, 276 timestamp_utc: ts, 277 prev_block_hash: prev_hash, 278 payload_json, 279 payload_digest, 280 blob_hashes, 281 block_hash, 282 }) 283 } 284 285 pub fn append_block( 286 &self, 287 block_type: BlockType, 288 payload_json: String, 289 blob_hashes: Vec, 290 ) -> Result { 291 let latest = self.latest_block()?.ok_or_else(|| { 292 "Cannot append to uninitialized ledger (Genesis block missing)".to_string() 293 })?; 294 295 let next_sequence = latest.sequence + 1; 296 let prev_block_hash = latest.block_hash; 297 let timestamp_utc = chrono::Utc::now().to_rfc3339(); 298 299 let block = LedgerBlock::new( 300 next_sequence, 301 block_type, 302 timestamp_utc, 303 prev_block_hash, 304 payload_json, 305 blob_hashes, 306 ); 307 308 self.insert_block_internal(&block)?; 309 Ok(block) 310 } 311 312 pub fn append_evaluation( 313 &self, 314 receipt: &EvaluationReceipt, 315 raw_metrics: Option<&[u8]>, 316 ) -> Result { 317 let mut blob_hashes = Vec::new(); 318 319 if let Some(metric_bytes) = raw_metrics { 320 let digest = self.blob_store.put_blob(metric_bytes)?; 321 let conn = self.conn.lock().map_err(|e| e.to_string())?; 322 let now = chrono::Utc::now().to_rfc3339(); 323 let _ = conn.execute( 324 "INSERT OR IGNORE INTO blobs_index (digest, size_bytes, created_at) VALUES (?1, ?2, ?3)", 325 params![digest, metric_bytes.len() as i64, now], 326 ); 327 blob_hashes.push(digest); 328 } 329 330 let payload_json = serde_json::to_string(receipt) 331 .map_err(|e| format!("Failed to serialize EvaluationReceipt: {}", e))?; 332 333 self.append_block(BlockType::Evaluation, payload_json, blob_hashes) 334 } 335 336 pub fn append_promotion( 337 &self, 338 gen_info: &GenerationInfo, 339 receipt_digest: &str, 340 ) -> Result { 341 let payload = serde_json::json!({ 342 "generation_id": gen_info.generation_id, 343 "installed_path": gen_info.installed_path.to_string_lossy(), 344 "receipt_digest": receipt_digest, 345 "state": format!("{:?}", gen_info.state), 346 "staged_timestamp": gen_info.staged_timestamp, 347 }) 348 .to_string(); 349 350 self.append_block(BlockType::Promotion, payload, Vec::new()) 351 } 352 353 pub fn append_rollback( 354 &self, 355 generation_id: &str, 356 reason: &str, 357 ) -> Result { 358 let payload = serde_json::json!({ 359 "generation_id": generation_id, 360 "reason": reason, 361 "rolled_back_at": chrono::Utc::now().to_rfc3339(), 362 }) 363 .to_string(); 364 365 self.append_block(BlockType::Rollback, payload, Vec::new()) 366 } 367 368 pub fn append_promotion_evidence( 369 &self, 370 evidence: &PromotionEvidencePayload, 371 ) -> Result { 372 let payload_json = serde_json::to_string(evidence) 373 .map_err(|e| format!("Failed to serialize PromotionEvidencePayload: {}", e))?; 374 375 self.append_block(BlockType::PromotionEvidence, payload_json, Vec::new()) 376 } 377 378 /// Signs and stores a Merkle checkpoint over every block hash. Reads only sequences and 379 /// hashes; payload and blob verification stays with `verify_chain_integrity`. 380 pub fn checkpoint(&self, signing_key: Option<&SigningKey>) -> Result { 381 // One lock for the read and the insert: no append through this handle lands between them. 382 let conn = self.conn.lock().map_err(|e| e.to_string())?; 383 let (leaf_hashes, last_sequence) = Self::leaf_hashes(&conn)?; 384 let Some(up_to_sequence) = last_sequence else { 385 return Err("Cannot create checkpoint on empty ledger".to_string()); 386 }; 387 let merkle_root = compute_merkle_root(&leaf_hashes); 388 let block_count = leaf_hashes.len() as u64; 389 390 let mut checkpoint = MerkleCheckpoint::new(up_to_sequence, merkle_root, block_count); 391 392 if let Some(key) = signing_key { 393 checkpoint.sign(key); 394 } 395 396 conn.execute( 397 "INSERT OR REPLACE INTO checkpoints ( 398 up_to_sequence, merkle_root, block_count, timestamp_utc, signature 399 ) VALUES (?1, ?2, ?3, ?4, ?5)", 400 params![ 401 checkpoint.up_to_sequence as i64, 402 checkpoint.merkle_root, 403 checkpoint.block_count as i64, 404 checkpoint.timestamp_utc, 405 checkpoint.signature, 406 ], 407 ) 408 .map_err(|e| format!("Failed to store Merkle checkpoint: {}", e))?; 409 410 Ok(checkpoint) 411 } 412 413 pub fn latest_checkpoint(&self) -> Result, String> { 414 let conn = self.conn.lock().map_err(|e| e.to_string())?; 415 let mut stmt = conn 416 .prepare( 417 "SELECT up_to_sequence, merkle_root, block_count, timestamp_utc, signature 418 FROM checkpoints ORDER BY up_to_sequence DESC LIMIT 1", 419 ) 420 .map_err(|e| e.to_string())?; 421 422 let mut rows = stmt.query([]).map_err(|e| e.to_string())?; 423 if let Some(row) = rows.next().map_err(|e| e.to_string())? { 424 let seq: i64 = row.get(0).map_err(|e| e.to_string())?; 425 let root: String = row.get(1).map_err(|e| e.to_string())?; 426 let count: i64 = row.get(2).map_err(|e| e.to_string())?; 427 let ts: String = row.get(3).map_err(|e| e.to_string())?; 428 let sig: Option = row.get(4).map_err(|e| e.to_string())?; 429 430 Ok(Some(MerkleCheckpoint { 431 up_to_sequence: seq as u64, 432 merkle_root: root, 433 block_count: count as u64, 434 timestamp_utc: ts, 435 signature: sig, 436 })) 437 } else { 438 Ok(None) 439 } 440 } 441 442 pub fn blob_store(&self) -> &BlobStore { 443 &self.blob_store 444 } 445 446 pub fn verify_chain_integrity( 447 &self, 448 verifying_key: Option<&VerifyingKey>, 449 ) -> Result { 450 let blocks = self.all_blocks()?; 451 if blocks.is_empty() { 452 return Err("Audit failed: ledger is empty (no Genesis block)".to_string()); 453 } 454 455 let mut total_blobs = 0; 456 let mut leaf_hashes = Vec::new(); 457 458 // 1. Validate Genesis block invariants 459 let genesis = &blocks[0]; 460 if genesis.sequence != 0 { 461 return Err(format!( 462 "Audit failed: Genesis block sequence is {}, expected 0", 463 genesis.sequence 464 )); 465 } 466 if genesis.block_type != BlockType::Genesis { 467 return Err(format!( 468 "Audit failed: Genesis block type is {:?}, expected GENESIS", 469 genesis.block_type 470 )); 471 } 472 if genesis.prev_block_hash != LedgerBlock::GENESIS_PREV_HASH { 473 return Err(format!( 474 "Audit failed: Genesis block prev_block_hash is {}, expected {}", 475 genesis.prev_block_hash, 476 LedgerBlock::GENESIS_PREV_HASH 477 )); 478 } 479 genesis.verify_integrity()?; 480 leaf_hashes.push(genesis.block_hash.clone()); 481 482 // 2. Iterate through block chain validating strict sequence and hash links 483 for i in 1..blocks.len() { 484 let block = &blocks[i]; 485 let prev_block = &blocks[i - 1]; 486 487 if block.sequence != i as u64 { 488 return Err(format!( 489 "Audit failed: Block sequence gap at index {}: sequence is {}", 490 i, block.sequence 491 )); 492 } 493 494 if block.prev_block_hash != prev_block.block_hash { 495 return Err(format!( 496 "Audit failed: Hash chain broken at sequence {}. Stored prev_hash={}, predecessor hash={}", 497 block.sequence, block.prev_block_hash, prev_block.block_hash 498 )); 499 } 500 501 // Verify payload digest and block hash 502 block.verify_integrity()?; 503 504 // Verify all referenced blobs exist and are uncorrupted 505 for bh in &block.blob_hashes { 506 total_blobs += 1; 507 if !self.blob_store.verify_blob(bh) { 508 return Err(format!( 509 "Audit failed: Content-addressed blob {} missing or corrupted at block sequence {}", 510 bh, block.sequence 511 )); 512 } 513 } 514 515 leaf_hashes.push(block.block_hash.clone()); 516 } 517 518 // 3. Compute the Merkle root, then verify the latest checkpoint against the blocks it 519 // covers, wherever it sits. Sequences equal indexes, checked above. 520 let computed_merkle_root = compute_merkle_root(&leaf_hashes); 521 let latest_sequence = blocks.last().unwrap().sequence; 522 let mut checkpoint_verified = false; 523 let mut signature_verified = false; 524 let mut checkpoint_sequence = None; 525 let mut blocks_after_checkpoint = blocks.len() as u64; 526 527 if let Some(checkpoint) = self.latest_checkpoint()? { 528 if checkpoint.up_to_sequence > latest_sequence { 529 return Err(format!( 530 "Audit failed: Checkpoint covers sequence {} but the ledger ends at {}", 531 checkpoint.up_to_sequence, latest_sequence 532 )); 533 } 534 let covered = &leaf_hashes[..=checkpoint.up_to_sequence as usize]; 535 if checkpoint.block_count != covered.len() as u64 { 536 return Err(format!( 537 "Audit failed: Checkpoint block count mismatch: stored={}, covered={}", 538 checkpoint.block_count, 539 covered.len() 540 )); 541 } 542 let covered_root = compute_merkle_root(covered); 543 if checkpoint.merkle_root != covered_root { 544 return Err(format!( 545 "Audit failed: Checkpoint Merkle root mismatch: stored={}, computed={}", 546 checkpoint.merkle_root, covered_root 547 )); 548 } 549 checkpoint_verified = true; 550 checkpoint_sequence = Some(checkpoint.up_to_sequence); 551 blocks_after_checkpoint = latest_sequence - checkpoint.up_to_sequence; 552 553 if let Some(vk) = verifying_key { 554 if checkpoint.verify_signature(vk) { 555 signature_verified = true; 556 } else { 557 return Err( 558 "Audit failed: Checkpoint Merkle root signature verification failed" 559 .to_string(), 560 ); 561 } 562 } 563 } 564 565 let latest = blocks.last().unwrap(); 566 Ok(LedgerAuditReport { 567 total_blocks: blocks.len() as u64, 568 total_blobs, 569 latest_sequence: latest.sequence, 570 latest_block_hash: latest.block_hash.clone(), 571 merkle_root: computed_merkle_root, 572 checkpoint_verified, 573 signature_verified, 574 chain_valid: true, 575 audit_timestamp_utc: chrono::Utc::now().to_rfc3339(), 576 checkpoint_sequence, 577 blocks_after_checkpoint, 578 }) 579 } 580 }