history.rs (17493B)
1 //! Complete protected local scoped causal coverage. This read supplies no 2 //! request permission, current-offer permission, installed order or stock hold. 3 use super::*; 4 use radroots_domain::{ 5 SourceId, UnixSeconds, 6 causal::{self, CausalAnalysis, CausalRecord, CausalScope}, 7 }; 8 use radroots_protocol::{commerce::DecodedRecord, private_rumor::DecodedRumor}; 9 use radroots_storage::workspace::seller_stock::StockListingCheckpointRef; 10 use sqlx::Row; 11 use std::collections::{BTreeMap, BTreeSet}; 12 13 /// Checked retained local causal coverage at independently acknowledged private 14 /// and public checkpoints. This grants no request, agreement or stock authority. 15 pub struct StockHistorySnapshot { 16 pub(super) scope: CausalScope, 17 pub(super) analysis: CausalAnalysis, 18 pub(super) sources: StockSourceCheckpointRef, 19 pub(super) listings: StockListingCheckpointRef, 20 pub(super) observed_at: UnixSeconds, 21 pub(super) records: usize, 22 pub(super) inventory: radroots_storage::inventory::InventoryCheckpointRef, 23 pub(super) checkpoint: Option<radroots_domain::CheckpointRef>, 24 } 25 impl StockHistorySnapshot { 26 /// Independently acknowledged inventory history containing local issued records. 27 pub const fn inventory_checkpoint( 28 &self, 29 ) -> radroots_storage::inventory::InventoryCheckpointRef { 30 self.inventory 31 } 32 /// Borrows complete local causal coverage data. This is not an installed 33 /// order, pending-decision fence or permission to accept the request. 34 pub fn checkpoint(&self) -> Option<&radroots_domain::CheckpointRef> { 35 self.checkpoint.as_ref() 36 } 37 /// Returns the exact selected participant/thread/order scope. 38 pub const fn scope(&self) -> CausalScope { 39 self.scope 40 } 41 /// Borrows the deterministic local graph classification and exact gaps. 42 pub const fn analysis(&self) -> &CausalAnalysis { 43 &self.analysis 44 } 45 /// Returns all private-source progress included in this checked snapshot. 46 pub const fn source_checkpoint(&self) -> StockSourceCheckpointRef { 47 self.sources 48 } 49 /// Returns public-source progress checked for original source existence. 50 /// This is not current-head or offer actionability permission. 51 pub const fn listing_checkpoint(&self) -> StockListingCheckpointRef { 52 self.listings 53 } 54 /// Returns the usable clock observation of the final transaction access check. 55 pub const fn observed_at(&self) -> UnixSeconds { 56 self.observed_at 57 } 58 /// Returns unique known records in the selected order and null quote scopes. 59 pub const fn known_records(&self) -> usize { 60 self.records 61 } 62 } 63 impl std::fmt::Debug for StockHistorySnapshot { 64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 65 f.write_str("StockHistorySnapshot(<private coverage>)") 66 } 67 } 68 /// Current verified access plus caller checkpoint data; not fresh authority. 69 pub(in crate::workspace::stock) struct InventoryRead<'a> { 70 pub binding: &'a WorkspaceBinding, 71 pub authority: &'a Authority, 72 pub minimum: radroots_storage::inventory::InventoryCheckpointRef, 73 } 74 pub(in crate::workspace::stock) struct Prepared { 75 pub records: BTreeMap<RecordId, DecodedRecord>, 76 pub inventory: radroots_storage::inventory::InventoryCheckpointRef, 77 inventory_proof: super::super::inventory::checkpoint::MinimumProof, 78 inventory_state: super::super::InventoryCheckpoint, 79 pub analysis: CausalAnalysis, 80 pub checkpoint: Option<radroots_domain::CheckpointRef>, 81 pub external: Vec<SourceId>, 82 pub uninterpreted: Vec<SourceId>, 83 ancestry: checkpoint::Proof, 84 public: super::super::public_source::history::Witness, 85 revision: u64, 86 known: [u8; 32], 87 unknown: [u8; 32], 88 } 89 fn hash(label: &[u8]) -> Sha256 { 90 let mut value = Sha256::new(); 91 value.update(label); 92 value 93 } 94 fn known_hash() -> Sha256 { 95 hash(b"radroots.seller_stock.causal_known_snapshot.v1\0") 96 } 97 fn unknown_hash() -> Sha256 { 98 hash(b"radroots.seller_stock.causal_unknown_snapshot.v1\0") 99 } 100 fn known_row(hash: &mut Sha256, revision: u64, id: RecordId, protected: &[u8]) { 101 hash.update(revision.to_be_bytes()); 102 hash.update(id.as_bytes()); 103 hash.update((protected.len() as u64).to_be_bytes()); 104 hash.update(protected); 105 } 106 fn unknown_row( 107 hash: &mut Sha256, 108 revision: u64, 109 envelope: EnvelopeEventId, 110 part: u8, 111 protected: &[u8], 112 ) { 113 hash.update(revision.to_be_bytes()); 114 hash.update(envelope.as_bytes()); 115 hash.update([part]); 116 hash.update((protected.len() as u64).to_be_bytes()); 117 hash.update(protected); 118 } 119 async fn header_at( 120 connection: &mut SqliteConnection, 121 input: &AttachmentInput, 122 crypto: &WorkspaceCrypto, 123 revision: u64, 124 ) -> Result<record::RetainedHeader, OperationError> { 125 let id: Vec<u8> = sqlx::query_scalar( 126 "SELECT envelope_id FROM stock_source_evidence WHERE revision=? AND length(envelope_id)=32", 127 ) 128 .bind(revision as i64) 129 .fetch_optional(&mut *connection) 130 .await 131 .map_err(|_| OperationError::RecoveryRequired)? 132 .ok_or(OperationError::RecoveryRequired)?; 133 let envelope = EnvelopeEventId::from_bytes( 134 id.try_into() 135 .map_err(|_| OperationError::RecoveryRequired)?, 136 ); 137 let header = record::read(connection, input, crypto, envelope) 138 .await? 139 .ok_or(OperationError::RecoveryRequired)?; 140 if header.header.revision.get() != revision { 141 return Err(OperationError::RecoveryRequired); 142 } 143 Ok(header) 144 } 145 async fn rumor_part( 146 connection: &mut SqliteConnection, 147 envelope: EnvelopeEventId, 148 part: u8, 149 ) -> Result<Option<Vec<u8>>, OperationError> { 150 sqlx::query_scalar::<_,Option<Vec<u8>>>("SELECT CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_source_parts WHERE envelope_id=? AND role=2 AND part=?") 151 .bind(envelope.as_bytes().as_slice()).bind(i64::from(part)).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)? 152 .map(|value|value.ok_or(OperationError::RecoveryRequired)).transpose() 153 } 154 async fn original_rumor( 155 connection: &mut SqliteConnection, 156 input: &AttachmentInput, 157 crypto: &WorkspaceCrypto, 158 header: &record::Header, 159 hash: &mut Sha256, 160 ) -> Result<DecodedRumor, OperationError> { 161 let envelope = header.manifest.envelope; 162 let piece = header.manifest.pieces[2]; 163 let mut raw = Zeroizing::new(Vec::new()); 164 for part in 0..piece.parts { 165 let protected = rumor_part(connection, envelope, part) 166 .await? 167 .ok_or(OperationError::RecoveryRequired)?; 168 unknown_row(hash, header.revision.get(), envelope, part, &protected); 169 let clear = crypto 170 .open_stock_record( 171 input, 172 "source_part", 173 &record::part_id(envelope, 2, part), 174 &protected, 175 ) 176 .await?; 177 clear.expose_secret(|bytes| { 178 let length = if part + 1 == piece.parts { 179 piece.bytes as usize - (usize::from(piece.parts) - 1) * 16 * 1024 180 } else { 181 16 * 1024 182 }; 183 if bytes.len() != length { 184 return Err(OperationError::RecoveryRequired); 185 } 186 raw.extend_from_slice(bytes); 187 Ok(()) 188 })?; 189 } 190 let count: i64 = sqlx::query_scalar( 191 "SELECT count(*) FROM stock_source_parts WHERE envelope_id=? AND role=2", 192 ) 193 .bind(envelope.as_bytes().as_slice()) 194 .fetch_one(connection) 195 .await 196 .map_err(|_| OperationError::RecoveryRequired)?; 197 if count != i64::from(piece.parts) 198 || raw.len() != piece.bytes as usize 199 || <[u8; 32]>::from(Sha256::digest(&*raw)) != piece.digest 200 { 201 return Err(OperationError::RecoveryRequired); 202 } 203 let rumor = DecodedRumor::decode(&raw).map_err(|_| OperationError::RecoveryRequired)?; 204 if rumor.event_id() != header.manifest.rumor { 205 return Err(OperationError::RecoveryRequired); 206 } 207 Ok(rumor) 208 } 209 pub(in crate::workspace::stock) async fn prepare( 210 connection: &mut SqliteConnection, 211 input: &AttachmentInput, 212 crypto: &WorkspaceCrypto, 213 inventory_read: InventoryRead<'_>, 214 scope: CausalScope, 215 listing_minimum: StockListingCheckpointRef, 216 ) -> Result<Prepared, OperationError> { 217 let authority = inventory_read.authority; 218 if inventory_read.minimum.authorization() != authority.authorization { 219 return Err(WorkspaceError::StaleCheckpoint.into()); 220 } 221 if scope.seller() != input.participant() { 222 return Err(OperationError::Unauthorized); 223 } 224 let progress = authority 225 .sources 226 .ok_or(OperationError::UnsupportedOperation)?; 227 let revision = progress.revision.get(); 228 let genesis = StockSourceCheckpointRef::from_host_metadata( 229 input.authority(), 230 Sequence::new(0).map_err(|_| OperationError::RecoveryRequired)?, 231 None, 232 )?; 233 let ancestry = checkpoint::authenticate( 234 connection, 235 input, 236 crypto, 237 progress, 238 checkpoint::Target::Minimum(genesis), 239 ) 240 .await?; 241 let mut records = BTreeMap::new(); 242 let mut known = known_hash(); 243 for revision in 1..=revision { 244 let retained = header_at(connection, input, crypto, revision).await?; 245 if let Some(id) = retained.header.manifest.record { 246 let (raw, protected) = record::canonical(connection, input, crypto, id) 247 .await? 248 .ok_or(OperationError::RecoveryRequired)?; 249 if Some(<[u8; 32]>::from(Sha256::digest(&*raw))) 250 != retained.header.manifest.canonical_digest 251 { 252 return Err(OperationError::RecoveryRequired); 253 } 254 known_row(&mut known, revision, id, &protected); 255 let decoded = radroots_protocol::commerce::decode(&raw) 256 .map_err(|_| OperationError::RecoveryRequired)?; 257 if scope.contains(decoded.content()) { 258 records.insert(id, decoded); 259 if records.len() > causal::MAX_CAUSAL_RECORDS { 260 return Err(WorkspaceError::Capacity.into()); 261 } 262 } 263 } 264 } 265 let inventory_state = authority 266 .inventory 267 .ok_or(OperationError::UnsupportedOperation)?; 268 super::super::inventory::check_head(connection, inventory_state).await?; 269 let inventory_proof = Box::pin( 270 super::super::inventory::checkpoint::authenticate_minimum_with_local( 271 connection, 272 input, 273 crypto, 274 inventory_read.binding, 275 authority, 276 inventory_read.minimum, 277 Some(super::super::inventory::checkpoint::LocalSources { 278 scope, 279 records: &mut records, 280 }), 281 ), 282 ) 283 .await?; 284 let inventory = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( 285 input.authority(), 286 inventory_state.revision, 287 inventory_state.head, 288 )? 289 .with_authorization( 290 authority 291 .authorization 292 .ok_or(OperationError::RecoveryRequired)?, 293 ); 294 let mut wanted: BTreeSet<_> = records 295 .values() 296 .flat_map(|record| record.content().header().parents().iter().copied()) 297 .collect(); 298 for id in records.keys() { 299 wanted.remove(&SourceId::from_bytes(id.into_bytes())); 300 } 301 let mut external = BTreeSet::new(); 302 let mut uninterpreted = BTreeSet::new(); 303 let mut unknown = unknown_hash(); 304 for revision in 1..=revision { 305 let retained = header_at(connection, input, crypto, revision).await?; 306 if let Some(id) = retained.header.manifest.record { 307 if wanted.contains(&SourceId::from_bytes(id.into_bytes())) { 308 return Err(OperationError::InvalidEvidence); 309 } 310 continue; 311 } 312 let rumor = 313 original_rumor(connection, input, crypto, &retained.header, &mut unknown).await?; 314 if rumor.author() != scope.buyer() && rumor.author() != scope.seller() { 315 continue; 316 } 317 let source = SourceId::from_bytes(rumor.event_id().into_bytes()); 318 if rumor.kind() == radroots_protocol::profile::COMMERCE_KIND { 319 // Unknown content cannot supply trustworthy thread/order semantics. 320 // Conservatively block this participant pair rather than assuming 321 // it is unrelated and resurrecting an older actionable record. 322 uninterpreted.insert(source); 323 if uninterpreted.len() > causal::MAX_CAUSAL_SOURCES { 324 return Err(WorkspaceError::Capacity.into()); 325 } 326 } else if rumor.kind() == 14 && wanted.contains(&source) { 327 external.insert(source); 328 } 329 } 330 for source in &external { 331 wanted.remove(source); 332 } 333 let public = super::super::public_source::history::prepare( 334 connection, 335 input, 336 crypto, 337 authority, 338 listing_minimum, 339 &wanted, 340 ) 341 .await?; 342 external.extend(public.present()); 343 let nodes: Vec<_> = records 344 .iter() 345 .map(|(id, record)| CausalRecord::new(*id, record.content())) 346 .collect(); 347 let external: Vec<_> = external.into_iter().collect(); 348 let uninterpreted: Vec<_> = uninterpreted.into_iter().collect(); 349 let coverage = radroots_protocol::commerce::CapturedCausalCoverage::capture( 350 scope, 351 &nodes, 352 &external, 353 &uninterpreted, 354 ) 355 .map_err(|error| match error { 356 radroots_protocol::commerce::RecordWireError::LimitExceeded => { 357 OperationError::Workspace(WorkspaceError::Capacity) 358 } 359 radroots_protocol::commerce::RecordWireError::InvalidInput => { 360 OperationError::InvalidEvidence 361 } 362 _ => OperationError::RecoveryRequired, 363 })?; 364 let (analysis, checkpoint) = coverage.into_parts(); 365 Ok(Prepared { 366 inventory, 367 inventory_state, 368 inventory_proof, 369 records, 370 analysis, 371 checkpoint, 372 external, 373 uninterpreted, 374 ancestry, 375 public, 376 revision, 377 known: known.finalize().into(), 378 unknown: unknown.finalize().into(), 379 }) 380 } 381 impl Prepared { 382 pub(in crate::workspace::stock) async fn confirm( 383 &self, 384 connection: &mut SqliteConnection, 385 ) -> Result<(), OperationError> { 386 self.ancestry.confirm(connection).await?; 387 super::super::inventory::check_head(connection, self.inventory_state).await?; 388 self.inventory_proof.confirm(connection).await?; 389 let mut known = known_hash(); 390 let mut unknown = unknown_hash(); 391 for revision in 1..=self.revision { 392 let row = sqlx::query( 393 "SELECT envelope_id,record_id FROM stock_source_evidence WHERE revision=?", 394 ) 395 .bind(revision as i64) 396 .fetch_optional(&mut *connection) 397 .await 398 .map_err(|_| OperationError::RecoveryRequired)? 399 .ok_or(OperationError::RecoveryRequired)?; 400 let envelope: Vec<u8> = row 401 .try_get(0) 402 .map_err(|_| OperationError::RecoveryRequired)?; 403 let envelope = EnvelopeEventId::from_bytes( 404 envelope 405 .try_into() 406 .map_err(|_| OperationError::RecoveryRequired)?, 407 ); 408 let id: Option<Vec<u8>> = row 409 .try_get(1) 410 .map_err(|_| OperationError::RecoveryRequired)?; 411 if let Some(id) = id { 412 let id = RecordId::from_bytes( 413 id.try_into() 414 .map_err(|_| OperationError::RecoveryRequired)?, 415 ); 416 let protected:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_source_records WHERE record_id=?").bind(id.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.flatten(); 417 known_row( 418 &mut known, 419 revision, 420 id, 421 &protected.ok_or(OperationError::RecoveryRequired)?, 422 ); 423 } else { 424 let mut count = 0; 425 for part in 0..4 { 426 if let Some(protected) = rumor_part(connection, envelope, part).await? { 427 unknown_row(&mut unknown, revision, envelope, part, &protected); 428 count += 1; 429 } 430 } 431 let actual: i64 = sqlx::query_scalar( 432 "SELECT count(*) FROM stock_source_parts WHERE envelope_id=? AND role=2", 433 ) 434 .bind(envelope.as_bytes().as_slice()) 435 .fetch_one(&mut *connection) 436 .await 437 .map_err(|_| OperationError::RecoveryRequired)?; 438 if count == 0 || count != actual { 439 return Err(OperationError::RecoveryRequired); 440 } 441 } 442 } 443 if <[u8; 32]>::from(known.finalize()) != self.known 444 || <[u8; 32]>::from(unknown.finalize()) != self.unknown 445 { 446 return Err(OperationError::RecoveryRequired); 447 } 448 self.public.confirm(connection).await 449 } 450 }