ledger.rs (37737B)
1 //! Bounded multipart operation framing for the multi-pool native ledger. 2 //! Framing authenticates original storage bytes; family-specific admission 3 //! must independently validate every business or physical effect. 4 use super::*; 5 use radroots_domain::{ActorRef, CheckpointDigest, CommandDigest, OperationId, PoolId}; 6 use radroots_storage::command::OperationError; 7 use sha2::{Digest, Sha256}; 8 use sqlx::Row; 9 use zeroize::Zeroizing; 10 11 pub(super) const BODY_MAX_BYTES: usize = 256 * 1024; 12 const PART_BYTES: usize = 16 * 1024; 13 const MAX_PARTS: usize = BODY_MAX_BYTES / PART_BYTES; 14 15 #[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] 16 #[serde(rename_all = "snake_case")] 17 pub(super) enum Family { 18 Inventory, 19 Consent, 20 Acceptance, 21 SigningPlan, 22 SigningClaim, 23 SigningEvidence, 24 Installation, 25 AbortedPreparation, 26 OriginalUnissued, 27 ReplayAdmission, 28 Envelope, 29 DeliveryAttempt, 30 DeliveryObservation, 31 RewrapAdmission, 32 RewrappedEnvelope, 33 } 34 35 #[derive(Serialize, Deserialize)] 36 #[serde(deny_unknown_fields)] 37 pub(super) struct Header { 38 pub version: u8, 39 pub family: Family, 40 #[serde(deserialize_with = "super::object")] 41 pub namespace: SellerAuthoritySelection, 42 pub actor: ActorRef, 43 pub operation: OperationId, 44 pub digest: CommandDigest, 45 pub transaction: TransactionId, 46 pub revision: Sequence, 47 #[serde(deserialize_with = "super::required_nullable")] 48 pub previous: Option<CheckpointDigest>, 49 pub head: CheckpointDigest, 50 #[serde(deserialize_with = "super::required_nullable")] 51 pub pool: Option<PoolId>, 52 #[serde(deserialize_with = "super::required_nullable")] 53 pub order: Option<radroots_domain::OrderId>, 54 #[serde(deserialize_with = "super::required_nullable")] 55 pub related_operation: Option<OperationId>, 56 #[serde(deserialize_with = "super::required_nullable")] 57 pub subject_grant: Option<GrantId>, 58 pub bytes: u32, 59 pub parts: u8, 60 pub body_digest: [u8; 32], 61 } 62 impl Header { 63 pub fn validate( 64 &self, 65 input: &AttachmentInput, 66 operation: OperationId, 67 ) -> Result<(), OperationError> { 68 if self.version != 5 69 || !self.namespace.matches_attachment(input) 70 || self.actor.participant() != input.participant() 71 || self.actor.role() != radroots_domain::ActorRole::Seller 72 || self.actor.organization().is_some() 73 || self.actor.grant_id().is_none() 74 || self.operation != operation 75 || self.revision.get() == 0 76 || (self.revision.get() == 1) != self.previous.is_none() 77 || (self.family == Family::Inventory) != self.pool.is_some() 78 || (self.family == Family::Inventory) != self.order.is_none() 79 || matches!( 80 self.family, 81 Family::Consent 82 | Family::SigningPlan 83 | Family::SigningClaim 84 | Family::SigningEvidence 85 | Family::Installation 86 | Family::AbortedPreparation 87 | Family::OriginalUnissued 88 | Family::ReplayAdmission 89 | Family::Envelope 90 | Family::DeliveryAttempt 91 | Family::DeliveryObservation 92 | Family::RewrappedEnvelope 93 | Family::RewrapAdmission 94 ) != self.related_operation.is_some() 95 || (self.family == Family::Consent) != self.subject_grant.is_some() 96 || self.bytes == 0 97 || self.bytes as usize > BODY_MAX_BYTES 98 || usize::from(self.parts) != (self.bytes as usize).div_ceil(PART_BYTES) 99 { 100 return Err(OperationError::RecoveryRequired); 101 } 102 Ok(()) 103 } 104 } 105 106 pub(super) struct Prepared { 107 pub protected: Vec<u8>, 108 parts: Vec<Vec<u8>>, 109 pub(super) header: Header, 110 } 111 pub(super) struct Retained { 112 pub header: Header, 113 pub body: Zeroizing<Vec<u8>>, 114 pub protected: Vec<u8>, 115 pub parts_witness: [u8; 32], 116 } 117 fn part_id(actor: ActorRef, operation: OperationId, part: u8) -> [u8; 32] { 118 let mut hash = Sha256::new(); 119 hash.update(b"radroots.seller_stock.operation_part_key.v1\0"); 120 hash.update(actor.participant().as_bytes()); 121 hash.update(operation.as_bytes()); 122 hash.update([part]); 123 hash.finalize().into() 124 } 125 fn part_hash() -> Sha256 { 126 let mut hash = Sha256::new(); 127 hash.update(b"radroots.seller_stock.operation_parts_snapshot.v1\0"); 128 hash 129 } 130 fn hash_part(hash: &mut Sha256, part: u8, grant: &[u8; 32], protected: &[u8]) { 131 hash.update([part]); 132 hash.update(grant); 133 hash.update((protected.len() as u64).to_be_bytes()); 134 hash.update(protected); 135 } 136 137 pub(super) async fn prepare( 138 crypto: &WorkspaceCrypto, 139 input: &AttachmentInput, 140 mut header: Header, 141 body: &[u8], 142 ) -> Result<Prepared, OperationError> { 143 if body.is_empty() || body.len() > BODY_MAX_BYTES { 144 return Err(WorkspaceError::Capacity.into()); 145 } 146 header.bytes = body.len() as u32; 147 header.parts = body.len().div_ceil(PART_BYTES) as u8; 148 header.body_digest = Sha256::digest(body).into(); 149 header.validate(input, header.operation)?; 150 let mut parts = Vec::with_capacity(usize::from(header.parts)); 151 for (index, clear) in body.chunks(PART_BYTES).enumerate() { 152 parts.push( 153 crypto 154 .seal_stock_record( 155 input, 156 "operation_part", 157 &part_id(header.actor, header.operation, index as u8), 158 clear, 159 ) 160 .await?, 161 ); 162 } 163 let clear = 164 Zeroizing::new(serde_json::to_vec(&header).map_err(|_| OperationError::StorageFailure)?); 165 if clear.len() > PART_BYTES { 166 return Err(WorkspaceError::Capacity.into()); 167 } 168 let protected = crypto 169 .seal_stock_record_for_catalog(input, "operation", header.operation.as_bytes(), 7, &clear) 170 .await?; 171 Ok(Prepared { 172 protected, 173 parts, 174 header, 175 }) 176 } 177 impl Prepared { 178 pub async fn insert_record( 179 &self, 180 connection: &mut SqliteConnection, 181 ) -> Result<(), OperationError> { 182 let h = &self.header; 183 sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation,subject_grant) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)") 184 .bind(h.actor.participant().as_bytes().as_slice()).bind(h.actor.grant_id().ok_or(OperationError::RecoveryRequired)?.as_bytes().as_slice()).bind(h.operation.as_bytes().as_slice()).bind(h.digest.as_bytes().as_slice()).bind(h.transaction.as_bytes().as_slice()).bind(h.pool.map(|v|v.as_bytes().to_vec())).bind(h.revision.get() as i64).bind(h.head.as_bytes().as_slice()).bind(&self.protected).bind(h.family.code()).bind(h.order.map(|v|v.as_bytes().to_vec())).bind(h.related_operation.map(|v|v.as_bytes().to_vec())).bind(h.subject_grant.map(|v|v.as_bytes().to_vec())).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; 185 self.insert_parts(connection, h.actor, h.operation).await 186 } 187 /// Called only within the existing owner's SQL transaction. Protection and 188 /// provider callbacks have already completed before entering this method. 189 pub async fn insert_parts( 190 &self, 191 connection: &mut SqliteConnection, 192 actor: ActorRef, 193 operation: OperationId, 194 ) -> Result<(), OperationError> { 195 let grant = actor.grant_id().ok_or(OperationError::RecoveryRequired)?; 196 for (index, protected) in self.parts.iter().enumerate() { 197 sqlx::query("INSERT INTO stock_operation_parts(actor,grant_id,operation_id,part,protected) VALUES(?,?,?,?,?)") 198 .bind(actor.participant().as_bytes().as_slice()) 199 .bind(grant.as_bytes().as_slice()) 200 .bind(operation.as_bytes().as_slice()) 201 .bind(index as i64) 202 .bind(protected) 203 .execute(&mut *connection) 204 .await 205 .map_err(|_|OperationError::StorageFailure)?; 206 } 207 Ok(()) 208 } 209 } 210 211 pub(super) async fn read( 212 connection: &mut SqliteConnection, 213 input: &AttachmentInput, 214 crypto: &WorkspaceCrypto, 215 operation: OperationId, 216 ) -> Result<Option<Retained>, OperationError> { 217 let row=sqlx::query("SELECT grant_id,command_digest,transaction_id,pool_id,revision,chain_head,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END,family,order_id,related_operation,subject_grant FROM stock_operations WHERE actor=? AND operation_id=?") 218 .bind(input.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) 219 .fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; 220 let Some(row) = row else { return Ok(None) }; 221 let protected: Vec<u8> = row 222 .try_get::<Option<Vec<u8>>, _>(6) 223 .map_err(|_| OperationError::RecoveryRequired)? 224 .ok_or(OperationError::RecoveryRequired)?; 225 let clear = crypto 226 .open_stock_record_for_catalog(input, "operation", operation.as_bytes(), 7, &protected) 227 .await?; 228 let header: Header = clear.expose_secret(|bytes| super::closed_record(bytes))?; 229 header.validate(input, operation)?; 230 let grant: Vec<u8> = row 231 .try_get(0) 232 .map_err(|_| OperationError::RecoveryRequired)?; 233 let digest: Vec<u8> = row 234 .try_get(1) 235 .map_err(|_| OperationError::RecoveryRequired)?; 236 let transaction: Vec<u8> = row 237 .try_get(2) 238 .map_err(|_| OperationError::RecoveryRequired)?; 239 let pool: Option<Vec<u8>> = row 240 .try_get(3) 241 .map_err(|_| OperationError::RecoveryRequired)?; 242 let revision: i64 = row 243 .try_get(4) 244 .map_err(|_| OperationError::RecoveryRequired)?; 245 let head: Vec<u8> = row 246 .try_get(5) 247 .map_err(|_| OperationError::RecoveryRequired)?; 248 let family: i64 = row 249 .try_get(7) 250 .map_err(|_| OperationError::RecoveryRequired)?; 251 let order: Option<Vec<u8>> = row 252 .try_get(8) 253 .map_err(|_| OperationError::RecoveryRequired)?; 254 let related: Option<Vec<u8>> = row 255 .try_get(9) 256 .map_err(|_| OperationError::RecoveryRequired)?; 257 let subject: Option<Vec<u8>> = row 258 .try_get(10) 259 .map_err(|_| OperationError::RecoveryRequired)?; 260 if header 261 .actor 262 .grant_id() 263 .map(|value| value.as_bytes().to_vec()) 264 != Some(grant) 265 || digest != header.digest.as_bytes() 266 || transaction != header.transaction.as_bytes() 267 || pool != header.pool.map(|value| value.as_bytes().to_vec()) 268 || revision <= 0 269 || revision as u64 != header.revision.get() 270 || head != header.head.as_bytes() 271 || family != header.family.code() 272 || order != header.order.map(|value| value.as_bytes().to_vec()) 273 || subject != header.subject_grant.map(|value| value.as_bytes().to_vec()) 274 || related 275 != header 276 .related_operation 277 .map(|value| value.as_bytes().to_vec()) 278 { 279 return Err(OperationError::RecoveryRequired); 280 } 281 let mut body = Zeroizing::new(Vec::with_capacity(header.bytes as usize)); 282 let mut witness = part_hash(); 283 for index in 0..header.parts { 284 let protected = read_part(connection, header.actor, operation, index).await?; 285 hash_part( 286 &mut witness, 287 index, 288 header 289 .actor 290 .grant_id() 291 .ok_or(OperationError::RecoveryRequired)? 292 .as_bytes(), 293 &protected, 294 ); 295 let clear = crypto 296 .open_stock_record( 297 input, 298 "operation_part", 299 &part_id(header.actor, operation, index), 300 &protected, 301 ) 302 .await?; 303 clear.expose_secret(|bytes| { 304 let expected = if index + 1 == header.parts { 305 header.bytes as usize - usize::from(index) * PART_BYTES 306 } else { 307 PART_BYTES 308 }; 309 if bytes.len() != expected { 310 return Err(OperationError::RecoveryRequired); 311 } 312 body.extend_from_slice(bytes); 313 Ok(()) 314 })?; 315 } 316 if body.len() != header.bytes as usize 317 || <[u8; 32]>::from(Sha256::digest(body.as_slice())) != header.body_digest 318 { 319 return Err(OperationError::RecoveryRequired); 320 } 321 let parts_witness = witness.finalize().into(); 322 confirm_parts( 323 connection, 324 header.actor, 325 operation, 326 parts_witness, 327 header.parts, 328 ) 329 .await?; 330 Ok(Some(Retained { 331 header, 332 body, 333 protected, 334 parts_witness, 335 })) 336 } 337 impl Family { 338 pub const fn code(self) -> i64 { 339 match self { 340 Self::Inventory => 0, 341 Self::Consent => 1, 342 Self::Acceptance => 2, 343 Self::SigningPlan => 3, 344 Self::SigningClaim => 4, 345 Self::SigningEvidence => 5, 346 Self::Installation => 6, 347 Self::AbortedPreparation => 7, 348 Self::OriginalUnissued => 8, 349 Self::ReplayAdmission => 9, 350 Self::Envelope => 10, 351 Self::DeliveryAttempt => 11, 352 Self::DeliveryObservation => 12, 353 Self::RewrapAdmission => 13, 354 Self::RewrappedEnvelope => 14, 355 } 356 } 357 } 358 pub(super) async fn confirm_header( 359 connection: &mut SqliteConnection, 360 header: &Header, 361 protected: &[u8], 362 ) -> Result<(), OperationError> { 363 let matched:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND grant_id=? AND operation_id=? AND command_digest=? AND transaction_id=? AND pool_id IS ? AND revision=? AND chain_head=? AND protected=? AND family=? AND order_id IS ? AND related_operation IS ? AND subject_grant IS ?") 364 .bind(header.actor.participant().as_bytes().as_slice()) 365 .bind(header.actor.grant_id().ok_or(OperationError::RecoveryRequired)?.as_bytes().as_slice()) 366 .bind(header.operation.as_bytes().as_slice()).bind(header.digest.as_bytes().as_slice()) 367 .bind(header.transaction.as_bytes().as_slice()).bind(header.pool.map(|v|v.as_bytes().to_vec())) 368 .bind(header.revision.get() as i64).bind(header.head.as_bytes().as_slice()).bind(protected) 369 .bind(header.family.code()).bind(header.order.map(|v|v.as_bytes().to_vec())) 370 .bind(header.related_operation.map(|v|v.as_bytes().to_vec())).bind(header.subject_grant.map(|v|v.as_bytes().to_vec())).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; 371 if matched != 1 { 372 return Err(OperationError::RecoveryRequired); 373 } 374 Ok(()) 375 } 376 async fn read_part( 377 connection: &mut SqliteConnection, 378 actor: ActorRef, 379 operation: OperationId, 380 part: u8, 381 ) -> Result<Vec<u8>, OperationError> { 382 let row=sqlx::query("SELECT grant_id,protected FROM stock_operation_parts WHERE actor=? AND operation_id=? AND part=? AND length(protected) BETWEEN 1 AND 262144") 383 .bind(actor.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(i64::from(part)) 384 .fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; 385 let grant: Vec<u8> = row 386 .try_get(0) 387 .map_err(|_| OperationError::RecoveryRequired)?; 388 if grant 389 != actor 390 .grant_id() 391 .ok_or(OperationError::RecoveryRequired)? 392 .as_bytes() 393 { 394 return Err(OperationError::RecoveryRequired); 395 } 396 row.try_get(1).map_err(|_| OperationError::RecoveryRequired) 397 } 398 pub(super) async fn confirm_parts( 399 connection: &mut SqliteConnection, 400 actor: ActorRef, 401 operation: OperationId, 402 expected: [u8; 32], 403 parts: u8, 404 ) -> Result<(), OperationError> { 405 if parts == 0 || usize::from(parts) > MAX_PARTS { 406 return Err(OperationError::RecoveryRequired); 407 } 408 let (count, actual) = raw_parts_witness( 409 connection, 410 actor.participant().as_bytes(), 411 operation.as_bytes(), 412 ) 413 .await?; 414 if count != parts || actual != expected { 415 return Err(OperationError::RecoveryRequired); 416 } 417 Ok(()) 418 } 419 pub(super) async fn raw_parts_witness( 420 connection: &mut SqliteConnection, 421 actor: &[u8; 32], 422 operation: &[u8; 32], 423 ) -> Result<(u8, [u8; 32]), OperationError> { 424 let count: i64 = sqlx::query_scalar( 425 "SELECT count(*) FROM stock_operation_parts WHERE actor=? AND operation_id=?", 426 ) 427 .bind(actor.as_slice()) 428 .bind(operation.as_slice()) 429 .fetch_one(&mut *connection) 430 .await 431 .map_err(|_| OperationError::RecoveryRequired)?; 432 if count <= 0 || count > MAX_PARTS as i64 { 433 return Err(OperationError::RecoveryRequired); 434 } 435 let mut hash = part_hash(); 436 for part in 0..count { 437 let row=sqlx::query("SELECT grant_id,protected FROM stock_operation_parts WHERE actor=? AND operation_id=? AND part=? AND length(protected) BETWEEN 1 AND 262144") 438 .bind(actor.as_slice()).bind(operation.as_slice()).bind(part).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; 439 let grant: Vec<u8> = row 440 .try_get(0) 441 .map_err(|_| OperationError::RecoveryRequired)?; 442 let grant: [u8; 32] = grant 443 .try_into() 444 .map_err(|_| OperationError::RecoveryRequired)?; 445 let protected: Vec<u8> = row 446 .try_get(1) 447 .map_err(|_| OperationError::RecoveryRequired)?; 448 hash_part(&mut hash, part as u8, &grant, &protected); 449 } 450 Ok((count as u8, hash.finalize().into())) 451 } 452 453 pub(super) struct MovementWitness { 454 pub id: [u8; 32], 455 pub pool: PoolId, 456 pub grant: GrantId, 457 pub protected: Vec<u8>, 458 } 459 /// A completely decoded original effect. Only the owning family decoder 460 /// supplies its pool effects and movement witnesses; SQL indexes do not. 461 pub(super) struct HistoryEntry { 462 pub deficit: Option<[u8; 32]>, 463 pub delivery: Option<super::delivery::Projection>, 464 pub envelope: Option<super::envelope::Projection>, 465 pub aborted: Option<super::inventory::abort::Projection>, 466 pub preparation: Option<[u8; 32]>, 467 pub header: Header, 468 pub protected: Vec<u8>, 469 pub parts_witness: [u8; 32], 470 pub pools: Vec<radroots_domain::stock::PoolSnapshot>, 471 pub mapping: Option<radroots_domain::stock::OptionPoolMapping>, 472 pub movements: Vec<MovementWitness>, 473 pub signing: Option<super::issuance::Projection>, 474 pub installation: Option<super::inventory::installation::Projection>, 475 /// Derived only by the independently verified obtained-evidence decoder. 476 pub local_record: Option<Box<radroots_protocol::commerce::DecodedRecord>>, 477 } 478 pub(super) async fn history( 479 connection: &mut SqliteConnection, 480 input: &AttachmentInput, 481 crypto: &WorkspaceCrypto, 482 binding: &WorkspaceBinding, 483 authority: &Authority, 484 operation: OperationId, 485 ) -> Result<Option<HistoryEntry>, OperationError> { 486 let family: Option<i64> = 487 sqlx::query_scalar("SELECT family FROM stock_operations WHERE actor=? AND operation_id=?") 488 .bind(input.participant().as_bytes().as_slice()) 489 .bind(operation.as_bytes().as_slice()) 490 .fetch_optional(&mut *connection) 491 .await 492 .map_err(|_| OperationError::RecoveryRequired)?; 493 if matches!(family, Some(11 | 12)) && authority.catalog >= 17 { 494 return Box::pin(delivery_history( 495 connection, input, crypto, binding, authority, operation, family, 496 )) 497 .await; 498 } 499 match family { 500 None => Ok(None), 501 Some(0) => { 502 Box::pin(history_family_0( 503 connection, input, crypto, binding, authority, operation, 504 )) 505 .await 506 } 507 Some(1) => { 508 Box::pin(history_family_1( 509 connection, input, crypto, binding, authority, operation, 510 )) 511 .await 512 } 513 Some(2) if matches!(authority.catalog, 9..=20) => { 514 Box::pin(history_family_2( 515 connection, input, crypto, binding, authority, operation, 516 )) 517 .await 518 } 519 Some(2) => Err(OperationError::UnsupportedOperation), 520 Some(3) if matches!(authority.catalog, 10..=20) => { 521 Box::pin(history_family_3( 522 connection, input, crypto, binding, authority, operation, 523 )) 524 .await 525 } 526 Some(4) if authority.catalog >= 11 => { 527 Box::pin(history_family_4( 528 connection, input, crypto, binding, authority, operation, 529 )) 530 .await 531 } 532 Some(5) if authority.catalog >= 11 => { 533 Box::pin(history_family_5( 534 connection, input, crypto, binding, authority, operation, 535 )) 536 .await 537 } 538 Some(6) if matches!(authority.catalog, 12..=20) => { 539 Box::pin(history_family_6( 540 connection, input, crypto, binding, authority, operation, 541 )) 542 .await 543 } 544 Some(7) if authority.catalog >= 13 => { 545 Box::pin(history_family_7( 546 connection, input, crypto, binding, authority, operation, 547 )) 548 .await 549 } 550 Some(8) if authority.catalog >= 14 => { 551 Box::pin(history_family_8( 552 connection, input, crypto, binding, authority, operation, 553 )) 554 .await 555 } 556 Some(9) if authority.catalog >= 15 => { 557 Box::pin(history_family_9( 558 connection, input, crypto, binding, authority, operation, 559 )) 560 .await 561 } 562 Some(10) if authority.catalog >= 16 => { 563 Box::pin(history_family_10( 564 connection, input, crypto, binding, authority, operation, 565 )) 566 .await 567 } 568 Some(13) if authority.catalog >= 18 => Ok(Some( 569 Box::pin(super::envelope::admission_history( 570 connection, input, crypto, binding, operation, 571 )) 572 .await?, 573 )), 574 Some(14) if authority.catalog >= 18 => { 575 Box::pin(history_family_10( 576 connection, input, crypto, binding, authority, operation, 577 )) 578 .await 579 } 580 Some(_) => Err(OperationError::RecoveryRequired), 581 } 582 } 583 // Isolate each authenticated family decoder from the dispatch polling frame. 584 async fn history_family_0( 585 connection: &mut SqliteConnection, 586 input: &AttachmentInput, 587 crypto: &WorkspaceCrypto, 588 binding: &WorkspaceBinding, 589 _authority: &Authority, 590 operation: OperationId, 591 ) -> Result<Option<HistoryEntry>, OperationError> { 592 { 593 let retained = Box::pin(super::inventory::read_operation( 594 connection, input, crypto, binding, operation, 595 )) 596 .await? 597 .ok_or(OperationError::RecoveryRequired)?; 598 let (header, parts_witness) = retained.frame.ok_or(OperationError::RecoveryRequired)?; 599 let movements = match (retained.movement, retained.movement_protected) { 600 (Some(id), Some(protected)) => vec![MovementWitness { 601 id, 602 pool: retained.receipt.pool().id(), 603 grant: retained.original_grant, 604 protected, 605 }], 606 (None, None) => vec![], 607 _ => return Err(OperationError::RecoveryRequired), 608 }; 609 Ok(Some(HistoryEntry { 610 deficit: retained.deficit_projection, 611 delivery: None, 612 envelope: None, 613 aborted: None, 614 preparation: None, 615 local_record: None, 616 installation: None, 617 signing: None, 618 header, 619 protected: retained.protected, 620 parts_witness, 621 pools: vec![retained.receipt.pool()], 622 mapping: retained.receipt.mapping(), 623 movements, 624 })) 625 } 626 } 627 async fn history_family_1( 628 connection: &mut SqliteConnection, 629 input: &AttachmentInput, 630 crypto: &WorkspaceCrypto, 631 _binding: &WorkspaceBinding, 632 authority: &Authority, 633 operation: OperationId, 634 ) -> Result<Option<HistoryEntry>, OperationError> { 635 { 636 let retained = Box::pin(super::consent::read( 637 connection, 638 input, 639 crypto, 640 authority.input.grant_id(), 641 operation, 642 )) 643 .await? 644 .ok_or(OperationError::RecoveryRequired)?; 645 let count: i64 = sqlx::query_scalar( 646 "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?", 647 ) 648 .bind(input.participant().as_bytes().as_slice()) 649 .bind(operation.as_bytes().as_slice()) 650 .fetch_one(connection) 651 .await 652 .map_err(|_| OperationError::RecoveryRequired)?; 653 if count != 0 { 654 return Err(OperationError::RecoveryRequired); 655 } 656 Ok(Some(HistoryEntry { 657 deficit: None, 658 delivery: None, 659 envelope: None, 660 aborted: None, 661 preparation: None, 662 local_record: None, 663 installation: None, 664 signing: None, 665 header: retained.frame.header, 666 protected: retained.frame.protected, 667 parts_witness: retained.frame.parts_witness, 668 pools: vec![], 669 mapping: None, 670 movements: vec![], 671 })) 672 } 673 } 674 async fn history_family_2( 675 connection: &mut SqliteConnection, 676 input: &AttachmentInput, 677 crypto: &WorkspaceCrypto, 678 _binding: &WorkspaceBinding, 679 _authority: &Authority, 680 operation: OperationId, 681 ) -> Result<Option<HistoryEntry>, OperationError> { 682 Ok(Some( 683 Box::pin(super::inventory::acceptance::codec::read( 684 connection, input, crypto, operation, 685 )) 686 .await? 687 .ok_or(OperationError::RecoveryRequired)? 688 .into_history(), 689 )) 690 } 691 async fn history_family_3( 692 connection: &mut SqliteConnection, 693 input: &AttachmentInput, 694 crypto: &WorkspaceCrypto, 695 _binding: &WorkspaceBinding, 696 _authority: &Authority, 697 operation: OperationId, 698 ) -> Result<Option<HistoryEntry>, OperationError> { 699 { 700 let retained = Box::pin(super::signing_plan::read_entry( 701 connection, input, crypto, operation, 702 )) 703 .await? 704 .ok_or(OperationError::RecoveryRequired)?; 705 Ok(Some(retained.into_history())) 706 } 707 } 708 async fn history_family_4( 709 connection: &mut SqliteConnection, 710 input: &AttachmentInput, 711 crypto: &WorkspaceCrypto, 712 _binding: &WorkspaceBinding, 713 _authority: &Authority, 714 operation: OperationId, 715 ) -> Result<Option<HistoryEntry>, OperationError> { 716 Ok(Some( 717 Box::pin(super::issuance::read_entry( 718 connection, input, crypto, operation, 719 )) 720 .await? 721 .ok_or(OperationError::RecoveryRequired)? 722 .into_history(), 723 )) 724 } 725 async fn history_family_5( 726 connection: &mut SqliteConnection, 727 input: &AttachmentInput, 728 crypto: &WorkspaceCrypto, 729 _binding: &WorkspaceBinding, 730 _authority: &Authority, 731 operation: OperationId, 732 ) -> Result<Option<HistoryEntry>, OperationError> { 733 Ok(Some( 734 Box::pin(super::issuance::evidence::read_entry( 735 connection, input, crypto, operation, 736 )) 737 .await? 738 .ok_or(OperationError::RecoveryRequired)? 739 .into_history(), 740 )) 741 } 742 async fn history_family_6( 743 connection: &mut SqliteConnection, 744 input: &AttachmentInput, 745 crypto: &WorkspaceCrypto, 746 _binding: &WorkspaceBinding, 747 _authority: &Authority, 748 operation: OperationId, 749 ) -> Result<Option<HistoryEntry>, OperationError> { 750 Ok(Some( 751 Box::pin(super::inventory::installation::read_entry( 752 connection, input, crypto, operation, 753 )) 754 .await? 755 .ok_or(OperationError::RecoveryRequired)? 756 .into_history(), 757 )) 758 } 759 async fn history_family_7( 760 connection: &mut SqliteConnection, 761 input: &AttachmentInput, 762 crypto: &WorkspaceCrypto, 763 _binding: &WorkspaceBinding, 764 _authority: &Authority, 765 operation: OperationId, 766 ) -> Result<Option<HistoryEntry>, OperationError> { 767 Ok(Some( 768 Box::pin(super::inventory::abort::read_entry( 769 connection, input, crypto, operation, 770 )) 771 .await? 772 .ok_or(OperationError::RecoveryRequired)? 773 .into_history(), 774 )) 775 } 776 async fn history_family_8( 777 connection: &mut SqliteConnection, 778 input: &AttachmentInput, 779 crypto: &WorkspaceCrypto, 780 _binding: &WorkspaceBinding, 781 _authority: &Authority, 782 operation: OperationId, 783 ) -> Result<Option<HistoryEntry>, OperationError> { 784 Ok(Some( 785 Box::pin(super::issuance::unissued::read_entry( 786 connection, input, crypto, operation, 787 )) 788 .await? 789 .ok_or(OperationError::RecoveryRequired)? 790 .into_history(), 791 )) 792 } 793 async fn history_family_9( 794 connection: &mut SqliteConnection, 795 input: &AttachmentInput, 796 crypto: &WorkspaceCrypto, 797 _binding: &WorkspaceBinding, 798 _authority: &Authority, 799 operation: OperationId, 800 ) -> Result<Option<HistoryEntry>, OperationError> { 801 Ok(Some( 802 Box::pin(super::issuance::replay_admission::read_entry( 803 connection, input, crypto, operation, 804 )) 805 .await? 806 .ok_or(OperationError::RecoveryRequired)? 807 .into_history(), 808 )) 809 } 810 async fn history_family_10( 811 connection: &mut SqliteConnection, 812 input: &AttachmentInput, 813 crypto: &WorkspaceCrypto, 814 binding: &WorkspaceBinding, 815 _authority: &Authority, 816 operation: OperationId, 817 ) -> Result<Option<HistoryEntry>, OperationError> { 818 Ok(Some( 819 Box::pin(super::envelope::read_entry( 820 connection, input, crypto, binding, operation, 821 )) 822 .await? 823 .ok_or(OperationError::RecoveryRequired)? 824 .into_history(), 825 )) 826 } 827 828 // Keep the new large delivery reports outside the legacy history polling frame. 829 async fn delivery_history( 830 connection: &mut SqliteConnection, 831 input: &AttachmentInput, 832 crypto: &WorkspaceCrypto, 833 binding: &WorkspaceBinding, 834 authority: &Authority, 835 operation: OperationId, 836 family: Option<i64>, 837 ) -> Result<Option<HistoryEntry>, OperationError> { 838 match family { 839 Some(11) => Ok(Some( 840 Box::pin(super::delivery::attempt::read_entry( 841 connection, 842 input, 843 crypto, 844 binding, 845 authority.input.grant_id(), 846 operation, 847 )) 848 .await? 849 .ok_or(OperationError::RecoveryRequired)? 850 .into_history(), 851 )), 852 Some(12) => Ok(Some( 853 Box::pin(super::delivery::observation::read_entry( 854 connection, 855 input, 856 crypto, 857 binding, 858 authority.input.grant_id(), 859 operation, 860 )) 861 .await? 862 .ok_or(OperationError::RecoveryRequired)? 863 .into_history(), 864 )), 865 _ => Err(OperationError::RecoveryRequired), 866 } 867 } 868 pub(super) fn hash_optional(hash: &mut Sha256, value: Option<&[u8]>) -> Result<(), OperationError> { 869 hash.update([u8::from(value.is_some())]); 870 if let Some(bytes) = value { 871 if bytes.len() != 32 { 872 return Err(OperationError::RecoveryRequired); 873 } 874 hash.update(bytes); 875 } 876 Ok(()) 877 } 878 impl HistoryEntry { 879 pub fn hash(&self, hash: &mut Sha256) -> Result<(), OperationError> { 880 let header = &self.header; 881 hash.update(header.revision.get().to_be_bytes()); 882 hash.update(header.actor.participant().as_bytes()); 883 hash.update( 884 header 885 .actor 886 .grant_id() 887 .ok_or(OperationError::RecoveryRequired)? 888 .as_bytes(), 889 ); 890 hash.update(header.operation.as_bytes()); 891 hash.update(header.digest.as_bytes()); 892 hash.update(header.transaction.as_bytes()); 893 hash_optional(hash, header.pool.as_ref().map(|v| v.as_bytes().as_slice()))?; 894 hash.update(header.head.as_bytes()); 895 hash.update((self.protected.len() as u64).to_be_bytes()); 896 hash.update(&self.protected); 897 hash.update(header.family.code().to_be_bytes()); 898 hash_optional(hash, header.order.as_ref().map(|v| v.as_bytes().as_slice()))?; 899 hash_optional( 900 hash, 901 header 902 .related_operation 903 .as_ref() 904 .map(|v| v.as_bytes().as_slice()), 905 )?; 906 hash_optional( 907 hash, 908 header 909 .subject_grant 910 .as_ref() 911 .map(|v| v.as_bytes().as_slice()), 912 )?; 913 hash.update([header.parts]); 914 hash.update(self.parts_witness); 915 if let Some(deficit) = self.deficit { 916 if header.family != Family::Inventory { 917 return Err(OperationError::RecoveryRequired); 918 } 919 hash.update(b"D19"); 920 hash.update(deficit); 921 } 922 match (header.family, self.aborted) { 923 (Family::AbortedPreparation, Some(projection)) => { 924 hash.update(projection.digest(header.actor.participant(), header.operation)) 925 } 926 (Family::AbortedPreparation, None) | (_, Some(_)) => { 927 return Err(OperationError::RecoveryRequired); 928 } 929 (_, None) => {} 930 } 931 if let Some(preparation) = self.preparation { 932 if header.family != Family::Acceptance { 933 return Err(OperationError::RecoveryRequired); 934 } 935 hash.update(b"P13"); 936 hash.update(preparation); 937 } 938 match (header.family, self.signing) { 939 ( 940 Family::SigningClaim 941 | Family::SigningEvidence 942 | Family::OriginalUnissued 943 | Family::ReplayAdmission, 944 Some(projection), 945 ) => hash.update(projection.digest(header.actor.participant(), header.operation)), 946 ( 947 Family::SigningClaim 948 | Family::SigningEvidence 949 | Family::OriginalUnissued 950 | Family::ReplayAdmission, 951 None, 952 ) => { 953 return Err(OperationError::RecoveryRequired); 954 } 955 (_, Some(_)) => return Err(OperationError::RecoveryRequired), 956 (_, None) => {} 957 } 958 match (header.family, self.installation) { 959 (Family::Installation, Some(projection)) => { 960 hash.update(projection.digest(header.actor.participant(), header.operation)) 961 } 962 (Family::Installation, None) | (_, Some(_)) => { 963 return Err(OperationError::RecoveryRequired); 964 } 965 (_, None) => {} 966 } 967 match (header.family, self.envelope) { 968 (Family::Envelope, Some(projection @ super::envelope::Projection::Original { .. })) => { 969 hash.update(projection.digest(header.actor.participant(), header.operation)) 970 } 971 ( 972 Family::RewrapAdmission, 973 Some(projection @ super::envelope::Projection::Admission { .. }), 974 ) => hash.update(projection.digest(header.actor.participant(), header.operation)), 975 ( 976 Family::RewrappedEnvelope, 977 Some(projection @ super::envelope::Projection::Rewrap { .. }), 978 ) => hash.update(projection.digest(header.actor.participant(), header.operation)), 979 (Family::Envelope | Family::RewrapAdmission | Family::RewrappedEnvelope, _) 980 | (_, Some(_)) => { 981 return Err(OperationError::RecoveryRequired); 982 } 983 (_, None) => {} 984 } 985 match (header.family, self.delivery) { 986 ( 987 Family::DeliveryAttempt, 988 Some(projection @ super::delivery::Projection::Attempt { .. }), 989 ) 990 | ( 991 Family::DeliveryObservation, 992 Some(projection @ super::delivery::Projection::Observation { .. }), 993 ) => { 994 hash.update(projection.digest(header.actor.participant(), header.operation)); 995 } 996 (Family::DeliveryAttempt | Family::DeliveryObservation, _) | (_, Some(_)) => { 997 return Err(OperationError::RecoveryRequired); 998 } 999 (_, None) => {} 1000 } 1001 if (header.family == Family::SigningEvidence) != self.local_record.is_some() { 1002 return Err(OperationError::RecoveryRequired); 1003 } 1004 if self.movements.len() > 64 1005 || self 1006 .movements 1007 .windows(2) 1008 .any(|pair| pair[0].id >= pair[1].id) 1009 { 1010 return Err(OperationError::RecoveryRequired); 1011 } 1012 hash.update([self.movements.len() as u8]); 1013 for movement in &self.movements { 1014 hash.update(movement.id); 1015 hash.update(movement.pool.as_bytes()); 1016 hash.update(movement.grant.as_bytes()); 1017 hash.update((movement.protected.len() as u64).to_be_bytes()); 1018 hash.update(&movement.protected); 1019 } 1020 Ok(()) 1021 } 1022 } 1023 1024 #[cfg(test)] 1025 mod tests;