lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

public_admission.rs (74340B)


      1 //! Actual encrypted public T0/T1/S. Installation and delivery remain separate.
      2 use super::*;
      3 use radroots_protocol::{intent::SigningReplay, listing::PublicSigningPlan};
      4 use radroots_storage::command::{BoundSigningPlan, ClaimAttemptRequest, PlanBindingOutcome};
      5 
      6 fn public_plan(prepared: &PreparedOperation, time: u64, targets: &[String]) -> PublicSigningPlan {
      7     PublicSigningPlan::capture(
      8         prepared.request().command().listing().unwrap(),
      9         UnixSeconds::new(time).unwrap(),
     10         targets,
     11         SigningReplay::NonReplayable,
     12     )
     13     .unwrap()
     14 }
     15 fn planned(outcome: PlanBindingOutcome) -> BoundSigningPlan {
     16     match outcome {
     17         PlanBindingOutcome::Committed(plan) => plan,
     18         PlanBindingOutcome::Unknown(_) => panic!("unexpected unknown T1"),
     19     }
     20 }
     21 
     22 #[tokio::test]
     23 async fn public_t1_retains_exact_encrypted_plan_reopens_and_replays_without_fresh_deadline() {
     24     let fixture = Fixture::new();
     25     let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
     26     let prepared = committed(
     27         store
     28             .admit_command_and_hold(
     29                 public_request(&binding, 80, "original public T1", "first"),
     30                 copy(&proof),
     31             )
     32             .await
     33             .unwrap(),
     34     );
     35     let targets = vec!["wss://public-plan.fixture.example/a".to_string()];
     36     fixture.clock.now.store(110, Ordering::SeqCst);
     37     let plan = public_plan(&prepared, 101, &targets);
     38     let wire = plan.protected_wire().to_vec();
     39     let digest = *plan.digest();
     40     let event = *plan.event().event_id();
     41     let retained = planned(
     42         store
     43             .bind_signing_intents(binding.clone(), plan.into(), copy(&proof))
     44             .await
     45             .unwrap(),
     46     );
     47     let transaction = retained.transaction_id();
     48     assert_eq!(retained.bound_at().get(), 110);
     49     assert_eq!(retained.plan().digest(), &digest);
     50     assert_eq!(
     51         retained.plan().listing().unwrap().event().event_id(),
     52         &event
     53     );
     54     assert_eq!(
     55         retained.chat_plan().err(),
     56         Some(OperationError::UnsupportedOperation)
     57     );
     58     assert!(matches!(
     59         store
     60             .claim_attempt(
     61                 ClaimAttemptRequest::new(
     62                     binding.clone(),
     63                     prepared.identity().operation_id(),
     64                     prepared.identity().command_digest(),
     65                     digest,
     66                     key()
     67                 ),
     68                 copy(&proof)
     69             )
     70             .await,
     71         Err(OperationError::UnsupportedOperation)
     72     ));
     73     let mut db = fixture.database().await;
     74     let attempts: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_attempts")
     75         .fetch_one(&mut db)
     76         .await
     77         .unwrap();
     78     assert_eq!(attempts, 0);
     79     db.close().await.unwrap();
     80     store.close().await.unwrap();
     81     for name in ["execution_v1.sqlite", "execution_v1.sqlite-wal"] {
     82         if let Ok(bytes) = std::fs::read(fixture.path.join(name)) {
     83             assert!(
     84                 !bytes
     85                     .windows(targets[0].len())
     86                     .any(|w| w == targets[0].as_bytes())
     87             );
     88         }
     89     }
     90     fixture.clock.now.store(160, Ordering::SeqCst);
     91     let reopened = fixture.reopen(input).await;
     92     let queried = reopened
     93         .signing_plan(
     94             binding.clone(),
     95             prepared.identity().operation_id(),
     96             prepared.identity().command_digest(),
     97             copy(&proof),
     98         )
     99         .await
    100         .unwrap()
    101         .unwrap();
    102     assert_eq!(queried.transaction_id(), transaction);
    103     assert_eq!(queried.plan().protected_wire(), wire);
    104     let replay = planned(
    105         reopened
    106             .bind_signing_intents(
    107                 binding.clone(),
    108                 public_plan(&prepared, 101, &targets).into(),
    109                 copy(&proof),
    110             )
    111             .await
    112             .unwrap(),
    113     );
    114     assert_eq!(replay.transaction_id(), transaction);
    115     assert_eq!(replay.plan().protected_wire(), wire);
    116     let other = vec!["wss://public-plan.fixture.example/other".to_string()];
    117     assert!(matches!(
    118         reopened
    119             .bind_signing_intents(
    120                 binding,
    121                 public_plan(&prepared, 101, &other).into(),
    122                 copy(&proof)
    123             )
    124             .await,
    125         Err(OperationError::IdempotencyConflict)
    126     ));
    127     reopened.close().await.unwrap();
    128 }
    129 
    130 #[tokio::test]
    131 async fn public_t1_refuses_wrong_proof_and_fresh_expiry_without_creating_a_plan() {
    132     let fixture = Fixture::new();
    133     let (store, _, proof, binding) = fixture.create_scoped(200, true).await;
    134     let prepared = committed(
    135         store
    136             .admit_command_and_hold(
    137                 public_request(&binding, 81, "fresh public T1", "first"),
    138                 copy(&proof),
    139             )
    140             .await
    141             .unwrap(),
    142     );
    143     let targets = vec!["wss://public-plan.fixture.example/a".to_string()];
    144     assert!(matches!(
    145         store
    146             .bind_signing_intents(
    147                 binding.clone(),
    148                 public_plan(&prepared, 100, &targets).into(),
    149                 AttachmentProof::from_protected_input(&[0; 32]).unwrap()
    150             )
    151             .await,
    152         Err(OperationError::Workspace(WorkspaceError::Unauthorized))
    153     ));
    154     fixture.clock.now.store(150, Ordering::SeqCst);
    155     assert!(matches!(
    156         store
    157             .bind_signing_intents(
    158                 binding.clone(),
    159                 public_plan(&prepared, 100, &targets).into(),
    160                 copy(&proof)
    161             )
    162             .await,
    163         Err(OperationError::DeadlineExceeded)
    164     ));
    165     assert!(
    166         store
    167             .signing_plan(
    168                 binding,
    169                 prepared.identity().operation_id(),
    170                 prepared.identity().command_digest(),
    171                 copy(&proof)
    172             )
    173             .await
    174             .unwrap()
    175             .is_none()
    176     );
    177     let mut db = fixture.database().await;
    178     let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans")
    179         .fetch_one(&mut db)
    180         .await
    181         .unwrap();
    182     assert_eq!(count, 0);
    183     db.close().await.unwrap();
    184     store.close().await.unwrap();
    185 }
    186 
    187 #[tokio::test]
    188 async fn accepted_public_t1_survives_observer_loss_and_close_drains_the_original_plan() {
    189     use futures::FutureExt;
    190     let fixture = Fixture::new();
    191     let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
    192     let prepared = committed(
    193         store
    194             .admit_command_and_hold(
    195                 public_request(&binding, 82, "owned public T1", "first"),
    196                 copy(&proof),
    197             )
    198             .await
    199             .unwrap(),
    200     );
    201     let plan = public_plan(
    202         &prepared,
    203         100,
    204         &["wss://public-plan.fixture.example/a".to_string()],
    205     );
    206     let wire = plan.protected_wire().to_vec();
    207     let (arrived, resume) = fixture.clock.arm(0);
    208     assert!(
    209         store
    210             .bind_signing_intents(binding.clone(), plan.into(), copy(&proof))
    211             .now_or_never()
    212             .is_none()
    213     );
    214     reached(arrived).await;
    215     resume.send(()).unwrap();
    216     store.close().await.unwrap();
    217     let reopened = fixture.reopen(input).await;
    218     let retained = reopened
    219         .signing_plan(
    220             binding,
    221             prepared.identity().operation_id(),
    222             prepared.identity().command_digest(),
    223             copy(&proof),
    224         )
    225         .await
    226         .unwrap()
    227         .unwrap();
    228     assert_eq!(retained.plan().protected_wire(), wire);
    229     assert!(retained.plan().listing().is_some());
    230     reopened.close().await.unwrap();
    231 }
    232 
    233 fn public_request(
    234     binding: &WorkspaceBinding,
    235     id: u8,
    236     title: &str,
    237     correlation: &str,
    238 ) -> AdmissionRequest {
    239     let context = CommandContextData::new(
    240         OperationId::from_bytes([id; 32]),
    241         binding.actor(),
    242         binding.input().workspace_id(),
    243         binding.input().authority(),
    244         binding.input().route_digest(),
    245         None,
    246         None,
    247         UnixSeconds::new(150).unwrap(),
    248         Some(CorrelationId::new(correlation).unwrap()),
    249     )
    250     .unwrap();
    251     let wire = json!({"type":"listing.publish", "context":context,"input":{
    252         "id":format!("{id:02x}").repeat(16),"title":title,"summary":"Quote required","description_markdown":"Public terms",
    253         "published_at":"100","profile":{"profile":"radroots.listing","version":1,"state":"active",
    254         "product":{"name":"Carrots","description":"Public description","producer":null,"origin_summary":null},
    255         "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch",
    256         "unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}},"increment":"1",
    257         "minimum":"1","price":{"type":"quote_required"},"supply":{"type":"available","amount":"10"},"lead_seconds":"0"}],
    258         "fulfillment":{"modes":["pickup"],"area":"Example region","lead_seconds":"0"},"authority":null,"media":[]}}});
    259     AdmissionRequest::from_protected_wire(binding.clone(), &serde_json::to_vec(&wire).unwrap())
    260         .unwrap()
    261 }
    262 async fn count(fixture: &Fixture) -> i64 {
    263     let mut db = fixture.database().await;
    264     let count = sqlx::query_scalar("SELECT count(*) FROM operations")
    265         .fetch_one(&mut db)
    266         .await
    267         .unwrap();
    268     db.close().await.unwrap();
    269     count
    270 }
    271 
    272 #[tokio::test]
    273 async fn public_t0_reopen_replay_retains_original_bytes_and_uses_the_same_operation_namespace() {
    274     let fixture = Fixture::new();
    275     let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
    276     let captured = public_request(&binding, 70, "public-preparation-carrots", "first");
    277     let digest = captured.command().digest();
    278     let wire = captured.command().protected_wire().to_vec();
    279     let original = committed(
    280         store
    281             .admit_command_and_hold(captured, copy(&proof))
    282             .await
    283             .unwrap(),
    284     );
    285     let anchor = original.identity();
    286     assert_eq!(original.revision().get(), 1);
    287     assert!(original.request().command().listing().is_some());
    288     assert_eq!(
    289         original.request().chat_command().err(),
    290         Some(OperationError::UnsupportedOperation)
    291     );
    292     store.close().await.unwrap();
    293     for name in ["execution_v1.sqlite", "execution_v1.sqlite-wal"] {
    294         if let Ok(bytes) = std::fs::read(fixture.path.join(name)) {
    295             assert!(
    296                 !bytes
    297                     .windows(b"public-preparation-carrots".len())
    298                     .any(|w| w == b"public-preparation-carrots")
    299             );
    300         }
    301     }
    302     fixture.clock.now.store(160, Ordering::SeqCst);
    303     let reopened = fixture.reopen(input).await;
    304     let retained = reopened
    305         .operation(
    306             binding.clone(),
    307             anchor.operation_id(),
    308             Some(digest),
    309             copy(&proof),
    310         )
    311         .await
    312         .unwrap()
    313         .unwrap();
    314     assert_eq!(retained.identity(), anchor);
    315     assert_eq!(retained.issuance_window(), original.issuance_window());
    316     assert_eq!(retained.request().command().protected_wire(), wire);
    317     let replay = committed(
    318         reopened
    319             .admit_command_and_hold(
    320                 public_request(&binding, 70, "public-preparation-carrots", "second"),
    321                 copy(&proof),
    322             )
    323             .await
    324             .unwrap(),
    325     );
    326     assert_eq!(replay.identity(), anchor);
    327     assert_eq!(replay.request().command().protected_wire(), wire);
    328     for captured in [
    329         public_request(&binding, 70, "changed terms", "second"),
    330         request(&binding, 70, "different family", "second"),
    331     ] {
    332         assert!(matches!(
    333             reopened
    334                 .admit_command_and_hold(captured, copy(&proof))
    335                 .await,
    336             Err(OperationError::IdempotencyConflict)
    337         ));
    338     }
    339     assert!(matches!(
    340         reopened
    341             .admit_command_and_hold(
    342                 public_request(&binding, 71, "new expired work", "second"),
    343                 copy(&proof)
    344             )
    345             .await,
    346         Err(OperationError::DeadlineExceeded)
    347     ));
    348     assert_eq!(count(&fixture).await, 1);
    349     reopened.close().await.unwrap();
    350 }
    351 
    352 #[tokio::test]
    353 async fn public_t0_requires_actual_seller_access_and_refuses_unverified_prerequisites_without_rows()
    354 {
    355     let buyer = Fixture::new();
    356     let (store, _, proof, binding) = buyer.create().await;
    357     assert!(matches!(
    358         store
    359             .admit_command_and_hold(
    360                 public_request(&binding, 72, "wrong scope", "one"),
    361                 copy(&proof)
    362             )
    363             .await,
    364         Err(OperationError::Unauthorized)
    365     ));
    366     assert_eq!(count(&buyer).await, 0);
    367     store.close().await.unwrap();
    368     let seller = Fixture::new();
    369     let (store, input, proof, binding) = seller.create_scoped(200, true).await;
    370     let wrong = AttachmentProof::from_protected_input(&[0; 32]).unwrap();
    371     assert!(matches!(
    372         store
    373             .admit_command_and_hold(public_request(&binding, 72, "wrong proof", "one"), wrong)
    374             .await,
    375         Err(OperationError::Workspace(WorkspaceError::Unauthorized))
    376     ));
    377     let captured = public_request(&binding, 72, "prerequisites", "one");
    378     let base: serde_json::Value =
    379         serde_json::from_slice(captured.command().protected_wire()).unwrap();
    380     for (field, value, expected) in [
    381         (
    382             "approval",
    383             json!({"intent_digest":"22".repeat(32),"scope":"unverified","expires_at":"150"}),
    384             OperationError::UnverifiedApproval,
    385         ),
    386         (
    387             "expected",
    388             serde_json::to_value(radroots_domain::ExpectedOrder::new(
    389                 radroots_domain::OrderId::from_bytes([0x33; 32]),
    390                 None,
    391                 radroots_domain::Sequence::new(1).unwrap(),
    392                 None,
    393                 binding.input().checkpoint().clone(),
    394             ))
    395             .unwrap(),
    396             OperationError::MissingHistory,
    397         ),
    398     ] {
    399         let mut wire = base.clone();
    400         wire["context"][field] = value;
    401         let request = AdmissionRequest::from_protected_wire(
    402             binding.clone(),
    403             &serde_json::to_vec(&wire).unwrap(),
    404         )
    405         .unwrap();
    406         assert!(
    407             matches!(store.admit_command_and_hold(request,copy(&proof)).await,Err(error) if error==expected)
    408         );
    409     }
    410     assert_eq!(count(&seller).await, 0);
    411     store.revoke(input, &proof).await.unwrap();
    412     assert!(matches!(
    413         store
    414             .admit_command_and_hold(public_request(&binding, 72, "revoked", "one"), copy(&proof))
    415             .await,
    416         Err(OperationError::Workspace(WorkspaceError::GrantRevoked))
    417     ));
    418     assert_eq!(count(&seller).await, 0);
    419     store.close().await.unwrap();
    420 }
    421 
    422 #[tokio::test]
    423 async fn accepted_public_t0_survives_observer_loss_and_close_drains_the_existing_owner() {
    424     use futures::FutureExt;
    425     let fixture = Fixture::new();
    426     let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
    427     let captured = public_request(&binding, 73, "retained after observer loss", "one");
    428     let digest = captured.command().digest();
    429     let (arrived, resume) = fixture.clock.arm(0);
    430     assert!(
    431         store
    432             .admit_command_and_hold(captured, copy(&proof))
    433             .now_or_never()
    434             .is_none()
    435     );
    436     reached(arrived).await;
    437     resume.send(()).unwrap();
    438     store.close().await.unwrap();
    439     let reopened = fixture.reopen(input).await;
    440     let retained = reopened
    441         .operation(
    442             binding,
    443             OperationId::from_bytes([73; 32]),
    444             Some(digest),
    445             copy(&proof),
    446         )
    447         .await
    448         .unwrap()
    449         .unwrap();
    450     assert!(retained.request().command().listing().is_some());
    451     assert_eq!(count(&fixture).await, 1);
    452     reopened.close().await.unwrap();
    453 }
    454 
    455 #[tokio::test]
    456 async fn public_queue_counts_decoded_ownership_and_releases_budget_after_draining() {
    457     let fixture = Fixture::new();
    458     let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
    459     let (arrived, resume) = fixture.clock.arm(1);
    460     let owner = store.clone();
    461     let first = public_request(&binding, 100, "first", "one");
    462     let secret = copy(&proof);
    463     let blocked = tokio::spawn(async move { owner.admit_command_and_hold(first, secret).await });
    464     reached(arrived).await;
    465     let mut queued = Vec::new();
    466     // Twenty queued plus one in-flight public capture consume 4032 KiB.
    467     for id in 1..=20 {
    468         let mut future = store
    469             .admit_command_and_hold(public_request(&binding, id, "queued", "one"), copy(&proof));
    470         assert!(futures::poll!(future.as_mut()).is_pending());
    471         queued.push(future);
    472     }
    473     assert!(matches!(
    474         store
    475             .admit_command_and_hold(
    476                 public_request(&binding, 21, "overflow", "one"),
    477                 copy(&proof)
    478             )
    479             .await,
    480         Err(OperationError::Workspace(WorkspaceError::Unavailable))
    481     ));
    482     resume.send(()).unwrap();
    483     committed(blocked.await.unwrap().unwrap());
    484     store.close().await.unwrap();
    485     for future in queued {
    486         assert!(
    487             committed(future.await.unwrap())
    488                 .request()
    489                 .command()
    490                 .listing()
    491                 .is_some()
    492         );
    493     }
    494     assert_eq!(count(&fixture).await, 21);
    495     let reopened = fixture.reopen(input).await;
    496     assert!(
    497         reopened
    498             .operation(
    499                 binding.clone(),
    500                 OperationId::from_bytes([21; 32]),
    501                 None,
    502                 copy(&proof)
    503             )
    504             .await
    505             .unwrap()
    506             .is_none()
    507     );
    508     committed(
    509         reopened
    510             .admit_command_and_hold(
    511                 public_request(&binding, 21, "after drain", "one"),
    512                 copy(&proof),
    513             )
    514             .await
    515             .unwrap(),
    516     );
    517     assert_eq!(count(&fixture).await, 22);
    518     reopened.close().await.unwrap();
    519 }
    520 
    521 #[tokio::test]
    522 async fn exact_generation_seven_retains_chat_without_rewrite_and_explicitly_refuses_public_writes()
    523 {
    524     let fixture = Fixture::new();
    525     let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
    526     let original = committed(
    527         store
    528             .admit_command_and_hold(
    529                 request(&binding, 74, "original chat", "first"),
    530                 copy(&proof),
    531             )
    532             .await
    533             .unwrap(),
    534     );
    535     store.close().await.unwrap();
    536     // Construct the exact old catalog around unchanged encrypted rows. This is
    537     // a retained-schema fixture, not a claim that an old binary was executed.
    538     let mut db = fixture.database().await;
    539     retain_legacy_issuance_catalog(&mut db).await;
    540     let current: String =
    541         sqlx::query_scalar("SELECT sql FROM sqlite_schema WHERE name='operations'")
    542             .fetch_one(&mut db)
    543             .await
    544             .unwrap();
    545     let index: String = sqlx::query_scalar(
    546         "SELECT sql FROM sqlite_schema WHERE name='operation_transaction_identity'",
    547     )
    548     .fetch_one(&mut db)
    549     .await
    550     .unwrap();
    551     let legacy = current.replace("'inbox.reply','listing.publish'", "'inbox.reply'");
    552     assert_ne!(legacy, current);
    553     for sql in [
    554         "CREATE TEMP TABLE retained_operations AS SELECT * FROM operations",
    555         "DROP TABLE operations",
    556         &legacy,
    557         &index,
    558         "INSERT INTO operations SELECT * FROM retained_operations",
    559         "DROP TABLE retained_operations",
    560         "PRAGMA user_version=7",
    561     ] {
    562         // Only exact catalog SQL read from our own synthetic database is used.
    563         sqlx::query(sqlx::AssertSqlSafe(sql.to_owned()))
    564             .execute(&mut db)
    565             .await
    566             .unwrap();
    567     }
    568     db.close().await.unwrap();
    569     let reopened = fixture.reopen(input.clone()).await;
    570     let retained = reopened
    571         .operation(
    572             binding.clone(),
    573             original.identity().operation_id(),
    574             Some(original.identity().command_digest()),
    575             copy(&proof),
    576         )
    577         .await
    578         .unwrap()
    579         .unwrap();
    580     assert_eq!(retained.identity(), original.identity());
    581     assert_eq!(
    582         retained.request().command().protected_wire(),
    583         original.request().command().protected_wire()
    584     );
    585     committed(
    586         reopened
    587             .admit_command_and_hold(
    588                 request(&binding, 75, "continued chat", "next"),
    589                 copy(&proof),
    590             )
    591             .await
    592             .unwrap(),
    593     );
    594     assert!(matches!(
    595         reopened
    596             .admit_command_and_hold(
    597                 public_request(&binding, 76, "unsupported public", "one"),
    598                 copy(&proof)
    599             )
    600             .await,
    601         Err(OperationError::UnsupportedOperation)
    602     ));
    603     reopened.close().await.unwrap();
    604     let mut db = fixture.database().await;
    605     let version: i64 = sqlx::query_scalar("PRAGMA user_version")
    606         .fetch_one(&mut db)
    607         .await
    608         .unwrap();
    609     assert_eq!(version, 7);
    610     let retained_sql: String =
    611         sqlx::query_scalar("SELECT sql FROM sqlite_schema WHERE name='operations'")
    612             .fetch_one(&mut db)
    613             .await
    614             .unwrap();
    615     assert_eq!(retained_sql, legacy);
    616     assert_eq!(count(&fixture).await, 2);
    617     // A misleading generation tag never makes the new schema an old schema.
    618     sqlx::query("PRAGMA user_version=8")
    619         .execute(&mut db)
    620         .await
    621         .unwrap();
    622     db.close().await.unwrap();
    623     assert!(matches!(
    624         NativeWorkspace::open_existing(
    625             &fixture.path,
    626             input,
    627             fixture.crypto(),
    628             fixture.clock.clone()
    629         )
    630         .await,
    631         Err(WorkspaceError::RecoveryRequired)
    632     ));
    633 }
    634 
    635 mod public_issuance {
    636     use super::*;
    637     use core::{cell::Cell, num::NonZeroU64};
    638     use nostr::JsonUtil;
    639     use radroots_nostr::{
    640         key::parse_secret_key,
    641         signing::{LocalSigner, OsNonceSource},
    642     };
    643     use radroots_protocol::plan::SigningTarget;
    644     use radroots_signing::{
    645         issuance::{OutcomeKind, SigningIntent},
    646         provider::{ParticipantProvider, ProviderCall},
    647         request::CancellationSignal,
    648     };
    649     use radroots_storage::command::{
    650         ArtifactEvidence, ClaimAttemptOutcome, EvidenceCaptureOutcome, SigningAttempt,
    651     };
    652     thread_local! { static CALLS:Cell<usize>=const {Cell::new(0)}; }
    653     fn signer_clock() -> Result<u64, radroots_signing::Error> {
    654         let first = CALLS.with(|calls| {
    655             let n = calls.get();
    656             calls.set(n + 1);
    657             n == 0
    658         });
    659         if first {
    660             Ok(100_000)
    661         } else {
    662             Err(radroots_signing::Error::new(
    663                 radroots_signing::error::Kind::InternalError,
    664             ))
    665         }
    666     }
    667     fn selection(
    668         binding: &WorkspaceBinding,
    669         prepared: &PreparedOperation,
    670         digest: [u8; 32],
    671     ) -> ClaimAttemptRequest {
    672         ClaimAttemptRequest::for_artifact(
    673             binding.clone(),
    674             prepared.identity().operation_id(),
    675             prepared.identity().command_digest(),
    676             digest,
    677             SigningTarget::PublicEvent,
    678         )
    679     }
    680     fn claimed(outcome: ClaimAttemptOutcome) -> SigningAttempt {
    681         match outcome {
    682             ClaimAttemptOutcome::Claimed(attempt) => attempt,
    683             _ => panic!("first claim must confirm commit"),
    684         }
    685     }
    686     async fn prepared(
    687         fixture: &Fixture,
    688         store: &NativeWorkspace,
    689         binding: &WorkspaceBinding,
    690         proof: &AttachmentProof,
    691         id: u8,
    692     ) -> (PreparedOperation, [u8; 32]) {
    693         let request = public_request(binding, id, "public signature fixture", "original");
    694         let mut wire: serde_json::Value =
    695             serde_json::from_slice(request.command().protected_wire()).unwrap();
    696         wire["input"]["profile"]["product"]["description"] = json!("x".repeat(4096));
    697         let request = AdmissionRequest::from_protected_wire(
    698             binding.clone(),
    699             &serde_json::to_vec(&wire).unwrap(),
    700         )
    701         .unwrap();
    702         let prepared = committed(
    703             store
    704                 .admit_command_and_hold(request, copy(proof))
    705                 .await
    706                 .unwrap(),
    707         );
    708         let plan = public_plan(
    709             &prepared,
    710             100,
    711             &["wss://public-signature.fixture.example/a".into()],
    712         );
    713         assert!(
    714             plan.event()
    715                 .fields()
    716                 .tags
    717                 .iter()
    718                 .any(|tag| tag.iter().any(|field| field.len() > 4096))
    719         );
    720         let digest = *plan.digest();
    721         planned(
    722             store
    723                 .bind_signing_intents(binding.clone(), plan.into(), copy(proof))
    724                 .await
    725                 .unwrap(),
    726         );
    727         let _ = fixture;
    728         (prepared, digest)
    729     }
    730     async fn obtain(attempt: &SigningAttempt) -> ArtifactEvidence {
    731         CALLS.with(|calls| calls.set(0));
    732         // Published synthetic scalar, independent of workstation custody.
    733         let signer = LocalSigner::with_clock(
    734             parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001")
    735                 .unwrap(),
    736             signer_clock,
    737         )
    738         .unwrap()
    739         .with_nonce_source(Arc::new(OsNonceSource));
    740         let state = signer.provider_state().await.unwrap();
    741         assert_eq!(state.identity(), key());
    742         assert_eq!(
    743             state.exact_issuance(),
    744             Some(radroots_signing::recovery::ReplayCapability::NonReplayable)
    745         );
    746         let cancellation = CancellationSignal::new();
    747         let intent = SigningIntent::from_plan(
    748             attempt.bound_plan().plan(),
    749             SigningTarget::PublicEvent,
    750             ProviderCall::new(key(), attempt.deadline_unix_ms(), cancellation.clone()),
    751         )
    752         .unwrap();
    753         assert_eq!(intent.binding(), attempt.binding());
    754         assert_eq!(intent.recipient(), None);
    755         let outcome = signer.sign_exact(intent).await;
    756         cancellation.cancel();
    757         let (_, kind) = outcome.into_parts();
    758         let OutcomeKind::Obtained(artifact) = kind else {
    759             panic!("qualified local signer must obtain public event")
    760         };
    761         assert_eq!(artifact.observed_at_unix_ms(), None);
    762         artifact.with_json(|raw| {
    763             let independent = nostr::Event::from_json(raw).unwrap();
    764             independent.verify().unwrap();
    765             assert_eq!(independent.kind.as_u16(), 30402);
    766             assert_eq!(
    767                 independent.id.as_bytes(),
    768                 &attempt.artifact().unwrap().event_id()
    769             );
    770             ArtifactEvidence::verify(attempt, raw, None).unwrap()
    771         })
    772     }
    773     fn captured(outcome: EvidenceCaptureOutcome) -> radroots_storage::command::EvidenceReceipt {
    774         match outcome {
    775             EvidenceCaptureOutcome::Committed(receipt) => receipt,
    776             _ => panic!("capture must confirm commit"),
    777         }
    778     }
    779     #[tokio::test]
    780     async fn actual_public_signature_captures_original_bytes_reopens_and_never_reclaims() {
    781         let fixture = Fixture::new();
    782         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
    783         let (prepared, digest) = prepared(&fixture, &store, &binding, &proof, 160).await;
    784         let attempt = claimed(
    785             store
    786                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
    787                 .await
    788                 .unwrap(),
    789         );
    790         assert!(matches!(
    791             attempt.seal(),
    792             Err(OperationError::UnsupportedOperation)
    793         ));
    794         assert!(matches!(
    795             store
    796                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
    797                 .await
    798                 .unwrap(),
    799             ClaimAttemptOutcome::Retained(_)
    800         ));
    801         let evidence = obtain(&attempt).await;
    802         assert_eq!(evidence.target().recipient(), None);
    803         use radroots_storage::command::protected::issuance::{ClaimRecord, EvidenceManifest};
    804         let claim_bytes = ClaimRecord::capture(&attempt).unwrap().encode().unwrap();
    805         let claim_json: serde_json::Value = serde_json::from_slice(&claim_bytes).unwrap();
    806         assert_eq!(claim_json["version"], 2);
    807         assert_eq!(claim_json["role"], 0);
    808         assert!(claim_json["recipient"].is_null());
    809         for field in [
    810             "version",
    811             "role",
    812             "recipient",
    813             "missing_role",
    814             "missing_recipient",
    815             "unknown",
    816         ] {
    817             let mut changed = claim_json.clone();
    818             match field {
    819                 "version" => changed["version"] = json!(1),
    820                 "role" => changed["role"] = json!(1),
    821                 "recipient" => changed["recipient"] = json!(key()),
    822                 "missing_role" => {
    823                     changed.as_object_mut().unwrap().remove("role");
    824                 }
    825                 "missing_recipient" => {
    826                     changed.as_object_mut().unwrap().remove("recipient");
    827                 }
    828                 _ => changed["unknown"] = json!(true),
    829             }
    830             let bound = store
    831                 .signing_plan(
    832                     binding.clone(),
    833                     prepared.identity().operation_id(),
    834                     prepared.identity().command_digest(),
    835                     copy(&proof),
    836                 )
    837                 .await
    838                 .unwrap()
    839                 .unwrap();
    840             assert!(
    841                 ClaimRecord::decode(
    842                     &serde_json::to_vec(&changed).unwrap(),
    843                     bound,
    844                     SigningTarget::PublicEvent
    845                 )
    846                 .is_err(),
    847                 "{field}"
    848             );
    849         }
    850         let manifest = EvidenceManifest::capture(
    851             &attempt,
    852             &evidence,
    853             radroots_domain::TransactionId::from_bytes([9; 32]),
    854         )
    855         .unwrap()
    856         .encode()
    857         .unwrap();
    858         let metadata: serde_json::Value = serde_json::from_slice(&manifest).unwrap();
    859         assert_eq!(metadata["version"], 2);
    860         assert_eq!(metadata["role"], 0);
    861         assert!(metadata["recipient"].is_null());
    862         for field in ["version", "role", "recipient"] {
    863             let mut changed = metadata.clone();
    864             changed[field] = match field {
    865                 "recipient" => json!(key()),
    866                 _ => json!(1),
    867             };
    868             assert!(
    869                 EvidenceManifest::decode(&serde_json::to_vec(&changed).unwrap(), &attempt).is_err()
    870             );
    871         }
    872         for (field, value) in [
    873             ("sig", json!("00".repeat(64))),
    874             ("id", json!("00".repeat(32))),
    875             ("kind", json!(13)),
    876             ("tags", json!([])),
    877             ("content", json!("other")),
    878             ("pubkey", json!("00".repeat(32))),
    879             ("created_at", json!(99)),
    880         ] {
    881             let mut changed: serde_json::Value = serde_json::from_str(evidence.raw_json()).unwrap();
    882             changed[field] = value;
    883             assert!(
    884                 matches!(
    885                     ArtifactEvidence::verify(&attempt, &changed.to_string(), None),
    886                     Err(OperationError::InvalidEvidence)
    887                 ),
    888                 "{field}"
    889             );
    890         }
    891         assert!(ArtifactEvidence::verify(&attempt, &"x".repeat(65537), None).is_err());
    892 
    893         let raw = evidence.raw_json().to_owned();
    894         let receipt = captured(
    895             store
    896                 .capture_evidence(input.clone(), &proof, &evidence)
    897                 .await
    898                 .unwrap(),
    899         );
    900         assert_eq!(receipt.target(), SigningTarget::PublicEvent);
    901         assert_eq!(receipt.observed_at_unix_ms(), None);
    902         let repeated = ArtifactEvidence::verify(&attempt, &raw, NonZeroU64::new(112_000)).unwrap();
    903         assert_eq!(
    904             captured(
    905                 store
    906                     .capture_evidence(input.clone(), &proof, &repeated)
    907                     .await
    908                     .unwrap()
    909             ),
    910             receipt
    911         );
    912         // The same valid event with another exact JSON encoding is a conflicting
    913         // callback, not permission to replace the original obtained bytes.
    914         let different =
    915             serde_json::to_string_pretty(&serde_json::from_str::<serde_json::Value>(&raw).unwrap())
    916                 .unwrap();
    917         assert_ne!(raw, different);
    918         let alternate = ArtifactEvidence::verify(&attempt, &different, None).unwrap();
    919         assert!(matches!(
    920             store
    921                 .capture_evidence(input.clone(), &proof, &alternate)
    922                 .await,
    923             Err(OperationError::IdempotencyConflict)
    924         ));
    925         let snapshot = store
    926             .operation_snapshot(
    927                 binding.clone(),
    928                 prepared.identity().operation_id(),
    929                 Some(prepared.identity().command_digest()),
    930                 copy(&proof),
    931             )
    932             .await
    933             .unwrap()
    934             .unwrap();
    935         assert_eq!(snapshot.artifacts().len(), 1);
    936         assert_eq!(snapshot.artifacts()[0].target(), SigningTarget::PublicEvent);
    937         assert_eq!(snapshot.artifacts()[0].obtained(), Some(receipt));
    938         assert!(snapshot.installation().is_none());
    939         store.close().await.unwrap();
    940         for name in ["execution_v1.sqlite", "execution_v1.sqlite-wal"] {
    941             if let Ok(bytes) = std::fs::read(fixture.path.join(name)) {
    942                 assert!(!bytes.windows(raw.len()).any(|part| part == raw.as_bytes()));
    943             }
    944         }
    945         fixture.clock.now.store(160, Ordering::SeqCst);
    946         let reopened = fixture.reopen(input).await;
    947         let recovered = reopened
    948             .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof))
    949             .await
    950             .unwrap()
    951             .unwrap();
    952         assert_eq!(recovered.receipt(), receipt);
    953         assert_eq!(recovered.evidence().raw_json(), raw);
    954         assert_eq!(recovered.attempt().attempt_id(), attempt.attempt_id());
    955         assert!(matches!(
    956             reopened
    957                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
    958                 .await
    959                 .unwrap(),
    960             ClaimAttemptOutcome::Retained(_)
    961         ));
    962         reopened.close().await.unwrap();
    963     }
    964     #[tokio::test]
    965     async fn public_obtained_capture_survives_revocation_expiry_and_later_clock_failure() {
    966         let fixture = Fixture::new();
    967         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
    968         let (prepared, digest) = prepared(&fixture, &store, &binding, &proof, 161).await;
    969         let attempt = claimed(
    970             store
    971                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
    972                 .await
    973                 .unwrap(),
    974         );
    975         let evidence = obtain(&attempt).await;
    976         store.revoke(input.clone(), &proof).await.unwrap();
    977         fixture.clock.now.store(0, Ordering::SeqCst);
    978         let receipt = captured(
    979             store
    980                 .capture_evidence(input.clone(), &proof, &evidence)
    981                 .await
    982                 .unwrap(),
    983         );
    984         assert_eq!(
    985             captured(
    986                 store
    987                     .capture_evidence(input.clone(), &proof, &evidence)
    988                     .await
    989                     .unwrap()
    990             ),
    991             receipt
    992         );
    993         assert!(
    994             store
    995                 .signing_attempt(selection(&binding, &prepared, digest), copy(&proof))
    996                 .await
    997                 .is_err()
    998         );
    999         store.close().await.unwrap();
   1000     }
   1001     #[tokio::test]
   1002     async fn public_claim_checks_current_proof_window_and_exact_target_without_dispatch() {
   1003         let fixture = Fixture::new();
   1004         let (store, _, proof, binding) = fixture.create_scoped(200, true).await;
   1005         let (prepared, digest) = prepared(&fixture, &store, &binding, &proof, 162).await;
   1006         assert!(matches!(
   1007             store
   1008                 .claim_attempt(
   1009                     selection(&binding, &prepared, digest),
   1010                     AttachmentProof::from_protected_input(&[0; 32]).unwrap()
   1011                 )
   1012                 .await,
   1013             Err(OperationError::Workspace(WorkspaceError::Unauthorized))
   1014         ));
   1015         assert!(matches!(
   1016             store
   1017                 .claim_attempt(
   1018                     ClaimAttemptRequest::new(
   1019                         binding.clone(),
   1020                         prepared.identity().operation_id(),
   1021                         prepared.identity().command_digest(),
   1022                         digest,
   1023                         key()
   1024                     ),
   1025                     copy(&proof)
   1026                 )
   1027                 .await,
   1028             Err(OperationError::UnsupportedOperation)
   1029         ));
   1030         fixture.clock.now.store(150, Ordering::SeqCst);
   1031         assert!(matches!(
   1032             store
   1033                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
   1034                 .await,
   1035             Err(OperationError::DeadlineExceeded)
   1036         ));
   1037         let mut db = fixture.database().await;
   1038         let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_attempts")
   1039             .fetch_one(&mut db)
   1040             .await
   1041             .unwrap();
   1042         assert_eq!(count, 0);
   1043         db.close().await.unwrap();
   1044         store.close().await.unwrap();
   1045     }
   1046     #[tokio::test]
   1047     async fn lost_public_claim_observer_retains_potential_issuance_without_new_dispatch() {
   1048         let fixture = Fixture::new();
   1049         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1050         let (prepared, digest) = prepared(&fixture, &store, &binding, &proof, 163).await;
   1051         let (arrived, resume) = fixture.clock.arm(1);
   1052         let mut pending = store.claim_attempt(selection(&binding, &prepared, digest), copy(&proof));
   1053         assert!(futures::poll!(pending.as_mut()).is_pending());
   1054         reached(arrived).await;
   1055         drop(pending);
   1056         resume.send(()).unwrap();
   1057         store.close().await.unwrap();
   1058         let reopened = fixture.reopen(input).await;
   1059         assert!(matches!(
   1060             reopened
   1061                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
   1062                 .await
   1063                 .unwrap(),
   1064             ClaimAttemptOutcome::Retained(_)
   1065         ));
   1066         assert!(
   1067             reopened
   1068                 .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof))
   1069                 .await
   1070                 .unwrap()
   1071                 .is_none()
   1072         );
   1073         reopened.close().await.unwrap();
   1074     }
   1075     #[tokio::test]
   1076     async fn accepted_public_capture_survives_observer_loss_and_drains_on_close() {
   1077         let fixture = Fixture::new();
   1078         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1079         let (prepared, digest) = prepared(&fixture, &store, &binding, &proof, 164).await;
   1080         let attempt = claimed(
   1081             store
   1082                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
   1083                 .await
   1084                 .unwrap(),
   1085         );
   1086         let evidence = obtain(&attempt).await;
   1087         let mut db = fixture.database().await;
   1088         let transaction = db.begin_with("BEGIN IMMEDIATE").await.unwrap();
   1089         let mut pending = store.capture_evidence(input.clone(), &proof, &evidence);
   1090         assert!(futures::poll!(pending.as_mut()).is_pending());
   1091         drop(pending);
   1092         transaction.rollback().await.unwrap();
   1093         db.close().await.unwrap();
   1094         store.close().await.unwrap();
   1095         let reopened = fixture.reopen(input).await;
   1096         let captured = reopened
   1097             .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof))
   1098             .await
   1099             .unwrap()
   1100             .unwrap();
   1101         assert_eq!(captured.evidence().raw_json(), evidence.raw_json());
   1102         reopened.close().await.unwrap();
   1103     }
   1104     fn install_request(
   1105         binding: &WorkspaceBinding,
   1106         prepared: &PreparedOperation,
   1107         digest: [u8; 32],
   1108     ) -> radroots_storage::command::InstallationRequest {
   1109         radroots_storage::command::InstallationRequest::new(
   1110             binding.clone(),
   1111             prepared.identity().operation_id(),
   1112             prepared.identity().command_digest(),
   1113             digest,
   1114         )
   1115     }
   1116     fn installed(
   1117         outcome: radroots_storage::command::InstallationOutcome,
   1118     ) -> radroots_storage::command::ListingInstallation {
   1119         match outcome {
   1120             radroots_storage::command::InstallationOutcome::ListingCommitted(v) => *v,
   1121             _ => panic!("public T2 must confirm original listing installation"),
   1122         }
   1123     }
   1124     async fn signed(
   1125         fixture: &Fixture,
   1126         store: &NativeWorkspace,
   1127         binding: &WorkspaceBinding,
   1128         input: &AttachmentInput,
   1129         proof: &AttachmentProof,
   1130         id: u8,
   1131     ) -> (PreparedOperation, [u8; 32], ArtifactEvidence) {
   1132         let (prepared, digest) = prepared(fixture, store, binding, proof, id).await;
   1133         let attempt = claimed(
   1134             store
   1135                 .claim_attempt(selection(binding, &prepared, digest), copy(proof))
   1136                 .await
   1137                 .unwrap(),
   1138         );
   1139         let evidence = obtain(&attempt).await;
   1140         captured(
   1141             store
   1142                 .capture_evidence(input.clone(), proof, &evidence)
   1143                 .await
   1144                 .unwrap(),
   1145         );
   1146         (prepared, digest, evidence)
   1147     }
   1148     async fn t2_counts(fixture: &Fixture) -> (i64, i64, i64) {
   1149         let mut db = fixture.database().await;
   1150         let counts=sqlx::query_as("SELECT (SELECT count(*) FROM listing_creations),(SELECT count(*) FROM listing_installations),(SELECT count(*) FROM public_publication_work)").fetch_one(&mut db).await.unwrap();
   1151         db.close().await.unwrap();
   1152         counts
   1153     }
   1154     #[tokio::test]
   1155     async fn public_t2_requires_actual_obtained_evidence_then_installs_once_after_first_issue_expiry()
   1156      {
   1157         let fixture = Fixture::new();
   1158         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1159         let (prepared, digest) = prepared(&fixture, &store, &binding, &proof, 170).await;
   1160         assert!(matches!(
   1161             store
   1162                 .install_transition_and_outbox(
   1163                     install_request(&binding, &prepared, digest),
   1164                     copy(&proof)
   1165                 )
   1166                 .await,
   1167             Err(OperationError::InvalidEvidence)
   1168         ));
   1169         let attempt = claimed(
   1170             store
   1171                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
   1172                 .await
   1173                 .unwrap(),
   1174         );
   1175         assert!(matches!(
   1176             store
   1177                 .install_transition_and_outbox(
   1178                     install_request(&binding, &prepared, digest),
   1179                     copy(&proof)
   1180                 )
   1181                 .await,
   1182             Err(OperationError::InvalidEvidence)
   1183         ));
   1184         assert_eq!(t2_counts(&fixture).await, (1, 0, 0));
   1185         let evidence = obtain(&attempt).await;
   1186         let receipt = captured(
   1187             store
   1188                 .capture_evidence(input.clone(), &proof, &evidence)
   1189                 .await
   1190                 .unwrap(),
   1191         );
   1192         let before = store
   1193             .operation_snapshot(
   1194                 binding.clone(),
   1195                 prepared.identity().operation_id(),
   1196                 Some(prepared.identity().command_digest()),
   1197                 copy(&proof),
   1198             )
   1199             .await
   1200             .unwrap()
   1201             .unwrap()
   1202             .checkpoint_digest();
   1203         fixture.clock.now.store(160, Ordering::SeqCst);
   1204         let result = installed(
   1205             store
   1206                 .install_transition_and_outbox(
   1207                     install_request(&binding, &prepared, digest),
   1208                     copy(&proof),
   1209                 )
   1210                 .await
   1211                 .unwrap(),
   1212         );
   1213         assert_eq!(result.basis(), receipt);
   1214         assert_eq!(result.revision(), receipt.event_id());
   1215         assert_eq!(result.author(), key());
   1216         assert_eq!(result.installed_at().get(), 160);
   1217         assert_eq!(
   1218             result.listing_id(),
   1219             prepared.request().command().listing().unwrap().input().id()
   1220         );
   1221         assert_eq!(t2_counts(&fixture).await, (1, 1, 1));
   1222         let snapshot = store
   1223             .operation_snapshot(
   1224                 binding.clone(),
   1225                 prepared.identity().operation_id(),
   1226                 Some(prepared.identity().command_digest()),
   1227                 copy(&proof),
   1228             )
   1229             .await
   1230             .unwrap()
   1231             .unwrap();
   1232         assert_eq!(snapshot.listing_installation(), Some(result));
   1233         assert!(snapshot.installation().is_none());
   1234         assert!(snapshot.installed_message().is_none());
   1235         assert!(snapshot.publications().is_empty());
   1236         assert!(snapshot.delivery_attempts().is_empty());
   1237         assert_eq!(snapshot.public_publications().len(), 1);
   1238         let work = snapshot.public_publications()[0];
   1239         assert_eq!(work.evidence().target(), SigningTarget::PublicEvent);
   1240         assert_eq!(work.evidence().target().recipient(), None);
   1241         assert_eq!(work.transaction_id(), result.transaction_id());
   1242         assert_eq!(work.queued_at(), result.installed_at());
   1243         let checkpoint = snapshot.checkpoint_digest();
   1244         assert_ne!(checkpoint, before);
   1245         store.close().await.unwrap();
   1246         fixture.clock.now.store(170, Ordering::SeqCst);
   1247         let reopened = fixture.reopen(input).await;
   1248         let replay = installed(
   1249             reopened
   1250                 .install_transition_and_outbox(
   1251                     install_request(&binding, &prepared, digest),
   1252                     copy(&proof),
   1253                 )
   1254                 .await
   1255                 .unwrap(),
   1256         );
   1257         assert_eq!(replay, result);
   1258         let snapshot = reopened
   1259             .operation_snapshot(
   1260                 binding.clone(),
   1261                 prepared.identity().operation_id(),
   1262                 Some(prepared.identity().command_digest()),
   1263                 copy(&proof),
   1264             )
   1265             .await
   1266             .unwrap()
   1267             .unwrap();
   1268         assert_eq!(snapshot.checkpoint_digest(), checkpoint);
   1269         let retained = reopened
   1270             .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof))
   1271             .await
   1272             .unwrap()
   1273             .unwrap();
   1274         assert_eq!(retained.evidence().raw_json(), evidence.raw_json());
   1275         assert_eq!(t2_counts(&fixture).await, (1, 1, 1));
   1276         reopened.close().await.unwrap();
   1277     }
   1278     #[tokio::test]
   1279     async fn another_initial_publish_cannot_claim_same_coordinate_before_any_signing() {
   1280         let fixture = Fixture::new();
   1281         let (store, _, proof, binding) = fixture.create_scoped(200, true).await;
   1282         let first = committed(
   1283             store
   1284                 .admit_command_and_hold(
   1285                     public_request(&binding, 171, "first coordinate", "one"),
   1286                     copy(&proof),
   1287                 )
   1288                 .await
   1289                 .unwrap(),
   1290         );
   1291         let second = public_request(&binding, 172, "other operation", "two");
   1292         let mut wire: serde_json::Value =
   1293             serde_json::from_slice(second.command().protected_wire()).unwrap();
   1294         wire["input"]["id"] = json!(first.request().command().listing().unwrap().input().id());
   1295         let second = AdmissionRequest::from_protected_wire(
   1296             binding.clone(),
   1297             &serde_json::to_vec(&wire).unwrap(),
   1298         )
   1299         .unwrap();
   1300         assert!(matches!(
   1301             store.admit_command_and_hold(second, copy(&proof)).await,
   1302             Err(OperationError::StaleState)
   1303         ));
   1304         assert_eq!(count(&fixture).await, 1);
   1305         assert_eq!(t2_counts(&fixture).await, (1, 0, 0));
   1306         let mut db = fixture.database().await;
   1307         let claims: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_attempts")
   1308             .fetch_one(&mut db)
   1309             .await
   1310             .unwrap();
   1311         assert_eq!(claims, 0);
   1312         db.close().await.unwrap();
   1313         store.close().await.unwrap();
   1314     }
   1315     #[tokio::test]
   1316     async fn public_t2_refuses_wrong_proof_digest_and_clock_rollback_without_partial_rows() {
   1317         let fixture = Fixture::new();
   1318         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1319         let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 173).await;
   1320         let wrong = AttachmentProof::from_protected_input(&[0x19; 32]).unwrap();
   1321         assert!(matches!(
   1322             store
   1323                 .install_transition_and_outbox(install_request(&binding, &prepared, digest), wrong)
   1324                 .await,
   1325             Err(OperationError::Workspace(WorkspaceError::Unauthorized))
   1326         ));
   1327         assert!(matches!(
   1328             store
   1329                 .install_transition_and_outbox(
   1330                     install_request(&binding, &prepared, [9; 32]),
   1331                     copy(&proof)
   1332                 )
   1333                 .await,
   1334             Err(OperationError::IdempotencyConflict)
   1335         ));
   1336         let (arrived, resume) = fixture.clock.arm(1);
   1337         let mut pending = store.install_transition_and_outbox(
   1338             install_request(&binding, &prepared, digest),
   1339             copy(&proof),
   1340         );
   1341         assert!(futures::poll!(pending.as_mut()).is_pending());
   1342         reached(arrived).await;
   1343         fixture.clock.now.store(99, Ordering::SeqCst);
   1344         resume.send(()).unwrap();
   1345         assert!(matches!(
   1346             pending.await,
   1347             Err(OperationError::Workspace(WorkspaceError::Unavailable))
   1348         ));
   1349         assert_eq!(t2_counts(&fixture).await, (1, 0, 0));
   1350         fixture.clock.now.store(100, Ordering::SeqCst);
   1351         installed(
   1352             store
   1353                 .install_transition_and_outbox(
   1354                     install_request(&binding, &prepared, digest),
   1355                     copy(&proof),
   1356                 )
   1357                 .await
   1358                 .unwrap(),
   1359         );
   1360         store.close().await.unwrap();
   1361     }
   1362     #[tokio::test]
   1363     async fn public_work_insertion_fault_rolls_back_revision_and_preserves_original_signature() {
   1364         let fixture = Fixture::new();
   1365         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1366         let (prepared, digest, evidence) =
   1367             signed(&fixture, &store, &binding, &input, &proof, 174).await;
   1368         let mut db = fixture.database().await;
   1369         sqlx::raw_sql("CREATE TRIGGER fail_public_work BEFORE INSERT ON public_publication_work BEGIN SELECT RAISE(ABORT,'isolated fixture'); END").execute(&mut db).await.unwrap();
   1370         assert!(matches!(
   1371             store
   1372                 .install_transition_and_outbox(
   1373                     install_request(&binding, &prepared, digest),
   1374                     copy(&proof)
   1375                 )
   1376                 .await,
   1377             Err(OperationError::StorageFailure)
   1378         ));
   1379         assert_eq!(t2_counts(&fixture).await, (1, 0, 0));
   1380         let retained = store
   1381             .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof))
   1382             .await
   1383             .unwrap()
   1384             .unwrap();
   1385         assert_eq!(retained.evidence().raw_json(), evidence.raw_json());
   1386         sqlx::query("DROP TRIGGER fail_public_work")
   1387             .execute(&mut db)
   1388             .await
   1389             .unwrap();
   1390         db.close().await.unwrap();
   1391         installed(
   1392             store
   1393                 .install_transition_and_outbox(
   1394                     install_request(&binding, &prepared, digest),
   1395                     copy(&proof),
   1396                 )
   1397                 .await
   1398                 .unwrap(),
   1399         );
   1400         assert_eq!(t2_counts(&fixture).await, (1, 1, 1));
   1401         store.close().await.unwrap();
   1402     }
   1403     #[tokio::test]
   1404     async fn public_t2_observer_loss_drains_and_reopens_original_installation() {
   1405         let fixture = Fixture::new();
   1406         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1407         let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 175).await;
   1408         let (arrived, resume) = fixture.clock.arm(1);
   1409         let mut pending = store.install_transition_and_outbox(
   1410             install_request(&binding, &prepared, digest),
   1411             copy(&proof),
   1412         );
   1413         assert!(futures::poll!(pending.as_mut()).is_pending());
   1414         reached(arrived).await;
   1415         drop(pending);
   1416         resume.send(()).unwrap();
   1417         store.close().await.unwrap();
   1418         let reopened = fixture.reopen(input).await;
   1419         let snapshot = reopened
   1420             .operation_snapshot(
   1421                 binding.clone(),
   1422                 prepared.identity().operation_id(),
   1423                 Some(prepared.identity().command_digest()),
   1424                 copy(&proof),
   1425             )
   1426             .await
   1427             .unwrap()
   1428             .unwrap();
   1429         let original = snapshot.listing_installation().unwrap();
   1430         assert_eq!(
   1431             installed(
   1432                 reopened
   1433                     .install_transition_and_outbox(
   1434                         install_request(&binding, &prepared, digest),
   1435                         copy(&proof)
   1436                     )
   1437                     .await
   1438                     .unwrap()
   1439             ),
   1440             original
   1441         );
   1442         assert_eq!(t2_counts(&fixture).await, (1, 1, 1));
   1443         reopened.close().await.unwrap();
   1444     }
   1445     #[tokio::test]
   1446     async fn public_t2_actual_commit_failure_is_unknown_and_blocks_until_reopen() {
   1447         let fixture = Fixture::new();
   1448         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1449         let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 176).await;
   1450         let mut db = fixture.database().await;
   1451         sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES workspace_grant(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_public_commit AFTER INSERT ON listing_installations BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut db).await.unwrap();
   1452         let radroots_storage::command::InstallationOutcome::Unknown(anchor) = store
   1453             .install_transition_and_outbox(
   1454                 install_request(&binding, &prepared, digest),
   1455                 copy(&proof),
   1456             )
   1457             .await
   1458             .unwrap()
   1459         else {
   1460             panic!("actual failed COMMIT must remain unknown")
   1461         };
   1462         assert_eq!(anchor.operation_id(), prepared.identity().operation_id());
   1463         assert!(anchor.transaction_id().is_some());
   1464         assert!(matches!(
   1465             store
   1466                 .install_transition_and_outbox(
   1467                     install_request(&binding, &prepared, digest),
   1468                     copy(&proof)
   1469                 )
   1470                 .await,
   1471             Err(OperationError::RecoveryRequired)
   1472         ));
   1473         store.close().await.unwrap();
   1474         sqlx::raw_sql("DROP TRIGGER fail_public_commit; DROP TABLE deferred_fault")
   1475             .execute(&mut db)
   1476             .await
   1477             .unwrap();
   1478         db.close().await.unwrap();
   1479         let reopened = fixture.reopen(input).await;
   1480         assert_eq!(t2_counts(&fixture).await, (1, 0, 0));
   1481         installed(
   1482             reopened
   1483                 .install_transition_and_outbox(
   1484                     install_request(&binding, &prepared, digest),
   1485                     copy(&proof),
   1486                 )
   1487                 .await
   1488                 .unwrap(),
   1489         );
   1490         reopened.close().await.unwrap();
   1491     }
   1492 
   1493     #[tokio::test]
   1494     async fn exact_generation_ten_retains_public_installation_but_refuses_fresh_public_delivery() {
   1495         use radroots_storage::command::{DeliveryAttemptRequest, DeliveryIntent};
   1496         use radroots_transport::{
   1497             Target, TargetSet,
   1498             policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy},
   1499         };
   1500         let fixture = Fixture::new();
   1501         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1502         let (prepared, digest, evidence) =
   1503             signed(&fixture, &store, &binding, &input, &proof, 187).await;
   1504         let installation = installed(
   1505             store
   1506                 .install_transition_and_outbox(
   1507                     install_request(&binding, &prepared, digest),
   1508                     copy(&proof),
   1509                 )
   1510                 .await
   1511                 .unwrap(),
   1512         );
   1513         let original = store
   1514             .operation_snapshot(
   1515                 binding.clone(),
   1516                 prepared.identity().operation_id(),
   1517                 None,
   1518                 copy(&proof),
   1519             )
   1520             .await
   1521             .unwrap()
   1522             .unwrap();
   1523         let work = original.public_publications()[0];
   1524         let checkpoint = original.checkpoint_digest();
   1525         store.close().await.unwrap();
   1526         let mut db = fixture.database().await;
   1527         retain_legacy_delivery_catalog(&mut db).await;
   1528         sqlx::query("PRAGMA user_version=10")
   1529             .execute(&mut db)
   1530             .await
   1531             .unwrap();
   1532         let catalog: Vec<(String, String)> = sqlx::query_as(
   1533             "SELECT name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY name",
   1534         )
   1535         .fetch_all(&mut db)
   1536         .await
   1537         .unwrap();
   1538         db.close().await.unwrap();
   1539         let reopened = fixture.reopen(input).await;
   1540         let actual = reopened
   1541             .operation_snapshot(
   1542                 binding.clone(),
   1543                 prepared.identity().operation_id(),
   1544                 None,
   1545                 copy(&proof),
   1546             )
   1547             .await
   1548             .unwrap()
   1549             .unwrap();
   1550         assert_eq!(actual.checkpoint_digest(), checkpoint);
   1551         assert_eq!(actual.listing_installation(), Some(installation));
   1552         assert_eq!(actual.public_publications(), &[work]);
   1553         assert_eq!(
   1554             reopened
   1555                 .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof))
   1556                 .await
   1557                 .unwrap()
   1558                 .unwrap()
   1559                 .evidence()
   1560                 .raw_json(),
   1561             evidence.raw_json()
   1562         );
   1563         let targets = TargetSet::new(vec![
   1564             Target::nostr_relay("wss://public-signature.fixture.example/a").unwrap(),
   1565         ])
   1566         .unwrap();
   1567         let delivery_request = DeliveryAttemptRequest::new(
   1568             binding.clone(),
   1569             work,
   1570             DeliveryIntent::public(
   1571                 &"18".repeat(32),
   1572                 work.evidence().event_id(),
   1573                 &targets,
   1574                 &SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()),
   1575                 core::num::NonZeroU64::new(140_000).unwrap(),
   1576             )
   1577             .unwrap(),
   1578         )
   1579         .unwrap();
   1580         assert!(matches!(
   1581             reopened
   1582                 .prepare_delivery_attempt(delivery_request, copy(&proof), None)
   1583                 .await,
   1584             Err(OperationError::UnsupportedOperation)
   1585         ));
   1586         let after = reopened
   1587             .operation_snapshot(
   1588                 binding.clone(),
   1589                 prepared.identity().operation_id(),
   1590                 None,
   1591                 copy(&proof),
   1592             )
   1593             .await
   1594             .unwrap()
   1595             .unwrap();
   1596         assert_eq!(after.checkpoint_digest(), checkpoint);
   1597         assert!(after.delivery_attempts().is_empty());
   1598         assert_eq!(
   1599             installed(
   1600                 reopened
   1601                     .install_transition_and_outbox(
   1602                         install_request(&binding, &prepared, digest),
   1603                         copy(&proof)
   1604                     )
   1605                     .await
   1606                     .unwrap()
   1607             ),
   1608             installation
   1609         );
   1610         committed(
   1611             reopened
   1612                 .admit_command_and_hold(
   1613                     request(
   1614                         &binding,
   1615                         188,
   1616                         "generation10 private continuation",
   1617                         "private",
   1618                     ),
   1619                     copy(&proof),
   1620                 )
   1621                 .await
   1622                 .unwrap(),
   1623         );
   1624         reopened.close().await.unwrap();
   1625         let mut db = fixture.database().await;
   1626         let retained: Vec<(String, String)> = sqlx::query_as(
   1627             "SELECT name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY name",
   1628         )
   1629         .fetch_all(&mut db)
   1630         .await
   1631         .unwrap();
   1632         assert_eq!(retained, catalog);
   1633         assert_eq!(
   1634             sqlx::query_scalar::<_, i64>("PRAGMA user_version")
   1635                 .fetch_one(&mut db)
   1636                 .await
   1637                 .unwrap(),
   1638             10
   1639         );
   1640         db.close().await.unwrap();
   1641     }
   1642 
   1643     #[tokio::test]
   1644     async fn exact_generation_nine_preserves_public_s_and_refuses_unfenced_new_effects() {
   1645         let fixture = Fixture::new();
   1646         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1647         let (prepared, digest, evidence) =
   1648             signed(&fixture, &store, &binding, &input, &proof, 177).await;
   1649         store.close().await.unwrap();
   1650         let mut db = fixture.database().await;
   1651         retain_legacy_delivery_catalog(&mut db).await;
   1652         sqlx::raw_sql("DROP TABLE public_publication_work; DROP TABLE listing_installations; DROP TABLE listing_creations; PRAGMA user_version=9").execute(&mut db).await.unwrap();
   1653         db.close().await.unwrap();
   1654         let reopened = fixture.reopen(input).await;
   1655         let retained = reopened
   1656             .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof))
   1657             .await
   1658             .unwrap()
   1659             .unwrap();
   1660         assert_eq!(retained.evidence().raw_json(), evidence.raw_json());
   1661         assert!(matches!(
   1662             reopened
   1663                 .install_transition_and_outbox(
   1664                     install_request(&binding, &prepared, digest),
   1665                     copy(&proof)
   1666                 )
   1667                 .await,
   1668             Err(OperationError::UnsupportedOperation)
   1669         ));
   1670         assert!(matches!(
   1671             reopened
   1672                 .admit_command_and_hold(
   1673                     public_request(&binding, 178, "fresh unsupported", "new"),
   1674                     copy(&proof)
   1675                 )
   1676                 .await,
   1677             Err(OperationError::UnsupportedOperation)
   1678         ));
   1679         assert!(matches!(
   1680             reopened
   1681                 .admit_command_and_hold(
   1682                     public_request(&binding, 177, "changed terms", "replay"),
   1683                     copy(&proof)
   1684                 )
   1685                 .await,
   1686             Err(OperationError::IdempotencyConflict)
   1687         ));
   1688         let replay = AdmissionRequest::from_protected_wire(
   1689             binding.clone(),
   1690             prepared.request().command().protected_wire(),
   1691         )
   1692         .unwrap();
   1693         assert_eq!(
   1694             committed(
   1695                 reopened
   1696                     .admit_command_and_hold(replay, copy(&proof))
   1697                     .await
   1698                     .unwrap()
   1699             )
   1700             .identity(),
   1701             prepared.identity()
   1702         );
   1703         assert!(matches!(
   1704             reopened
   1705                 .claim_attempt(selection(&binding, &prepared, digest), copy(&proof))
   1706                 .await
   1707                 .unwrap(),
   1708             ClaimAttemptOutcome::Retained(_)
   1709         ));
   1710         committed(
   1711             reopened
   1712                 .admit_command_and_hold(
   1713                     request(&binding, 179, "legacy private continuation", "private"),
   1714                     copy(&proof),
   1715                 )
   1716                 .await
   1717                 .unwrap(),
   1718         );
   1719         reopened.close().await.unwrap();
   1720     }
   1721     #[tokio::test]
   1722     async fn public_t2_requires_current_grant_even_after_obtained_capture() {
   1723         let fixture = Fixture::new();
   1724         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1725         let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 180).await;
   1726         store.revoke(input, &proof).await.unwrap();
   1727         assert!(matches!(
   1728             store
   1729                 .install_transition_and_outbox(
   1730                     install_request(&binding, &prepared, digest),
   1731                     copy(&proof)
   1732                 )
   1733                 .await,
   1734             Err(OperationError::Workspace(WorkspaceError::GrantRevoked))
   1735         ));
   1736         assert_eq!(t2_counts(&fixture).await, (1, 0, 0));
   1737         store.close().await.unwrap();
   1738     }
   1739     #[tokio::test]
   1740     async fn retained_listing_graph_refuses_changed_decision_and_orphaned_installation_without_repair()
   1741      {
   1742         let fixture = Fixture::new();
   1743         let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1744         let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 181).await;
   1745         installed(
   1746             store
   1747                 .install_transition_and_outbox(
   1748                     install_request(&binding, &prepared, digest),
   1749                     copy(&proof),
   1750                 )
   1751                 .await
   1752                 .unwrap(),
   1753         );
   1754         let mut db = fixture.database().await;
   1755         sqlx::query("PRAGMA foreign_keys=OFF")
   1756             .execute(&mut db)
   1757             .await
   1758             .unwrap();
   1759         let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM listing_creations")
   1760             .fetch_one(&mut db)
   1761             .await
   1762             .unwrap();
   1763         sqlx::query("UPDATE listing_creations SET transaction_id=zeroblob(32)")
   1764             .execute(&mut db)
   1765             .await
   1766             .unwrap();
   1767         assert!(matches!(
   1768             store
   1769                 .operation_snapshot(
   1770                     binding.clone(),
   1771                     prepared.identity().operation_id(),
   1772                     Some(prepared.identity().command_digest()),
   1773                     copy(&proof)
   1774                 )
   1775                 .await,
   1776             Err(OperationError::RecoveryRequired)
   1777         ));
   1778         sqlx::query("UPDATE listing_creations SET transaction_id=?,protected=?")
   1779             .bind(prepared.transaction_id().as_bytes().as_slice())
   1780             .bind(&original)
   1781             .execute(&mut db)
   1782             .await
   1783             .unwrap();
   1784         let event: Vec<u8> = sqlx::query_scalar("SELECT event_id FROM listing_installations")
   1785             .fetch_one(&mut db)
   1786             .await
   1787             .unwrap();
   1788         let installed_row: Vec<u8> =
   1789             sqlx::query_scalar("SELECT protected FROM listing_installations")
   1790                 .fetch_one(&mut db)
   1791                 .await
   1792                 .unwrap();
   1793         for update in [
   1794             "UPDATE listing_installations SET event_id=zeroblob(32)",
   1795             "UPDATE public_publication_work SET plan_digest=zeroblob(32)",
   1796         ] {
   1797             sqlx::query(update).execute(&mut db).await.unwrap();
   1798             assert!(matches!(
   1799                 store
   1800                     .operation_snapshot(
   1801                         binding.clone(),
   1802                         prepared.identity().operation_id(),
   1803                         Some(prepared.identity().command_digest()),
   1804                         copy(&proof)
   1805                     )
   1806                     .await,
   1807                 Err(OperationError::RecoveryRequired)
   1808             ));
   1809             sqlx::query("UPDATE listing_installations SET event_id=?,protected=?")
   1810                 .bind(&event)
   1811                 .bind(&installed_row)
   1812                 .execute(&mut db)
   1813                 .await
   1814                 .unwrap();
   1815             sqlx::query("UPDATE public_publication_work SET plan_digest=?")
   1816                 .bind(digest.as_slice())
   1817                 .execute(&mut db)
   1818                 .await
   1819                 .unwrap();
   1820         }
   1821         sqlx::query("DELETE FROM listing_installations")
   1822             .execute(&mut db)
   1823             .await
   1824             .unwrap();
   1825         assert!(matches!(
   1826             store
   1827                 .operation_snapshot(
   1828                     binding.clone(),
   1829                     prepared.identity().operation_id(),
   1830                     Some(prepared.identity().command_digest()),
   1831                     copy(&proof)
   1832                 )
   1833                 .await,
   1834             Err(OperationError::RecoveryRequired)
   1835         ));
   1836         sqlx::raw_sql("DELETE FROM listing_creations; DELETE FROM artifact_evidence_parts; DELETE FROM artifact_evidence; DELETE FROM signing_attempts; DELETE FROM signing_plan_parts; DELETE FROM signing_plans; DELETE FROM operations").execute(&mut db).await.unwrap();
   1837         assert!(matches!(
   1838             store
   1839                 .operation(
   1840                     binding.clone(),
   1841                     prepared.identity().operation_id(),
   1842                     Some(prepared.identity().command_digest()),
   1843                     copy(&proof)
   1844                 )
   1845                 .await,
   1846             Err(OperationError::RecoveryRequired)
   1847         ));
   1848         db.close().await.unwrap();
   1849         store.close().await.unwrap();
   1850     }
   1851 }
   1852 
   1853 #[path = "legacy_delivery_catalog.rs"]
   1854 mod legacy_delivery_catalog;
   1855 use legacy_delivery_catalog::retain_legacy_delivery_catalog;
   1856 
   1857 pub(super) async fn retain_legacy_issuance_catalog(db: &mut SqliteConnection) {
   1858     retain_legacy_delivery_catalog(db).await;
   1859     sqlx::raw_sql("DROP TABLE public_publication_work; DROP TABLE listing_installations; DROP TABLE listing_creations").execute(&mut *db).await.unwrap();
   1860     use sqlx::Row;
   1861     let rows=sqlx::query("SELECT name,sql FROM sqlite_schema WHERE name IN ('signing_attempts','signing_attempt_identity','signing_attempt_transaction_identity','artifact_evidence','artifact_evidence_transaction_identity','artifact_evidence_parts','chat_publication_work')").fetch_all(&mut *db).await.unwrap();
   1862     let definitions = rows
   1863         .into_iter()
   1864         .map(|row| {
   1865             let name: String = row.get(0);
   1866             let ddl: String = row.get(1);
   1867             let ddl = ddl
   1868                 .replace("artifact_evidence", "seal_evidence")
   1869                 .replace("artifact_key", "recipient")
   1870                 .replace(
   1871                     "CHECK(length(recipient)=32 OR (length(recipient)=1 AND hex(recipient)='00'))",
   1872                     "CHECK(length(recipient)=32)",
   1873                 );
   1874             (name, ddl)
   1875         })
   1876         .collect::<std::collections::BTreeMap<_, _>>();
   1877     for table in [
   1878         "signing_attempts",
   1879         "artifact_evidence",
   1880         "artifact_evidence_parts",
   1881         "chat_publication_work",
   1882     ] {
   1883         sqlx::query(sqlx::AssertSqlSafe(format!(
   1884             "CREATE TEMP TABLE retained_{table} AS SELECT * FROM {table}"
   1885         )))
   1886         .execute(&mut *db)
   1887         .await
   1888         .unwrap();
   1889     }
   1890     for table in [
   1891         "chat_publication_work",
   1892         "artifact_evidence_parts",
   1893         "artifact_evidence",
   1894         "signing_attempts",
   1895     ] {
   1896         sqlx::query(sqlx::AssertSqlSafe(format!("DROP TABLE {table}")))
   1897             .execute(&mut *db)
   1898             .await
   1899             .unwrap();
   1900     }
   1901     for name in [
   1902         "signing_attempts",
   1903         "signing_attempt_identity",
   1904         "signing_attempt_transaction_identity",
   1905         "artifact_evidence",
   1906         "artifact_evidence_transaction_identity",
   1907         "artifact_evidence_parts",
   1908         "chat_publication_work",
   1909     ] {
   1910         sqlx::query(sqlx::AssertSqlSafe(definitions[name].clone()))
   1911             .execute(&mut *db)
   1912             .await
   1913             .unwrap();
   1914     }
   1915     for table in [
   1916         "signing_attempts",
   1917         "artifact_evidence",
   1918         "artifact_evidence_parts",
   1919         "chat_publication_work",
   1920     ] {
   1921         let legacy = table.replace("artifact_evidence", "seal_evidence");
   1922         sqlx::query(sqlx::AssertSqlSafe(format!(
   1923             "INSERT INTO {legacy} SELECT * FROM retained_{table}"
   1924         )))
   1925         .execute(&mut *db)
   1926         .await
   1927         .unwrap();
   1928         sqlx::query(sqlx::AssertSqlSafe(format!("DROP TABLE retained_{table}")))
   1929             .execute(&mut *db)
   1930             .await
   1931             .unwrap();
   1932     }
   1933     sqlx::query("PRAGMA user_version=8")
   1934         .execute(db)
   1935         .await
   1936         .unwrap();
   1937 }
   1938 
   1939 #[tokio::test]
   1940 async fn exact_generation_eight_preserves_public_t1_and_refuses_public_s_without_rewrite() {
   1941     use radroots_protocol::plan::SigningTarget;
   1942     let fixture = Fixture::new();
   1943     let (store, input, proof, binding) = fixture.create_scoped(200, true).await;
   1944     let prepared = committed(
   1945         store
   1946             .admit_command_and_hold(
   1947                 public_request(&binding, 165, "retained generation8 public plan", "first"),
   1948                 copy(&proof),
   1949             )
   1950             .await
   1951             .unwrap(),
   1952     );
   1953     let plan = public_plan(
   1954         &prepared,
   1955         100,
   1956         &["wss://public-signature.fixture.example/a".into()],
   1957     );
   1958     let wire = plan.protected_wire().to_vec();
   1959     let digest = *plan.digest();
   1960     planned(
   1961         store
   1962             .bind_signing_intents(binding.clone(), plan.into(), copy(&proof))
   1963             .await
   1964             .unwrap(),
   1965     );
   1966     store.close().await.unwrap();
   1967     let mut db = fixture.database().await;
   1968     retain_legacy_issuance_catalog(&mut db).await;
   1969     db.close().await.unwrap();
   1970     let reopened = fixture.reopen(input).await;
   1971     let retained = reopened
   1972         .signing_plan(
   1973             binding.clone(),
   1974             prepared.identity().operation_id(),
   1975             prepared.identity().command_digest(),
   1976             copy(&proof),
   1977         )
   1978         .await
   1979         .unwrap()
   1980         .unwrap();
   1981     assert_eq!(retained.plan().protected_wire(), wire);
   1982     let request = || {
   1983         ClaimAttemptRequest::for_artifact(
   1984             binding.clone(),
   1985             prepared.identity().operation_id(),
   1986             prepared.identity().command_digest(),
   1987             digest,
   1988             SigningTarget::PublicEvent,
   1989         )
   1990     };
   1991     assert!(
   1992         reopened
   1993             .obtained_evidence(request(), copy(&proof))
   1994             .await
   1995             .unwrap()
   1996             .is_none()
   1997     );
   1998     assert!(matches!(
   1999         reopened.claim_attempt(request(), copy(&proof)).await,
   2000         Err(OperationError::UnsupportedOperation)
   2001     ));
   2002     reopened.close().await.unwrap();
   2003     let mut db = fixture.database().await;
   2004     let version: i64 = sqlx::query_scalar("PRAGMA user_version")
   2005         .fetch_one(&mut db)
   2006         .await
   2007         .unwrap();
   2008     assert_eq!(version, 8);
   2009     db.close().await.unwrap();
   2010 }