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/merkle.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 / merkle.rs` 83 lines ยท 2603 bytes Raw Blame History 1 use p256::ecdsa::signature::{Signer, Verifier}; 2 use p256::ecdsa::{Signature, SigningKey, VerifyingKey}; 3 use serde::{Deserialize, Serialize}; 4 use sha2::{Digest, Sha256}; 5 6 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] 7 pub struct MerkleCheckpoint { 8 pub up_to_sequence: u64, 9 pub merkle_root: String, 10 pub block_count: u64, 11 pub timestamp_utc: String, 12 pub signature: Option, 13 } 14 15 impl MerkleCheckpoint { 16 pub fn new(up_to_sequence: u64, merkle_root: String, block_count: u64) -> Self { 17 Self { 18 up_to_sequence, 19 merkle_root, 20 block_count, 21 timestamp_utc: chrono::Utc::now().to_rfc3339(), 22 signature: None, 23 } 24 } 25 26 pub fn sign(&mut self, signing_key: &SigningKey) { 27 let sig: Signature = signing_key.sign(self.merkle_root.as_bytes()); 28 self.signature = Some(format!("p256:{}", hex::encode(sig.to_bytes()))); 29 } 30 31 pub fn verify_signature(&self, verifying_key: &VerifyingKey) -> bool { 32 if let Some(ref sig_str) = self.signature { 33 if let Some(hex_str) = sig_str.strip_prefix("p256:") { 34 if let Ok(sig_bytes) = hex::decode(hex_str) { 35 if let Ok(sig) = Signature::from_slice(&sig_bytes) { 36 return verifying_key 37 .verify(self.merkle_root.as_bytes(), &sig) 38 .is_ok(); 39 } 40 } 41 } 42 } 43 false 44 } 45 } 46 47 pub fn compute_merkle_root(leaf_hashes: &[String]) -> String { 48 if leaf_hashes.is_empty() { 49 return "`0000000000000000000000000000000000000000000000000000000000000000`".to_string(); 50 } 51 if leaf_hashes.len() == 1 { 52 return leaf_hashes[0].clone(); 53 } 54 55 let mut current_level: Vec = leaf_hashes.to_vec(); 56 57 while current_level.len() > 1 { 58 let mut next_level = Vec::new(); 59 let len = current_level.len(); 60 let mut i = 0; 61 62 while i < len { 63 let left = ¤t_level[i]; 64 let right = if i + 1 < len { 65 ¤t_level[i + 1] 66 } else { 67 // Odd leaf: duplicate right child as per standard Merkle tree specification 68 ¤t_level[i] 69 }; 70 71 let mut hasher = Sha256::new(); 72 hasher.update(left.as_bytes()); 73 hasher.update(right.as_bytes()); 74 next_level.push(format!("{:x}", hasher.finalize())); 75 76 i += 2; 77 } 78 79 current_level = next_level; 80 } 81 82 current_level[0].clone() 83 }