evidence.rs (18935B)
1 //! Append-only obtained bytes. Capture never obtains fresh business permission. 2 use super::super::inventory::{Turn, checkpoint}; 3 use super::*; 4 use radroots_signing::{ 5 issuance::{OutcomeKind, SigningOutcome}, 6 request::CancellationSignal, 7 }; 8 use std::num::NonZeroU64; 9 use zeroize::Zeroizing; 10 mod codec; 11 pub(in crate::workspace::stock) mod selection; 12 pub(in crate::workspace::stock) use codec::{Retained, read_entry}; 13 const MAX_RAW: usize = 64 * 1024; 14 15 /// Independently checked obtained bytes. A store error leaves the caller's 16 /// original borrowed value intact. This supplies no installation or retry right. 17 pub struct StockEvidenceCapture { 18 request: StockEvidenceRequest, 19 } 20 impl StockEvidenceCapture { 21 pub fn verify( 22 binding: WorkspaceBinding, 23 attempt: &StockSigningAttempt, 24 raw: &str, 25 observed: Option<NonZeroU64>, 26 ) -> Result<Self, OperationError> { 27 if raw.len() > MAX_RAW { 28 return Err(WorkspaceError::Capacity.into()); 29 } 30 if binding.input().workspace_id() != attempt.attempt().workspace_id() 31 || binding.actor().participant() != attempt.bound_plan().preparation().rumor().author() 32 { 33 return Err(OperationError::InvalidEvidence); 34 } 35 let selected = claim::intent( 36 attempt.bound_plan(), 37 attempt.recipient(), 38 CancellationSignal::new(), 39 )?; 40 if selected.binding() != attempt.binding() { 41 return Err(OperationError::InvalidEvidence); 42 } 43 let (_, kind) = SigningOutcome::capture(&selected, raw.into(), observed).into_parts(); 44 let OutcomeKind::Obtained(signed) = kind else { 45 return Err(OperationError::InvalidEvidence); 46 }; 47 Ok(Self { 48 request: StockEvidenceRequest::from_obtained_wire( 49 binding, 50 attempt.attempt().operation_id(), 51 attempt.attempt().command_digest(), 52 attempt.attempt_id(), 53 attempt.recipient(), 54 *attempt.binding().digest(), 55 raw, 56 signed.observed_at_unix_ms(), 57 )?, 58 }) 59 } 60 /// Transfers bounded original data into the shared port. The host still 61 /// authenticates its actual retained claim and verifies these bytes again. 62 pub fn into_request(self) -> StockEvidenceRequest { 63 self.request 64 } 65 pub fn with_json<T>(&self, use_json: impl FnOnce(&str) -> T) -> T { 66 self.request.with_json(use_json) 67 } 68 pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> { 69 self.request.observed_at_unix_ms() 70 } 71 } 72 impl std::fmt::Debug for StockEvidenceCapture { 73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 74 f.write_str("StockEvidenceCapture(<redacted>)") 75 } 76 } 77 78 pub struct StockCapturedEvidence { 79 receipt: StockEvidenceReceipt, 80 raw: Zeroizing<String>, 81 } 82 impl StockCapturedEvidence { 83 pub const fn receipt(&self) -> StockEvidenceReceipt { 84 self.receipt 85 } 86 pub fn with_json<T>(&self, use_json: impl FnOnce(&str) -> T) -> T { 87 use_json(&self.raw) 88 } 89 } 90 impl std::fmt::Debug for StockCapturedEvidence { 91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 92 f.write_str("StockCapturedEvidence(<redacted>)") 93 } 94 } 95 /// At most 32 authenticated references in append order. The cursor discovers 96 /// retained bytes after process loss without reconstructing a signer output. 97 #[derive(Debug)] 98 pub struct StockEvidencePage { 99 receipts: Vec<StockEvidenceReceipt>, 100 next: Option<Sequence>, 101 } 102 impl StockEvidencePage { 103 pub fn receipts(&self) -> &[StockEvidenceReceipt] { 104 &self.receipts 105 } 106 pub const fn next(&self) -> Option<Sequence> { 107 self.next 108 } 109 } 110 111 pub(in crate::workspace) async fn page( 112 turn: &mut Turn<'_>, 113 request: StockClaimRequest, 114 after: Option<Sequence>, 115 proof: AttachmentProof, 116 ) -> Result<StockEvidencePage, OperationError> { 117 let auth = Box::pin(super::super::signing_plan::load( 118 turn, 119 &request.binding, 120 request.minimum, 121 request.operation, 122 request.digest, 123 &proof, 124 )) 125 .await?; 126 Box::pin(page_authorized(turn, request, after, proof, auth)).await 127 } 128 129 async fn page_authorized( 130 turn: &mut Turn<'_>, 131 request: StockClaimRequest, 132 after: Option<Sequence>, 133 proof: AttachmentProof, 134 auth: super::super::signing_plan::Authorized, 135 ) -> Result<StockEvidencePage, OperationError> { 136 if auth.access.authority.catalog < 11 { 137 return Err(OperationError::UnsupportedOperation); 138 } 139 let minimum = InventoryCheckpointRef::from_host_metadata( 140 turn.selected.authority(), 141 Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, 142 None, 143 )?; 144 let witness = Box::pin(checkpoint::authenticate_minimum( 145 turn.connection, 146 turn.selected, 147 turn.crypto, 148 &auth.access.current, 149 &auth.access.authority, 150 minimum, 151 )) 152 .await?; 153 let selected = selection::page( 154 turn.connection, 155 turn.selected.participant(), 156 request.operation, 157 request.recipient, 158 after, 159 ) 160 .await?; 161 let more = selected.len() > 32; 162 let mut last = None; 163 let mut receipts = Vec::with_capacity(selected.len().min(32)); 164 for value in selected.iter().take(32).copied() { 165 let retained = selection::open( 166 turn.connection, 167 turn.selected, 168 turn.crypto, 169 request.operation, 170 request.recipient, 171 value, 172 ) 173 .await?; 174 last = Some(value.revision); 175 receipts.push(retained.value.receipt); 176 } 177 let mut tx = turn 178 .connection 179 .begin_with("BEGIN IMMEDIATE") 180 .await 181 .map_err(|_| OperationError::StorageFailure)?; 182 let checked: Result<(), OperationError> = async { 183 witness.confirm(&mut tx).await?; 184 if selection::page( 185 &mut tx, 186 turn.selected.participant(), 187 request.operation, 188 request.recipient, 189 after, 190 ) 191 .await? 192 != selected 193 { 194 return Err(OperationError::RecoveryRequired); 195 } 196 auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false) 197 .await?; 198 Ok(()) 199 } 200 .await; 201 if tx.rollback().await.is_err() { 202 *turn.uncertain = true; 203 return Err(OperationError::RecoveryRequired); 204 } 205 checked?; 206 let next = if more { 207 Some(last.ok_or(OperationError::RecoveryRequired)?) 208 } else { 209 None 210 }; 211 Ok(StockEvidencePage { receipts, next }) 212 } 213 214 pub(in crate::workspace) async fn capture( 215 turn: &mut Turn<'_>, 216 supplied: StockEvidenceRequest, 217 proof: AttachmentProof, 218 ) -> Result<StockEvidenceOutcome, OperationError> { 219 if *turn.uncertain { 220 return Err(OperationError::RecoveryRequired); 221 } 222 turn.namespace.validate()?; 223 let input = supplied.binding().input(); 224 if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(input) { 225 return Err(OperationError::Unauthorized); 226 } 227 let (authority, record, root, grant) = 228 super::super::read(turn.connection, input, turn.crypto).await?; 229 if authority.catalog < 11 { 230 return Err(OperationError::UnsupportedOperation); 231 } 232 record.authenticate_retained_capture(input, &proof)?; 233 let original = Box::pin(claim::read_entry( 234 turn.connection, 235 turn.selected, 236 turn.crypto, 237 OperationId::from_bytes(*supplied.signing_attempt_id().as_bytes()), 238 )) 239 .await? 240 .ok_or(OperationError::RecoveryRequired)?; 241 if original.frame.header.actor != supplied.binding().actor() 242 || original.report.binding().digest() != supplied.intent_digest() 243 { 244 return Err(OperationError::InvalidEvidence); 245 } 246 if original.report.attempt().operation_id() != supplied.operation_id() 247 || original.report.attempt().command_digest() != supplied.command_digest() 248 || original.report.recipient() != supplied.recipient() 249 { 250 return Err(OperationError::InvalidEvidence); 251 } 252 // Verify again against the actual protected claim, never a caller descriptor. 253 let checked = supplied 254 .with_json(|raw| { 255 StockEvidenceCapture::verify( 256 supplied.binding().clone(), 257 &original.report, 258 raw, 259 supplied.observed_at_unix_ms(), 260 ) 261 })? 262 .into_request(); 263 let digest: [u8; 32] = checked.with_json(|raw| Sha256::digest(raw.as_bytes()).into()); 264 let before = authority 265 .inventory 266 .ok_or(OperationError::RecoveryRequired)?; 267 let minimum = InventoryCheckpointRef::from_host_metadata( 268 input.authority(), 269 Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, 270 None, 271 )?; 272 let witness = Box::pin(checkpoint::authenticate_minimum( 273 turn.connection, 274 turn.selected, 275 turn.crypto, 276 supplied.binding(), 277 &authority, 278 minimum, 279 )) 280 .await?; 281 let existing = lookup( 282 turn.connection, 283 turn.selected, 284 turn.crypto, 285 original.report.bound_plan().plan().operation_id(), 286 original.report.recipient(), 287 digest, 288 ) 289 .await?; 290 let (frame, updated_root, receipt) = if let Some(retained) = &existing { 291 if checked.with_json(|raw| retained.value.raw.as_str() != raw) 292 || retained.value.receipt.signing_attempt_id() != original.report.attempt_id() 293 { 294 return Err(OperationError::RecoveryRequired); 295 } 296 (None, None, retained.value.receipt) 297 } else { 298 let entry = OperationId::from_bytes(super::super::super::random()?); 299 let transaction = TransactionId::from_bytes(super::super::super::random()?); 300 let revision = Sequence::new( 301 before 302 .revision 303 .get() 304 .checked_add(1) 305 .ok_or(WorkspaceError::Capacity)?, 306 ) 307 .map_err(|_| WorkspaceError::Capacity)?; 308 let body = Zeroizing::new(codec::encode(&original, &checked)); 309 let mut header = ledger::Header { 310 version: 5, 311 family: ledger::Family::SigningEvidence, 312 namespace: SellerAuthoritySelection::from_attachment(turn.selected), 313 actor: original.frame.header.actor, 314 operation: entry, 315 digest: original.frame.header.digest, 316 transaction, 317 revision, 318 previous: before.head, 319 head: radroots_domain::CheckpointDigest::from_bytes([0; 32]), 320 pool: None, 321 order: original.frame.header.order, 322 related_operation: original.frame.header.related_operation, 323 subject_grant: None, 324 bytes: 0, 325 parts: 0, 326 body_digest: [0; 32], 327 }; 328 header.head = codec::head(&header, &body); 329 let mut next = authority.clone(); 330 next.inventory = Some(InventoryCheckpoint { 331 revision, 332 head: Some(header.head), 333 ..before 334 }); 335 let frame = ledger::prepare(turn.crypto, turn.selected, header, &body).await?; 336 let updated = turn 337 .crypto 338 .seal_stock_root(turn.selected, next.catalog, &next.encode()?) 339 .await?; 340 let receipt = StockEvidenceReceipt::from_committed_store( 341 CommitAttempt::new( 342 input.workspace_id(), 343 original.report.bound_plan().plan().operation_id(), 344 original.frame.header.digest, 345 Some(transaction), 346 ), 347 original.report.attempt_id(), 348 original.report.recipient(), 349 digest, 350 checked.observed_at_unix_ms(), 351 )?; 352 (Some(frame), Some(updated), receipt) 353 }; 354 let mut tx = turn 355 .connection 356 .begin_with("BEGIN IMMEDIATE") 357 .await 358 .map_err(|_| OperationError::StorageFailure)?; 359 let changed:Result<(),OperationError>=async { 360 turn.namespace.validate()?; 361 super::super::unchanged(&mut tx,input,authority.catalog,&root,&grant).await?; 362 record.authenticate_retained_capture(input,&proof)?; 363 witness.confirm(&mut tx).await?;original.confirm(&mut tx).await?; 364 if let Some(existing)=&existing {existing.confirm(&mut tx).await?;} 365 if let Some(frame)=&frame { 366 frame.insert_record(&mut tx).await?; 367 sqlx::query("INSERT INTO stock_signing_evidence(actor,operation_id,recipient,evidence_digest,entry_id) VALUES(?,?,?,?,?)").bind(input.participant().as_bytes().as_slice()).bind(receipt.attempt().operation_id().as_bytes().as_slice()).bind(receipt.recipient().as_bytes().as_slice()).bind(digest.as_slice()).bind(frame.header.operation.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 368 let result=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(updated_root.as_ref().ok_or(OperationError::RecoveryRequired)?).bind(&root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 369 if result.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);} 370 } 371 turn.namespace.validate()?;Ok(()) 372 }.await; 373 if let Err(error) = changed { 374 if tx.rollback().await.is_err() { 375 *turn.uncertain = true; 376 return Ok(StockEvidenceOutcome::Unknown(receipt.attempt())); 377 } 378 return Err(error); 379 } 380 let done = if frame.is_some() { 381 tx.commit().await 382 } else { 383 tx.rollback().await 384 }; 385 if done.is_err() { 386 *turn.uncertain = true; 387 return Ok(StockEvidenceOutcome::Unknown(receipt.attempt())); 388 } 389 Ok(StockEvidenceOutcome::Committed(receipt)) 390 } 391 392 async fn lookup( 393 connection: &mut SqliteConnection, 394 input: &AttachmentInput, 395 crypto: &WorkspaceCrypto, 396 operation: OperationId, 397 recipient: PublicKey, 398 digest: [u8; 32], 399 ) -> Result<Option<codec::Retained>, OperationError> { 400 let Some(entry) = selection::entry( 401 connection, 402 input.participant(), 403 operation, 404 recipient, 405 digest, 406 ) 407 .await? 408 else { 409 return Ok(None); 410 }; 411 let retained = read_entry(connection, input, crypto, entry) 412 .await? 413 .ok_or(OperationError::RecoveryRequired)?; 414 if retained.value.receipt.attempt().operation_id() != operation 415 || retained.value.receipt.recipient() != recipient 416 || retained.value.receipt.digest() != &digest 417 { 418 return Err(OperationError::RecoveryRequired); 419 } 420 Ok(Some(retained)) 421 } 422 423 pub(in crate::workspace) async fn read( 424 turn: &mut Turn<'_>, 425 request: StockClaimRequest, 426 digest: [u8; 32], 427 proof: AttachmentProof, 428 ) -> Result<Option<StockCapturedEvidence>, OperationError> { 429 let auth = Box::pin(super::super::signing_plan::load( 430 turn, 431 &request.binding, 432 request.minimum, 433 request.operation, 434 request.digest, 435 &proof, 436 )) 437 .await?; 438 Box::pin(read_authorized(turn, request, digest, proof, auth)).await 439 } 440 441 async fn read_authorized( 442 turn: &mut Turn<'_>, 443 request: StockClaimRequest, 444 digest: [u8; 32], 445 proof: AttachmentProof, 446 auth: super::super::signing_plan::Authorized, 447 ) -> Result<Option<StockCapturedEvidence>, OperationError> { 448 if auth.access.authority.catalog < 11 { 449 return Err(OperationError::UnsupportedOperation); 450 } 451 let claim = claim::existing(turn, &auth, request.operation, request.recipient).await?; 452 let retained = lookup( 453 turn.connection, 454 turn.selected, 455 turn.crypto, 456 request.operation, 457 request.recipient, 458 digest, 459 ) 460 .await?; 461 if retained.is_some() && claim.0.is_none() { 462 return Err(OperationError::RecoveryRequired); 463 } 464 // Full protected ancestry proves natural evidence presence/absence. 465 let minimum = InventoryCheckpointRef::from_host_metadata( 466 turn.selected.authority(), 467 Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, 468 None, 469 )?; 470 let witness = Box::pin(checkpoint::authenticate_minimum( 471 turn.connection, 472 turn.selected, 473 turn.crypto, 474 &auth.access.current, 475 &auth.access.authority, 476 minimum, 477 )) 478 .await?; 479 let mut tx = turn 480 .connection 481 .begin_with("BEGIN IMMEDIATE") 482 .await 483 .map_err(|_| OperationError::StorageFailure)?; 484 let checked: Result<(), OperationError> = async { 485 witness.confirm(&mut tx).await?; 486 if selection::entry( 487 &mut tx, 488 turn.selected.participant(), 489 request.operation, 490 request.recipient, 491 digest, 492 ) 493 .await? 494 != retained.as_ref().map(|value| value.frame.header.operation) 495 { 496 return Err(OperationError::RecoveryRequired); 497 } 498 claim.1.confirm(&mut tx).await?; 499 auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false) 500 .await?; 501 if let Some(value) = &retained { 502 value.confirm(&mut tx).await?; 503 } 504 Ok(()) 505 } 506 .await; 507 if tx.rollback().await.is_err() { 508 *turn.uncertain = true; 509 return Err(OperationError::RecoveryRequired); 510 } 511 checked?; 512 Ok(retained.map(|value| value.value)) 513 } 514 impl NativeWorkspace { 515 pub async fn stock_signing_evidence_page( 516 &self, 517 request: StockClaimRequest, 518 after: Option<Sequence>, 519 proof: &AttachmentProof, 520 ) -> Result<StockEvidencePage, OperationError> { 521 self.worker 522 .stock_signing_evidence_page( 523 request, 524 after, 525 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, 526 ) 527 .await 528 } 529 pub async fn capture_stock_signing_evidence( 530 &self, 531 evidence: &StockEvidenceCapture, 532 proof: &AttachmentProof, 533 ) -> Result<StockEvidenceOutcome, OperationError> { 534 radroots_storage::inventory::InventoryStore::capture_stock_evidence( 535 self, 536 &evidence.request, 537 proof, 538 ) 539 .await 540 } 541 pub async fn stock_signing_evidence( 542 &self, 543 request: StockClaimRequest, 544 digest: [u8; 32], 545 proof: &AttachmentProof, 546 ) -> Result<Option<StockCapturedEvidence>, OperationError> { 547 self.worker 548 .stock_signing_evidence( 549 request, 550 digest, 551 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, 552 ) 553 .await 554 } 555 }