inventory.rs (50620B)
1 //! Owner-private inventory effects on the existing connection owner. 2 pub(in crate::workspace) mod abort; 3 pub(in crate::workspace) mod acceptance; 4 mod allocations; 5 pub(in crate::workspace::stock) mod backing; 6 mod changes; 7 pub(super) mod checkpoint; 8 mod codec; 9 pub(in crate::workspace::stock) mod deficit; 10 mod inspection; 11 pub(in crate::workspace) mod installation; 12 mod mapping; 13 mod plan; 14 use super::*; 15 use checkpoint::{MinimumProof, authenticate_minimum, authenticate_projection}; 16 pub(super) async fn grant_minimum( 17 connection: &mut SqliteConnection, 18 input: &AttachmentInput, 19 crypto: &WorkspaceCrypto, 20 binding: &WorkspaceBinding, 21 authority: &Authority, 22 minimum: radroots_storage::inventory::InventoryCheckpointRef, 23 ) -> Result<MinimumProof, WorkspaceError> { 24 authenticate_minimum(connection, input, crypto, binding, authority, minimum) 25 .await 26 .map_err(|_| WorkspaceError::RecoveryRequired) 27 } 28 use codec::{Movement, MovementKind, OperationWire, decode_operation, encode_operation}; 29 use plan::{plan_effect, record_version}; 30 use radroots_domain::{ 31 CheckpointDigest, CommandDigest, OperationId, PoolId, UnixSeconds, 32 stock::{PhysicalBalances, PoolBalances, PoolSnapshot}, 33 }; 34 use radroots_storage::{ 35 command::{CommitAttempt, OperationError, protected::same_binding}, 36 inventory::{InventoryOutcome, InventoryReceipt, InventoryRequest}, 37 }; 38 use serde_json::value::RawValue; 39 use sha2::{Digest, Sha256}; 40 use sqlx::Row; 41 42 pub(super) async fn check_head( 43 connection: &mut SqliteConnection, 44 checkpoint: InventoryCheckpoint, 45 ) -> Result<(), WorkspaceError> { 46 super::issuance::check_counts(connection).await?; 47 let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") 48 .fetch_one(&mut *connection) 49 .await 50 .map_err(|_| WorkspaceError::RecoveryRequired)?; 51 if catalog >= 19 { 52 let invalid: i64 = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM stock_deficits d LEFT JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.operation_id WHERE o.family IS NULL OR o.family!=0) OR EXISTS(SELECT 1 FROM pragma_foreign_key_check('stock_deficits'))") 53 .fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; 54 if invalid != 0 { 55 return Err(WorkspaceError::RecoveryRequired); 56 } 57 } 58 if catalog >= 20 { 59 let invalid: i64 = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM stock_obligation_changes d LEFT JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.operation_id WHERE o.family IS NULL OR o.family!=6) OR EXISTS(SELECT 1 FROM pragma_foreign_key_check('stock_obligation_changes'))").fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; 60 if invalid != 0 { 61 return Err(WorkspaceError::RecoveryRequired); 62 } 63 } 64 if let Some(expected) = checkpoint.orders { 65 let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_orders") 66 .fetch_one(&mut *connection) 67 .await 68 .map_err(|_| WorkspaceError::RecoveryRequired)?; 69 if count != expected.get() as i64 { 70 return Err(WorkspaceError::RecoveryRequired); 71 } 72 } 73 let row=sqlx::query("SELECT count(*),coalesce(max(revision),0),coalesce(sum(CASE WHEN revision=? AND chain_head=? THEN 1 ELSE 0 END),0) FROM stock_operations") 74 .bind(checkpoint.revision.get() as i64).bind(checkpoint.head.map(|id|id.as_bytes().to_vec())).fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; 75 let count: i64 = row 76 .try_get(0) 77 .map_err(|_| WorkspaceError::RecoveryRequired)?; 78 let max: i64 = row 79 .try_get(1) 80 .map_err(|_| WorkspaceError::RecoveryRequired)?; 81 let matched: i64 = row 82 .try_get(2) 83 .map_err(|_| WorkspaceError::RecoveryRequired)?; 84 let pools: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_pools") 85 .fetch_one(&mut *connection) 86 .await 87 .map_err(|_| WorkspaceError::RecoveryRequired)?; 88 let movements: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_movements") 89 .fetch_one(&mut *connection) 90 .await 91 .map_err(|_| WorkspaceError::RecoveryRequired)?; 92 if let Some(expected) = checkpoint.mappings { 93 let actual: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_mappings") 94 .fetch_one(&mut *connection) 95 .await 96 .map_err(|_| WorkspaceError::RecoveryRequired)?; 97 if actual != expected.get() as i64 { 98 return Err(WorkspaceError::RecoveryRequired); 99 } 100 } 101 if pools != checkpoint.pools.get() as i64 || movements != checkpoint.movements.get() as i64 { 102 return Err(WorkspaceError::RecoveryRequired); 103 } 104 if count != checkpoint.revision.get() as i64 105 || max != count 106 || matched != i64::from(checkpoint.head.is_some()) 107 { 108 return Err(WorkspaceError::RecoveryRequired); 109 } 110 Ok(()) 111 } 112 pub(super) struct Access { 113 pub(super) authority: Authority, 114 pub(super) record: StockRecord, 115 pub(super) root: Vec<u8>, 116 pub(super) grant: Vec<u8>, 117 pub(super) current: WorkspaceBinding, 118 pub(super) minimum_proof: MinimumProof, 119 identity_proof: Option<MinimumProof>, 120 projection_proof: Option<MinimumProof>, 121 mapping_read: Option<mapping::MappingRead>, 122 } 123 pub(in crate::workspace) struct Turn<'a> { 124 pub connection: &'a mut SqliteConnection, 125 pub namespace: &'a Namespace, 126 pub selected: &'a AttachmentInput, 127 pub crypto: &'a WorkspaceCrypto, 128 pub clock: &'a dyn WorkspaceClock, 129 pub uncertain: &'a mut bool, 130 } 131 impl Access { 132 /// Rechecks authenticated store state inside the caller's actual SQL 133 /// transaction. Family-specific permissions and deadlines remain separate. 134 pub(super) async fn confirm( 135 &self, 136 connection: &mut SqliteConnection, 137 namespace: &Namespace, 138 clock: &dyn WorkspaceClock, 139 proof: &AttachmentProof, 140 ) -> Result<WorkspaceBinding, OperationError> { 141 namespace.validate()?; 142 super::unchanged( 143 connection, 144 self.current.input(), 145 self.authority.catalog, 146 &self.root, 147 &self.grant, 148 ) 149 .await?; 150 if let Some(state) = self.authority.authorization { 151 grants::check_state(connection, state).await?; 152 } 153 check_head( 154 connection, 155 self.authority 156 .inventory 157 .ok_or(OperationError::UnsupportedOperation)?, 158 ) 159 .await?; 160 self.minimum_proof.confirm(connection).await?; 161 if let Some(identity) = &self.identity_proof { 162 identity.confirm(connection).await?; 163 } 164 let current = self 165 .record 166 .authenticate(self.current.input(), proof, clock.now()?)?; 167 same_binding(&self.current, ¤t)?; 168 if current.observed_at() < self.current.observed_at() { 169 return Err(WorkspaceError::Unavailable.into()); 170 } 171 namespace.validate()?; 172 Ok(current) 173 } 174 } 175 impl Turn<'_> { 176 pub(super) async fn access( 177 &mut self, 178 binding: &WorkspaceBinding, 179 minimum: radroots_storage::inventory::InventoryCheckpointRef, 180 proof: &AttachmentProof, 181 ) -> Result<Access, OperationError> { 182 if *self.uncertain { 183 return Err(OperationError::RecoveryRequired); 184 } 185 self.namespace.validate()?; 186 if !SellerAuthoritySelection::from_attachment(self.selected) 187 .matches_attachment(binding.input()) 188 { 189 return Err(OperationError::Unauthorized); 190 } 191 let (authority, record, root, grant) = 192 super::read(self.connection, binding.input(), self.crypto).await?; 193 let current = record.authenticate(binding.input(), proof, self.clock.now()?)?; 194 if current.scope() != WorkspaceScope::SellerStockOwner { 195 return Err(OperationError::Unauthorized); 196 } 197 same_binding(binding, ¤t)?; 198 if current.observed_at() < binding.observed_at() { 199 return Err(WorkspaceError::Unavailable.into()); 200 } 201 if authority.authorization != minimum.authorization() { 202 return Err(WorkspaceError::StaleCheckpoint.into()); 203 } 204 let current = if let Some(state) = authority.authorization { 205 current.with_stock_authorization(state)? 206 } else { 207 current 208 }; 209 if authority.inventory.is_none() { 210 return Err(OperationError::UnsupportedOperation); 211 } 212 213 let mut minimum_proof = Box::pin(authenticate_minimum( 214 self.connection, 215 self.selected, 216 self.crypto, 217 ¤t, 218 &authority, 219 minimum, 220 )) 221 .await?; 222 self.namespace.validate()?; 223 if authority.catalog >= 19 && minimum.revision().get() != 0 { 224 let genesis = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( 225 self.selected.authority(), 226 Sequence::new(0).map_err(|_| OperationError::RecoveryRequired)?, 227 None, 228 )?; 229 minimum_proof = Box::pin(authenticate_minimum( 230 self.connection, 231 self.selected, 232 self.crypto, 233 ¤t, 234 &authority, 235 genesis, 236 )) 237 .await?; 238 } 239 Ok(Access { 240 authority, 241 record, 242 root, 243 grant, 244 current, 245 minimum_proof, 246 identity_proof: None, 247 projection_proof: None, 248 mapping_read: None, 249 }) 250 } 251 pub async fn create( 252 &mut self, 253 request: InventoryRequest, 254 proof: AttachmentProof, 255 ) -> Result<InventoryOutcome, OperationError> { 256 let mut access = self 257 .access(request.binding(), request.minimum_checkpoint(), &proof) 258 .await?; 259 access 260 .record 261 .require(StockAction::ReadOperations, request.command().pool_id())?; 262 if let Some(input) = request.command().mapping_input() { 263 mapping::require(&access, input.key())?; 264 } 265 let context = request.command().context(); 266 let operation = context.operation_id(); 267 let digest = request.command().digest(); 268 // Retained identity precedes every fresh deadline or pool-existence check. 269 let retained = read_operation( 270 self.connection, 271 self.selected, 272 self.crypto, 273 request.binding(), 274 operation, 275 ) 276 .await?; 277 access.identity_proof = Some( 278 checkpoint::authenticate_identity( 279 self.connection, 280 self.selected, 281 self.crypto, 282 &access.current, 283 &access.authority, 284 checkpoint::IdentityTarget::Operation( 285 operation, 286 retained.as_ref().map(Retained::identity).transpose()?, 287 ), 288 ) 289 .await?, 290 ); 291 if let Some(retained) = retained { 292 if retained.digest != digest { 293 return Err(OperationError::IdempotencyConflict); 294 } 295 self.confirm(&access, &proof, Some(&retained), None, None, None) 296 .await?; 297 return Ok(InventoryOutcome::Committed(Box::new(retained.receipt))); 298 } 299 if request.replay_only() { 300 return Err(OperationError::RecoveryRequired); 301 } 302 if request.command().mapping_input().is_none() { 303 access.record.require( 304 match request.command().kind() { 305 radroots_storage::inventory::InventoryCommandKind::MapOption => { 306 return Err(OperationError::RecoveryRequired); 307 } 308 radroots_storage::inventory::InventoryCommandKind::CreatePool => { 309 StockAction::CreatePool 310 } 311 radroots_storage::inventory::InventoryCommandKind::AddStock => { 312 StockAction::AddStock 313 } 314 radroots_storage::inventory::InventoryCommandKind::RemoveStock => { 315 StockAction::RemoveStock 316 } 317 radroots_storage::inventory::InventoryCommandKind::SpoilStock => { 318 StockAction::SpoilStock 319 } 320 }, 321 request.command().pool_id(), 322 )?; 323 } 324 // An original captured command may be replayed under a replacement grant, 325 // but a new effect must have been captured under this current grant. 326 if request.command().context().actor() != access.current.actor() { 327 return Err(OperationError::Unauthorized); 328 } 329 if access.current.observed_at() < request.binding().observed_at() { 330 return Err(WorkspaceError::Unavailable.into()); 331 } 332 if access.current.observed_at() >= context.not_after() { 333 return Err(OperationError::DeadlineExceeded); 334 } 335 let catalog = access.authority.version(); 336 if catalog < 3 && request.command().correction_input().is_some() { 337 return Err(OperationError::UnsupportedOperation); 338 } 339 let existing = read_pool( 340 self.connection, 341 self.selected, 342 self.crypto, 343 request.command().pool_id(), 344 ) 345 .await?; 346 let before = existing.as_ref().map(|v| v.pool); 347 access.projection_proof = Some( 348 authenticate_projection( 349 self.connection, 350 self.selected, 351 self.crypto, 352 &access.current, 353 &access.authority, 354 request.command().pool_id(), 355 before, 356 ) 357 .await?, 358 ); 359 let losses = if catalog >= 19 { 360 Box::pin(deficit::plan( 361 self.connection, 362 self.selected, 363 self.crypto, 364 request.command(), 365 before, 366 access 367 .authority 368 .inventory 369 .ok_or(OperationError::UnsupportedOperation)? 370 .revision 371 .get() 372 .checked_add(1) 373 .ok_or(WorkspaceError::Capacity)?, 374 )) 375 .await? 376 } else { 377 Vec::new() 378 }; 379 let (pool, quantity, movement_kind) = 380 plan_effect(request.command(), before, deficit::quantity(&losses)?)?; 381 let mapping = mapping::prepare(self, &access, &request, pool).await?; 382 let label = if let Some(input) = request.command().creation_input() { 383 input.label() 384 } else { 385 existing 386 .as_ref() 387 .ok_or(OperationError::StaleState)? 388 .view 389 .label() 390 }; 391 let transaction = TransactionId::from_bytes(super::super::random()?); 392 let movement = if quantity == radroots_domain::stock::StockTicks::ZERO { 393 None 394 } else { 395 Some(super::super::random()?) 396 }; 397 let checkpoint = access 398 .authority 399 .inventory 400 .ok_or(OperationError::UnsupportedOperation)?; 401 let revision = Sequence::new( 402 checkpoint 403 .revision 404 .get() 405 .checked_add(1) 406 .ok_or(WorkspaceError::Capacity)?, 407 ) 408 .map_err(|_| WorkspaceError::Capacity)?; 409 let head = chain_head(ChainInput { 410 previous: checkpoint.head, 411 revision, 412 binding: request.binding(), 413 operation, 414 digest, 415 transaction, 416 pool, 417 movement, 418 })?; 419 let attempt = CommitAttempt::new( 420 self.selected.workspace_id(), 421 operation, 422 digest, 423 Some(transaction), 424 ); 425 let receipt_checkpoint = 426 radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( 427 self.selected.authority(), 428 revision, 429 Some(head), 430 )? 431 .with_optional_authorization(access.authority.authorization); 432 let receipt = if let Some(mapping) = &mapping { 433 InventoryReceipt::from_committed_mapping( 434 attempt, 435 pool, 436 mapping.effect.after, 437 receipt_checkpoint, 438 )? 439 } else { 440 InventoryReceipt::from_committed_store( 441 attempt, 442 request.command().kind(), 443 pool, 444 receipt_checkpoint, 445 )? 446 }; 447 let receipt = 448 receipt.with_deficits(losses.iter().map(|loss| loss.metadata(pool.id())).collect())?; 449 let protected_pool = if mapping.is_some() { 450 None 451 } else { 452 Some( 453 self.crypto 454 .seal_stock_record( 455 self.selected, 456 "pool", 457 pool.id().as_bytes(), 458 &encode(&PoolWire { 459 version: 1, 460 label, 461 pool, 462 })?, 463 ) 464 .await?, 465 ) 466 }; 467 let protected_movement = if let Some(id) = movement { 468 Some( 469 self.crypto 470 .seal_stock_record_for_catalog( 471 self.selected, 472 "movement", 473 &id, 474 catalog, 475 &encode(&Movement { 476 version: record_version(catalog)?, 477 operation, 478 digest, 479 pool: pool.id(), 480 quantity, 481 kind: movement_kind, 482 })?, 483 ) 484 .await?, 485 ) 486 } else { 487 None 488 }; 489 let command: &RawValue = serde_json::from_slice(request.command().protected_wire()) 490 .map_err(|_| OperationError::InvalidCommand)?; 491 let operation_body = encode_operation( 492 &OperationWire { 493 version: record_version(catalog)?, 494 before: if catalog >= 3 { Some(before) } else { None }, 495 selection: request.binding().input(), 496 scope: request.binding().scope(), 497 principal: request.binding().principal_id(), 498 grant_revision: request.binding().grant_revision(), 499 grant_expires_at: request.binding().expires_at(), 500 observed_at: request.binding().observed_at(), 501 minimum_revision: request.minimum_checkpoint().revision(), 502 minimum_head: request.minimum_checkpoint().head(), 503 transaction, 504 revision, 505 previous_head: checkpoint.head, 506 head, 507 command, 508 pool, 509 movement, 510 }, 511 catalog, 512 access.authority.authorization, 513 mapping.as_ref().map(|value| value.effect), 514 &losses, 515 )?; 516 let framed = if matches!(catalog, 7..=20) { 517 Some( 518 super::ledger::prepare( 519 self.crypto, 520 self.selected, 521 super::ledger::Header { 522 version: 5, 523 family: super::ledger::Family::Inventory, 524 namespace: SellerAuthoritySelection::from_attachment(self.selected), 525 actor: request.binding().actor(), 526 operation, 527 digest, 528 transaction, 529 revision, 530 previous: checkpoint.head, 531 head, 532 pool: Some(pool.id()), 533 order: None, 534 related_operation: None, 535 subject_grant: None, 536 bytes: 0, 537 parts: 0, 538 body_digest: [0; 32], 539 }, 540 &operation_body, 541 ) 542 .await?, 543 ) 544 } else { 545 None 546 }; 547 let protected_operation = if let Some(framed) = &framed { 548 framed.protected.clone() 549 } else { 550 self.crypto 551 .seal_stock_record_for_catalog( 552 self.selected, 553 "operation", 554 operation.as_bytes(), 555 catalog, 556 &operation_body, 557 ) 558 .await? 559 }; 560 access.authority.inventory = Some(InventoryCheckpoint { 561 orders: checkpoint.orders, 562 mappings: checkpoint 563 .mappings 564 .map(|count| { 565 Sequence::new( 566 count 567 .get() 568 .checked_add(u64::from( 569 mapping 570 .as_ref() 571 .is_some_and(|value| value.effect.before.is_none()), 572 )) 573 .ok_or(WorkspaceError::Capacity)?, 574 ) 575 .map_err(|_| WorkspaceError::Capacity) 576 }) 577 .transpose()?, 578 revision, 579 head: Some(head), 580 pools: Sequence::new( 581 checkpoint 582 .pools 583 .get() 584 .checked_add(u64::from(before.is_none())) 585 .ok_or(WorkspaceError::Capacity)?, 586 ) 587 .map_err(|_| WorkspaceError::Capacity)?, 588 movements: Sequence::new( 589 checkpoint 590 .movements 591 .get() 592 .checked_add(u64::from(movement.is_some())) 593 .ok_or(WorkspaceError::Capacity)?, 594 ) 595 .map_err(|_| WorkspaceError::Capacity)?, 596 }); 597 let root = self 598 .crypto 599 .seal_stock_root(self.selected, catalog, &access.authority.encode()?) 600 .await?; 601 self.namespace.validate()?; 602 let mut tx = self 603 .connection 604 .begin_with("BEGIN IMMEDIATE") 605 .await 606 .map_err(|_| OperationError::StorageFailure)?; 607 let changed:Result<(),OperationError>=async { 608 super::unchanged(&mut tx,access.current.input(),access.authority.version(),&access.root,&access.grant).await?; 609 if let Some(state)=access.authority.authorization { grants::check_state(&mut tx,state).await?; } 610 check_head(&mut tx,checkpoint).await?; 611 access.minimum_proof.confirm(&mut tx).await?; 612 if let Some(identity)=&access.identity_proof {identity.confirm(&mut tx).await?;} 613 if let Some(proof)=&access.projection_proof {proof.confirm(&mut tx).await?;} 614 let current=access.record.authenticate(request.binding().input(),&proof,self.clock.now()?)?; 615 same_binding(request.binding(),¤t)?; 616 if current.observed_at()<access.current.observed_at() {return Err(WorkspaceError::Unavailable.into());} 617 if current.observed_at()>=context.not_after() {return Err(OperationError::DeadlineExceeded);} 618 self.namespace.validate()?; 619 let absent:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=?").bind(request.binding().actor().participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 620 if absent!=0 {return Err(OperationError::StaleState);} 621 if let Some(mapping)=&mapping { 622 let original=existing.as_ref().ok_or(OperationError::RecoveryRequired)?; 623 let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=? AND revision=? AND protected=?").bind(pool.id().as_bytes().as_slice()).bind(pool.version().get() as i64).bind(&original.protected).fetch_one(&mut *tx).await.map_err(|_|OperationError::RecoveryRequired)?; 624 if count!=1 {return Err(OperationError::RecoveryRequired);} 625 mapping.apply(&mut tx).await?; 626 } else if let Some(before)=before { 627 let original=existing.as_ref().ok_or(OperationError::RecoveryRequired)?; 628 let updated=sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=? AND revision=? AND protected=?") 629 .bind(pool.version().get() as i64).bind(protected_pool).bind(pool.id().as_bytes().as_slice()).bind(before.version().get() as i64).bind(&original.protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 630 if updated.rows_affected()!=1 {return Err(OperationError::StaleState);} 631 } else { 632 let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=?").bind(pool.id().as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 633 if count!=0 {return Err(OperationError::StaleState);} 634 sqlx::query("INSERT INTO stock_pools(pool_id,revision,protected) VALUES(?,?,?)").bind(pool.id().as_bytes().as_slice()).bind(pool.version().get() as i64).bind(protected_pool).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 635 } 636 sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected) VALUES(?,?,?,?,?,?,?,?,?)") 637 .bind(request.binding().actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(digest.as_bytes().as_slice()).bind(transaction.as_bytes().as_slice()).bind(pool.id().as_bytes().as_slice()).bind(revision.get() as i64).bind(head.as_bytes().as_slice()).bind(protected_operation).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 638 if let Some(framed)=&framed {framed.insert_parts(&mut tx,request.binding().actor(),operation).await?;} 639 if catalog >= 19 { deficit::insert(&mut tx, request.binding().actor().participant(), operation, pool.id(), &losses).await?; } 640 if let (Some(id),Some(protected))=(movement,protected_movement) { 641 sqlx::query("INSERT INTO stock_movements(movement_id,actor,grant_id,operation_id,pool_id,protected) VALUES(?,?,?,?,?,?)").bind(id.as_slice()).bind(request.binding().actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(pool.id().as_bytes().as_slice()).bind(protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 642 } 643 let changed=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(root).bind(&access.root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 644 if changed.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);}self.namespace.validate()?;Ok(()) 645 }.await; 646 if let Err(error) = changed { 647 if tx.rollback().await.is_err() { 648 *self.uncertain = true; 649 return Ok(InventoryOutcome::Unknown(attempt)); 650 } 651 return Err(error); 652 } 653 if tx.commit().await.is_err() { 654 *self.uncertain = true; 655 return Ok(InventoryOutcome::Unknown(attempt)); 656 } 657 Ok(InventoryOutcome::Committed(Box::new(receipt))) 658 } 659 async fn confirm( 660 &mut self, 661 access: &Access, 662 proof: &AttachmentProof, 663 operation: Option<&Retained>, 664 pool: Option<&RetainedPool>, 665 absent_operation: Option<OperationId>, 666 absent_pool: Option<PoolId>, 667 ) -> Result<(), OperationError> { 668 let mut tx = self 669 .connection 670 .begin_with("BEGIN IMMEDIATE") 671 .await 672 .map_err(|_| OperationError::StorageFailure)?; 673 let checked:Result<(),OperationError>=async { 674 self.namespace.validate()?; 675 super::unchanged(&mut tx,access.current.input(),access.authority.version(),&access.root,&access.grant).await?; 676 if let Some(state)=access.authority.authorization { grants::check_state(&mut tx,state).await?; } 677 check_head(&mut tx,access.authority.inventory.ok_or(OperationError::UnsupportedOperation)?).await?; 678 access.minimum_proof.confirm(&mut tx).await?; 679 if let Some(identity)=&access.identity_proof {identity.confirm(&mut tx).await?;} 680 if let Some(proof)=&access.projection_proof {proof.confirm(&mut tx).await?;} 681 if let Some(mapping)=&access.mapping_read {mapping.confirm(&mut tx).await?;} 682 let current=access.record.authenticate(access.current.input(),proof,self.clock.now()?)?; 683 same_binding(&access.current,¤t)?; 684 if current.observed_at()<access.current.observed_at() {return Err(WorkspaceError::Unavailable.into());} 685 if let Some(operation)=absent_operation {let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=?").bind(current.actor().participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?;if count!=0 {return Err(OperationError::RecoveryRequired);}} 686 if let Some(id)=absent_pool {let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=?").bind(id.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?;if count!=0 {return Err(OperationError::RecoveryRequired);}} 687 if let Some(retained)=operation { 688 let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=? AND protected=?").bind(current.actor().participant().as_bytes().as_slice()).bind(retained.receipt.attempt().operation_id().as_bytes().as_slice()).bind(&retained.protected).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 689 if count!=1 {return Err(OperationError::RecoveryRequired);} 690 if let Some((header,parts))=&retained.frame { 691 super::ledger::confirm_header(&mut tx,header,&retained.protected).await?; 692 super::ledger::confirm_parts(&mut tx,header.actor,header.operation,*parts,header.parts).await?; 693 } 694 let movement_count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?").bind(current.actor().participant().as_bytes().as_slice()).bind(retained.receipt.attempt().operation_id().as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 695 if movement_count!=i64::from(retained.movement.is_some()) {return Err(OperationError::RecoveryRequired);} 696 if let (Some(id),Some(protected))=(retained.movement,retained.movement_protected.as_ref()) { 697 let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE movement_id=? AND protected=?").bind(id.as_slice()).bind(protected).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 698 if count!=1 {return Err(OperationError::RecoveryRequired);} 699 } 700 701 } 702 if let Some(pool)=pool {let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=? AND revision=? AND protected=?").bind(pool.pool.id().as_bytes().as_slice()).bind(pool.pool.version().get() as i64).bind(&pool.protected).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?;if count!=1 {return Err(OperationError::RecoveryRequired);}} 703 Ok(()) 704 }.await; 705 if tx.rollback().await.is_err() { 706 *self.uncertain = true; 707 return Err(OperationError::RecoveryRequired); 708 } 709 checked 710 } 711 pub async fn creation( 712 &mut self, 713 binding: WorkspaceBinding, 714 minimum: radroots_storage::inventory::InventoryCheckpointRef, 715 operation: OperationId, 716 digest: Option<CommandDigest>, 717 proof: AttachmentProof, 718 ) -> Result<Option<InventoryReceipt>, OperationError> { 719 let mut access = self.access(&binding, minimum, &proof).await?; 720 let result = read_operation( 721 self.connection, 722 self.selected, 723 self.crypto, 724 &binding, 725 operation, 726 ) 727 .await?; 728 access.identity_proof = Some( 729 checkpoint::authenticate_identity( 730 self.connection, 731 self.selected, 732 self.crypto, 733 &access.current, 734 &access.authority, 735 checkpoint::IdentityTarget::Operation( 736 operation, 737 result.as_ref().map(Retained::identity).transpose()?, 738 ), 739 ) 740 .await?, 741 ); 742 if !access.record.allows_action(StockAction::ReadOperations) { 743 return Err(OperationError::Unauthorized); 744 } 745 if let Some(retained) = &result { 746 access 747 .record 748 .require(StockAction::ReadOperations, retained.receipt.pool().id())?; 749 if let Some(mapping) = retained.receipt.mapping() { 750 mapping::require(&access, mapping.key())?; 751 } 752 } 753 if let Some(retained) = &result 754 && digest.is_some_and(|d| d != retained.digest) 755 { 756 return Err(OperationError::IdempotencyConflict); 757 } 758 self.confirm( 759 &access, 760 &proof, 761 result.as_ref(), 762 None, 763 result.is_none().then_some(operation), 764 None, 765 ) 766 .await?; 767 Ok(result.map(|v| v.receipt)) 768 } 769 pub async fn option_mapping( 770 &mut self, 771 binding: WorkspaceBinding, 772 minimum: radroots_storage::inventory::InventoryCheckpointRef, 773 key: radroots_domain::stock::OptionMappingKey, 774 proof: AttachmentProof, 775 ) -> Result<Option<radroots_domain::stock::OptionPoolMapping>, OperationError> { 776 let mut access = self.access(&binding, minimum, &proof).await?; 777 mapping::require(&access, key)?; 778 let retained = mapping::read(self.connection, self.selected, self.crypto, key).await?; 779 let result = retained.as_ref().map(|value| value.value); 780 let witness = checkpoint::authenticate_mapping_projection( 781 self.connection, 782 self.selected, 783 self.crypto, 784 &access.current, 785 &access.authority, 786 key, 787 result, 788 ) 789 .await?; 790 access.mapping_read = Some(mapping::MappingRead { 791 key, 792 retained, 793 proof: witness, 794 }); 795 self.confirm(&access, &proof, None, None, None, None) 796 .await?; 797 Ok(result) 798 } 799 pub async fn pool( 800 &mut self, 801 binding: WorkspaceBinding, 802 minimum: radroots_storage::inventory::InventoryCheckpointRef, 803 id: PoolId, 804 proof: AttachmentProof, 805 ) -> Result<Option<radroots_domain::stock::PoolView>, OperationError> { 806 let mut access = self.access(&binding, minimum, &proof).await?; 807 access.record.require(StockAction::ReadPools, id)?; 808 let result = read_pool(self.connection, self.selected, self.crypto, id).await?; 809 access.projection_proof = Some( 810 authenticate_projection( 811 self.connection, 812 self.selected, 813 self.crypto, 814 &access.current, 815 &access.authority, 816 id, 817 result.as_ref().map(|v| v.pool), 818 ) 819 .await?, 820 ); 821 self.confirm( 822 &access, 823 &proof, 824 None, 825 result.as_ref(), 826 None, 827 result.is_none().then_some(id), 828 ) 829 .await?; 830 Ok(result.map(|v| v.view)) 831 } 832 } 833 struct RetainedPool { 834 view: radroots_domain::stock::PoolView, 835 pool: PoolSnapshot, 836 protected: Vec<u8>, 837 } 838 #[derive(Serialize)] 839 struct PoolWire<'a> { 840 version: u8, 841 label: &'a str, 842 pool: PoolSnapshot, 843 } 844 #[derive(Deserialize)] 845 #[serde(deny_unknown_fields)] 846 struct PoolDecode { 847 version: u8, 848 label: String, 849 pool: PoolSnapshot, 850 } 851 async fn read_pool( 852 connection: &mut SqliteConnection, 853 input: &AttachmentInput, 854 crypto: &WorkspaceCrypto, 855 id: PoolId, 856 ) -> Result<Option<RetainedPool>, OperationError> { 857 let row=sqlx::query("SELECT revision,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_pools WHERE pool_id=?").bind(id.as_bytes().as_slice()).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?; 858 let Some(row) = row else { return Ok(None) }; 859 let revision: i64 = row 860 .try_get(0) 861 .map_err(|_| OperationError::RecoveryRequired)?; 862 let protected: Vec<u8> = row 863 .try_get::<Option<Vec<u8>>, _>(1) 864 .map_err(|_| OperationError::RecoveryRequired)? 865 .ok_or(OperationError::RecoveryRequired)?; 866 let clear = crypto 867 .open_stock_record(input, "pool", id.as_bytes(), &protected) 868 .await?; 869 let decoded: PoolDecode = clear 870 .expose_secret(|bytes| super::closed_record(bytes)) 871 .map_err(|_| OperationError::RecoveryRequired)?; 872 if decoded.version != 1 873 || decoded.label.len() > 160 874 || decoded.label.chars().any(char::is_control) 875 || decoded.pool.id() != id 876 || revision <= 0 877 || decoded.pool.version().get() != revision as u64 878 { 879 return Err(OperationError::RecoveryRequired); 880 } 881 let view = radroots_domain::stock::PoolView::new(&decoded.label, decoded.pool) 882 .map_err(|_| OperationError::RecoveryRequired)?; 883 Ok(Some(RetainedPool { 884 view, 885 pool: decoded.pool, 886 protected, 887 })) 888 } 889 pub(super) struct Retained { 890 pub(super) deficit_projection: Option<[u8; 32]>, 891 pub(super) frame: Option<(super::ledger::Header, [u8; 32])>, 892 pub(super) original_grant: GrantId, 893 pub(super) previous_head: Option<CheckpointDigest>, 894 pub(super) movement: Option<[u8; 32]>, 895 pub(super) movement_protected: Option<Vec<u8>>, 896 pub(super) receipt: InventoryReceipt, 897 pub(super) digest: CommandDigest, 898 pub(super) protected: Vec<u8>, 899 } 900 impl Retained { 901 fn identity(&self) -> Result<checkpoint::EntryIdentity, OperationError> { 902 Ok(checkpoint::EntryIdentity { 903 operation: self.receipt.attempt().operation_id(), 904 revision: self.receipt.checkpoint().revision(), 905 head: self 906 .receipt 907 .checkpoint() 908 .head() 909 .ok_or(OperationError::RecoveryRequired)?, 910 protected_digest: Sha256::digest(&self.protected).into(), 911 }) 912 } 913 } 914 pub(super) async fn read_operation( 915 connection: &mut SqliteConnection, 916 input: &AttachmentInput, 917 crypto: &WorkspaceCrypto, 918 binding: &WorkspaceBinding, 919 operation: OperationId, 920 ) -> Result<Option<Retained>, OperationError> { 921 let row=sqlx::query("SELECT CASE WHEN length(command_digest)=32 THEN command_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(pool_id)=32 THEN pool_id END,revision,CASE WHEN length(chain_head)=32 THEN chain_head END,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END,grant_id FROM stock_operations WHERE actor=? AND operation_id=?") 922 .bind(binding.actor().participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; 923 let Some(row) = row else { return Ok(None) }; 924 let protected: Vec<u8> = row 925 .try_get::<Option<Vec<u8>>, _>(5) 926 .map_err(|_| OperationError::RecoveryRequired)? 927 .ok_or(OperationError::RecoveryRequired)?; 928 let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") 929 .fetch_one(&mut *connection) 930 .await 931 .map_err(|_| OperationError::RecoveryRequired)?; 932 let (frame, request, decoded) = if matches!(catalog, 7..=20) { 933 let retained = super::ledger::read(connection, input, crypto, operation) 934 .await? 935 .ok_or(OperationError::RecoveryRequired)?; 936 if retained.protected != protected { 937 return Err(OperationError::RecoveryRequired); 938 } 939 if retained.header.family != super::ledger::Family::Inventory { 940 return Err(OperationError::IdempotencyConflict); 941 } 942 let (request, decoded) = decode_operation(retained.body.as_slice(), catalog)?; 943 if retained.header.actor != request.binding().actor() 944 || retained.header.previous != decoded.previous_head 945 { 946 return Err(OperationError::RecoveryRequired); 947 } 948 ( 949 Some((retained.header, retained.parts_witness)), 950 request, 951 decoded, 952 ) 953 } else { 954 let clear = crypto 955 .open_stock_record_for_catalog( 956 input, 957 "operation", 958 operation.as_bytes(), 959 catalog, 960 &protected, 961 ) 962 .await?; 963 let (request, decoded) = clear.expose_secret(|bytes| decode_operation(bytes, catalog))?; 964 (None, request, decoded) 965 }; 966 if !SellerAuthoritySelection::from_attachment(request.binding().input()) 967 .matches_attachment(binding.input()) 968 || request.binding().actor().participant() != binding.actor().participant() 969 { 970 return Err(OperationError::RecoveryRequired); 971 } 972 let digest = request.command().digest(); 973 let original_grant: Vec<u8> = row 974 .try_get(6) 975 .map_err(|_| OperationError::RecoveryRequired)?; 976 if original_grant != request.binding().input().grant_id().as_bytes() { 977 return Err(OperationError::RecoveryRequired); 978 } 979 let deficit_projection = if catalog >= 19 { 980 let expected = Box::pin(deficit::plan( 981 connection, 982 input, 983 crypto, 984 request.command(), 985 decoded.before, 986 decoded.revision.get(), 987 )) 988 .await 989 .map_err(|_| OperationError::RecoveryRequired)?; 990 if expected != decoded.losses { 991 return Err(OperationError::RecoveryRequired); 992 } 993 let digest = deficit::digest(decoded.pool.id(), &decoded.losses)?; 994 if deficit::raw_projection( 995 connection, 996 binding.actor().participant().as_bytes(), 997 operation.as_bytes(), 998 ) 999 .await? 1000 != digest 1001 { 1002 return Err(OperationError::RecoveryRequired); 1003 } 1004 Some(digest) 1005 } else { 1006 None 1007 }; 1008 let (planned, quantity, movement_kind) = plan_effect( 1009 request.command(), 1010 decoded.before, 1011 deficit::quantity(&decoded.losses)?, 1012 ) 1013 .map_err(|_| OperationError::RecoveryRequired)?; 1014 let expected_mapping = mapping::effect( 1015 request.command(), 1016 decoded.pool, 1017 decoded.mapping.and_then(|value| value.before), 1018 ) 1019 .map_err(|_| OperationError::RecoveryRequired)?; 1020 if expected_mapping != decoded.mapping || (catalog < 5 && decoded.mapping.is_some()) { 1021 return Err(OperationError::RecoveryRequired); 1022 } 1023 if decoded.version != record_version(catalog)? 1024 || request.command().context().operation_id() != operation 1025 || decoded.revision.get() == 0 1026 || (decoded.revision.get() == 1) != decoded.previous_head.is_none() 1027 || decoded.pool != planned 1028 || (catalog == 2 && decoded.before.is_some()) 1029 { 1030 return Err(OperationError::RecoveryRequired); 1031 } 1032 let head = chain_head(ChainInput { 1033 previous: decoded.previous_head, 1034 revision: decoded.revision, 1035 binding: request.binding(), 1036 operation, 1037 digest, 1038 transaction: decoded.transaction, 1039 pool: decoded.pool, 1040 movement: decoded.movement, 1041 })?; 1042 let pool_id = decoded.pool.id(); 1043 for (column, expected) in [ 1044 (0, digest.as_bytes()), 1045 (1, decoded.transaction.as_bytes()), 1046 (2, pool_id.as_bytes()), 1047 (4, head.as_bytes()), 1048 ] { 1049 let observed: Vec<u8> = row 1050 .try_get(column) 1051 .map_err(|_| OperationError::RecoveryRequired)?; 1052 if observed != expected { 1053 return Err(OperationError::RecoveryRequired); 1054 } 1055 } 1056 let revision: i64 = row 1057 .try_get(3) 1058 .map_err(|_| OperationError::RecoveryRequired)?; 1059 if revision <= 0 || revision as u64 != decoded.revision.get() || head != decoded.head { 1060 return Err(OperationError::RecoveryRequired); 1061 } 1062 let count: i64 = 1063 sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?") 1064 .bind(binding.actor().participant().as_bytes().as_slice()) 1065 .bind(operation.as_bytes().as_slice()) 1066 .fetch_one(&mut *connection) 1067 .await 1068 .map_err(|_| OperationError::RecoveryRequired)?; 1069 if count != i64::from(decoded.movement.is_some()) { 1070 return Err(OperationError::RecoveryRequired); 1071 } 1072 let movement_protected = if let Some(id) = decoded.movement { 1073 let protected:Vec<u8>=sqlx::query_scalar("SELECT protected FROM stock_movements WHERE movement_id=? AND actor=? AND grant_id=? AND operation_id=? AND pool_id=? AND length(protected) BETWEEN 1 AND 262144").bind(id.as_slice()).bind(binding.actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(decoded.pool.id().as_bytes().as_slice()).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; 1074 let clear = crypto 1075 .open_stock_record_for_catalog(input, "movement", &id, catalog, &protected) 1076 .await?; 1077 let movement: Movement = clear 1078 .expose_secret(|bytes| super::closed_record(bytes)) 1079 .map_err(|_| OperationError::RecoveryRequired)?; 1080 if movement.version != record_version(catalog)? 1081 || movement.operation != operation 1082 || movement.digest != digest 1083 || movement.pool != decoded.pool.id() 1084 || movement.quantity != quantity 1085 || movement.kind != movement_kind 1086 || movement.quantity == radroots_domain::stock::StockTicks::ZERO 1087 { 1088 return Err(OperationError::RecoveryRequired); 1089 } 1090 Some(protected) 1091 } else { 1092 if quantity != radroots_domain::stock::StockTicks::ZERO { 1093 return Err(OperationError::RecoveryRequired); 1094 } 1095 None 1096 }; 1097 let attempt = CommitAttempt::new( 1098 input.workspace_id(), 1099 operation, 1100 digest, 1101 Some(decoded.transaction), 1102 ); 1103 let checkpoint = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( 1104 request.command().context().authority(), 1105 decoded.revision, 1106 Some(decoded.head), 1107 )? 1108 .with_optional_authorization(decoded.authorization); 1109 let receipt = if let Some(mapping) = decoded.mapping { 1110 InventoryReceipt::from_committed_mapping(attempt, decoded.pool, mapping.after, checkpoint)? 1111 } else { 1112 InventoryReceipt::from_committed_store( 1113 attempt, 1114 request.command().kind(), 1115 decoded.pool, 1116 checkpoint, 1117 )? 1118 }; 1119 let receipt = receipt.with_deficits( 1120 decoded 1121 .losses 1122 .iter() 1123 .map(|loss| loss.metadata(decoded.pool.id())) 1124 .collect(), 1125 )?; 1126 Ok(Some(Retained { 1127 deficit_projection, 1128 frame, 1129 original_grant: request.binding().input().grant_id(), 1130 previous_head: decoded.previous_head, 1131 movement: decoded.movement, 1132 movement_protected, 1133 receipt, 1134 digest, 1135 protected, 1136 })) 1137 } 1138 fn encode(value: &impl Serialize) -> Result<zeroize::Zeroizing<Vec<u8>>, OperationError> { 1139 let bytes = zeroize::Zeroizing::new( 1140 serde_json::to_vec(value).map_err(|_| OperationError::StorageFailure)?, 1141 ); 1142 if bytes.len() > 16 * 1024 { 1143 return Err(OperationError::InvalidCommand); 1144 } 1145 Ok(bytes) 1146 } 1147 struct ChainInput<'a> { 1148 previous: Option<CheckpointDigest>, 1149 revision: Sequence, 1150 binding: &'a WorkspaceBinding, 1151 operation: OperationId, 1152 digest: CommandDigest, 1153 transaction: TransactionId, 1154 pool: PoolSnapshot, 1155 movement: Option<[u8; 32]>, 1156 } 1157 fn chain_head(value: ChainInput<'_>) -> Result<CheckpointDigest, OperationError> { 1158 let ChainInput { 1159 previous, 1160 revision, 1161 binding, 1162 operation, 1163 digest, 1164 transaction, 1165 pool, 1166 movement, 1167 } = value; 1168 let mut h = Sha256::new(); 1169 h.update(b"radroots.seller_stock.inventory_chain.v1\0"); 1170 h.update([u8::from(previous.is_some())]); 1171 h.update(previous.map(|v| *v.as_bytes()).unwrap_or([0; 32])); 1172 h.update(revision.get().to_be_bytes()); 1173 h.update(binding.input().workspace_id().as_bytes()); 1174 h.update(binding.actor().participant().as_bytes()); 1175 h.update(binding.input().grant_id().as_bytes()); 1176 h.update(operation.as_bytes()); 1177 h.update(digest.as_bytes()); 1178 h.update(transaction.as_bytes()); 1179 h.update(pool.id().as_bytes()); 1180 h.update(encode(&pool)?.as_slice()); 1181 h.update([u8::from(movement.is_some())]); 1182 h.update(movement.unwrap_or([0; 32])); 1183 Ok(CheckpointDigest::from_bytes(h.finalize().into())) 1184 }