crumb-spec
Crumb Protocol specification and filesystem standard for sovereign AI agents
Brought by drakestapleton
crumb-spec / src / ledger.rs
| 1 | //! The Cryptographic Crumb Ledger. |
| 2 | //! |
| 3 | //! Provides hash-chained, chronological action vector verification |
| 4 | //! for multi-agent stigmergic coordination and immutable repository history. |
| 5 | |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | use thiserror::Error; |
| 8 | |
| 9 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 10 | #[serde(rename_all = "lowercase")] |
| 11 | pub enum CrumbAction { |
| 12 | Create, |
| 13 | Modify, |
| 14 | Delete, |
| 15 | Audit, |
| 16 | Test, |
| 17 | Build, |
| 18 | Custom(String), |
| 19 | } |
| 20 | |
| 21 | impl CrumbAction { |
| 22 | pub fn as_str(&self) -> &str { |
| 23 | match self { |
| 24 | Self::Create => "create", |
| 25 | Self::Modify => "modify", |
| 26 | Self::Delete => "delete", |
| 27 | Self::Audit => "audit", |
| 28 | Self::Test => "test", |
| 29 | Self::Build => "build", |
| 30 | Self::Custom(s) => s.as_str(), |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | #[derive(Error, Debug, PartialEq, Eq, Clone)] |
| 36 | pub enum LedgerError { |
| 37 | #[error("Hash mismatch at index {index}: computed {computed:?}, recorded {recorded:?}")] |
| 38 | HashMismatch { |
| 39 | index: u64, |
| 40 | computed: [u8; 32], |
| 41 | recorded: [u8; 32], |
| 42 | }, |
| 43 | #[error("Parent hash mismatch at index {index}: expected {expected:?}, found {found:?}")] |
| 44 | ParentHashMismatch { |
| 45 | index: u64, |
| 46 | expected: [u8; 32], |
| 47 | found: [u8; 32], |
| 48 | }, |
| 49 | #[error("Chronological sequencing violation at index {index}: previous timestamp {previous} > current timestamp {current}")] |
| 50 | ChronologicalViolation { |
| 51 | index: u64, |
| 52 | previous: u64, |
| 53 | current: u64, |
| 54 | }, |
| 55 | #[error("Invalid index sequence at {index}: expected {expected}")] |
| 56 | InvalidIndex { |
| 57 | index: u64, |
| 58 | expected: u64, |
| 59 | }, |
| 60 | #[error("Missing parent event for event at index {0}")] |
| 61 | MissingParent(u64), |
| 62 | #[error("Genesis parent hash must be all zeros, got {0:?}")] |
| 63 | InvalidGenesisParent([u8; 32]), |
| 64 | #[error("Serialization error: {0}")] |
| 65 | Serialization(String), |
| 66 | #[error("Deserialization error: {0}")] |
| 67 | Deserialization(String), |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 71 | pub struct LedgerEvent { |
| 72 | pub index: u64, |
| 73 | pub timestamp: u64, |
| 74 | pub agent: String, |
| 75 | pub action: CrumbAction, |
| 76 | pub target: String, |
| 77 | pub intent: String, |
| 78 | pub payload_hash: [u8; 32], |
| 79 | pub parent_hash: [u8; 32], |
| 80 | pub hash: [u8; 32], |
| 81 | } |
| 82 | |
| 83 | impl LedgerEvent { |
| 84 | pub fn compute_hash( |
| 85 | index: u64, |
| 86 | timestamp: u64, |
| 87 | agent: &str, |
| 88 | action: &CrumbAction, |
| 89 | target: &str, |
| 90 | intent: &str, |
| 91 | payload_hash: &[u8; 32], |
| 92 | parent_hash: &[u8; 32], |
| 93 | ) -> [u8; 32] { |
| 94 | let mut hasher = blake3::Hasher::new(); |
| 95 | hasher.update(b"CRUMB_LEDGER_EVENT_V1"); |
| 96 | hasher.update(&index.to_be_bytes()); |
| 97 | hasher.update(×tamp.to_be_bytes()); |
| 98 | hasher.update(&(agent.len() as u32).to_be_bytes()); |
| 99 | hasher.update(agent.as_bytes()); |
| 100 | let action_str = action.as_str(); |
| 101 | hasher.update(&(action_str.len() as u32).to_be_bytes()); |
| 102 | hasher.update(action_str.as_bytes()); |
| 103 | hasher.update(&(target.len() as u32).to_be_bytes()); |
| 104 | hasher.update(target.as_bytes()); |
| 105 | hasher.update(&(intent.len() as u32).to_be_bytes()); |
| 106 | hasher.update(intent.as_bytes()); |
| 107 | hasher.update(payload_hash); |
| 108 | hasher.update(parent_hash); |
| 109 | *hasher.finalize().as_bytes() |
| 110 | } |
| 111 | |
| 112 | pub fn new( |
| 113 | index: u64, |
| 114 | timestamp: u64, |
| 115 | agent: String, |
| 116 | action: CrumbAction, |
| 117 | target: String, |
| 118 | intent: String, |
| 119 | payload: &[u8], |
| 120 | parent_hash: [u8; 32], |
| 121 | ) -> Self { |
| 122 | let payload_hash = *blake3::hash(payload).as_bytes(); |
| 123 | let hash = Self::compute_hash( |
| 124 | index, |
| 125 | timestamp, |
| 126 | &agent, |
| 127 | &action, |
| 128 | &target, |
| 129 | &intent, |
| 130 | &payload_hash, |
| 131 | &parent_hash, |
| 132 | ); |
| 133 | |
| 134 | Self { |
| 135 | index, |
| 136 | timestamp, |
| 137 | agent, |
| 138 | action, |
| 139 | target, |
| 140 | intent, |
| 141 | payload_hash, |
| 142 | parent_hash, |
| 143 | hash, |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | pub fn verify_hash(&self) -> Result<(), LedgerError> { |
| 148 | let computed = Self::compute_hash( |
| 149 | self.index, |
| 150 | self.timestamp, |
| 151 | &self.agent, |
| 152 | &self.action, |
| 153 | &self.target, |
| 154 | &self.intent, |
| 155 | &self.payload_hash, |
| 156 | &self.parent_hash, |
| 157 | ); |
| 158 | |
| 159 | if computed != self.hash { |
| 160 | return Err(LedgerError::HashMismatch { |
| 161 | index: self.index, |
| 162 | computed, |
| 163 | recorded: self.hash, |
| 164 | }); |
| 165 | } |
| 166 | |
| 167 | Ok(()) |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 172 | pub struct CrumbLedger { |
| 173 | pub events: Vec<LedgerEvent>, |
| 174 | } |
| 175 | |
| 176 | impl CrumbLedger { |
| 177 | pub fn new() -> Self { |
| 178 | Self { events: Vec::new() } |
| 179 | } |
| 180 | |
| 181 | pub fn len(&self) -> usize { |
| 182 | self.events.len() |
| 183 | } |
| 184 | |
| 185 | pub fn is_empty(&self) -> bool { |
| 186 | self.events.is_empty() |
| 187 | } |
| 188 | |
| 189 | pub fn last_event(&self) -> Option<&LedgerEvent> { |
| 190 | self.events.last() |
| 191 | } |
| 192 | |
| 193 | pub fn head_hash(&self) -> [u8; 32] { |
| 194 | self.events |
| 195 | .last() |
| 196 | .map(|e| e.hash) |
| 197 | .unwrap_or([0u8; 32]) |
| 198 | } |
| 199 | |
| 200 | pub fn append( |
| 201 | &mut self, |
| 202 | agent: String, |
| 203 | action: CrumbAction, |
| 204 | target: String, |
| 205 | intent: String, |
| 206 | payload: &[u8], |
| 207 | timestamp: u64, |
| 208 | ) -> Result<&LedgerEvent, LedgerError> { |
| 209 | let index = self.events.len() as u64; |
| 210 | let parent_hash = if let Some(last) = self.events.last() { |
| 211 | if timestamp < last.timestamp { |
| 212 | return Err(LedgerError::ChronologicalViolation { |
| 213 | index, |
| 214 | previous: last.timestamp, |
| 215 | current: timestamp, |
| 216 | }); |
| 217 | } |
| 218 | last.hash |
| 219 | } else { |
| 220 | [0u8; 32] |
| 221 | }; |
| 222 | |
| 223 | let event = LedgerEvent::new( |
| 224 | index, |
| 225 | timestamp, |
| 226 | agent, |
| 227 | action, |
| 228 | target, |
| 229 | intent, |
| 230 | payload, |
| 231 | parent_hash, |
| 232 | ); |
| 233 | |
| 234 | self.events.push(event); |
| 235 | Ok(self.events.last().expect("event just pushed")) |
| 236 | } |
| 237 | |
| 238 | pub fn verify_chain(&self) -> Result<(), LedgerError> { |
| 239 | for (i, event) in self.events.iter().enumerate() { |
| 240 | if event.index != i as u64 { |
| 241 | return Err(LedgerError::InvalidIndex { |
| 242 | index: event.index, |
| 243 | expected: i as u64, |
| 244 | }); |
| 245 | } |
| 246 | |
| 247 | event.verify_hash()?; |
| 248 | |
| 249 | if i == 0 { |
| 250 | if event.parent_hash != [0u8; 32] { |
| 251 | return Err(LedgerError::InvalidGenesisParent(event.parent_hash)); |
| 252 | } |
| 253 | } else { |
| 254 | let prev = &self.events[i - 1]; |
| 255 | if event.parent_hash != prev.hash { |
| 256 | return Err(LedgerError::ParentHashMismatch { |
| 257 | index: event.index, |
| 258 | expected: prev.hash, |
| 259 | found: event.parent_hash, |
| 260 | }); |
| 261 | } |
| 262 | if event.timestamp < prev.timestamp { |
| 263 | return Err(LedgerError::ChronologicalViolation { |
| 264 | index: event.index, |
| 265 | previous: prev.timestamp, |
| 266 | current: event.timestamp, |
| 267 | }); |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | Ok(()) |
| 273 | } |
| 274 | |
| 275 | pub fn verify_parent(&self, event: &LedgerEvent) -> Result<(), LedgerError> { |
| 276 | if event.index == 0 { |
| 277 | if event.parent_hash != [0u8; 32] { |
| 278 | return Err(LedgerError::InvalidGenesisParent(event.parent_hash)); |
| 279 | } |
| 280 | return Ok(()); |
| 281 | } |
| 282 | |
| 283 | let parent_idx = (event.index - 1) as usize; |
| 284 | if parent_idx >= self.events.len() { |
| 285 | return Err(LedgerError::MissingParent(event.index)); |
| 286 | } |
| 287 | |
| 288 | let expected_parent = &self.events[parent_idx]; |
| 289 | if event.parent_hash != expected_parent.hash { |
| 290 | return Err(LedgerError::ParentHashMismatch { |
| 291 | index: event.index, |
| 292 | expected: expected_parent.hash, |
| 293 | found: event.parent_hash, |
| 294 | }); |
| 295 | } |
| 296 | |
| 297 | Ok(()) |
| 298 | } |
| 299 | |
| 300 | pub fn to_json(&self) -> Result<String, LedgerError> { |
| 301 | serde_json::to_string_pretty(self) |
| 302 | .map_err(|e| LedgerError::Serialization(e.to_string())) |
| 303 | } |
| 304 | |
| 305 | pub fn from_json(json_str: &str) -> Result<Self, LedgerError> { |
| 306 | serde_json::from_str(json_str) |
| 307 | .map_err(|e| LedgerError::Deserialization(e.to_string())) |
| 308 | } |
| 309 | |
| 310 | pub fn to_binary(&self) -> Result<Vec<u8>, LedgerError> { |
| 311 | bincode::serialize(self) |
| 312 | .map_err(|e| LedgerError::Serialization(e.to_string())) |
| 313 | } |
| 314 | |
| 315 | pub fn from_binary(bytes: &[u8]) -> Result<Self, LedgerError> { |
| 316 | bincode::deserialize(bytes) |
| 317 | .map_err(|e| LedgerError::Deserialization(e.to_string())) |
| 318 | } |
| 319 | } |