tests.rs (39767B)
1 use super::*; 2 pub(in crate::workspace::stock) fn catalog_authority_schema(catalog: i64) -> &'static str { 3 match catalog { 4 1 => "radroots.seller_stock.authority.v1", 5 2 => "radroots.seller_stock.authority.v2", 6 3 => "radroots.seller_stock.authority.v3", 7 4 => "radroots.seller_stock.authority.v4", 8 5 => "radroots.seller_stock.authority.v5", 9 6 => "radroots.seller_stock.authority.v6", 10 7 => "radroots.seller_stock.authority.v7", 11 8 => "radroots.seller_stock.authority.v8", 12 9 => "radroots.seller_stock.authority.v9", 13 10 => "radroots.seller_stock.authority.v10", 14 11 => "radroots.seller_stock.authority.v11", 15 12 => "radroots.seller_stock.authority.v12", 16 13 => "radroots.seller_stock.authority.v13", 17 14 => "radroots.seller_stock.authority.v14", 18 15 => "radroots.seller_stock.authority.v15", 19 16 => "radroots.seller_stock.authority.v16", 20 17 => "radroots.seller_stock.authority.v17", 21 18 => "radroots.seller_stock.authority.v18", 22 19 => "radroots.seller_stock.authority.v19", 23 20 => "radroots.seller_stock.authority.v20", 24 _ => panic!("unsupported private stock fixture catalog"), 25 } 26 } 27 use crate::workspace::{ 28 fs::Kind, 29 tests::{CryptoFixture, participant}, 30 }; 31 use radroots_domain::{CommandContextData, OperationId, PoolId, UnixSeconds}; 32 use radroots_storage::{ 33 command::OperationError, 34 inventory::{InventoryCheckpointRef, InventoryRequest, InventoryStore}, 35 }; 36 struct Clock; 37 impl WorkspaceClock for Clock { 38 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 39 Ok(UnixSeconds::new(100).unwrap()) 40 } 41 } 42 43 #[tokio::test] 44 async fn current_grant_set_reopens_with_original_namespace_after_one_grant_change() { 45 let fixture = CryptoFixture::new(); 46 let path = fixture.root().join("grant-reopen"); 47 let enrollment = StockEnrollment::prepare( 48 SellerStockConfig::new( 49 participant(), 50 participant(), 51 "owner", 52 UnixSeconds::new(200).unwrap(), 53 ) 54 .unwrap(), 55 &Clock, 56 ) 57 .unwrap(); 58 let store = NativeWorkspace::initialize_seller_stock( 59 &path, 60 &enrollment, 61 fixture.crypto(), 62 Arc::new(Clock), 63 ) 64 .await 65 .unwrap(); 66 let binding = store 67 .authenticate(enrollment.input().clone(), enrollment.proof()) 68 .await 69 .unwrap(); 70 let minimum = store 71 .stock_authority(enrollment.input().clone(), enrollment.proof()) 72 .await 73 .unwrap() 74 .inventory_checkpoint() 75 .unwrap(); 76 let context = CommandContextData::new( 77 OperationId::from_bytes([7; 32]), 78 binding.actor(), 79 enrollment.input().workspace_id(), 80 enrollment.input().authority(), 81 enrollment.input().route_digest(), 82 None, 83 None, 84 UnixSeconds::new(150).unwrap(), 85 None, 86 ) 87 .unwrap(); 88 let wire = serde_json::json!({"type":"stock.create_pool","context":context,"input":{"id":PoolId::from_bytes([8;32]),"label":"reopen","unit":"each","tick_scale":"0","initial_quantity":"1"}}); 89 let copy = enrollment 90 .proof() 91 .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) 92 .unwrap(); 93 let result = store 94 .execute_inventory( 95 InventoryRequest::from_protected_wire( 96 binding.clone(), 97 minimum, 98 &serde_json::to_vec(&wire).unwrap(), 99 ) 100 .unwrap(), 101 copy, 102 ) 103 .await 104 .unwrap(); 105 let minimum = match result { 106 radroots_storage::inventory::InventoryOutcome::Committed(v) => v.checkpoint(), 107 _ => panic!("creation must confirm"), 108 }; 109 let grant = StockGrantEnrollment::prepare( 110 &SellerAuthoritySelection::from_attachment(enrollment.input()), 111 "device".into(), 112 UnixSeconds::new(200).unwrap(), 113 StockGrantScope::full_inventory(), 114 ) 115 .unwrap(); 116 assert!(matches!( 117 store 118 .enroll_stock_grant(binding, minimum, enrollment.proof(), &grant) 119 .await 120 .unwrap(), 121 StockGrantOutcome::Committed(_) 122 )); 123 store.close().await.unwrap(); 124 std::fs::copy( 125 path.join("stock_execution_v1.sqlite"), 126 fixture.root().join("synthetic-before-revocation.sqlite"), 127 ) 128 .unwrap(); 129 let namespace = Namespace::acquire_kind(&path, false, Kind::SellerStock).unwrap(); 130 let mut connection = SqliteConnection::connect_with( 131 &sqlx::sqlite::SqliteConnectOptions::new() 132 .filename(namespace.database_path()) 133 .read_only(true), 134 ) 135 .await 136 .unwrap(); 137 assert_eq!(schema::admit(&mut connection).await, Ok(schema::CURRENT)); 138 assert_eq!(schema::integrity(&mut connection).await, Ok(())); 139 let root: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_authority") 140 .fetch_one(&mut connection) 141 .await 142 .unwrap(); 143 let clear = fixture 144 .crypto() 145 .open_stock_root(enrollment.input(), schema::CURRENT, &root) 146 .await 147 .unwrap(); 148 let authority = clear 149 .expose_secret(|bytes| Authority::decode(bytes, schema::CURRENT)) 150 .unwrap(); 151 clear.expose_secret(|bytes| { 152 let original:serde_json::Value=serde_json::from_slice(bytes).unwrap(); 153 assert_eq!(original["inventory"]["mappings"],"0"); 154 for bad in [serde_json::json!([]),serde_json::json!({"revision":"1","pools":"1","movements":"1","head":original["inventory"]["head"]})] { 155 let mut value=original.clone();value["inventory"]=bad; 156 assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),schema::CURRENT).is_err()); 157 } 158 for bad in [ 159 serde_json::json!([]), 160 serde_json::json!({"revision":"0","records":"0","parts":"0"}), 161 serde_json::json!({"revision":"0","records":"0","parts":"0","head":null,"extra":true}), 162 serde_json::json!({"revision":"1","records":"0","parts":"2","head":"01".repeat(32)}), 163 serde_json::json!({"revision":"1","records":"0","parts":"13","head":"01".repeat(32)}), 164 serde_json::json!({"revision":"1","records":"2","parts":"3","head":"01".repeat(32)}), 165 ] { 166 let mut value=original.clone();value["sources"]=bad; 167 assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),schema::CURRENT).is_err()); 168 } 169 }); 170 assert_eq!(authority.input, *enrollment.input()); 171 assert_eq!( 172 grants::check_state(&mut connection, authority.authorization.unwrap()).await, 173 Ok(()) 174 ); 175 assert!( 176 read(&mut connection, enrollment.input(), &fixture.crypto()) 177 .await 178 .is_ok() 179 ); 180 connection.close().await.unwrap(); 181 drop(namespace); 182 let reopened = NativeWorkspace::open_seller_stock( 183 &path, 184 enrollment.input().clone(), 185 fixture.crypto(), 186 Arc::new(Clock), 187 ) 188 .await 189 .unwrap(); 190 reopened.close().await.unwrap(); 191 } 192 193 #[tokio::test] 194 async fn current_and_retained_roots_bind_the_complete_namespace_with_distinct_catalog_contexts() { 195 use radroots_storage::workspace::seller_stock::SellerAuthoritySelection; 196 use serde_json::json; 197 let fixture = CryptoFixture::new(); 198 let (owner, _, _) = SellerStockConfig::new( 199 participant(), 200 participant(), 201 "root-context", 202 UnixSeconds::new(200).unwrap(), 203 ) 204 .unwrap() 205 .enroll( 206 UnixSeconds::new(100).unwrap(), 207 WorkspaceId::from_bytes([1; 32]), 208 ExecutorId::from_bytes([2; 32]), 209 GrantId::from_bytes([3; 32]), 210 AttachmentProof::from_protected_input(&[7; 32]).unwrap(), 211 ) 212 .unwrap(); 213 let namespace = SellerAuthoritySelection::from_attachment(&owner); 214 let caller = namespace.attachment(GrantId::from_bytes([9; 32])).unwrap(); 215 let crypto = fixture.crypto(); 216 let clear = b"synthetic context payload"; 217 for version in 4..=schema::CURRENT { 218 let current = crypto 219 .seal_stock_root(&owner, version, clear) 220 .await 221 .unwrap(); 222 crypto 223 .open_stock_root(&caller, version, ¤t) 224 .await 225 .unwrap() 226 .expose_secret(|bytes| assert_eq!(bytes, clear)); 227 let retained = crypto.seal_stock_root(&owner, 3, clear).await.unwrap(); 228 assert!(crypto.open_stock_root(&caller, 3, &retained).await.is_err()); 229 assert!(crypto.open_stock_root(&owner, 3, ¤t).await.is_err()); 230 assert!( 231 crypto 232 .open_stock_root(&owner, if version == 4 { 5 } else { version - 1 }, ¤t) 233 .await 234 .is_err() 235 ); 236 let value = serde_json::to_value(&namespace).unwrap(); 237 let other_key = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; 238 for (path, bad) in [ 239 ("/workspace_id", json!("0b".repeat(32))), 240 ("/authority/executor_id", json!("0b".repeat(32))), 241 ("/authority/generation", json!("2")), 242 ("/participant", json!(other_key)), 243 ("/endpoint", json!("local://another-namespace")), 244 ("/endpoint_identity", json!(other_key)), 245 ("/checkpoint/digest", json!("0b".repeat(32))), 246 ("/route_digest", json!("0b".repeat(32))), 247 ] { 248 let mut changed = value.clone(); 249 *changed.pointer_mut(path).unwrap() = bad; 250 let selected: SellerAuthoritySelection = serde_json::from_value(changed).unwrap(); 251 assert!( 252 crypto 253 .open_stock_root( 254 &selected.attachment(GrantId::from_bytes([9; 32])).unwrap(), 255 version, 256 ¤t 257 ) 258 .await 259 .is_err(), 260 "{path}" 261 ); 262 } 263 } 264 } 265 266 #[tokio::test] 267 async fn retained_inventory_v2_keeps_original_records_and_refuses_new_correction_without_upgrade() { 268 retained_inventory_catalog(2).await; 269 } 270 #[tokio::test] 271 async fn retained_inventory_v3_preserves_correction_and_original_records_without_upgrade() { 272 retained_inventory_catalog(3).await; 273 } 274 #[tokio::test] 275 async fn retained_inventory_v4_preserves_scoped_grants_and_original_effects_without_adding_mappings() 276 { 277 retained_inventory_catalog(4).await; 278 } 279 #[tokio::test] 280 async fn retained_inventory_v5_preserves_mappings_and_never_adds_source_tables() { 281 retained_inventory_catalog(5).await; 282 } 283 #[tokio::test] 284 async fn retained_inventory_v6_preserves_original_physical_and_source_capabilities() { 285 retained_inventory_catalog(6).await; 286 } 287 #[tokio::test] 288 async fn retained_inventory_v7_keeps_consent_ledger_without_public_source_tables() { 289 retained_inventory_catalog(7).await; 290 } 291 #[tokio::test] 292 async fn retained_v8_preserves_physical_and_private_source_progress_with_public_sources() { 293 retained_inventory_catalog(8).await; 294 } 295 #[tokio::test] 296 async fn retained_v9_preserves_prior_families_and_acceptance_admission() { 297 retained_inventory_catalog(9).await; 298 } 299 #[tokio::test] 300 async fn retained_v10_preserves_prior_families_and_signing_plan_retention() { 301 retained_inventory_catalog(10).await; 302 } 303 #[tokio::test] 304 async fn retained_v11_preserves_prior_families_and_adds_claims_and_obtained_evidence() { 305 assert_eq!(schema::CURRENT, 20); 306 retained_inventory_catalog(11).await; 307 } 308 // Exact catalog fixtures exercise retained/successor codecs; they are not 309 // evidence from a predecessor executable or a factory migration. 310 pub(super) async fn literal_catalog( 311 fixture: &CryptoFixture, 312 path: &std::path::Path, 313 catalog: i64, 314 ) -> (AttachmentInput, AttachmentProof) { 315 let (input, proof, record) = SellerStockConfig::new( 316 participant(), 317 participant(), 318 "retained-stock-owner", 319 UnixSeconds::new(200).unwrap(), 320 ) 321 .unwrap() 322 .enroll( 323 UnixSeconds::new(100).unwrap(), 324 WorkspaceId::from_bytes([1; 32]), 325 ExecutorId::from_bytes([2; 32]), 326 GrantId::from_bytes([3; 32]), 327 AttachmentProof::from_protected_input(&[0xA3; 32]).unwrap(), 328 ) 329 .unwrap(); 330 literal_catalog_contents( 331 fixture, 332 path, 333 catalog, 334 &input, 335 record, 336 TransactionId::from_bytes([9; 32]), 337 ) 338 .await; 339 (input, proof) 340 } 341 342 /// Creates an exact retained schema/root with a caller's enrollment and key. 343 /// This is literal-shape/current-code evidence, never predecessor-binary evidence. 344 pub(in crate::workspace::stock) async fn literal_enrollment_catalog( 345 fixture: &CryptoFixture, 346 path: &std::path::Path, 347 catalog: i64, 348 enrollment: &StockEnrollment, 349 ) { 350 assert!(matches!(catalog, 13..=19)); 351 let record = enrollment.record.lock().unwrap().take().unwrap(); 352 literal_catalog_contents( 353 fixture, 354 path, 355 catalog, 356 enrollment.input(), 357 record, 358 enrollment.transaction_id(), 359 ) 360 .await; 361 } 362 async fn literal_catalog_contents( 363 fixture: &CryptoFixture, 364 path: &std::path::Path, 365 catalog: i64, 366 input: &AttachmentInput, 367 record: GrantRecord, 368 transaction: TransactionId, 369 ) { 370 let input = input.clone(); 371 // Literal retained catalog/root shapes from published creation/correction source; not predecessor-binary evidence. 372 let crypto = fixture.crypto(); 373 let grant_clear = if catalog >= 4 { 374 StockGrantRecord::from_enrollment(record) 375 .unwrap() 376 .encode() 377 .unwrap() 378 } else { 379 record.encode().unwrap() 380 }; 381 let grant = if catalog >= 4 { 382 crypto 383 .seal_stock_record(&input, "grant", input.grant_id().as_bytes(), &grant_clear) 384 .await 385 .unwrap() 386 } else { 387 crypto 388 .seal_stock(&input, false, &grant_clear) 389 .await 390 .unwrap() 391 }; 392 // The v4 namespace, grant2 and operation3 envelopes remain frozen literals. 393 let mut value = if catalog >= 4 { 394 serde_json::json!({"version":4,"namespace":SellerAuthoritySelection::from_attachment(&input),"administrator":input.grant_id(),"transaction":transaction,"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null},"authorization":grants::single_state(input.grant_id(),&grant).unwrap()}) 395 } else { 396 serde_json::json!({"version":catalog,"input":input,"transaction":transaction,"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null}}) 397 }; 398 if catalog >= 5 { 399 value["version"] = serde_json::json!(catalog); 400 value["inventory"]["mappings"] = serde_json::json!("0"); 401 } 402 if catalog >= 6 { 403 value["sources"] = 404 serde_json::json!({"revision":"0","records":"0","parts":"0","head":null}); 405 } 406 if catalog >= 7 { 407 value["inventory"]["orders"] = serde_json::json!("0"); 408 } 409 if matches!(catalog, 8..=19) { 410 value["public_sources"] = 411 serde_json::json!({"revision":"0","events":"0","heads":"0","parts":"0","head":null}); 412 } 413 let clear = zeroize::Zeroizing::new(serde_json::to_vec(&value).unwrap()); 414 let root = crypto 415 .seal_stock_root(&input, catalog, &clear) 416 .await 417 .unwrap(); 418 let namespace = Namespace::acquire_kind(path, true, Kind::SellerStock).unwrap(); 419 let mut connection = SqliteConnection::connect_with( 420 &sqlx::sqlite::SqliteConnectOptions::new() 421 .filename(namespace.database_path()) 422 .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) 423 .synchronous(sqlx::sqlite::SqliteSynchronous::Full), 424 ) 425 .await 426 .unwrap(); 427 let mut tx = connection.begin_with("BEGIN IMMEDIATE").await.unwrap(); 428 for (_, _, _, sql) in schema::objects(catalog).unwrap() { 429 sqlx::raw_sql(sql).execute(&mut *tx).await.unwrap(); 430 } 431 sqlx::query("INSERT INTO stock_authority(singleton,protected) VALUES(1,?)") 432 .bind(root) 433 .execute(&mut *tx) 434 .await 435 .unwrap(); 436 sqlx::query("INSERT INTO stock_grants(grant_id,protected) VALUES(?,?)") 437 .bind(input.grant_id().as_bytes().as_slice()) 438 .bind(grant) 439 .execute(&mut *tx) 440 .await 441 .unwrap(); 442 sqlx::query(match catalog { 443 2 => "PRAGMA user_version=2", 444 3 => "PRAGMA user_version=3", 445 4 => "PRAGMA user_version=4", 446 5 => "PRAGMA user_version=5", 447 6 => "PRAGMA user_version=6", 448 7 => "PRAGMA user_version=7", 449 8 => "PRAGMA user_version=8", 450 9 => "PRAGMA user_version=9", 451 10 => "PRAGMA user_version=10", 452 11 => "PRAGMA user_version=11", 453 12 => "PRAGMA user_version=12", 454 13 => "PRAGMA user_version=13", 455 14 => "PRAGMA user_version=14", 456 15 => "PRAGMA user_version=15", 457 16 => "PRAGMA user_version=16", 458 17 => "PRAGMA user_version=17", 459 18 => "PRAGMA user_version=18", 460 19 => "PRAGMA user_version=19", 461 _ => unreachable!(), 462 }) 463 .execute(&mut *tx) 464 .await 465 .unwrap(); 466 tx.commit().await.unwrap(); 467 connection.close().await.unwrap(); 468 drop(namespace); 469 } 470 471 async fn retained_inventory_catalog(catalog: i64) { 472 use radroots_storage::inventory::{InventoryCommandKind, InventoryOutcome}; 473 let fixture = CryptoFixture::new(); 474 let path = fixture.root().join("retained-v2"); 475 let (input, proof) = literal_catalog(&fixture, &path, catalog).await; 476 let store = 477 NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) 478 .await 479 .unwrap(); 480 let binding = store.authenticate(input.clone(), &proof).await.unwrap(); 481 let authority = store.stock_authority(input.clone(), &proof).await.unwrap(); 482 assert_eq!(authority.source_checkpoint().is_some(), catalog >= 6); 483 assert_eq!( 484 authority.listing_checkpoint().is_some(), 485 matches!(catalog, 8..=18) 486 ); 487 let minimum = authority.inventory_checkpoint().unwrap(); 488 assert_eq!( 489 store 490 .inspect_stock( 491 binding.clone(), 492 minimum, 493 PoolId::from_bytes([8; 32]), 494 proof 495 .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) 496 .unwrap() 497 ) 498 .await, 499 Err(OperationError::UnsupportedOperation) 500 ); 501 let context = CommandContextData::new( 502 OperationId::from_bytes([7; 32]), 503 binding.actor(), 504 input.workspace_id(), 505 input.authority(), 506 input.route_digest(), 507 None, 508 None, 509 UnixSeconds::new(150).unwrap(), 510 None, 511 ) 512 .unwrap(); 513 let wire = serde_json::json!({"type":"stock.create_pool","context":context,"input":{"id":PoolId::from_bytes([8;32]),"label":"retained","unit":"each","tick_scale":"0","initial_quantity":"1"}}); 514 let copy = || { 515 proof 516 .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) 517 .unwrap() 518 }; 519 let created = match store 520 .execute_inventory( 521 InventoryRequest::from_protected_wire( 522 binding.clone(), 523 minimum, 524 &serde_json::to_vec(&wire).unwrap(), 525 ) 526 .unwrap(), 527 copy(), 528 ) 529 .await 530 .unwrap() 531 { 532 InventoryOutcome::Committed(receipt) => *receipt, 533 InventoryOutcome::Unknown(_) => panic!("retained creation must confirm"), 534 }; 535 assert_eq!(created.kind(), InventoryCommandKind::CreatePool); 536 assert_eq!(created.pool().balances().physical().available.get(), 1); 537 store.close().await.unwrap(); 538 let store = 539 NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) 540 .await 541 .unwrap(); 542 assert_eq!( 543 store 544 .inventory_operation( 545 binding.clone(), 546 created.checkpoint(), 547 OperationId::from_bytes([7; 32]), 548 Some(created.attempt().command_digest()), 549 copy() 550 ) 551 .await 552 .unwrap(), 553 Some(created.clone()) 554 ); 555 let mut mapping = serde_json::json!({"type":"stock.map_option","context":context,"input":{"listing":{"kind":30402,"author":participant(),"d":"0a".repeat(16)},"option_id":"0b".repeat(32),"pool_id":PoolId::from_bytes([8;32]),"expected_mapping_version":"0","per_sale_unit":{"amount":"1","unit":"each"}}}); 556 mapping["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([11; 32])); 557 let mapped = store 558 .execute_inventory( 559 InventoryRequest::from_protected_wire( 560 binding.clone(), 561 created.checkpoint(), 562 &serde_json::to_vec(&mapping).unwrap(), 563 ) 564 .unwrap(), 565 copy(), 566 ) 567 .await; 568 if catalog < 5 { 569 assert_eq!(mapped, Err(OperationError::UnsupportedOperation)); 570 } else { 571 let InventoryOutcome::Committed(mapped) = mapped.unwrap() else { 572 panic!("retained mapping must confirm") 573 }; 574 assert_eq!(mapped.mapping().unwrap().version().get(), 1); 575 assert_eq!(mapped.pool(), created.pool()); 576 } 577 let mut corrected = serde_json::json!({"type":"stock.adjust","context":context,"input":{"pool_id":PoolId::from_bytes([8;32]),"expected_version":"1","direction":"add","amount":"1","reason":"new correction profile"}}); 578 corrected["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([10; 32])); 579 let correction = store 580 .execute_inventory( 581 InventoryRequest::from_protected_wire( 582 binding.clone(), 583 created.checkpoint(), 584 &serde_json::to_vec(&corrected).unwrap(), 585 ) 586 .unwrap(), 587 copy(), 588 ) 589 .await; 590 let mut latest = created.checkpoint(); 591 if catalog == 2 { 592 assert!(matches!( 593 correction, 594 Err(OperationError::UnsupportedOperation) 595 )); 596 } else { 597 match correction.unwrap() { 598 InventoryOutcome::Committed(value) => { 599 assert_eq!(value.pool().version().get(), 2); 600 assert_eq!(value.pool().balances().physical().available.get(), 2); 601 latest = value.checkpoint(); 602 } 603 InventoryOutcome::Unknown(_) => panic!("retained correction must confirm"), 604 } 605 } 606 if catalog >= 6 { 607 // The caller's minimum is newer than this original operation. A 608 // hidden SQL identity must still fail protected absence verification. 609 let mut raw = SqliteConnection::connect_with( 610 &sqlx::sqlite::SqliteConnectOptions::new() 611 .filename(path.join("stock_execution_v1.sqlite")) 612 .foreign_keys(false), 613 ) 614 .await 615 .unwrap(); 616 sqlx::query("UPDATE stock_operations SET operation_id=? WHERE operation_id=?") 617 .bind([0x78_u8; 32].as_slice()) 618 .bind([7_u8; 32].as_slice()) 619 .execute(&mut raw) 620 .await 621 .unwrap(); 622 assert!(matches!( 623 store 624 .inventory_operation( 625 binding.clone(), 626 latest, 627 OperationId::from_bytes([7; 32]), 628 None, 629 copy() 630 ) 631 .await, 632 Err(OperationError::RecoveryRequired 633 | OperationError::Workspace(WorkspaceError::RecoveryRequired)) 634 )); 635 assert!(matches!( 636 store 637 .execute_inventory( 638 InventoryRequest::from_protected_wire( 639 binding.clone(), 640 latest, 641 &serde_json::to_vec(&wire).unwrap() 642 ) 643 .unwrap(), 644 copy() 645 ) 646 .await, 647 Err(OperationError::RecoveryRequired 648 | OperationError::Workspace(WorkspaceError::RecoveryRequired)) 649 )); 650 sqlx::query("UPDATE stock_operations SET operation_id=? WHERE operation_id=?") 651 .bind([7_u8; 32].as_slice()) 652 .bind([0x78_u8; 32].as_slice()) 653 .execute(&mut raw) 654 .await 655 .unwrap(); 656 raw.close().await.unwrap(); 657 assert_eq!( 658 store 659 .inventory_operation( 660 binding.clone(), 661 latest, 662 OperationId::from_bytes([7; 32]), 663 None, 664 copy() 665 ) 666 .await 667 .unwrap(), 668 Some(created.clone()) 669 ); 670 } 671 if catalog >= 4 { 672 let child = StockGrantEnrollment::prepare( 673 &SellerAuthoritySelection::from_attachment(&input), 674 "retained-device".into(), 675 UnixSeconds::new(200).unwrap(), 676 StockGrantScope::full_inventory(), 677 ) 678 .unwrap(); 679 let receipt = match store 680 .enroll_stock_grant(binding.clone(), latest, &proof, &child) 681 .await 682 .unwrap() 683 { 684 StockGrantOutcome::Committed(value) => value, 685 _ => panic!("retained grant must confirm"), 686 }; 687 latest = latest.with_authorization(receipt.authorization()); 688 let delegated = store 689 .authenticate(child.input().clone(), child.proof()) 690 .await 691 .unwrap(); 692 let child_proof = child 693 .proof() 694 .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) 695 .unwrap(); 696 assert_eq!( 697 store 698 .pool(delegated, latest, PoolId::from_bytes([8; 32]), child_proof) 699 .await 700 .unwrap() 701 .unwrap() 702 .snapshot() 703 .balances() 704 .physical() 705 .available 706 .get(), 707 2 708 ); 709 } 710 store.close().await.unwrap(); 711 let reopened = 712 NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) 713 .await 714 .unwrap(); 715 assert_eq!( 716 reopened 717 .inventory_operation( 718 binding.clone(), 719 latest, 720 OperationId::from_bytes([7; 32]), 721 None, 722 copy() 723 ) 724 .await 725 .unwrap(), 726 Some(created) 727 ); 728 reopened.close().await.unwrap(); 729 let mut connection = SqliteConnection::connect_with( 730 &sqlx::sqlite::SqliteConnectOptions::new().filename(path.join("stock_execution_v1.sqlite")), 731 ) 732 .await 733 .unwrap(); 734 assert_eq!(schema::admit(&mut connection).await.unwrap(), catalog); 735 let protected: Vec<u8> = 736 sqlx::query_scalar("SELECT protected FROM stock_operations WHERE operation_id=?") 737 .bind(OperationId::from_bytes([7; 32]).as_bytes().as_slice()) 738 .fetch_one(&mut connection) 739 .await 740 .unwrap(); 741 let old = if matches!(catalog, 7..=18) { 742 let retained = ledger::read( 743 &mut connection, 744 &input, 745 &fixture.crypto(), 746 OperationId::from_bytes([7; 32]), 747 ) 748 .await 749 .unwrap() 750 .unwrap(); 751 assert_eq!(retained.header.version, 5); 752 assert_eq!(retained.header.family.code(), 0); 753 retained.body 754 } else { 755 let old = fixture 756 .crypto() 757 .open_stock_record_for_catalog( 758 &input, 759 "operation", 760 OperationId::from_bytes([7; 32]).as_bytes(), 761 catalog, 762 &protected, 763 ) 764 .await 765 .unwrap(); 766 old.expose_secret(|bytes| zeroize::Zeroizing::new(bytes.to_vec())) 767 }; 768 { 769 let bytes = old.as_slice(); 770 let value: serde_json::Value = serde_json::from_slice(bytes).unwrap(); 771 let value = if catalog >= 4 { 772 assert_eq!(value["version"], if catalog == 4 { 3 } else { 4 }); 773 if catalog == 4 { 774 assert!(value.get("mapping").is_none()); 775 } else { 776 assert_eq!(value["mapping"], serde_json::Value::Null); 777 } 778 value["operation"].clone() 779 } else { 780 value 781 }; 782 assert_eq!(value["version"], if catalog == 2 { 1 } else { 2 }); 783 if catalog == 2 { 784 assert!(value.get("before").is_none()); 785 } else { 786 assert_eq!(value["before"], serde_json::Value::Null); 787 } 788 } 789 if catalog >= 6 { 790 // Exercise the actual minimum/projection witness after provider IO, 791 // inside a real SQL transaction. Row counts and the protected header 792 // stay unchanged while one referenced ciphertext changes. 793 for part in [false, true] { 794 if part && !matches!(catalog, 7..=18) { 795 continue; 796 } 797 let (authority, _, _, _) = read(&mut connection, &input, &fixture.crypto()) 798 .await 799 .unwrap(); 800 let minimum = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( 801 input.authority(), 802 Sequence::new(0).unwrap(), 803 None, 804 ) 805 .unwrap() 806 .with_optional_authorization(authority.authorization); 807 let witness = inventory::grant_minimum( 808 &mut connection, 809 &input, 810 &fixture.crypto(), 811 &binding, 812 &authority, 813 minimum, 814 ) 815 .await 816 .unwrap(); 817 let (select, mutate, restore) = if part { 818 ( 819 "SELECT protected FROM stock_operation_parts WHERE operation_id=? AND part=0", 820 "UPDATE stock_operation_parts SET protected=randomblob(length(protected)) WHERE operation_id=? AND part=0", 821 "UPDATE stock_operation_parts SET protected=? WHERE operation_id=? AND part=0", 822 ) 823 } else { 824 ( 825 "SELECT protected FROM stock_movements WHERE operation_id=?", 826 "UPDATE stock_movements SET protected=randomblob(length(protected)) WHERE operation_id=?", 827 "UPDATE stock_movements SET protected=? WHERE operation_id=?", 828 ) 829 }; 830 let original: Vec<u8> = sqlx::query_scalar(select) 831 .bind(OperationId::from_bytes([7; 32]).as_bytes().as_slice()) 832 .fetch_one(&mut connection) 833 .await 834 .unwrap(); 835 sqlx::query(mutate) 836 .bind(OperationId::from_bytes([7; 32]).as_bytes().as_slice()) 837 .execute(&mut connection) 838 .await 839 .unwrap(); 840 let mut tx = connection.begin_with("BEGIN IMMEDIATE").await.unwrap(); 841 assert_eq!( 842 witness.confirm(&mut tx).await, 843 Err(OperationError::RecoveryRequired) 844 ); 845 tx.rollback().await.unwrap(); 846 sqlx::query(restore) 847 .bind(original) 848 .bind(OperationId::from_bytes([7; 32]).as_bytes().as_slice()) 849 .execute(&mut connection) 850 .await 851 .unwrap(); 852 let mut tx = connection.begin_with("BEGIN IMMEDIATE").await.unwrap(); 853 assert_eq!(witness.confirm(&mut tx).await, Ok(())); 854 tx.rollback().await.unwrap(); 855 } 856 } 857 sqlx::query(match catalog { 858 2 => "PRAGMA user_version=3", 859 3 => "PRAGMA user_version=4", 860 4 => "PRAGMA user_version=5", 861 5 => "PRAGMA user_version=6", 862 6 => "PRAGMA user_version=7", 863 7 => "PRAGMA user_version=6", 864 8 => "PRAGMA user_version=7", 865 9 => "PRAGMA user_version=8", 866 10 => "PRAGMA user_version=9", 867 11 => "PRAGMA user_version=10", 868 12 => "PRAGMA user_version=11", 869 13 => "PRAGMA user_version=12", 870 14 => "PRAGMA user_version=13", 871 15 => "PRAGMA user_version=14", 872 16 => "PRAGMA user_version=15", 873 17 => "PRAGMA user_version=16", 874 18 => "PRAGMA user_version=17", 875 _ => unreachable!(), 876 }) 877 .execute(&mut connection) 878 .await 879 .unwrap(); 880 connection.close().await.unwrap(); 881 assert!( 882 NativeWorkspace::open_seller_stock(&path, input, fixture.crypto(), Arc::new(Clock)) 883 .await 884 .is_err() 885 ); 886 } 887 #[tokio::test] 888 async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() { 889 let fixture = CryptoFixture::new(); 890 let path = fixture.root().join("retained-v1"); 891 let (input, proof, record) = SellerStockConfig::new( 892 participant(), 893 participant(), 894 "retained-stock-owner", 895 UnixSeconds::new(200).unwrap(), 896 ) 897 .unwrap() 898 .enroll( 899 UnixSeconds::new(100).unwrap(), 900 WorkspaceId::from_bytes([1; 32]), 901 ExecutorId::from_bytes([2; 32]), 902 GrantId::from_bytes([3; 32]), 903 AttachmentProof::from_protected_input(&[0xA3; 32]).unwrap(), 904 ) 905 .unwrap(); 906 // Exact version1 shape introduced by a4cc1a1c; this is a literal retained 907 // codec/catalog fixture, not a claim that a predecessor binary ran here. 908 let clear=zeroize::Zeroizing::new(serde_json::to_vec(&serde_json::json!({"version":1,"input":input,"transaction":TransactionId::from_bytes([9;32]),"revocation":"1"})).unwrap()); 909 let crypto = fixture.crypto(); 910 let root = crypto.seal_stock(&input, true, &clear).await.unwrap(); 911 let grant = crypto 912 .seal_stock(&input, false, &record.encode().unwrap()) 913 .await 914 .unwrap(); 915 let namespace = Namespace::acquire_kind(&path, true, Kind::SellerStock).unwrap(); 916 let mut connection = SqliteConnection::connect_with( 917 &sqlx::sqlite::SqliteConnectOptions::new() 918 .filename(namespace.database_path()) 919 .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) 920 .synchronous(sqlx::sqlite::SqliteSynchronous::Full), 921 ) 922 .await 923 .unwrap(); 924 let mut tx = connection.begin_with("BEGIN IMMEDIATE").await.unwrap(); 925 for (_, _, _, sql) in schema::objects(1).unwrap() { 926 sqlx::raw_sql(sql).execute(&mut *tx).await.unwrap(); 927 } 928 sqlx::query("INSERT INTO stock_authority(singleton,protected) VALUES(1,?)") 929 .bind(root) 930 .execute(&mut *tx) 931 .await 932 .unwrap(); 933 sqlx::query("INSERT INTO stock_grants(grant_id,protected) VALUES(?,?)") 934 .bind(input.grant_id().as_bytes().as_slice()) 935 .bind(grant) 936 .execute(&mut *tx) 937 .await 938 .unwrap(); 939 sqlx::query("PRAGMA user_version=1") 940 .execute(&mut *tx) 941 .await 942 .unwrap(); 943 tx.commit().await.unwrap(); 944 connection.close().await.unwrap(); 945 drop(namespace); 946 let store = 947 NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) 948 .await 949 .unwrap(); 950 let binding = store.authenticate(input.clone(), &proof).await.unwrap(); 951 assert!( 952 store 953 .stock_authority(input.clone(), &proof) 954 .await 955 .unwrap() 956 .inventory_checkpoint() 957 .is_none() 958 ); 959 let context = CommandContextData::new( 960 OperationId::from_bytes([7; 32]), 961 binding.actor(), 962 input.workspace_id(), 963 input.authority(), 964 input.route_digest(), 965 None, 966 None, 967 UnixSeconds::new(150).unwrap(), 968 None, 969 ) 970 .unwrap(); 971 let wire = serde_json::json!({"type":"stock.create_pool","context":context,"input":{"id":PoolId::from_bytes([8;32]),"label":"retained","unit":"each","tick_scale":"0","initial_quantity":"1"}}); 972 let request = InventoryRequest::from_protected_wire( 973 binding, 974 InventoryCheckpointRef::from_host_metadata( 975 input.authority(), 976 Sequence::new(0).unwrap(), 977 None, 978 ) 979 .unwrap(), 980 &serde_json::to_vec(&wire).unwrap(), 981 ) 982 .unwrap(); 983 let copy = proof 984 .with_secret(|b| AttachmentProof::from_protected_input(b)) 985 .unwrap(); 986 assert!(matches!( 987 store.execute_inventory(request, copy).await, 988 Err(OperationError::UnsupportedOperation) 989 )); 990 store.close().await.unwrap(); 991 let mut connection = SqliteConnection::connect_with( 992 &sqlx::sqlite::SqliteConnectOptions::new() 993 .filename(path.join("stock_execution_v1.sqlite")) 994 .read_only(true), 995 ) 996 .await 997 .unwrap(); 998 assert_eq!(schema::admit(&mut connection).await.unwrap(), 1); 999 connection.close().await.unwrap(); 1000 } 1001 1002 #[tokio::test] 1003 async fn retained_v12_preserves_initial_installation_catalog_without_upgrade() { 1004 assert_eq!(schema::CURRENT, 20); 1005 retained_inventory_catalog(12).await; 1006 } 1007 1008 #[tokio::test] 1009 async fn retained_v13_authenticates_literal_catalog_and_original_inventory_records() { 1010 assert_eq!(schema::CURRENT, 20); 1011 retained_inventory_catalog(13).await; 1012 } 1013 1014 #[tokio::test] 1015 async fn retained_v14_authenticates_literal_catalog_and_original_inventory_records() { 1016 assert_eq!(schema::CURRENT, 20); 1017 retained_inventory_catalog(14).await; 1018 } 1019 1020 #[tokio::test] 1021 async fn retained_v15_authenticates_literal_catalog_and_original_inventory_records() { 1022 assert_eq!(schema::CURRENT, 20); 1023 retained_inventory_catalog(15).await; 1024 } 1025 1026 #[tokio::test] 1027 async fn retained_v16_authenticates_literal_catalog_and_original_inventory_records() { 1028 assert_eq!(schema::CURRENT, 20); 1029 retained_inventory_catalog(16).await; 1030 } 1031 1032 #[tokio::test] 1033 async fn retained_v17_authenticates_original_delivery_catalog_without_upgrade() { 1034 assert_eq!(schema::CURRENT, 20); 1035 retained_inventory_catalog(17).await; 1036 } 1037 1038 #[tokio::test] 1039 async fn retained_v18_authenticates_original_rewrap_catalog_without_upgrade() { 1040 assert_eq!(schema::CURRENT, 20); 1041 retained_inventory_catalog(18).await; 1042 } 1043 1044 #[tokio::test] 1045 async fn retained_v19_preserves_deficit_catalog_without_obligation_transition_table_or_upgrade() { 1046 assert_eq!(schema::CURRENT, 20); 1047 let fixture = CryptoFixture::new(); 1048 let path = fixture.root().join("retained19"); 1049 let (input, proof) = literal_catalog(&fixture, &path, 19).await; 1050 let store = 1051 NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) 1052 .await 1053 .unwrap(); 1054 let binding = store.authenticate(input.clone(), &proof).await.unwrap(); 1055 assert_eq!(binding.actor().participant(), input.participant()); 1056 store.close().await.unwrap(); 1057 let mut raw = SqliteConnection::connect_with( 1058 &sqlx::sqlite::SqliteConnectOptions::new().filename(path.join("stock_execution_v1.sqlite")), 1059 ) 1060 .await 1061 .unwrap(); 1062 assert_eq!( 1063 sqlx::query_scalar::<_, i64>("PRAGMA user_version") 1064 .fetch_one(&mut raw) 1065 .await 1066 .unwrap(), 1067 19 1068 ); 1069 assert_eq!( 1070 sqlx::query_scalar::<_, i64>( 1071 "SELECT count(*) FROM sqlite_schema WHERE type='table' AND name='stock_deficits'" 1072 ) 1073 .fetch_one(&mut raw) 1074 .await 1075 .unwrap(), 1076 1 1077 ); 1078 assert_eq!(sqlx::query_scalar::<_,i64>("SELECT count(*) FROM sqlite_schema WHERE type='table' AND name='stock_obligation_changes'").fetch_one(&mut raw).await.unwrap(),0); 1079 raw.close().await.unwrap(); 1080 }