signing_plan.rs (18009B)
1 //! Atomic T1 over the same protected stock ledger and connection owner as T0. 2 use super::*; 3 use inventory::{ 4 Access, Turn, acceptance, 5 checkpoint::{self, EntryIdentity, IdentityTarget, MinimumProof}, 6 }; 7 use radroots_domain::{CheckpointDigest, CommandDigest, OperationId, UnixSeconds}; 8 use radroots_protocol::commerce::CommerceSigningPlan; 9 use radroots_signing::commerce::VerifiedCommerceSigningPlan; 10 use radroots_storage::{ 11 command::{CommitAttempt, OperationError}, 12 inventory::InventoryCheckpointRef, 13 }; 14 use sha2::{Digest, Sha256}; 15 pub(in crate::workspace::stock) mod codec; 16 pub(super) use codec::read_entry; 17 18 /// A bounded candidate, with actual encryption and original route verification. 19 /// Only a confirmed host transaction can turn it into a bound plan. 20 pub struct StockSigningPlanRequest { 21 binding: WorkspaceBinding, 22 minimum: InventoryCheckpointRef, 23 verified: VerifiedCommerceSigningPlan, 24 } 25 impl StockSigningPlanRequest { 26 pub fn new( 27 binding: WorkspaceBinding, 28 minimum: InventoryCheckpointRef, 29 verified: VerifiedCommerceSigningPlan, 30 ) -> Result<Self, OperationError> { 31 if verified.plan().protected_wire().len() > ledger::BODY_MAX_BYTES - codec::PREFIX_BYTES { 32 return Err(WorkspaceError::Capacity.into()); 33 } 34 Ok(Self { 35 binding, 36 minimum, 37 verified, 38 }) 39 } 40 pub(in crate::workspace) fn attempt(&self) -> CommitAttempt { 41 CommitAttempt::new( 42 self.binding.input().workspace_id(), 43 self.verified.plan().operation_id(), 44 self.verified.plan().command_digest(), 45 None, 46 ) 47 } 48 } 49 impl std::fmt::Debug for StockSigningPlanRequest { 50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 51 f.write_str("StockSigningPlanRequest(<redacted>)") 52 } 53 } 54 /// Original complete plan read from a confirmed T1. This is not a dispatch 55 /// permission, a signer invocation, evidence capture or installed agreement. 56 pub struct StockBoundSigningPlan { 57 attempt: CommitAttempt, 58 preparation: StockAcceptanceReceipt, 59 plan: CommerceSigningPlan, 60 bound_at: UnixSeconds, 61 checkpoint: InventoryCheckpointRef, 62 intents: [[u8; 32]; 2], 63 } 64 impl StockBoundSigningPlan { 65 /// Exact per-recipient signing intent commitments, in complete plan order. 66 pub const fn intent_digests(&self) -> &[[u8; 32]; 2] { 67 &self.intents 68 } 69 pub const fn attempt(&self) -> CommitAttempt { 70 self.attempt 71 } 72 pub const fn preparation(&self) -> &StockAcceptanceReceipt { 73 &self.preparation 74 } 75 pub const fn plan(&self) -> &CommerceSigningPlan { 76 &self.plan 77 } 78 pub const fn bound_at(&self) -> UnixSeconds { 79 self.bound_at 80 } 81 pub const fn checkpoint(&self) -> InventoryCheckpointRef { 82 self.checkpoint 83 } 84 } 85 impl std::fmt::Debug for StockBoundSigningPlan { 86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 87 f.write_str("StockBoundSigningPlan(<redacted>)") 88 } 89 } 90 #[derive(Debug)] 91 pub enum StockSigningPlanOutcome { 92 Bound(Box<StockBoundSigningPlan>), 93 Unknown(CommitAttempt), 94 } 95 96 pub(in crate::workspace::stock) struct Authorized { 97 pub(in crate::workspace::stock) access: Access, 98 pub(in crate::workspace::stock) original: acceptance::codec::Retained, 99 pub(in crate::workspace::stock) command: radroots_protocol::command::CapturedStockCommitment, 100 pub(in crate::workspace::stock) original_proof: MinimumProof, 101 pub(in crate::workspace::stock) consent: consent::Retained, 102 pub(in crate::workspace::stock) consent_proof: MinimumProof, 103 pub(in crate::workspace::stock) plan: Option<codec::Retained>, 104 pub(in crate::workspace::stock) plan_proof: MinimumProof, 105 } 106 impl Authorized { 107 pub(in crate::workspace::stock) async fn confirm( 108 &self, 109 connection: &mut SqliteConnection, 110 namespace: &super::super::fs::Namespace, 111 clock: &dyn WorkspaceClock, 112 proof: &AttachmentProof, 113 fresh: bool, 114 ) -> Result<WorkspaceBinding, OperationError> { 115 self.original_proof.confirm(connection).await?; 116 self.consent_proof.confirm(connection).await?; 117 self.plan_proof.confirm(connection).await?; 118 self.original.confirm(connection).await?; 119 if let Some(plan) = &self.plan { 120 plan.confirm(connection).await?; 121 } 122 let current = self 123 .access 124 .confirm(connection, namespace, clock, proof) 125 .await?; 126 acceptance::check_consent( 127 &self.access, 128 &self.consent, 129 &self.command, 130 fresh, 131 current.observed_at(), 132 )?; 133 if fresh 134 && (current.observed_at() < self.original.receipt.prepared_at() 135 || current.observed_at() >= self.original.receipt.first_issue_deadline()) 136 { 137 return Err(OperationError::DeadlineExceeded); 138 } 139 Ok(current) 140 } 141 } 142 pub(in crate::workspace::stock) async fn load( 143 turn: &mut Turn<'_>, 144 binding: &WorkspaceBinding, 145 minimum: InventoryCheckpointRef, 146 operation: OperationId, 147 digest: CommandDigest, 148 proof: &AttachmentProof, 149 ) -> Result<Authorized, OperationError> { 150 let access = Box::pin(turn.access(binding, minimum, proof)).await?; 151 if !matches!(access.authority.catalog, 10..=20) { 152 return Err(OperationError::UnsupportedOperation); 153 } 154 let original = Box::pin(acceptance::codec::read( 155 turn.connection, 156 turn.selected, 157 turn.crypto, 158 operation, 159 )) 160 .await? 161 .ok_or(OperationError::StaleState)?; 162 if original.frame.header.digest != digest { 163 return Err(OperationError::IdempotencyConflict); 164 } 165 let original_proof = Box::pin(checkpoint::authenticate_identity( 166 turn.connection, 167 turn.selected, 168 turn.crypto, 169 &access.current, 170 &access.authority, 171 IdentityTarget::Operation(operation, Some(original.identity())), 172 )) 173 .await?; 174 let command = original.command()?; 175 let (consent, consent_proof) = 176 Box::pin(acceptance::current_consent(turn, &access, &command)).await?; 177 acceptance::check_consent( 178 &access, 179 &consent, 180 &command, 181 false, 182 access.current.observed_at(), 183 )?; 184 for pool in original.affected_pools()? { 185 if !consent.resources.contains(pool) { 186 return Err(OperationError::Unauthorized); 187 } 188 access.record.require(StockAction::ReadOperations, pool)?; 189 } 190 let id: Option<Vec<u8>> = sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE actor=? AND related_operation=? AND family=3 AND length(operation_id)=32") 191 .bind(turn.selected.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_| OperationError::RecoveryRequired)?; 192 let plan = if let Some(id) = id { 193 Some( 194 read_entry( 195 turn.connection, 196 turn.selected, 197 turn.crypto, 198 OperationId::from_bytes( 199 id.try_into() 200 .map_err(|_| OperationError::RecoveryRequired)?, 201 ), 202 ) 203 .await? 204 .ok_or(OperationError::RecoveryRequired)?, 205 ) 206 } else { 207 None 208 }; 209 let plan_proof = Box::pin(checkpoint::authenticate_identity( 210 turn.connection, 211 turn.selected, 212 turn.crypto, 213 &access.current, 214 &access.authority, 215 IdentityTarget::SigningPlan { 216 operation, 217 expected: plan.as_ref().map(codec::Retained::identity), 218 }, 219 )) 220 .await?; 221 Ok(Authorized { 222 access, 223 original, 224 command, 225 original_proof, 226 consent, 227 consent_proof, 228 plan, 229 plan_proof, 230 }) 231 } 232 pub(in crate::workspace) async fn bind( 233 turn: &mut Turn<'_>, 234 request: StockSigningPlanRequest, 235 proof: AttachmentProof, 236 ) -> Result<StockSigningPlanOutcome, OperationError> { 237 let plan = request.verified.plan(); 238 let auth = load( 239 turn, 240 &request.binding, 241 request.minimum, 242 plan.operation_id(), 243 plan.command_digest(), 244 &proof, 245 ) 246 .await?; 247 if let Some(original) = &auth.plan { 248 if original.bound.plan.protected_wire() != plan.protected_wire() { 249 return Err(OperationError::IdempotencyConflict); 250 } 251 } else { 252 CommerceSigningPlan::parse( 253 plan.operation_id(), 254 plan.command_digest(), 255 auth.original.receipt.rumor(), 256 plan.protected_wire(), 257 ) 258 .map_err(|_| OperationError::InvalidEvidence)?; 259 if request.verified.deadline_unix_ms() 260 != auth 261 .original 262 .receipt 263 .first_issue_deadline() 264 .get() 265 .checked_mul(1000) 266 .ok_or(OperationError::RecoveryRequired)? 267 { 268 return Err(OperationError::InvalidCommand); 269 } 270 acceptance::check_consent( 271 &auth.access, 272 &auth.consent, 273 &auth.command, 274 true, 275 auth.access.current.observed_at(), 276 )?; 277 } 278 if auth.plan.is_some() { 279 confirm_read(turn, &auth, &proof).await?; 280 return Ok(StockSigningPlanOutcome::Bound(Box::new( 281 auth.plan.ok_or(OperationError::RecoveryRequired)?.bound, 282 ))); 283 } 284 auth.original 285 .confirm_replacement_residual( 286 turn.connection, 287 turn.selected, 288 turn.crypto, 289 auth.access 290 .authority 291 .inventory 292 .ok_or(OperationError::RecoveryRequired)? 293 .revision 294 .get() 295 .checked_add(1) 296 .ok_or(OperationError::RecoveryRequired)?, 297 ) 298 .await?; 299 let current_order = Box::pin(super::order_state::signing_state( 300 turn, 301 &auth.access, 302 auth.original.receipt.order_id(), 303 plan.operation_id(), 304 false, 305 )) 306 .await?; 307 let backing = Box::pin(inventory::backing::read( 308 turn, 309 &auth.access, 310 &auth.original.affected_pool_snapshots()?, 311 )) 312 .await?; 313 let before = auth 314 .access 315 .authority 316 .inventory 317 .ok_or(OperationError::RecoveryRequired)?; 318 let revision = Sequence::new( 319 before 320 .revision 321 .get() 322 .checked_add(1) 323 .ok_or(WorkspaceError::Capacity)?, 324 ) 325 .map_err(|_| WorkspaceError::Capacity)?; 326 let bound_at = auth.access.current.observed_at(); 327 let transaction = TransactionId::from_bytes(super::super::random()?); 328 let entry = OperationId::from_bytes(super::super::random()?); 329 let plan = request.verified.into_plan(); 330 let intents = codec::intents(&plan, auth.original.receipt.first_issue_deadline())?; 331 let body = codec::encode(&auth.original, &plan, bound_at)?; 332 let mut header = ledger::Header { 333 version: 5, 334 family: ledger::Family::SigningPlan, 335 namespace: SellerAuthoritySelection::from_attachment(turn.selected), 336 actor: auth.access.current.actor(), 337 operation: entry, 338 digest: plan.command_digest(), 339 transaction, 340 revision, 341 previous: before.head, 342 head: CheckpointDigest::from_bytes([0; 32]), 343 pool: None, 344 order: Some(auth.original.receipt.order_id()), 345 related_operation: Some(plan.operation_id()), 346 subject_grant: None, 347 bytes: 0, 348 parts: 0, 349 body_digest: [0; 32], 350 }; 351 header.head = codec::head(&header, &body); 352 let checkpoint = InventoryCheckpointRef::from_host_metadata( 353 turn.selected.authority(), 354 revision, 355 Some(header.head), 356 )? 357 .with_optional_authorization(auth.access.authority.authorization); 358 let attempt = CommitAttempt::new( 359 turn.selected.workspace_id(), 360 plan.operation_id(), 361 plan.command_digest(), 362 Some(transaction), 363 ); 364 let head = header.head; 365 let framed = ledger::prepare(turn.crypto, turn.selected, header, &body).await?; 366 let mut next = auth.access.authority.clone(); 367 next.inventory = Some(InventoryCheckpoint { 368 revision, 369 head: Some(head), 370 ..before 371 }); 372 let root = turn 373 .crypto 374 .seal_stock_root(turn.selected, next.catalog, &next.encode()?) 375 .await?; 376 let mut tx = turn 377 .connection 378 .begin_with("BEGIN IMMEDIATE") 379 .await 380 .map_err(|_| OperationError::StorageFailure)?; 381 // Do not borrow the connection again while the transaction is live. 382 let changed: Result<(), OperationError> = async { 383 auth.original_proof.confirm(&mut tx).await?; auth.consent_proof.confirm(&mut tx).await?; auth.plan_proof.confirm(&mut tx).await?; auth.original.confirm(&mut tx).await?; 384 let current = auth.access.confirm(&mut tx, turn.namespace, turn.clock, &proof).await?; 385 for pool in &backing { pool.confirm(&mut tx).await?; } 386 if let Some(current_order) = ¤t_order {current_order.confirm(&mut tx).await?;} 387 acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, current.observed_at())?; 388 if current.observed_at() < bound_at || current.observed_at() >= auth.original.receipt.first_issue_deadline() { return Err(OperationError::DeadlineExceeded); } 389 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(?,?,?,?,?,NULL,?,?,?,3,?,?,NULL)") 390 .bind(auth.access.current.actor().participant().as_bytes().as_slice()).bind(auth.access.current.input().grant_id().as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).bind(plan.command_digest().as_bytes().as_slice()).bind(transaction.as_bytes().as_slice()).bind(revision.get() as i64).bind(head.as_bytes().as_slice()).bind(&framed.protected).bind(auth.original.receipt.order_id().as_bytes().as_slice()).bind(plan.operation_id().as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; 391 framed.insert_parts(&mut tx, auth.access.current.actor(), entry).await?; 392 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)?; 393 if updated.rows_affected() != 1 { return Err(OperationError::RecoveryRequired); } 394 turn.namespace.validate()?; Ok(()) 395 }.await; 396 if let Err(error) = changed { 397 if tx.rollback().await.is_err() { 398 *turn.uncertain = true; 399 return Ok(StockSigningPlanOutcome::Unknown(attempt)); 400 } 401 return Err(error); 402 } 403 if tx.commit().await.is_err() { 404 *turn.uncertain = true; 405 return Ok(StockSigningPlanOutcome::Unknown(attempt)); 406 } 407 Ok(StockSigningPlanOutcome::Bound(Box::new( 408 StockBoundSigningPlan { 409 attempt, 410 intents, 411 preparation: auth.original.receipt, 412 plan, 413 bound_at, 414 checkpoint, 415 }, 416 ))) 417 } 418 async fn confirm_read( 419 turn: &mut Turn<'_>, 420 auth: &Authorized, 421 proof: &AttachmentProof, 422 ) -> Result<(), OperationError> { 423 let mut tx = turn 424 .connection 425 .begin_with("BEGIN IMMEDIATE") 426 .await 427 .map_err(|_| OperationError::StorageFailure)?; 428 let checked: Result<(), OperationError> = async { 429 auth.original_proof.confirm(&mut tx).await?; 430 auth.consent_proof.confirm(&mut tx).await?; 431 auth.plan_proof.confirm(&mut tx).await?; 432 auth.original.confirm(&mut tx).await?; 433 if let Some(plan) = &auth.plan { 434 plan.confirm(&mut tx).await?; 435 } 436 let current = auth 437 .access 438 .confirm(&mut tx, turn.namespace, turn.clock, proof) 439 .await?; 440 acceptance::check_consent( 441 &auth.access, 442 &auth.consent, 443 &auth.command, 444 false, 445 current.observed_at(), 446 )?; 447 Ok(()) 448 } 449 .await; 450 if tx.rollback().await.is_err() { 451 *turn.uncertain = true; 452 return Err(OperationError::RecoveryRequired); 453 } 454 checked 455 } 456 pub(in crate::workspace) async fn read( 457 turn: &mut Turn<'_>, 458 binding: WorkspaceBinding, 459 minimum: InventoryCheckpointRef, 460 operation: OperationId, 461 digest: CommandDigest, 462 proof: AttachmentProof, 463 ) -> Result<Option<StockBoundSigningPlan>, OperationError> { 464 let auth = load(turn, &binding, minimum, operation, digest, &proof).await?; 465 confirm_read(turn, &auth, &proof).await?; 466 Ok(auth.plan.map(|value| value.bound)) 467 } 468 impl NativeWorkspace { 469 pub async fn bind_stock_signing_intents( 470 &self, 471 request: StockSigningPlanRequest, 472 proof: &AttachmentProof, 473 ) -> Result<StockSigningPlanOutcome, OperationError> { 474 self.worker 475 .bind_stock_signing_intents( 476 request, 477 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, 478 ) 479 .await 480 } 481 pub async fn stock_signing_plan( 482 &self, 483 binding: WorkspaceBinding, 484 minimum: InventoryCheckpointRef, 485 operation: OperationId, 486 digest: CommandDigest, 487 proof: &AttachmentProof, 488 ) -> Result<Option<StockBoundSigningPlan>, OperationError> { 489 self.worker 490 .stock_signing_plan( 491 binding, 492 minimum, 493 operation, 494 digest, 495 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, 496 ) 497 .await 498 } 499 }