tests.rs (33125B)
1 //! Real native observation persistence over independent signed inputs. A 2 //! selected head remains observation evidence, never business permission. 3 use super::*; 4 use crate::workspace::tests::{CryptoFixture, participant}; 5 use radroots_domain::{PublicKey, UnixSeconds}; 6 use radroots_storage::{ 7 command::OperationError, workspace::seller_stock::StockListingCheckpointRef, 8 }; 9 use std::sync::atomic::{AtomicU64, Ordering}; 10 #[path = "test_provider.rs"] 11 mod provider; 12 13 struct Clock(AtomicU64); 14 impl WorkspaceClock for Clock { 15 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 16 UnixSeconds::new(self.0.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) 17 } 18 } 19 fn vectors() -> serde_json::Value { 20 serde_json::from_str(include_str!( 21 "../../../../tests/fixtures/stock_public_sources.v1.json" 22 )) 23 .unwrap() 24 } 25 fn vector(name: &str) -> String { 26 vectors()["vectors"] 27 .as_array() 28 .unwrap() 29 .iter() 30 .find(|row| row["name"] == name) 31 .unwrap()["raw"] 32 .as_str() 33 .unwrap() 34 .into() 35 } 36 struct Rig { 37 catalog: i64, 38 fixture: CryptoFixture, 39 path: std::path::PathBuf, 40 store: NativeWorkspace, 41 enrollment: StockEnrollment, 42 binding: WorkspaceBinding, 43 clock: Arc<Clock>, 44 } 45 impl Rig { 46 async fn new() -> Self { 47 Self::with_catalog(super::super::schema::CURRENT).await 48 } 49 async fn with_catalog(catalog: i64) -> Self { 50 let fixture = CryptoFixture::new(); 51 let path = fixture.root().join("public-sources"); 52 let owner = PublicKey::from_hex(vectors()["author"].as_str().unwrap()).unwrap(); 53 let clock = Arc::new(Clock(AtomicU64::new(150))); 54 let enrollment = StockEnrollment::prepare( 55 SellerStockConfig::new( 56 owner, 57 participant(), 58 "public-source-owner", 59 UnixSeconds::new(300).unwrap(), 60 ) 61 .unwrap(), 62 clock.as_ref(), 63 ) 64 .unwrap(); 65 let store = if catalog == super::super::schema::CURRENT { 66 NativeWorkspace::initialize_seller_stock( 67 &path, 68 &enrollment, 69 fixture.crypto(), 70 clock.clone(), 71 ) 72 .await 73 .unwrap() 74 } else { 75 super::super::tests::literal_enrollment_catalog(&fixture, &path, catalog, &enrollment) 76 .await; 77 NativeWorkspace::open_seller_stock( 78 &path, 79 enrollment.input().clone(), 80 fixture.crypto(), 81 clock.clone(), 82 ) 83 .await 84 .unwrap() 85 }; 86 let binding = store 87 .authenticate(enrollment.input().clone(), enrollment.proof()) 88 .await 89 .unwrap(); 90 Self { 91 catalog, 92 fixture, 93 path, 94 store, 95 enrollment, 96 binding, 97 clock, 98 } 99 } 100 fn authority_schema(&self) -> &'static str { 101 crate::workspace::stock::tests::catalog_authority_schema(self.catalog) 102 } 103 fn capture_raw(&self, raw: &str) -> StockListingCapture { 104 let mut observed = ObservedHead::listing( 105 self.enrollment.input().participant(), 106 vectors()["d"].as_str().unwrap(), 107 ) 108 .unwrap(); 109 observed.observe(raw).unwrap(); 110 StockListingCapture::prepare( 111 SellerAuthoritySelection::from_attachment(self.enrollment.input()), 112 &observed, 113 ) 114 .unwrap() 115 } 116 fn capture(&self, name: &str) -> StockListingCapture { 117 self.capture_raw(&vector(name)) 118 } 119 async fn minimum(&self) -> StockListingCheckpointRef { 120 self.store 121 .stock_authority(self.enrollment.input().clone(), self.enrollment.proof()) 122 .await 123 .unwrap() 124 .listing_checkpoint() 125 .unwrap() 126 } 127 async fn retain(&self, capture: &StockListingCapture) -> StockListingReceipt { 128 committed( 129 self.store 130 .retain_stock_listing( 131 self.binding.clone(), 132 self.minimum().await, 133 capture, 134 self.enrollment.proof(), 135 ) 136 .await 137 .unwrap(), 138 ) 139 } 140 } 141 fn committed(value: StockListingOutcome) -> StockListingReceipt { 142 match value { 143 StockListingOutcome::Committed(value) => *value, 144 _ => panic!("retention must confirm"), 145 } 146 } 147 148 #[tokio::test] 149 async fn native_original_observation_reopens_and_deduplicates_transport_encodings_without_replacement() 150 { 151 let r = Rig::new().await; 152 let capture = r.capture("listing_fixed"); 153 let before = r 154 .store 155 .stock_authority(r.enrollment.input().clone(), r.enrollment.proof()) 156 .await 157 .unwrap(); 158 let receipt = r.retain(&capture).await; 159 assert_eq!(receipt.transaction_id(), capture.transaction_id()); 160 assert_eq!(receipt.checkpoint().revision().get(), 1); 161 assert!(receipt.selected_at_retention()); 162 let alias = serde_json::to_string_pretty( 163 &serde_json::from_str::<serde_json::Value>(&vector("listing_fixed")).unwrap(), 164 ) 165 .unwrap(); 166 assert_ne!(alias, vector("listing_fixed")); 167 let alias = r.capture_raw(&alias); 168 assert_ne!(alias.transaction_id(), capture.transaction_id()); 169 assert_eq!(r.retain(&alias).await, receipt); 170 let after = r 171 .store 172 .stock_authority(r.enrollment.input().clone(), r.enrollment.proof()) 173 .await 174 .unwrap(); 175 assert_eq!(before.inventory_checkpoint(), after.inventory_checkpoint()); 176 assert_eq!(before.source_checkpoint(), after.source_checkpoint()); 177 let source = r 178 .store 179 .stock_listing_source( 180 r.binding.clone(), 181 receipt.checkpoint(), 182 capture.listing_revision(), 183 r.enrollment.proof(), 184 ) 185 .await 186 .unwrap() 187 .unwrap(); 188 assert_eq!(source.raw_json(), vector("listing_fixed")); 189 assert!(source.is_current_observed()); 190 assert!(matches!( 191 source.interpret_at_observation().unwrap(), 192 radroots_nostr::public_ingress::Interpretation::Listing(_) 193 )); 194 r.store.close().await.unwrap(); 195 let store = NativeWorkspace::open_seller_stock( 196 &r.path, 197 r.enrollment.input().clone(), 198 r.fixture.crypto(), 199 r.clock.clone(), 200 ) 201 .await 202 .unwrap(); 203 let source = store 204 .stock_listing_head( 205 r.binding.clone(), 206 receipt.checkpoint(), 207 capture.listing_revision().coordinate(), 208 r.enrollment.proof(), 209 ) 210 .await 211 .unwrap() 212 .unwrap(); 213 assert_eq!(source.receipt(), &receipt); 214 assert_eq!(source.raw_json(), vector("listing_fixed")); 215 store.close().await.unwrap(); 216 } 217 218 #[tokio::test] 219 async fn protected_heads_match_independent_timestamp_and_id_oracles_without_profile_fallback() { 220 for steps in vectors()["ranking_oracles"].as_array().unwrap() { 221 let r = Rig::new().await; 222 for step in steps.as_array().unwrap() { 223 let capture = r.capture(step["input"].as_str().unwrap()); 224 r.retain(&capture).await; 225 let head = r 226 .store 227 .stock_listing_head( 228 r.binding.clone(), 229 r.minimum().await, 230 capture.listing_revision().coordinate(), 231 r.enrollment.proof(), 232 ) 233 .await 234 .unwrap() 235 .unwrap(); 236 assert_eq!( 237 head.receipt().listing_revision().event_id().to_string(), 238 step["head"].as_str().unwrap() 239 ); 240 } 241 let old = r.capture("listing_fixed"); 242 let original = r 243 .store 244 .stock_listing_source( 245 r.binding.clone(), 246 r.minimum().await, 247 old.listing_revision(), 248 r.enrollment.proof(), 249 ) 250 .await 251 .unwrap() 252 .unwrap(); 253 assert_eq!(original.raw_json(), vector("listing_fixed")); 254 r.store.close().await.unwrap(); 255 } 256 for (name, expected) in [ 257 ("listing_unsupported", "unsupported"), 258 ("listing_unknown_field", "invalid"), 259 ("listing_future", "clock_ahead"), 260 ] { 261 let r = Rig::new().await; 262 let old = r.capture("listing_fixed"); 263 r.retain(&old).await; 264 let next = r.capture(name); 265 r.retain(&next).await; 266 let head = r 267 .store 268 .stock_listing_head( 269 r.binding.clone(), 270 r.minimum().await, 271 old.listing_revision().coordinate(), 272 r.enrollment.proof(), 273 ) 274 .await 275 .unwrap() 276 .unwrap(); 277 assert_eq!(head.receipt().listing_revision(), next.listing_revision()); 278 let classification = match head.interpret_at_observation().unwrap() { 279 radroots_nostr::public_ingress::Interpretation::Unsupported => "unsupported", 280 radroots_nostr::public_ingress::Interpretation::Invalid => "invalid", 281 radroots_nostr::public_ingress::Interpretation::ClockAhead => "clock_ahead", 282 _ => panic!("must not fall back"), 283 }; 284 assert_eq!(classification, expected); 285 let old = r 286 .store 287 .stock_listing_source( 288 r.binding.clone(), 289 r.minimum().await, 290 old.listing_revision(), 291 r.enrollment.proof(), 292 ) 293 .await 294 .unwrap() 295 .unwrap(); 296 assert!(!old.is_current_observed()); 297 assert!(old.receipt().selected_at_retention()); 298 r.store.close().await.unwrap(); 299 } 300 } 301 302 #[tokio::test] 303 async fn full_event_bounds_and_invalid_profile_bytes_are_retained_after_signature_admission() { 304 for name in [ 305 "listing_exact_event_bound", 306 "listing_large_profile", 307 "listing_duplicate_d", 308 "listing_ambiguous_d", 309 "listing_contradictory_price", 310 "listing_recurring_price", 311 "listing_duplicate_profile", 312 ] { 313 let r = Rig::new().await; 314 let capture = r.capture(name); 315 let receipt = r.retain(&capture).await; 316 let source = r 317 .store 318 .stock_listing_source( 319 r.binding.clone(), 320 receipt.checkpoint(), 321 capture.listing_revision(), 322 r.enrollment.proof(), 323 ) 324 .await 325 .unwrap() 326 .unwrap(); 327 assert_eq!(source.raw_json(), vector(name)); 328 if name == "listing_exact_event_bound" { 329 assert_eq!(source.raw_json().len(), 65536); 330 } 331 r.store.close().await.unwrap(); 332 } 333 let r = Rig::new().await; 334 for name in ["bad_id", "bad_signature", "capability"] { 335 let mut observed = ObservedHead::listing( 336 r.enrollment.input().participant(), 337 vectors()["d"].as_str().unwrap(), 338 ) 339 .unwrap(); 340 assert!(observed.observe(&vector(name)).is_err()); 341 assert!( 342 StockListingCapture::prepare( 343 SellerAuthoritySelection::from_attachment(r.enrollment.input()), 344 &observed 345 ) 346 .is_err() 347 ); 348 } 349 let capture = r.capture("listing_fixed"); 350 let wrong = SellerStockConfig::new( 351 participant(), 352 participant(), 353 "wrong", 354 UnixSeconds::new(300).unwrap(), 355 ) 356 .unwrap() 357 .enroll( 358 UnixSeconds::new(150).unwrap(), 359 WorkspaceId::from_bytes([1; 32]), 360 ExecutorId::from_bytes([2; 32]), 361 GrantId::from_bytes([3; 32]), 362 AttachmentProof::from_protected_input(&[4; 32]).unwrap(), 363 ) 364 .unwrap() 365 .0; 366 let mut observed = ObservedHead::listing( 367 r.enrollment.input().participant(), 368 vectors()["d"].as_str().unwrap(), 369 ) 370 .unwrap(); 371 observed.observe(&vector("listing_fixed")).unwrap(); 372 assert!(matches!( 373 StockListingCapture::prepare(SellerAuthoritySelection::from_attachment(&wrong), &observed), 374 Err(WorkspaceError::WrongNamespace) 375 )); 376 let wrong_proof = AttachmentProof::from_protected_input(&[9; 32]).unwrap(); 377 assert!( 378 r.store 379 .retain_stock_listing(r.binding.clone(), r.minimum().await, &capture, &wrong_proof) 380 .await 381 .is_err() 382 ); 383 r.clock.0.store(300, Ordering::SeqCst); 384 assert!(matches!( 385 r.store 386 .retain_stock_listing( 387 r.binding.clone(), 388 StockListingCheckpointRef::from_host_metadata( 389 r.enrollment.input().authority(), 390 radroots_domain::Sequence::new(0).unwrap(), 391 None 392 ) 393 .unwrap(), 394 &capture, 395 r.enrollment.proof() 396 ) 397 .await, 398 Err(OperationError::Workspace(WorkspaceError::GrantExpired)) 399 )); 400 r.store.close().await.unwrap(); 401 } 402 403 async fn database(r: &Rig) -> SqliteConnection { 404 SqliteConnection::connect_with( 405 &sqlx::sqlite::SqliteConnectOptions::new() 406 .filename(r.path.join("stock_execution_v1.sqlite")) 407 .foreign_keys(false), 408 ) 409 .await 410 .unwrap() 411 } 412 413 #[tokio::test] 414 async fn every_public_write_window_rolls_back_exact_progress_and_retained_originals() { 415 for (initial, trigger) in [ 416 ( 417 false, 418 "CREATE TRIGGER fault BEFORE INSERT ON stock_public_events BEGIN SELECT RAISE(ABORT,'fixture'); END", 419 ), 420 ( 421 false, 422 "CREATE TRIGGER fault BEFORE INSERT ON stock_public_parts BEGIN SELECT RAISE(ABORT,'fixture'); END", 423 ), 424 ( 425 false, 426 "CREATE TRIGGER fault BEFORE INSERT ON stock_public_heads BEGIN SELECT RAISE(ABORT,'fixture'); END", 427 ), 428 ( 429 true, 430 "CREATE TRIGGER fault BEFORE UPDATE ON stock_public_heads BEGIN SELECT RAISE(ABORT,'fixture'); END", 431 ), 432 ( 433 false, 434 "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fixture'); END", 435 ), 436 ] { 437 let r = Rig::new().await; 438 if initial { 439 r.retain(&r.capture("listing_fixed")).await; 440 } 441 let minimum = r.minimum().await; 442 let capture = r.capture("listing_unsupported"); 443 let mut raw = database(&r).await; 444 sqlx::raw_sql(trigger).execute(&mut raw).await.unwrap(); 445 assert_eq!( 446 r.store 447 .retain_stock_listing(r.binding.clone(), minimum, &capture, r.enrollment.proof()) 448 .await, 449 Err(OperationError::StorageFailure) 450 ); 451 assert_eq!(r.minimum().await, minimum); 452 let events: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_public_events") 453 .fetch_one(&mut raw) 454 .await 455 .unwrap(); 456 assert_eq!(events, i64::from(initial)); 457 let parts: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_public_parts") 458 .fetch_one(&mut raw) 459 .await 460 .unwrap(); 461 assert_eq!(parts, i64::from(initial)); 462 sqlx::raw_sql("DROP TRIGGER fault") 463 .execute(&mut raw) 464 .await 465 .unwrap(); 466 raw.close().await.unwrap(); 467 assert_eq!( 468 r.retain(&capture).await.transaction_id(), 469 capture.transaction_id() 470 ); 471 r.store.close().await.unwrap(); 472 } 473 } 474 475 #[tokio::test] 476 async fn failed_public_commit_keeps_original_identity_and_requires_drain_and_reopen() { 477 let r = Rig::new().await; 478 let capture = r.capture("listing_fixed"); 479 let minimum = r.minimum().await; 480 let mut raw = database(&r).await; 481 sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fault AFTER INSERT ON stock_public_events BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut raw).await.unwrap(); 482 assert_eq!( 483 r.store 484 .retain_stock_listing(r.binding.clone(), minimum, &capture, r.enrollment.proof()) 485 .await 486 .unwrap(), 487 StockListingOutcome::Unknown { 488 transaction: capture.transaction_id(), 489 listing: capture.listing_revision() 490 } 491 ); 492 assert!(matches!( 493 r.store 494 .stock_listing_head( 495 r.binding.clone(), 496 minimum, 497 capture.listing_revision().coordinate(), 498 r.enrollment.proof() 499 ) 500 .await, 501 Err(OperationError::RecoveryRequired) 502 )); 503 r.store.close().await.unwrap(); 504 sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") 505 .execute(&mut raw) 506 .await 507 .unwrap(); 508 raw.close().await.unwrap(); 509 let store = NativeWorkspace::open_seller_stock( 510 &r.path, 511 r.enrollment.input().clone(), 512 r.fixture.crypto(), 513 r.clock.clone(), 514 ) 515 .await 516 .unwrap(); 517 assert!( 518 store 519 .stock_listing_head( 520 r.binding.clone(), 521 minimum, 522 capture.listing_revision().coordinate(), 523 r.enrollment.proof() 524 ) 525 .await 526 .unwrap() 527 .is_none() 528 ); 529 let receipt = committed( 530 store 531 .retain_stock_listing(r.binding.clone(), minimum, &capture, r.enrollment.proof()) 532 .await 533 .unwrap(), 534 ); 535 assert_eq!(receipt.transaction_id(), capture.transaction_id()); 536 store.close().await.unwrap(); 537 } 538 539 #[tokio::test] 540 async fn changed_projection_and_hidden_original_identity_refuse_without_repair() { 541 for projection in [true, false] { 542 let r = Rig::new().await; 543 let original = r.capture("listing_fixed"); 544 r.retain(&original).await; 545 r.retain(&r.capture("listing_unsupported")).await; 546 let minimum = r.minimum().await; 547 let mut raw = database(&r).await; 548 if projection { 549 sqlx::query("UPDATE stock_public_heads SET listing_d=?") 550 .bind([0x77_u8; 16].as_slice()) 551 .execute(&mut raw) 552 .await 553 .unwrap(); 554 } else { 555 sqlx::query("UPDATE stock_public_events SET event_id=? WHERE event_id=?") 556 .bind([0x78_u8; 32].as_slice()) 557 .bind(original.listing_revision().event_id().as_bytes().as_slice()) 558 .execute(&mut raw) 559 .await 560 .unwrap(); 561 } 562 assert!( 563 r.store 564 .stock_listing_source( 565 r.binding.clone(), 566 minimum, 567 original.listing_revision(), 568 r.enrollment.proof() 569 ) 570 .await 571 .is_err() 572 ); 573 if !projection { 574 assert!( 575 r.store 576 .retain_stock_listing( 577 r.binding.clone(), 578 minimum, 579 &original, 580 r.enrollment.proof() 581 ) 582 .await 583 .is_err() 584 ); 585 sqlx::query("UPDATE stock_public_events SET event_id=? WHERE event_id=?") 586 .bind(original.listing_revision().event_id().as_bytes().as_slice()) 587 .bind([0x78_u8; 32].as_slice()) 588 .execute(&mut raw) 589 .await 590 .unwrap(); 591 } else { 592 sqlx::query("UPDATE stock_public_heads SET listing_d=?") 593 .bind( 594 original 595 .listing_revision() 596 .coordinate() 597 .d() 598 .as_bytes() 599 .as_slice(), 600 ) 601 .execute(&mut raw) 602 .await 603 .unwrap(); 604 } 605 assert_eq!( 606 r.store 607 .stock_listing_source( 608 r.binding.clone(), 609 minimum, 610 original.listing_revision(), 611 r.enrollment.proof() 612 ) 613 .await 614 .unwrap() 615 .unwrap() 616 .raw_json(), 617 vector("listing_fixed") 618 ); 619 raw.close().await.unwrap(); 620 r.store.close().await.unwrap(); 621 } 622 } 623 624 #[tokio::test] 625 async fn physical_grants_have_no_public_source_access_and_exact_current_generation_is_required() { 626 let r = Rig::new().await; 627 let capture = r.capture("listing_fixed"); 628 let original = r.retain(&capture).await; 629 let stale = r.minimum().await; 630 let inventory = r 631 .store 632 .stock_authority(r.enrollment.input().clone(), r.enrollment.proof()) 633 .await 634 .unwrap() 635 .inventory_checkpoint() 636 .unwrap(); 637 let child = StockGrantEnrollment::prepare( 638 &SellerAuthoritySelection::from_attachment(r.enrollment.input()), 639 "physical".into(), 640 UnixSeconds::new(290).unwrap(), 641 StockGrantScope::full_inventory(), 642 ) 643 .unwrap(); 644 assert!(matches!( 645 r.store 646 .enroll_stock_grant(r.binding.clone(), inventory, r.enrollment.proof(), &child) 647 .await 648 .unwrap(), 649 StockGrantOutcome::Committed(_) 650 )); 651 assert_eq!( 652 r.store 653 .retain_stock_listing(r.binding.clone(), stale, &capture, r.enrollment.proof()) 654 .await, 655 Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint)) 656 ); 657 let minimum = r.minimum().await; 658 let binding = r 659 .store 660 .authenticate(child.input().clone(), child.proof()) 661 .await 662 .unwrap(); 663 assert_eq!( 664 r.store 665 .retain_stock_listing(binding.clone(), minimum, &capture, child.proof()) 666 .await, 667 Err(OperationError::Unauthorized) 668 ); 669 assert!(matches!( 670 r.store 671 .stock_listing_head( 672 binding, 673 minimum, 674 capture.listing_revision().coordinate(), 675 child.proof() 676 ) 677 .await, 678 Err(OperationError::Unauthorized) 679 )); 680 let receipt = r.retain(&capture).await; 681 assert_eq!(receipt, original); 682 assert_eq!(minimum.revision(), stale.revision()); 683 assert_eq!(minimum.head(), stale.head()); 684 assert_ne!(minimum.authorization(), stale.authorization()); 685 let read = r 686 .store 687 .stock_listing_head( 688 r.binding.clone(), 689 minimum, 690 capture.listing_revision().coordinate(), 691 r.enrollment.proof(), 692 ) 693 .await 694 .unwrap() 695 .unwrap(); 696 assert_eq!(read.selection_checkpoint(), minimum); 697 assert_eq!(read.receipt(), &original); 698 let fork = StockListingCheckpointRef::from_host_metadata( 699 r.enrollment.input().authority(), 700 minimum.revision(), 701 Some(radroots_domain::CheckpointDigest::from_bytes([0x44; 32])), 702 ) 703 .unwrap() 704 .with_optional_authorization(minimum.authorization()); 705 assert!( 706 r.store 707 .stock_listing_head( 708 r.binding.clone(), 709 fork, 710 capture.listing_revision().coordinate(), 711 r.enrollment.proof() 712 ) 713 .await 714 .is_err() 715 ); 716 r.clock.0.store(149, Ordering::SeqCst); 717 assert!( 718 r.store 719 .stock_listing_source( 720 r.binding.clone(), 721 minimum, 722 capture.listing_revision(), 723 r.enrollment.proof() 724 ) 725 .await 726 .is_err() 727 ); 728 r.store.close().await.unwrap(); 729 } 730 731 #[tokio::test] 732 async fn acknowledged_public_progress_detects_whole_database_restore() { 733 let r = Rig::new().await; 734 let first = r.capture("listing_fixed"); 735 r.retain(&first).await; 736 r.store.close().await.unwrap(); 737 let snapshot = r.fixture.root().join("old-public.sqlite"); 738 std::fs::copy(r.path.join("stock_execution_v1.sqlite"), &snapshot).unwrap(); 739 let store = NativeWorkspace::open_seller_stock( 740 &r.path, 741 r.enrollment.input().clone(), 742 r.fixture.crypto(), 743 r.clock.clone(), 744 ) 745 .await 746 .unwrap(); 747 let minimum = store 748 .stock_authority(r.enrollment.input().clone(), r.enrollment.proof()) 749 .await 750 .unwrap() 751 .listing_checkpoint() 752 .unwrap(); 753 let next = r.capture("listing_unsupported"); 754 let latest = committed( 755 store 756 .retain_stock_listing(r.binding.clone(), minimum, &next, r.enrollment.proof()) 757 .await 758 .unwrap(), 759 ); 760 store.close().await.unwrap(); 761 std::fs::copy(snapshot, r.path.join("stock_execution_v1.sqlite")).unwrap(); 762 let store = NativeWorkspace::open_seller_stock( 763 &r.path, 764 r.enrollment.input().clone(), 765 r.fixture.crypto(), 766 r.clock.clone(), 767 ) 768 .await 769 .unwrap(); 770 assert!( 771 store 772 .stock_listing_head( 773 r.binding.clone(), 774 latest.checkpoint(), 775 first.listing_revision().coordinate(), 776 r.enrollment.proof() 777 ) 778 .await 779 .is_err() 780 ); 781 store.close().await.unwrap(); 782 } 783 784 #[tokio::test] 785 async fn actual_inventory_private_sources_consent_and_grant_changes_preserve_public_progress() { 786 use nostr::{EventBuilder, JsonUtil, Keys, Kind, Timestamp}; 787 use radroots_domain::{CommandContextData, OperationId, PoolId}; 788 use radroots_protocol::command::CapturedOrderAcceptance; 789 use radroots_signing::{provider::ProviderCall, request::CancellationSignal}; 790 use radroots_storage::inventory::{InventoryOutcome, InventoryRequest, InventoryStore}; 791 use radroots_storage::workspace::seller_stock::StockResources; 792 let r = Rig::new().await; 793 let public = r.capture("listing_fixed"); 794 let first = r.retain(&public).await; 795 let inventory = r 796 .store 797 .stock_authority(r.enrollment.input().clone(), r.enrollment.proof()) 798 .await 799 .unwrap() 800 .inventory_checkpoint() 801 .unwrap(); 802 let context = CommandContextData::new( 803 OperationId::from_bytes([0x61; 32]), 804 r.binding.actor(), 805 r.enrollment.input().workspace_id(), 806 r.enrollment.input().authority(), 807 r.enrollment.input().route_digest(), 808 None, 809 None, 810 UnixSeconds::new(250).unwrap(), 811 None, 812 ) 813 .unwrap(); 814 let wire = serde_json::json!({"type":"stock.create_pool","context":context,"input":{"id":PoolId::from_bytes([0x62;32]),"label":"source coexistence","unit":"each","tick_scale":"0","initial_quantity":"1"}}); 815 let request = InventoryRequest::from_protected_wire( 816 r.binding.clone(), 817 inventory, 818 &serde_json::to_vec(&wire).unwrap(), 819 ) 820 .unwrap(); 821 let created = match r 822 .store 823 .execute_inventory( 824 request, 825 r.enrollment 826 .proof() 827 .with_secret(|secret| AttachmentProof::from_protected_input(secret)) 828 .unwrap(), 829 ) 830 .await 831 .unwrap() 832 { 833 InventoryOutcome::Committed(receipt) => receipt, 834 _ => panic!("pool must confirm"), 835 }; 836 let sender = Keys::parse(&format!("{:064x}", 1)).unwrap(); 837 let recipient = 838 nostr::PublicKey::from_hex(&r.enrollment.input().participant().to_hex()).unwrap(); 839 let rumor = EventBuilder::new(Kind::from(14), "synthetic source coexistence") 840 .custom_created_at(Timestamp::from(150)) 841 .build(sender.public_key()); 842 let wrap = EventBuilder::gift_wrap(&sender, &recipient, rumor, []) 843 .await 844 .unwrap(); 845 let signer = radroots_nostr::signing::LocalSigner::with_clock( 846 radroots_nostr::key::SecretKey::parse(&format!("{:064x}", 3)).unwrap(), 847 || Ok(150), 848 ) 849 .unwrap(); 850 let opened = radroots_nostr::commerce::open( 851 &signer, 852 ProviderCall::new( 853 r.enrollment.input().participant(), 854 std::num::NonZeroU64::new(2000).unwrap(), 855 CancellationSignal::new(), 856 ), 857 &wrap.as_json(), 858 ) 859 .await 860 .unwrap(); 861 let private = StockSourceCapture::prepare( 862 SellerAuthoritySelection::from_attachment(r.enrollment.input()), 863 &opened, 864 ) 865 .unwrap(); 866 let state = r 867 .store 868 .stock_authority(r.enrollment.input().clone(), r.enrollment.proof()) 869 .await 870 .unwrap(); 871 let private_receipt = match r 872 .store 873 .retain_stock_source( 874 r.binding.clone(), 875 state.source_checkpoint().unwrap(), 876 &private, 877 r.enrollment.proof(), 878 ) 879 .await 880 .unwrap() 881 { 882 StockSourceOutcome::Committed(receipt) => receipt, 883 _ => panic!("private evidence must confirm"), 884 }; 885 let mut wire = serde_json::json!({"type":"orders.accept","context":context,"input":{"request":"21".repeat(32),"terms_digest":"24".repeat(32),"allocation":{"type":"automatic"}}}); 886 wire["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([0x63; 32])); 887 wire["context"]["expected"] = serde_json::json!({"agreement":null,"buyer_head":"21".repeat(32),"checkpoint":{"coverage":"scope_satisfied","digest":"22".repeat(32),"missing":[],"sequence":"1"},"order_id":"23".repeat(32),"seller_sequence":"0"}); 888 let unapproved = CapturedOrderAcceptance::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 889 wire["context"]["approval"] = serde_json::json!({"intent_digest":unapproved.approval_intent_digest(),"scope":"orders.accept","expires_at":"250"}); 890 let consent = StockConsentCapture::prepare( 891 SellerAuthoritySelection::from_attachment(r.enrollment.input()), 892 r.enrollment.input().grant_id(), 893 StockConsentMode::ExecuteAndRecover, 894 StockResources::all_pools(), 895 UnixSeconds::new(240).unwrap(), 896 CapturedOrderAcceptance::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(), 897 ) 898 .unwrap(); 899 let consent = match r 900 .store 901 .issue_stock_consent( 902 r.binding.clone(), 903 created.checkpoint(), 904 &consent, 905 r.enrollment.proof(), 906 ) 907 .await 908 .unwrap() 909 { 910 StockConsentOutcome::Committed(receipt) => receipt, 911 _ => panic!("consent must confirm"), 912 }; 913 let child = StockGrantEnrollment::prepare( 914 &SellerAuthoritySelection::from_attachment(r.enrollment.input()), 915 "coexistence".into(), 916 UnixSeconds::new(290).unwrap(), 917 StockGrantScope::full_inventory(), 918 ) 919 .unwrap(); 920 assert!(matches!( 921 r.store 922 .enroll_stock_grant( 923 r.binding.clone(), 924 consent.checkpoint(), 925 r.enrollment.proof(), 926 &child 927 ) 928 .await 929 .unwrap(), 930 StockGrantOutcome::Committed(_) 931 )); 932 let state = r 933 .store 934 .stock_authority(r.enrollment.input().clone(), r.enrollment.proof()) 935 .await 936 .unwrap(); 937 let current = state.listing_checkpoint().unwrap(); 938 assert_eq!(current.revision(), first.checkpoint().revision()); 939 assert_eq!(current.head(), first.checkpoint().head()); 940 let current_private = state.source_checkpoint().unwrap(); 941 assert_eq!( 942 current_private.revision(), 943 private_receipt.checkpoint().revision() 944 ); 945 assert_eq!(current_private.head(), private_receipt.checkpoint().head()); 946 assert_eq!(state.inventory_checkpoint().unwrap().revision().get(), 2); 947 let source = r 948 .store 949 .stock_listing_head( 950 r.binding.clone(), 951 current, 952 public.listing_revision().coordinate(), 953 r.enrollment.proof(), 954 ) 955 .await 956 .unwrap() 957 .unwrap(); 958 assert_eq!(source.raw_json(), vector("listing_fixed")); 959 assert!( 960 r.store 961 .stock_source( 962 r.binding.clone(), 963 current_private, 964 private.envelope_id(), 965 r.enrollment.proof() 966 ) 967 .await 968 .unwrap() 969 .is_some() 970 ); 971 let pool = r 972 .store 973 .pool( 974 r.binding.clone(), 975 state.inventory_checkpoint().unwrap(), 976 created.pool().id(), 977 r.enrollment 978 .proof() 979 .with_secret(|secret| AttachmentProof::from_protected_input(secret)) 980 .unwrap(), 981 ) 982 .await 983 .unwrap() 984 .unwrap(); 985 assert_eq!(pool.snapshot().balances().physical().available.get(), 1); 986 r.store.close().await.unwrap(); 987 }