inventory.rs (23320B)
1 //! Typed owner-private stock transactions. Values and receipt construction 2 //! establish no authority or durable effect; concrete qualified hosts do that. 3 use crate::{ 4 command::{CommitAttempt, OperationError}, 5 workspace::{AttachmentProof, WorkspaceBinding, WorkspaceScope, WorkspaceStore}, 6 }; 7 use radroots_domain::{CommandDigest, OperationId, PoolId, TransactionId, stock::PoolSnapshot}; 8 pub use radroots_protocol::command::{CapturedInventoryCommand, InventoryCommandKind}; 9 use radroots_transport::BoxFuture; 10 mod abort; 11 mod acceptance; 12 mod deficit; 13 mod snapshot; 14 pub use snapshot::StockSnapshot; 15 mod delivery; 16 pub use deficit::StockDeficit; 17 mod delivery_state; 18 mod envelope; 19 mod evidence; 20 mod rewrap; 21 pub use abort::{StockAbortOutcome, StockAbortReceipt, StockAbortRequest}; 22 pub use acceptance::{StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest}; 23 pub use delivery::{ 24 StockDeliveryAttempt, StockDeliveryAttemptOutcome, StockDeliveryObservation, 25 StockDeliveryObservationOutcome, StockDeliveryObservationReceipt, StockDeliveryRequest, 26 }; 27 pub use delivery_state::{ 28 StockDeliveryObservationPage, StockDeliverySummary, StockDeliveryTargetProgress, 29 }; 30 pub use envelope::{ 31 StockEnvelopeOutcome, StockEnvelopeReceipt, StockEnvelopeRequest, StockEnvelopeSource, 32 }; 33 pub use evidence::{ 34 StockEvidenceOutcome, StockEvidenceReceipt, StockEvidenceRequest, StockEvidenceSource, 35 }; 36 pub use rewrap::{ 37 StockRewrapAdmission, StockRewrapOutcome, StockRewrapPage, StockRewrapRequest, StockRewrapState, 38 }; 39 40 /// Exact captured owner-private inventory command and original authenticated observation. 41 pub struct InventoryRequest { 42 binding: WorkspaceBinding, 43 minimum: InventoryCheckpointRef, 44 command: CapturedInventoryCommand, 45 replay_only: bool, 46 } 47 impl InventoryRequest { 48 pub fn new( 49 binding: WorkspaceBinding, 50 minimum: InventoryCheckpointRef, 51 command: impl Into<CapturedInventoryCommand>, 52 ) -> Result<Self, OperationError> { 53 Self::build(binding, minimum, command.into(), false) 54 } 55 /// An explicitly retained original command under a current grant. A missing 56 /// original operation requires recovery and can never create a fresh effect. 57 pub fn replay_from_protected_wire( 58 binding: WorkspaceBinding, 59 minimum: InventoryCheckpointRef, 60 wire: &[u8], 61 ) -> Result<Self, OperationError> { 62 Self::build( 63 binding, 64 minimum, 65 CapturedInventoryCommand::parse(wire).map_err(|_| OperationError::RecoveryRequired)?, 66 true, 67 ) 68 } 69 fn build( 70 binding: WorkspaceBinding, 71 minimum: InventoryCheckpointRef, 72 command: CapturedInventoryCommand, 73 replay_only: bool, 74 ) -> Result<Self, OperationError> { 75 let context = command.context(); 76 let selection = binding.input(); 77 if binding.scope() != WorkspaceScope::SellerStockOwner { 78 return Err(OperationError::Unauthorized); 79 } 80 if (!replay_only && context.actor() != binding.actor()) 81 || context.workspace_id() != selection.workspace_id() 82 || context.authority() != selection.authority() 83 || context.route_digest() != selection.route_digest() 84 || context.actor().participant() != binding.actor().participant() 85 || context.actor().role() != binding.actor().role() 86 || context.actor().organization() != binding.actor().organization() 87 { 88 return Err(OperationError::InvalidCommand); 89 } 90 if context.expected().is_some() { 91 return Err(OperationError::MissingHistory); 92 } 93 if context.approval().is_some() { 94 return Err(OperationError::UnverifiedApproval); 95 } 96 if command.protected_wire().len() > 16 * 1024 { 97 return Err(OperationError::InvalidCommand); 98 } 99 if minimum.authority() != selection.authority() { 100 return Err(crate::workspace::WorkspaceError::StaleAuthority.into()); 101 } 102 Ok(Self { 103 binding, 104 minimum, 105 command, 106 replay_only, 107 }) 108 } 109 /// Reconstructs captured data only; the concrete host must reauthenticate it. 110 pub fn from_protected_wire( 111 binding: WorkspaceBinding, 112 minimum: InventoryCheckpointRef, 113 wire: &[u8], 114 ) -> Result<Self, OperationError> { 115 Self::new( 116 binding, 117 minimum, 118 CapturedInventoryCommand::parse(wire).map_err(|_| OperationError::RecoveryRequired)?, 119 ) 120 } 121 /// Independently retained acknowledged minimum, never guessed from a cache. 122 pub const fn minimum_checkpoint(&self) -> InventoryCheckpointRef { 123 self.minimum 124 } 125 pub const fn binding(&self) -> &WorkspaceBinding { 126 &self.binding 127 } 128 pub const fn command(&self) -> &CapturedInventoryCommand { 129 &self.command 130 } 131 pub const fn replay_only(&self) -> bool { 132 self.replay_only 133 } 134 pub fn retained_copy(&self) -> Result<Self, OperationError> { 135 Self::build( 136 self.binding.clone(), 137 self.minimum, 138 CapturedInventoryCommand::parse(self.command.protected_wire()) 139 .map_err(|_| OperationError::RecoveryRequired)?, 140 self.replay_only, 141 ) 142 } 143 } 144 impl core::fmt::Debug for InventoryRequest { 145 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 146 f.write_str("InventoryRequest(<redacted>)") 147 } 148 } 149 /// A claimed acknowledged inventory checkpoint. The trusted host must retain 150 /// its provenance independently; this value alone establishes no authority. 151 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 152 pub struct InventoryCheckpointRef { 153 authority: radroots_domain::AuthorityRef, 154 revision: radroots_domain::Sequence, 155 head: Option<radroots_domain::CheckpointDigest>, 156 authorization: Option<crate::workspace::seller_stock::StockAuthorizationRef>, 157 } 158 impl InventoryCheckpointRef { 159 pub fn from_host_metadata( 160 authority: radroots_domain::AuthorityRef, 161 revision: radroots_domain::Sequence, 162 head: Option<radroots_domain::CheckpointDigest>, 163 ) -> Result<Self, crate::workspace::WorkspaceError> { 164 if (revision.get() == 0) != head.is_none() { 165 return Err(crate::workspace::WorkspaceError::InvalidInput); 166 } 167 Ok(Self { 168 authority, 169 revision, 170 head, 171 authorization: None, 172 }) 173 } 174 /// Binds an independently retained authorization-state observation. Metadata 175 /// alone supplies neither credential possession nor checkpoint provenance. 176 pub const fn with_authorization( 177 mut self, 178 value: crate::workspace::seller_stock::StockAuthorizationRef, 179 ) -> Self { 180 self.authorization = Some(value); 181 self 182 } 183 pub const fn with_optional_authorization( 184 mut self, 185 value: Option<crate::workspace::seller_stock::StockAuthorizationRef>, 186 ) -> Self { 187 self.authorization = value; 188 self 189 } 190 pub const fn authorization( 191 self, 192 ) -> Option<crate::workspace::seller_stock::StockAuthorizationRef> { 193 self.authorization 194 } 195 pub const fn authority(self) -> radroots_domain::AuthorityRef { 196 self.authority 197 } 198 pub const fn revision(self) -> radroots_domain::Sequence { 199 self.revision 200 } 201 pub const fn head(self) -> Option<radroots_domain::CheckpointDigest> { 202 self.head 203 } 204 } 205 /// Confirmed owner-private inventory effect, without any signature or publication claim. 206 #[derive(Clone, Debug, Eq, PartialEq)] 207 pub struct InventoryReceipt { 208 attempt: CommitAttempt, 209 pool: PoolSnapshot, 210 kind: InventoryCommandKind, 211 deficits: Vec<StockDeficit>, 212 mapping: Option<radroots_domain::stock::OptionPoolMapping>, 213 checkpoint: InventoryCheckpointRef, 214 } 215 impl InventoryReceipt { 216 /// Reconstructs only metadata. A host must confirm its actual transaction. 217 pub fn from_committed_store( 218 attempt: CommitAttempt, 219 kind: InventoryCommandKind, 220 pool: PoolSnapshot, 221 checkpoint: InventoryCheckpointRef, 222 ) -> Result<Self, OperationError> { 223 if attempt.transaction_id().is_none() 224 || pool.version().get() == 0 225 || (kind == InventoryCommandKind::CreatePool && pool.version().get() != 1) 226 || (kind != InventoryCommandKind::CreatePool && pool.version().get() < 2) 227 || kind == InventoryCommandKind::MapOption 228 || checkpoint.revision().get() == 0 229 { 230 return Err(OperationError::RecoveryRequired); 231 } 232 Ok(Self { 233 attempt, 234 kind, 235 pool, 236 mapping: None, 237 deficits: Vec::new(), 238 checkpoint, 239 }) 240 } 241 /// Reconstructs mapping-effect metadata only. A qualified host must confirm 242 /// the original transaction and its unchanged referenced pool separately. 243 pub fn from_committed_mapping( 244 attempt: CommitAttempt, 245 pool: PoolSnapshot, 246 mapping: radroots_domain::stock::OptionPoolMapping, 247 checkpoint: InventoryCheckpointRef, 248 ) -> Result<Self, OperationError> { 249 if attempt.transaction_id().is_none() 250 || checkpoint.revision().get() == 0 251 || pool.version().get() == 0 252 || mapping.pool_id() != pool.id() 253 || mapping.pool_unit() != pool.unit() 254 { 255 return Err(OperationError::RecoveryRequired); 256 } 257 Ok(Self { 258 attempt, 259 pool, 260 kind: InventoryCommandKind::MapOption, 261 mapping: Some(mapping), 262 deficits: Vec::new(), 263 checkpoint, 264 }) 265 } 266 /// Adds retained allocation metadata only; this creates no effect or authority. 267 pub fn with_deficits(mut self, deficits: Vec<StockDeficit>) -> Result<Self, OperationError> { 268 if deficits.len() > 32 269 || deficits.iter().any(|value| { 270 value.pool() != self.pool.id() 271 || value.backing().deficit() == radroots_domain::stock::StockTicks::ZERO 272 }) 273 || deficits.iter().enumerate().any(|(index, value)| { 274 deficits[..index].iter().any(|prior| { 275 prior.acceptance() == value.acceptance() && prior.line() == value.line() 276 }) 277 }) 278 || (!deficits.is_empty() 279 && !matches!( 280 self.kind, 281 InventoryCommandKind::SpoilStock | InventoryCommandKind::RemoveStock 282 )) 283 { 284 return Err(OperationError::RecoveryRequired); 285 } 286 self.deficits = deficits; 287 Ok(self) 288 } 289 /// Deficits caused by this transaction at its retained checkpoint. 290 /// These are not a current full-obligation balance or disclosure grant. 291 pub fn deficits(&self) -> &[StockDeficit] { 292 &self.deficits 293 } 294 /// Original private mapping effect; absent for physical inventory commands. 295 pub const fn mapping(&self) -> Option<radroots_domain::stock::OptionPoolMapping> { 296 self.mapping 297 } 298 /// Exact effect family retained by the original command. 299 pub const fn kind(&self) -> InventoryCommandKind { 300 self.kind 301 } 302 /// Checkpoint retained by the trusted host for subsequent recovery admission. 303 pub const fn checkpoint(&self) -> InventoryCheckpointRef { 304 self.checkpoint 305 } 306 pub const fn attempt(&self) -> CommitAttempt { 307 self.attempt 308 } 309 pub const fn pool(&self) -> PoolSnapshot { 310 self.pool 311 } 312 pub const fn transaction_id(&self) -> Option<TransactionId> { 313 self.attempt.transaction_id() 314 } 315 } 316 /// Unknown completion retains the original operation/digest/transaction anchor. 317 #[derive(Clone, Debug, Eq, PartialEq)] 318 pub enum InventoryOutcome { 319 Committed(Box<InventoryReceipt>), 320 Unknown(CommitAttempt), 321 } 322 /// Native and browser hosts enforce these same atomic rules, never a memory 323 /// success placeholder. No signing or network work occurs in these methods. 324 pub trait InventoryStore: WorkspaceStore { 325 /// Appends already obtained bytes against the actual protected original 326 /// claim. This performs no signing or installation and renews no permission. 327 /// Unsupported hosts refuse. Borrowed original evidence survives errors. 328 fn capture_stock_evidence<'a>( 329 &'a self, 330 _request: &'a StockEvidenceRequest, 331 _proof: &'a AttachmentProof, 332 ) -> BoxFuture<'a, Result<StockEvidenceOutcome, OperationError>> { 333 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 334 } 335 /// Reconciles only already obtained original bytes after a failed/unknown 336 /// append. A qualified host resolves its actual connection/commit state 337 /// while retaining writer ownership; it cannot sign or renew a first issue. 338 /// Unsupported hosts refuse, with the borrowed original left intact. 339 fn reconcile_stock_evidence<'a>( 340 &'a self, 341 _request: &'a StockEvidenceRequest, 342 _proof: &'a AttachmentProof, 343 ) -> BoxFuture<'a, Result<StockEvidenceOutcome, OperationError>> { 344 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 345 } 346 /// Retains an obtained outer against actual original stock S/T2. The host 347 /// must verify exact containment and commit before any transport right. 348 /// Capture grants no dispatch permission; unsupported hosts refuse. 349 fn capture_stock_envelope<'a>( 350 &'a self, 351 _request: StockEnvelopeRequest, 352 _proof: AttachmentProof, 353 _candidate: &'a crate::command::PrivateEnvelopeCandidate, 354 ) -> BoxFuture<'a, Result<StockEnvelopeOutcome, OperationError>> { 355 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 356 } 357 /// Confirms one explicit wrapping admission before invoking wrapping. 358 /// Only a qualified host's newly confirmed claim qualifies one invocation; 359 /// existing and uncertain admissions never qualify another invocation. 360 fn prepare_stock_rewrap( 361 &self, 362 _request: StockRewrapRequest, 363 _proof: AttachmentProof, 364 ) -> BoxFuture<'_, Result<StockRewrapOutcome, OperationError>> { 365 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 366 } 367 /// Queries an admission and any actual captured envelope without qualifying 368 /// another wrapping invocation. Missing bytes cannot authorize regeneration. 369 fn stock_rewrap_attempt( 370 &self, 371 _request: StockRewrapRequest, 372 _proof: AttachmentProof, 373 ) -> BoxFuture<'_, Result<Option<StockRewrapState>, OperationError>> { 374 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 375 } 376 /// Repairs the original caller's retained writer state without a fresh 377 /// clock. Returns no history, wrapping permit or dispatch permission; 378 /// subsequent status reads still require current recovery access. 379 fn reconcile_stock_rewrap_admission( 380 &self, 381 _request: StockRewrapRequest, 382 _proof: AttachmentProof, 383 ) -> BoxFuture<'_, Result<(), OperationError>> { 384 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 385 } 386 /// Appends an obtained additional outer to its actual original admission. 387 fn capture_stock_rewrap<'a>( 388 &'a self, 389 _request: StockRewrapRequest, 390 _proof: AttachmentProof, 391 _candidate: &'a crate::command::PrivateEnvelopeCandidate, 392 ) -> BoxFuture<'a, Result<StockEnvelopeOutcome, OperationError>> { 393 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 394 } 395 /// Reconciles the original additional outer on its retained connection 396 /// owner. This never obtains new wrapping material or renews permission. 397 fn reconcile_stock_rewrap<'a>( 398 &'a self, 399 _request: StockRewrapRequest, 400 _proof: AttachmentProof, 401 _candidate: &'a crate::command::PrivateEnvelopeCandidate, 402 ) -> BoxFuture<'a, Result<StockEnvelopeOutcome, OperationError>> { 403 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 404 } 405 /// Pages additional-envelope descriptors under current recovery access. 406 /// Queries retain original identities without loading every raw envelope. 407 fn stock_rewraps( 408 &self, 409 _request: StockEnvelopeRequest, 410 _after: Option<radroots_domain::Sequence>, 411 _proof: AttachmentProof, 412 ) -> BoxFuture<'_, Result<StockRewrapPage, OperationError>> { 413 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 414 } 415 /// Reads the exact original retained outer under current recovery access. 416 /// Absence is not permission to generate or dispatch a replacement. 417 fn stock_envelope( 418 &self, 419 _request: StockEnvelopeRequest, 420 _proof: AttachmentProof, 421 ) -> BoxFuture<'_, Result<Option<StockEnvelopeSource>, OperationError>> { 422 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 423 } 424 /// Reconciles borrowed original outer material on the same retained owner. 425 /// Unsupported hosts cannot replace this with another wrap or a new writer. 426 fn reconcile_stock_envelope<'a>( 427 &'a self, 428 _request: StockEnvelopeRequest, 429 _proof: AttachmentProof, 430 _candidate: &'a crate::command::PrivateEnvelopeCandidate, 431 ) -> BoxFuture<'a, Result<StockEnvelopeOutcome, OperationError>> { 432 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 433 } 434 /// Commits an actual potential invocation before transport. Existing or 435 /// uncertain attempts never confer another dispatch right. 436 /// A fresh claim must enforce the requested expected-attempt-count 437 /// precondition against authenticated history in the same transaction. 438 fn prepare_stock_delivery_attempt( 439 &self, 440 _request: StockDeliveryRequest, 441 _proof: AttachmentProof, 442 ) -> BoxFuture<'_, Result<StockDeliveryAttemptOutcome, OperationError>> { 443 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 444 } 445 /// Reads one original request without replay or deadline renewal. 446 fn stock_delivery_attempt( 447 &self, 448 _source: StockEnvelopeRequest, 449 _request_id: radroots_transport::sink::DeliveryRequestId, 450 _proof: AttachmentProof, 451 ) -> BoxFuture<'_, Result<Option<StockDeliveryAttempt>, OperationError>> { 452 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 453 } 454 /// Reads bounded current per-endpoint progress under current recovery access. 455 fn stock_delivery_summary( 456 &self, 457 _source: StockEnvelopeRequest, 458 _proof: AttachmentProof, 459 ) -> BoxFuture<'_, Result<StockDeliverySummary, OperationError>> { 460 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 461 } 462 /// Captures already obtained original outcome data without requiring a 463 /// fresh clock or live grant. The caller retains its original across errors. 464 fn record_stock_delivery_observation<'a>( 465 &'a self, 466 _binding: &'a WorkspaceBinding, 467 _proof: &'a AttachmentProof, 468 _observation: &'a StockDeliveryObservation, 469 ) -> BoxFuture<'a, Result<StockDeliveryObservationOutcome, OperationError>> { 470 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 471 } 472 /// Reconciles only the borrowed obtained outcome on its original owner. 473 fn reconcile_stock_delivery_observation<'a>( 474 &'a self, 475 _binding: &'a WorkspaceBinding, 476 _proof: &'a AttachmentProof, 477 _observation: &'a StockDeliveryObservation, 478 ) -> BoxFuture<'a, Result<StockDeliveryObservationOutcome, OperationError>> { 479 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 480 } 481 /// Pages original independent outcomes; a read never issues transport. 482 fn stock_delivery_observations( 483 &self, 484 _source: StockEnvelopeRequest, 485 _after: Option<radroots_domain::Sequence>, 486 _proof: AttachmentProof, 487 ) -> BoxFuture<'_, Result<StockDeliveryObservationPage, OperationError>> { 488 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 489 } 490 /// Prepares an original acceptance with complete atomic holds and the order 491 /// fence. Unsupported hosts execute no fallback or simulated stock effect. 492 fn prepare_stock_acceptance( 493 &self, 494 _request: StockAcceptanceRequest, 495 _proof: AttachmentProof, 496 ) -> BoxFuture<'_, Result<StockAcceptanceOutcome, OperationError>> { 497 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 498 } 499 /// Explicit original-preparation cleanup. The concrete store must prove 500 /// every original invocation unissued, exclude outstanding replay and 501 /// obtained output, and retain the exact release atomically. Neither this 502 /// port nor an unsupported host supplies those proofs. 503 fn abort_proven_unissued( 504 &self, 505 _request: StockAbortRequest, 506 _proof: AttachmentProof, 507 ) -> BoxFuture<'_, Result<StockAbortOutcome, OperationError>> { 508 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 509 } 510 /// Reads original cleanup under current access; absence is not permission 511 /// to retry issuance or release. Unsupported hosts refuse explicitly. 512 fn stock_preparation_abort( 513 &self, 514 _request: StockAbortRequest, 515 _proof: AttachmentProof, 516 ) -> BoxFuture<'_, Result<Option<StockAbortReceipt>, OperationError>> { 517 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 518 } 519 /// Reads current owner-private configuration after authenticating retained 520 /// progress. Physical inventory scopes confer no configuration access. 521 fn option_mapping( 522 &self, 523 binding: WorkspaceBinding, 524 minimum: InventoryCheckpointRef, 525 key: radroots_domain::stock::OptionMappingKey, 526 proof: AttachmentProof, 527 ) -> BoxFuture<'_, Result<Option<radroots_domain::stock::OptionPoolMapping>, OperationError>>; 528 fn execute_inventory( 529 &self, 530 request: InventoryRequest, 531 proof: AttachmentProof, 532 ) -> BoxFuture<'_, Result<InventoryOutcome, OperationError>>; 533 fn inventory_operation( 534 &self, 535 binding: WorkspaceBinding, 536 minimum: InventoryCheckpointRef, 537 operation: OperationId, 538 digest: Option<CommandDigest>, 539 proof: AttachmentProof, 540 ) -> BoxFuture<'_, Result<Option<InventoryReceipt>, OperationError>>; 541 /// Reads one current physical/installed-backing snapshot. Unsupported hosts 542 /// refuse; a physical-only read must never be filled with invented totals. 543 fn inspect_stock( 544 &self, 545 _binding: WorkspaceBinding, 546 _minimum: InventoryCheckpointRef, 547 _id: PoolId, 548 _proof: AttachmentProof, 549 ) -> BoxFuture<'_, Result<Option<StockSnapshot>, OperationError>> { 550 Box::pin(async { Err(OperationError::UnsupportedOperation) }) 551 } 552 fn pool( 553 &self, 554 binding: WorkspaceBinding, 555 minimum: InventoryCheckpointRef, 556 id: PoolId, 557 proof: AttachmentProof, 558 ) -> BoxFuture<'_, Result<Option<radroots_domain::stock::PoolView>, OperationError>>; 559 }