claim.rs (17106B)
1 //! First-dispatch linearization. Existing claims never create a new permit. 2 use super::super::{ 3 inventory::{ 4 Turn, acceptance, 5 checkpoint::{self, EntryIdentity, IdentityTarget}, 6 }, 7 signing_plan, 8 }; 9 use super::*; 10 use radroots_signing::{ 11 issuance::{IntentBinding, SigningIntent}, 12 provider::ProviderCall, 13 request::CancellationSignal, 14 }; 15 use std::{num::NonZeroU64, sync::Arc}; 16 mod dispatch; 17 pub use dispatch::{StockDispatchOutcome, StockUnissuedInvocation}; 18 pub(in crate::workspace::stock) mod codec; 19 pub(in crate::workspace::stock) use codec::read_entry; 20 21 /// Captured selector data, without permission or provider capability evidence. 22 pub struct StockClaimRequest { 23 pub(super) binding: WorkspaceBinding, 24 pub(super) minimum: InventoryCheckpointRef, 25 pub(super) operation: OperationId, 26 pub(super) digest: CommandDigest, 27 pub(super) recipient: PublicKey, 28 } 29 impl StockClaimRequest { 30 pub const fn new( 31 binding: WorkspaceBinding, 32 minimum: InventoryCheckpointRef, 33 operation: OperationId, 34 digest: CommandDigest, 35 recipient: PublicKey, 36 ) -> Self { 37 Self { 38 binding, 39 minimum, 40 operation, 41 digest, 42 recipient, 43 } 44 } 45 pub(in crate::workspace) fn attempt(&self) -> CommitAttempt { 46 CommitAttempt::new( 47 self.binding.input().workspace_id(), 48 self.operation, 49 self.digest, 50 None, 51 ) 52 } 53 } 54 impl std::fmt::Debug for StockClaimRequest { 55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 56 f.write_str("StockClaimRequest(<redacted>)") 57 } 58 } 59 60 /// An original durable claim. This report provides no fresh dispatch permit. 61 #[derive(Clone)] 62 pub struct StockSigningAttempt { 63 bound: Arc<StockBoundSigningPlan>, 64 recipient: PublicKey, 65 entry: EntryIdentity, 66 transaction: TransactionId, 67 claimed_at: UnixSeconds, 68 binding: IntentBinding, 69 } 70 impl StockSigningAttempt { 71 pub fn attempt_id(&self) -> SigningAttemptId { 72 SigningAttemptId::from_bytes(*self.entry.operation.as_bytes()) 73 } 74 pub const fn transaction_id(&self) -> TransactionId { 75 self.transaction 76 } 77 pub const fn claimed_at(&self) -> UnixSeconds { 78 self.claimed_at 79 } 80 pub const fn recipient(&self) -> PublicKey { 81 self.recipient 82 } 83 pub const fn binding(&self) -> IntentBinding { 84 self.binding 85 } 86 pub fn bound_plan(&self) -> &StockBoundSigningPlan { 87 &self.bound 88 } 89 pub fn attempt(&self) -> CommitAttempt { 90 CommitAttempt::new( 91 self.bound.attempt().workspace_id(), 92 self.bound.plan().operation_id(), 93 self.bound.plan().command_digest(), 94 Some(self.transaction), 95 ) 96 } 97 } 98 impl std::fmt::Debug for StockSigningAttempt { 99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 100 f.write_str("StockSigningAttempt(<redacted>)") 101 } 102 } 103 104 /// Single-use confirmed first-dispatch boundary, distinct from actual provider 105 /// capability and destination policy. Those remain caller obligations before 106 /// invoking the signer. An original/recovered claim cannot construct this type. 107 /// 108 /// ```compile_fail 109 /// use radroots_storage_sqlite::workspace::StockDispatchPermit; 110 /// fn extract(permit: StockDispatchPermit) { 111 /// let _ = permit.into_signing_intent(radroots_signing::request::CancellationSignal::new()); 112 /// } 113 /// ``` 114 pub struct StockDispatchPermit { 115 report: StockSigningAttempt, 116 } 117 impl StockDispatchPermit { 118 pub const fn report(&self) -> &StockSigningAttempt { 119 &self.report 120 } 121 /// Consumes this first-dispatch permit to expose the unchanged exact intent. 122 /// The returned report anchors later capture; it cannot reissue a permit. 123 fn into_intent( 124 self, 125 cancellation: CancellationSignal, 126 ) -> Result<(SigningIntent, StockSigningAttempt), OperationError> { 127 let intent = intent(&self.report.bound, self.report.recipient, cancellation)?; 128 if intent.binding() != self.report.binding { 129 return Err(OperationError::RecoveryRequired); 130 } 131 Ok((intent, self.report)) 132 } 133 } 134 impl std::fmt::Debug for StockDispatchPermit { 135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 136 f.write_str("StockDispatchPermit(<redacted>)") 137 } 138 } 139 #[derive(Debug)] 140 pub enum StockClaimOutcome { 141 Fresh(StockDispatchPermit), 142 Existing(StockSigningAttempt), 143 Unknown(CommitAttempt), 144 } 145 pub(in crate::workspace::stock) fn intent( 146 bound: &StockBoundSigningPlan, 147 recipient: PublicKey, 148 cancellation: CancellationSignal, 149 ) -> Result<SigningIntent, OperationError> { 150 let seal = bound 151 .plan() 152 .seals() 153 .iter() 154 .find(|seal| seal.recipient() == recipient) 155 .ok_or(OperationError::InvalidCommand)?; 156 let deadline = NonZeroU64::new( 157 bound 158 .preparation() 159 .first_issue_deadline() 160 .get() 161 .checked_mul(1000) 162 .ok_or(OperationError::RecoveryRequired)?, 163 ) 164 .ok_or(OperationError::RecoveryRequired)?; 165 SigningIntent::from_commerce_seal( 166 seal, 167 ProviderCall::new(seal.fields().author, deadline, cancellation), 168 ) 169 .map_err(|_| OperationError::InvalidEvidence) 170 } 171 #[derive(Serialize, Deserialize)] 172 #[serde(deny_unknown_fields)] 173 struct Body { 174 version: u8, 175 operation: OperationId, 176 plan_entry: OperationId, 177 plan_transaction: TransactionId, 178 plan_head: radroots_domain::CheckpointDigest, 179 plan_digest: [u8; 32], 180 recipient: PublicKey, 181 intent: [u8; 32], 182 deadline: UnixSeconds, 183 claimed_at: UnixSeconds, 184 } 185 186 pub(in crate::workspace::stock) async fn existing( 187 turn: &mut Turn<'_>, 188 auth: &signing_plan::Authorized, 189 operation: OperationId, 190 recipient: PublicKey, 191 ) -> Result<(Option<codec::Retained>, checkpoint::MinimumProof), OperationError> { 192 let id:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_signing_claims WHERE actor=? AND operation_id=? AND recipient=?") 193 .bind(turn.selected.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; 194 let retained = if let Some(id) = id { 195 Some( 196 read_entry( 197 turn.connection, 198 turn.selected, 199 turn.crypto, 200 OperationId::from_bytes( 201 id.try_into() 202 .map_err(|_| OperationError::RecoveryRequired)?, 203 ), 204 ) 205 .await? 206 .ok_or(OperationError::RecoveryRequired)?, 207 ) 208 } else { 209 None 210 }; 211 let witness = checkpoint::authenticate_identity( 212 turn.connection, 213 turn.selected, 214 turn.crypto, 215 &auth.access.current, 216 &auth.access.authority, 217 IdentityTarget::SigningClaim { 218 operation, 219 recipient, 220 expected: retained.as_ref().map(codec::Retained::identity), 221 }, 222 ) 223 .await?; 224 Ok((retained, witness)) 225 } 226 async fn confirm_read( 227 turn: &mut Turn<'_>, 228 auth: &signing_plan::Authorized, 229 witness: &checkpoint::MinimumProof, 230 retained: Option<&codec::Retained>, 231 proof: &AttachmentProof, 232 ) -> Result<(), OperationError> { 233 let mut tx = turn 234 .connection 235 .begin_with("BEGIN IMMEDIATE") 236 .await 237 .map_err(|_| OperationError::StorageFailure)?; 238 let checked: Result<(), OperationError> = async { 239 witness.confirm(&mut tx).await?; 240 if let Some(value) = retained { 241 value.confirm(&mut tx).await?; 242 } 243 auth.confirm(&mut tx, turn.namespace, turn.clock, proof, false) 244 .await?; 245 Ok(()) 246 } 247 .await; 248 if tx.rollback().await.is_err() { 249 *turn.uncertain = true; 250 return Err(OperationError::RecoveryRequired); 251 } 252 checked 253 } 254 pub(in crate::workspace) async fn claim( 255 turn: &mut Turn<'_>, 256 request: StockClaimRequest, 257 proof: AttachmentProof, 258 ) -> Result<StockClaimOutcome, OperationError> { 259 let mut auth = Box::pin(signing_plan::load( 260 turn, 261 &request.binding, 262 request.minimum, 263 request.operation, 264 request.digest, 265 &proof, 266 )) 267 .await?; 268 if auth.access.authority.catalog < 11 { 269 return Err(OperationError::UnsupportedOperation); 270 } 271 let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; 272 let selected = intent(&plan.bound, request.recipient, CancellationSignal::new())?; 273 let (retained, witness) = existing(turn, &auth, request.operation, request.recipient).await?; 274 if let Some(retained) = retained { 275 confirm_read(turn, &auth, &witness, Some(&retained), &proof).await?; 276 return Ok(StockClaimOutcome::Existing(retained.report)); 277 } 278 let current_order = Box::pin(super::super::order_state::signing_state( 279 turn, 280 &auth.access, 281 auth.original.receipt.order_id(), 282 request.operation, 283 true, 284 )) 285 .await?; 286 // A later self copy may finish an installed original, but new issuance 287 // from a pending amendment must retain its approved original residual. 288 let installed = current_order 289 .as_ref() 290 .and_then(|state| state.witness.expected) 291 .is_some_and(|state| state.phase == super::super::order_state::Phase::Installed); 292 if !installed { 293 auth.original 294 .confirm_replacement_residual( 295 turn.connection, 296 turn.selected, 297 turn.crypto, 298 auth.access 299 .authority 300 .inventory 301 .ok_or(OperationError::RecoveryRequired)? 302 .revision 303 .get() 304 .checked_add(1) 305 .ok_or(OperationError::RecoveryRequired)?, 306 ) 307 .await?; 308 } 309 let at = auth.access.current.observed_at(); 310 acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, at)?; 311 if at < plan.bound.bound_at() || at >= plan.bound.preparation().first_issue_deadline() { 312 return Err(OperationError::DeadlineExceeded); 313 } 314 let backing = Box::pin(super::super::inventory::backing::read( 315 turn, 316 &auth.access, 317 &auth.original.affected_pool_snapshots()?, 318 )) 319 .await?; 320 let entry = OperationId::from_bytes(super::super::super::random()?); 321 let transaction = TransactionId::from_bytes(super::super::super::random()?); 322 let before = auth 323 .access 324 .authority 325 .inventory 326 .ok_or(OperationError::RecoveryRequired)?; 327 let revision = Sequence::new( 328 before 329 .revision 330 .get() 331 .checked_add(1) 332 .ok_or(WorkspaceError::Capacity)?, 333 ) 334 .map_err(|_| WorkspaceError::Capacity)?; 335 let body = Body { 336 version: 1, 337 operation: request.operation, 338 plan_entry: plan.frame.header.operation, 339 plan_transaction: plan 340 .bound 341 .attempt() 342 .transaction_id() 343 .ok_or(OperationError::RecoveryRequired)?, 344 plan_head: plan.frame.header.head, 345 plan_digest: *plan.bound.plan().digest(), 346 recipient: request.recipient, 347 intent: *selected.binding().digest(), 348 deadline: plan.bound.preparation().first_issue_deadline(), 349 claimed_at: at, 350 }; 351 let clear = zeroize::Zeroizing::new( 352 serde_json::to_vec(&body).map_err(|_| OperationError::StorageFailure)?, 353 ); 354 if clear.len() > 16 * 1024 { 355 return Err(WorkspaceError::Capacity.into()); 356 } 357 let mut header = ledger::Header { 358 version: 5, 359 family: ledger::Family::SigningClaim, 360 namespace: SellerAuthoritySelection::from_attachment(turn.selected), 361 actor: auth.access.current.actor(), 362 operation: entry, 363 digest: request.digest, 364 transaction, 365 revision, 366 previous: before.head, 367 head: radroots_domain::CheckpointDigest::from_bytes([0; 32]), 368 pool: None, 369 order: Some(plan.bound.preparation().order_id()), 370 related_operation: Some(request.operation), 371 subject_grant: None, 372 bytes: 0, 373 parts: 0, 374 body_digest: [0; 32], 375 }; 376 header.head = codec::head(&header, &clear); 377 let head = header.head; 378 let framed = ledger::prepare(turn.crypto, turn.selected, header, &clear).await?; 379 let entry_identity = EntryIdentity { 380 operation: entry, 381 revision, 382 head, 383 protected_digest: Sha256::digest(&framed.protected).into(), 384 }; 385 let mut next = auth.access.authority.clone(); 386 next.inventory = Some(InventoryCheckpoint { 387 revision, 388 head: Some(head), 389 ..before 390 }); 391 let root = turn 392 .crypto 393 .seal_stock_root(turn.selected, next.catalog, &next.encode()?) 394 .await?; 395 let anchor = CommitAttempt::new( 396 turn.selected.workspace_id(), 397 request.operation, 398 request.digest, 399 Some(transaction), 400 ); 401 let mut tx = turn 402 .connection 403 .begin_with("BEGIN IMMEDIATE") 404 .await 405 .map_err(|_| OperationError::StorageFailure)?; 406 let changed:Result<(),OperationError>=async { 407 witness.confirm(&mut tx).await?; 408 let current=auth.confirm(&mut tx,turn.namespace,turn.clock,&proof,true).await?; 409 for pool in &backing { pool.confirm(&mut tx).await?; } 410 if let Some(current_order) = ¤t_order {current_order.confirm(&mut tx).await?;} 411 if current.observed_at()<at {return Err(WorkspaceError::Unavailable.into());} 412 framed.insert_record(&mut tx).await?; 413 sqlx::query("INSERT INTO stock_signing_claims(actor,operation_id,recipient,entry_id) VALUES(?,?,?,?)").bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation.as_bytes().as_slice()).bind(request.recipient.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 414 let updated=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(root).bind(&auth.access.root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 415 if updated.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);} turn.namespace.validate()?;Ok(()) 416 }.await; 417 if let Err(error) = changed { 418 if tx.rollback().await.is_err() { 419 *turn.uncertain = true; 420 return Ok(StockClaimOutcome::Unknown(anchor)); 421 } 422 return Err(error); 423 } 424 if tx.commit().await.is_err() { 425 *turn.uncertain = true; 426 return Ok(StockClaimOutcome::Unknown(anchor)); 427 } 428 let bound = Arc::new( 429 auth.plan 430 .take() 431 .ok_or(OperationError::RecoveryRequired)? 432 .bound, 433 ); 434 Ok(StockClaimOutcome::Fresh(StockDispatchPermit { 435 report: StockSigningAttempt { 436 bound, 437 recipient: request.recipient, 438 entry: entry_identity, 439 transaction, 440 claimed_at: at, 441 binding: selected.binding(), 442 }, 443 })) 444 } 445 pub(in crate::workspace) async fn read( 446 turn: &mut Turn<'_>, 447 request: StockClaimRequest, 448 proof: AttachmentProof, 449 ) -> Result<Option<StockSigningAttempt>, OperationError> { 450 let auth = Box::pin(signing_plan::load( 451 turn, 452 &request.binding, 453 request.minimum, 454 request.operation, 455 request.digest, 456 &proof, 457 )) 458 .await?; 459 if auth.access.authority.catalog < 11 { 460 return Err(OperationError::UnsupportedOperation); 461 } 462 let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; 463 intent(&plan.bound, request.recipient, CancellationSignal::new())?; 464 let (retained, witness) = existing(turn, &auth, request.operation, request.recipient).await?; 465 confirm_read(turn, &auth, &witness, retained.as_ref(), &proof).await?; 466 Ok(retained.map(|value| value.report)) 467 } 468 impl NativeWorkspace { 469 pub async fn claim_stock_signing_attempt( 470 &self, 471 request: StockClaimRequest, 472 proof: &AttachmentProof, 473 ) -> Result<StockClaimOutcome, OperationError> { 474 self.worker 475 .claim_stock_signing_attempt( 476 request, 477 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, 478 ) 479 .await 480 } 481 pub async fn stock_signing_attempt( 482 &self, 483 request: StockClaimRequest, 484 proof: &AttachmentProof, 485 ) -> Result<Option<StockSigningAttempt>, OperationError> { 486 self.worker 487 .stock_signing_attempt( 488 request, 489 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, 490 ) 491 .await 492 } 493 }