lib

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

workspace_issuance.rs (32519B)


      1 use super::*;
      2 use core::{cell::Cell, num::NonZeroU64};
      3 use radroots_nostr::{
      4     key::parse_secret_key,
      5     signing::{LocalSigner, OsNonceSource},
      6 };
      7 use radroots_signing::{
      8     issuance::{OutcomeKind, SigningIntent},
      9     provider::{ParticipantProvider, ProviderCall},
     10     request::CancellationSignal,
     11 };
     12 use radroots_storage::command::{
     13     ArtifactEvidence, CapturedArtifact, ClaimAttemptOutcome, ClaimAttemptRequest,
     14     EvidenceCaptureOutcome, SigningAttempt,
     15 };
     16 thread_local! {static CALLS:Cell<usize>=const {Cell::new(0)};static MISSING:Cell<bool>=const {Cell::new(false)};}
     17 fn signer_clock() -> Result<u64, radroots_signing::Error> {
     18     let count = CALLS.with(|calls| {
     19         let value = calls.get() + 1;
     20         calls.set(value);
     21         value
     22     });
     23     if count > 1 && MISSING.with(Cell::get) {
     24         Err(radroots_signing::Error::new(
     25             radroots_signing::error::Kind::InternalError,
     26         ))
     27     } else {
     28         Ok(100_000)
     29     }
     30 }
     31 fn selection(
     32     binding: &WorkspaceBinding,
     33     prepared: &PreparedOperation,
     34     plan_digest: [u8; 32],
     35     recipient: PublicKey,
     36 ) -> ClaimAttemptRequest {
     37     ClaimAttemptRequest::new(
     38         binding.clone(),
     39         prepared.identity().operation_id(),
     40         prepared.identity().command_digest(),
     41         plan_digest,
     42         recipient,
     43     )
     44 }
     45 fn claim(outcome: ClaimAttemptOutcome) -> SigningAttempt {
     46     match outcome {
     47         ClaimAttemptOutcome::Claimed(value) => value,
     48         _ => panic!("first actual claim must confirm its commit"),
     49     }
     50 }
     51 async fn prepare(
     52     fixture: &Fixture,
     53     store: &NativeWorkspace,
     54     binding: &WorkspaceBinding,
     55     proof: &AttachmentProof,
     56     id: u8,
     57     large: bool,
     58 ) -> (PreparedOperation, [u8; 32], Vec<PublicKey>) {
     59     let mut captured = peer_request(binding, id);
     60     if large {
     61         let mut value: serde_json::Value =
     62             serde_json::from_slice(captured.command().protected_wire()).unwrap();
     63         value["input"]["text"] = "\0".repeat(3500).into();
     64         captured = AdmissionRequest::from_protected_wire(
     65             binding.clone(),
     66             &serde_json::to_vec(&value).unwrap(),
     67         )
     68         .unwrap();
     69     }
     70     let prepared = committed(
     71         store
     72             .admit_command_and_hold(captured, copy(proof))
     73             .await
     74             .unwrap(),
     75     );
     76     let plan = plan(
     77         prepared.request().chat_command().unwrap(),
     78         100,
     79         "native-issuance",
     80     );
     81     let digest = *plan.digest();
     82     let recipients = plan.seals().iter().map(|seal| seal.recipient()).collect();
     83     bound(
     84         store
     85             .bind_signing_intents(binding.clone(), (plan).into(), copy(proof))
     86             .await
     87             .unwrap(),
     88     );
     89     let _ = fixture;
     90     (prepared, digest, recipients)
     91 }
     92 async fn obtain(attempt: &SigningAttempt, missing: bool) -> ArtifactEvidence {
     93     CALLS.with(|calls| calls.set(0));
     94     MISSING.with(|value| value.set(missing));
     95     // Published synthetic key in a qualified local provider, isolated from all host custody.
     96     let signer = LocalSigner::with_clock(
     97         parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001")
     98             .unwrap(),
     99         signer_clock,
    100     )
    101     .unwrap()
    102     .with_nonce_source(Arc::new(OsNonceSource));
    103     let observed = signer.provider_state().await.unwrap();
    104     assert_eq!(observed.identity(), key());
    105     assert_eq!(
    106         observed.exact_issuance(),
    107         Some(radroots_signing::recovery::ReplayCapability::NonReplayable)
    108     );
    109     let intent = SigningIntent::from_chat_seal(
    110         attempt.binding().operation_id(),
    111         attempt.bound_plan().prepared().identity().command_digest(),
    112         attempt.seal().unwrap(),
    113         ProviderCall::new(key(), attempt.deadline_unix_ms(), CancellationSignal::new()),
    114     )
    115     .unwrap();
    116     assert_eq!(intent.binding(), attempt.binding());
    117     let outcome = signer.sign_exact(intent).await;
    118     assert_eq!(outcome.binding(), attempt.binding());
    119     let (_, kind) = outcome.into_parts();
    120     let OutcomeKind::Obtained(artifact) = kind else {
    121         panic!("actual local exact signing must obtain")
    122     };
    123     assert_eq!(artifact.observed_at_unix_ms().is_none(), missing);
    124     artifact.with_json(|raw| {
    125         ArtifactEvidence::verify(attempt, raw, artifact.observed_at_unix_ms()).unwrap()
    126     })
    127 }
    128 fn captured(outcome: EvidenceCaptureOutcome) -> radroots_storage::command::EvidenceReceipt {
    129     match outcome {
    130         EvidenceCaptureOutcome::Committed(value) => value,
    131         _ => panic!("fixture capture must confirm commit"),
    132     }
    133 }
    134 #[tokio::test]
    135 async fn real_exact_peer_and_self_signatures_capture_reopen_and_never_reclaim_original_intents() {
    136     let fixture = Fixture::new();
    137     let (store, input, proof, binding) = fixture.create().await;
    138     let (prepared, digest, recipients) =
    139         prepare(&fixture, &store, &binding, &proof, 130, false).await;
    140     let mut originals = Vec::new();
    141     for recipient in recipients {
    142         let first = claim(
    143             store
    144                 .claim_attempt(
    145                     selection(&binding, &prepared, digest, recipient),
    146                     copy(&proof),
    147                 )
    148                 .await
    149                 .unwrap(),
    150         );
    151         let signature = obtain(&first, true).await;
    152         let raw = signature.raw_json().to_owned();
    153         let receipt = captured(
    154             store
    155                 .capture_evidence(input.clone(), &proof, &signature)
    156                 .await
    157                 .unwrap(),
    158         );
    159         assert_eq!(receipt.observed_at_unix_ms(), None);
    160         let duplicate = store
    161             .claim_attempt(
    162                 selection(&binding, &prepared, digest, recipient),
    163                 copy(&proof),
    164             )
    165             .await
    166             .unwrap();
    167         assert!(matches!(duplicate, ClaimAttemptOutcome::Retained(_)));
    168         let repeated = ArtifactEvidence::verify(&first, &raw, NonZeroU64::new(111_000)).unwrap();
    169         assert_eq!(
    170             captured(
    171                 store
    172                     .capture_evidence(input.clone(), &proof, &repeated)
    173                     .await
    174                     .unwrap()
    175             ),
    176             receipt
    177         );
    178         originals.push((recipient, raw, receipt, first.attempt_id()));
    179     }
    180     store.close().await.unwrap();
    181     fixture.clock.now.store(151, Ordering::SeqCst);
    182     let reopened = fixture.reopen(input).await;
    183     for (recipient, raw, receipt, id) in originals {
    184         let original = reopened
    185             .signing_attempt(
    186                 selection(&binding, &prepared, digest, recipient),
    187                 copy(&proof),
    188             )
    189             .await
    190             .unwrap()
    191             .unwrap();
    192         assert_eq!(original.attempt_id(), id);
    193         let recovered: CapturedArtifact = reopened
    194             .obtained_evidence(
    195                 selection(&binding, &prepared, digest, recipient),
    196                 copy(&proof),
    197             )
    198             .await
    199             .unwrap()
    200             .unwrap();
    201         assert_eq!(recovered.evidence().raw_json(), raw);
    202         assert_eq!(recovered.receipt(), receipt);
    203         assert!(matches!(
    204             reopened
    205                 .claim_attempt(
    206                     selection(&binding, &prepared, digest, recipient),
    207                     copy(&proof)
    208                 )
    209                 .await
    210                 .unwrap(),
    211             ClaimAttemptOutcome::Retained(_)
    212         ));
    213     }
    214     reopened.close().await.unwrap();
    215 }
    216 #[tokio::test]
    217 async fn late_revoked_expired_and_missing_clock_capture_retains_bytes_without_new_rights() {
    218     for mode in 0..3 {
    219         let fixture = Fixture::new();
    220         let (store, input, proof, binding) = fixture.create().await;
    221         let (prepared, digest, recipients) =
    222             prepare(&fixture, &store, &binding, &proof, 131, false).await;
    223         let first = claim(
    224             store
    225                 .claim_attempt(
    226                     selection(&binding, &prepared, digest, recipients[0]),
    227                     copy(&proof),
    228                 )
    229                 .await
    230                 .unwrap(),
    231         );
    232         let evidence = obtain(&first, true).await;
    233         if mode == 0 {
    234             fixture.clock.now.store(201, Ordering::SeqCst);
    235         }
    236         if mode == 1 {
    237             store.revoke(input.clone(), &proof).await.unwrap();
    238         }
    239         if mode == 2 {
    240             fixture.clock.now.store(0, Ordering::SeqCst);
    241         }
    242         let receipt = captured(
    243             store
    244                 .capture_evidence(input.clone(), &proof, &evidence)
    245                 .await
    246                 .unwrap(),
    247         );
    248         assert_eq!(receipt.observed_at_unix_ms(), None);
    249         assert!(
    250             store
    251                 .claim_attempt(
    252                     selection(&binding, &prepared, digest, recipients[1]),
    253                     copy(&proof)
    254                 )
    255                 .await
    256                 .is_err()
    257         );
    258         store.close().await.unwrap();
    259         let reopened = fixture.reopen(input.clone()).await;
    260         assert_eq!(
    261             captured(
    262                 reopened
    263                     .capture_evidence(input, &proof, &evidence)
    264                     .await
    265                     .unwrap()
    266             ),
    267             receipt
    268         );
    269         reopened.close().await.unwrap();
    270     }
    271 }
    272 #[tokio::test]
    273 async fn one_recipient_obtained_does_not_invent_the_other_and_failed_capture_keeps_caller_original()
    274 {
    275     let fixture = Fixture::new();
    276     let (store, input, proof, binding) = fixture.create().await;
    277     let (prepared, digest, recipients) =
    278         prepare(&fixture, &store, &binding, &proof, 132, true).await;
    279     let first = claim(
    280         store
    281             .claim_attempt(
    282                 selection(&binding, &prepared, digest, recipients[0]),
    283                 copy(&proof),
    284             )
    285             .await
    286             .unwrap(),
    287     );
    288     let evidence = obtain(&first, false).await;
    289     let raw = evidence.raw_json().to_owned();
    290     assert!(raw.len() > 16384);
    291     let second = claim(
    292         store
    293             .claim_attempt(
    294                 selection(&binding, &prepared, digest, recipients[1]),
    295                 copy(&proof),
    296             )
    297             .await
    298             .unwrap(),
    299     );
    300     let mut database = fixture.database().await;
    301     sqlx::raw_sql("CREATE TRIGGER refuse_evidence BEFORE INSERT ON artifact_evidence_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ABORT,'synthetic capture failure'); END").execute(&mut database).await.unwrap();
    302     assert!(matches!(
    303         store
    304             .capture_evidence(input.clone(), &proof, &evidence)
    305             .await,
    306         Err(OperationError::StorageFailure)
    307     ));
    308     assert_eq!(evidence.raw_json(), raw);
    309     let count: i64 = sqlx::query_scalar("SELECT count(*) FROM artifact_evidence")
    310         .fetch_one(&mut database)
    311         .await
    312         .unwrap();
    313     assert_eq!(count, 0);
    314     sqlx::raw_sql("DROP TRIGGER refuse_evidence")
    315         .execute(&mut database)
    316         .await
    317         .unwrap();
    318     database.close().await.unwrap();
    319     captured(
    320         store
    321             .capture_evidence(input, &proof, &evidence)
    322             .await
    323             .unwrap(),
    324     );
    325     assert!(
    326         store
    327             .obtained_evidence(
    328                 selection(&binding, &prepared, digest, recipients[1]),
    329                 copy(&proof)
    330             )
    331             .await
    332             .unwrap()
    333             .is_none()
    334     );
    335     assert!(matches!(
    336         store
    337             .claim_attempt(
    338                 selection(
    339                     &binding,
    340                     &prepared,
    341                     digest,
    342                     second.seal().unwrap().recipient()
    343                 ),
    344                 copy(&proof)
    345             )
    346             .await
    347             .unwrap(),
    348         ClaimAttemptOutcome::Retained(_)
    349     ));
    350     store.close().await.unwrap();
    351 }
    352 #[tokio::test]
    353 async fn verification_refuses_wrong_field_signature_and_binding_before_capture() {
    354     let fixture = Fixture::new();
    355     let (store, _, proof, binding) = fixture.create().await;
    356     let (prepared, digest, recipients) =
    357         prepare(&fixture, &store, &binding, &proof, 133, false).await;
    358     let first = claim(
    359         store
    360             .claim_attempt(
    361                 selection(&binding, &prepared, digest, recipients[0]),
    362                 copy(&proof),
    363             )
    364             .await
    365             .unwrap(),
    366     );
    367     let evidence = obtain(&first, false).await;
    368     let second = claim(
    369         store
    370             .claim_attempt(
    371                 selection(&binding, &prepared, digest, recipients[1]),
    372                 copy(&proof),
    373             )
    374             .await
    375             .unwrap(),
    376     );
    377     assert!(!evidence.matches_attempt(&second));
    378     for (field, value) in [
    379         ("sig", serde_json::json!("00".repeat(64))),
    380         ("id", serde_json::json!("00".repeat(32))),
    381         ("pubkey", serde_json::json!(keys(2).public_key().to_hex())),
    382         ("content", serde_json::json!("changed")),
    383         ("kind", serde_json::json!(14)),
    384         ("created_at", serde_json::json!(98)),
    385         ("tags", serde_json::json!([["p", "changed"]])),
    386     ] {
    387         let mut changed: serde_json::Value = serde_json::from_str(evidence.raw_json()).unwrap();
    388         changed[field] = value;
    389         assert!(
    390             matches!(
    391                 ArtifactEvidence::verify(&first, &changed.to_string(), None),
    392                 Err(OperationError::InvalidEvidence)
    393             ),
    394             "{field}"
    395         );
    396     }
    397     assert!(ArtifactEvidence::verify(&first, &"x".repeat(65537), None).is_err());
    398     store.close().await.unwrap();
    399 }
    400 
    401 #[tokio::test]
    402 async fn lost_claim_observer_reopens_as_retained_potential_issuance_not_a_second_dispatch() {
    403     let fixture = Fixture::new();
    404     let (store, input, proof, binding) = fixture.create().await;
    405     let (prepared, digest, recipients) =
    406         prepare(&fixture, &store, &binding, &proof, 140, false).await;
    407     let (arrived, resume) = fixture.clock.arm(1);
    408     let mut first = store.claim_attempt(
    409         selection(&binding, &prepared, digest, recipients[0]),
    410         copy(&proof),
    411     );
    412     assert!(futures::poll!(first.as_mut()).is_pending());
    413     reached(arrived).await;
    414     drop(first);
    415     resume.send(()).unwrap();
    416     store.close().await.unwrap();
    417     let reopened = fixture.reopen(input).await;
    418     assert!(matches!(
    419         reopened
    420             .claim_attempt(
    421                 selection(&binding, &prepared, digest, recipients[0]),
    422                 copy(&proof)
    423             )
    424             .await
    425             .unwrap(),
    426         ClaimAttemptOutcome::Retained(_)
    427     ));
    428     assert!(
    429         reopened
    430             .obtained_evidence(
    431                 selection(&binding, &prepared, digest, recipients[0]),
    432                 copy(&proof)
    433             )
    434             .await
    435             .unwrap()
    436             .is_none()
    437     );
    438     reopened.close().await.unwrap();
    439 }
    440 #[tokio::test]
    441 async fn accepted_capture_survives_lost_observer_and_conservative_byte_exhaustion() {
    442     let fixture = Fixture::new();
    443     let (store, input, proof, binding) = fixture.create().await;
    444     let (prepared, digest, recipients) =
    445         prepare(&fixture, &store, &binding, &proof, 141, true).await;
    446     let first = claim(
    447         store
    448             .claim_attempt(
    449                 selection(&binding, &prepared, digest, recipients[0]),
    450                 copy(&proof),
    451             )
    452             .await
    453             .unwrap(),
    454     );
    455     let evidence = obtain(&first, true).await;
    456     let mut database = fixture.database().await;
    457     let transaction = database.begin_with("BEGIN IMMEDIATE").await.unwrap();
    458     let mut waiting = Vec::new();
    459     for _ in 0..16 {
    460         let mut call = store.capture_evidence(input.clone(), &proof, &evidence);
    461         assert!(futures::poll!(call.as_mut()).is_pending());
    462         waiting.push(call);
    463     }
    464     assert!(matches!(
    465         store
    466             .capture_evidence(input.clone(), &proof, &evidence)
    467             .await,
    468         Err(OperationError::Workspace(WorkspaceError::Unavailable))
    469     ));
    470     drop(waiting.remove(0));
    471     transaction.rollback().await.unwrap();
    472     database.close().await.unwrap();
    473     let mut retained = None;
    474     for call in waiting {
    475         let receipt = captured(call.await.unwrap());
    476         if let Some(original) = retained {
    477             assert_eq!(receipt, original);
    478         } else {
    479             retained = Some(receipt);
    480         }
    481     }
    482     store.close().await.unwrap();
    483     let reopened = fixture.reopen(input).await;
    484     let original = reopened
    485         .obtained_evidence(
    486             selection(&binding, &prepared, digest, recipients[0]),
    487             copy(&proof),
    488         )
    489         .await
    490         .unwrap()
    491         .unwrap();
    492     assert_eq!(original.evidence().raw_json(), evidence.raw_json());
    493     assert_eq!(Some(original.receipt()), retained);
    494     reopened.close().await.unwrap();
    495 }
    496 #[tokio::test]
    497 async fn actual_claim_commit_uncertainty_latches_and_reopen_never_infers_a_safe_reissue() {
    498     let fixture = Fixture::new();
    499     let (store, input, proof, binding) = fixture.create().await;
    500     let (prepared, digest, recipients) =
    501         prepare(&fixture, &store, &binding, &proof, 142, false).await;
    502     let mut database = fixture.database().await;
    503     sqlx::raw_sql("CREATE TABLE claim_commit_fault (parent INTEGER REFERENCES workspace_grant(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER claim_commit_fault_trigger AFTER INSERT ON signing_attempts BEGIN INSERT INTO claim_commit_fault VALUES(2); END").execute(&mut database).await.unwrap();
    504     database.close().await.unwrap();
    505     let outcome = store
    506         .claim_attempt(
    507             selection(&binding, &prepared, digest, recipients[0]),
    508             copy(&proof),
    509         )
    510         .await
    511         .unwrap();
    512     match outcome {
    513         ClaimAttemptOutcome::Unknown(anchor) => {
    514             assert_eq!(anchor.operation_id(), prepared.identity().operation_id());
    515             assert_eq!(
    516                 anchor.command_digest(),
    517                 prepared.identity().command_digest()
    518             );
    519             assert!(anchor.transaction_id().is_some());
    520         }
    521         _ => panic!("unconfirmed commit must stay unknown"),
    522     }
    523     assert!(matches!(
    524         store
    525             .operation_snapshot(
    526                 binding.clone(),
    527                 prepared.identity().operation_id(),
    528                 None,
    529                 copy(&proof)
    530             )
    531             .await,
    532         Err(OperationError::RecoveryRequired)
    533     ));
    534     assert!(matches!(
    535         store
    536             .signing_attempt(
    537                 selection(&binding, &prepared, digest, recipients[0]),
    538                 copy(&proof)
    539             )
    540             .await,
    541         Err(OperationError::RecoveryRequired)
    542     ));
    543     store.close().await.unwrap();
    544     let mut database = fixture.database().await;
    545     sqlx::raw_sql("DROP TRIGGER claim_commit_fault_trigger; DROP TABLE claim_commit_fault")
    546         .execute(&mut database)
    547         .await
    548         .unwrap();
    549     database.close().await.unwrap();
    550     let reopened = fixture.reopen(input).await;
    551     assert!(
    552         reopened
    553             .signing_attempt(
    554                 selection(&binding, &prepared, digest, recipients[0]),
    555                 copy(&proof)
    556             )
    557             .await
    558             .unwrap()
    559             .is_none()
    560     );
    561     reopened.close().await.unwrap();
    562 }
    563 #[tokio::test]
    564 async fn uncertain_capture_keeps_original_bytes_until_safe_reopen_and_exact_retry() {
    565     let fixture = Fixture::new();
    566     let (store, input, proof, binding) = fixture.create().await;
    567     let (prepared, digest, recipients) =
    568         prepare(&fixture, &store, &binding, &proof, 143, true).await;
    569     let first = claim(
    570         store
    571             .claim_attempt(
    572                 selection(&binding, &prepared, digest, recipients[0]),
    573                 copy(&proof),
    574             )
    575             .await
    576             .unwrap(),
    577     );
    578     let evidence = obtain(&first, true).await;
    579     let raw = evidence.raw_json().to_owned();
    580     let mut database = fixture.database().await;
    581     sqlx::raw_sql("CREATE TRIGGER capture_unknown BEFORE INSERT ON artifact_evidence_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ROLLBACK,'synthetic unknown capture'); END").execute(&mut database).await.unwrap();
    582     database.close().await.unwrap();
    583     let outcome = store
    584         .capture_evidence(input.clone(), &proof, &evidence)
    585         .await
    586         .unwrap();
    587     match outcome {
    588         EvidenceCaptureOutcome::Unknown(anchor) => {
    589             assert_eq!(anchor.operation_id(), prepared.identity().operation_id());
    590             assert_eq!(
    591                 anchor.command_digest(),
    592                 prepared.identity().command_digest()
    593             );
    594         }
    595         _ => panic!("uncertain capture must not report a known commit/rollback"),
    596     }
    597     assert_eq!(evidence.raw_json(), raw);
    598     store.close().await.unwrap();
    599     let mut database = fixture.database().await;
    600     sqlx::raw_sql("DROP TRIGGER capture_unknown")
    601         .execute(&mut database)
    602         .await
    603         .unwrap();
    604     database.close().await.unwrap();
    605     let reopened = fixture.reopen(input.clone()).await;
    606     captured(
    607         reopened
    608             .capture_evidence(input, &proof, &evidence)
    609             .await
    610             .unwrap(),
    611     );
    612     let original = reopened
    613         .obtained_evidence(
    614             selection(&binding, &prepared, digest, recipients[0]),
    615             copy(&proof),
    616         )
    617         .await
    618         .unwrap()
    619         .unwrap();
    620     assert_eq!(original.evidence().raw_json(), raw);
    621     reopened.close().await.unwrap();
    622 }
    623 
    624 #[tokio::test]
    625 async fn missing_preparation_plan_and_attempt_are_distinct_from_wrong_plan_identity() {
    626     let fixture = Fixture::new();
    627     let (store, _, proof, binding) = fixture.create().await;
    628     let request = peer_request(&binding, 145);
    629     let operation = request.command().context().operation_id();
    630     let command = request.command().digest();
    631     let selector =
    632         |digest| ClaimAttemptRequest::new(binding.clone(), operation, command, digest, key());
    633     assert!(
    634         store
    635             .signing_attempt(selector([0; 32]), copy(&proof))
    636             .await
    637             .unwrap()
    638             .is_none()
    639     );
    640     assert!(
    641         store
    642             .obtained_evidence(selector([0; 32]), copy(&proof))
    643             .await
    644             .unwrap()
    645             .is_none()
    646     );
    647     assert!(matches!(
    648         store.claim_attempt(selector([0; 32]), copy(&proof)).await,
    649         Err(OperationError::RecoveryRequired)
    650     ));
    651     let prepared = committed(
    652         store
    653             .admit_command_and_hold(request, copy(&proof))
    654             .await
    655             .unwrap(),
    656     );
    657     assert!(
    658         store
    659             .signing_attempt(selector([0; 32]), copy(&proof))
    660             .await
    661             .unwrap()
    662             .is_none()
    663     );
    664     assert!(
    665         store
    666             .obtained_evidence(selector([0; 32]), copy(&proof))
    667             .await
    668             .unwrap()
    669             .is_none()
    670     );
    671     let retained = plan(
    672         prepared.request().chat_command().unwrap(),
    673         100,
    674         "missing-claim",
    675     );
    676     let digest = *retained.digest();
    677     bound(
    678         store
    679             .bind_signing_intents(binding.clone(), (retained).into(), copy(&proof))
    680             .await
    681             .unwrap(),
    682     );
    683     assert!(
    684         store
    685             .signing_attempt(selector(digest), copy(&proof))
    686             .await
    687             .unwrap()
    688             .is_none()
    689     );
    690     assert!(
    691         store
    692             .obtained_evidence(selector(digest), copy(&proof))
    693             .await
    694             .unwrap()
    695             .is_none()
    696     );
    697     assert!(matches!(
    698         store.claim_attempt(selector([0; 32]), copy(&proof)).await,
    699         Err(OperationError::IdempotencyConflict)
    700     ));
    701     assert!(matches!(
    702         store.signing_attempt(selector([0; 32]), copy(&proof)).await,
    703         Err(OperationError::IdempotencyConflict)
    704     ));
    705     assert!(matches!(
    706         store
    707             .obtained_evidence(selector([0; 32]), copy(&proof))
    708             .await,
    709         Err(OperationError::IdempotencyConflict)
    710     ));
    711     store.close().await.unwrap();
    712 }
    713 
    714 #[tokio::test]
    715 async fn fresh_claim_refuses_rollback_and_expiry_before_and_inside_the_transaction() {
    716     for inside in [false, true] {
    717         for now in [99, 150] {
    718             let fixture = Fixture::new();
    719             let (store, _, proof, binding) = fixture.create().await;
    720             let (prepared, digest, recipients) =
    721                 prepare(&fixture, &store, &binding, &proof, 146, false).await;
    722             let request = selection(&binding, &prepared, digest, recipients[0]);
    723             let result = if inside {
    724                 let (arrived, resume) = fixture.clock.arm(1);
    725                 let mut call = store.claim_attempt(request, copy(&proof));
    726                 assert!(futures::poll!(call.as_mut()).is_pending());
    727                 reached(arrived).await;
    728                 fixture.clock.now.store(now, Ordering::SeqCst);
    729                 resume.send(()).unwrap();
    730                 call.await
    731             } else {
    732                 fixture.clock.now.store(now, Ordering::SeqCst);
    733                 store.claim_attempt(request, copy(&proof)).await
    734             };
    735             assert!(
    736                 if now == 99 {
    737                     matches!(
    738                         result,
    739                         Err(OperationError::Workspace(WorkspaceError::Unavailable))
    740                     )
    741                 } else {
    742                     matches!(result, Err(OperationError::DeadlineExceeded))
    743                 },
    744                 "inside={inside} now={now}: {result:?}"
    745             );
    746             fixture.clock.now.store(100, Ordering::SeqCst);
    747             assert!(
    748                 store
    749                     .signing_attempt(
    750                         selection(&binding, &prepared, digest, recipients[0]),
    751                         copy(&proof)
    752                     )
    753                     .await
    754                     .unwrap()
    755                     .is_none()
    756             );
    757             store.close().await.unwrap();
    758             let mut database = fixture.database().await;
    759             let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_attempts")
    760                 .fetch_one(&mut database)
    761                 .await
    762                 .unwrap();
    763             assert_eq!(count, 0);
    764             database.close().await.unwrap();
    765         }
    766     }
    767 }
    768 
    769 #[tokio::test]
    770 async fn known_claim_insert_rollback_leaves_no_invocation_and_allows_one_new_claim() {
    771     let fixture = Fixture::new();
    772     let (store, _, proof, binding) = fixture.create().await;
    773     let (prepared, digest, recipients) =
    774         prepare(&fixture, &store, &binding, &proof, 147, false).await;
    775     let mut database = fixture.database().await;
    776     sqlx::raw_sql("CREATE TRIGGER refuse_claim BEFORE INSERT ON signing_attempts BEGIN SELECT RAISE(ABORT,'synthetic claim failure'); END").execute(&mut database).await.unwrap();
    777     assert!(matches!(
    778         store
    779             .claim_attempt(
    780                 selection(&binding, &prepared, digest, recipients[0]),
    781                 copy(&proof)
    782             )
    783             .await,
    784         Err(OperationError::StorageFailure)
    785     ));
    786     assert!(
    787         store
    788             .signing_attempt(
    789                 selection(&binding, &prepared, digest, recipients[0]),
    790                 copy(&proof)
    791             )
    792             .await
    793             .unwrap()
    794             .is_none()
    795     );
    796     sqlx::raw_sql("DROP TRIGGER refuse_claim")
    797         .execute(&mut database)
    798         .await
    799         .unwrap();
    800     let original = claim(
    801         store
    802             .claim_attempt(
    803                 selection(&binding, &prepared, digest, recipients[0]),
    804                 copy(&proof),
    805             )
    806             .await
    807             .unwrap(),
    808     );
    809     let retained = match store
    810         .claim_attempt(
    811             selection(&binding, &prepared, digest, recipients[0]),
    812             copy(&proof),
    813         )
    814         .await
    815         .unwrap()
    816     {
    817         ClaimAttemptOutcome::Retained(value) => value,
    818         _ => panic!("second claim must remain retained"),
    819     };
    820     assert_eq!(retained.attempt_id(), original.attempt_id());
    821     database.close().await.unwrap();
    822     store.close().await.unwrap();
    823 }
    824 
    825 #[tokio::test]
    826 async fn exact_legacy_private_claim_evidence_bytes_recover_and_continue_without_catalog_rewrite() {
    827     for version in [7, 8] {
    828         let fixture = Fixture::new();
    829         let (store, input, proof, binding) = fixture.create().await;
    830         let (prepared, digest, recipients) =
    831             prepare(&fixture, &store, &binding, &proof, 166, false).await;
    832         let first = claim(
    833             store
    834                 .claim_attempt(
    835                     selection(&binding, &prepared, digest, recipients[0]),
    836                     copy(&proof),
    837                 )
    838                 .await
    839                 .unwrap(),
    840         );
    841         let original_claim =
    842             radroots_storage::command::protected::issuance::ClaimRecord::capture(&first)
    843                 .unwrap()
    844                 .encode()
    845                 .unwrap();
    846         let claim_json: serde_json::Value = serde_json::from_slice(&original_claim).unwrap();
    847         assert_eq!(claim_json["version"], 1);
    848         assert_eq!(claim_json["recipient"], json!(recipients[0]));
    849         assert!(claim_json.get("role").is_none());
    850         let evidence = obtain(&first, false).await;
    851         let receipt = captured(
    852             store
    853                 .capture_evidence(input.clone(), &proof, &evidence)
    854                 .await
    855                 .unwrap(),
    856         );
    857         let raw = evidence.raw_json().to_owned();
    858         store.close().await.unwrap();
    859         let mut db = fixture.database().await;
    860         super::super::public_admission::retain_legacy_issuance_catalog(&mut db).await;
    861         if version == 7 {
    862             let ddl: String =
    863                 sqlx::query_scalar("SELECT sql FROM sqlite_schema WHERE name='operations'")
    864                     .fetch_one(&mut db)
    865                     .await
    866                     .unwrap();
    867             let index: String = sqlx::query_scalar(
    868                 "SELECT sql FROM sqlite_schema WHERE name='operation_transaction_identity'",
    869             )
    870             .fetch_one(&mut db)
    871             .await
    872             .unwrap();
    873             let old = ddl.replace("'inbox.reply','listing.publish'", "'inbox.reply'");
    874             // Preserve the exact encrypted T0 and the original dependent rows.
    875             sqlx::query("PRAGMA foreign_keys=OFF")
    876                 .execute(&mut db)
    877                 .await
    878                 .unwrap();
    879             for statement in [
    880                 "CREATE TEMP TABLE retained_operations AS SELECT * FROM operations",
    881                 "DROP TABLE operations",
    882                 &old,
    883                 &index,
    884                 "INSERT INTO operations SELECT * FROM retained_operations",
    885                 "DROP TABLE retained_operations",
    886                 "PRAGMA user_version=7",
    887             ] {
    888                 sqlx::query(sqlx::AssertSqlSafe(statement.to_owned()))
    889                     .execute(&mut db)
    890                     .await
    891                     .unwrap();
    892             }
    893         }
    894         db.close().await.unwrap();
    895         let reopened = fixture.reopen(input.clone()).await;
    896         let recovered = reopened
    897             .obtained_evidence(
    898                 selection(&binding, &prepared, digest, recipients[0]),
    899                 copy(&proof),
    900             )
    901             .await
    902             .unwrap()
    903             .unwrap();
    904         assert_eq!(recovered.receipt(), receipt);
    905         assert_eq!(recovered.evidence().raw_json(), raw);
    906         assert!(matches!(
    907             reopened
    908                 .claim_attempt(
    909                     selection(&binding, &prepared, digest, recipients[0]),
    910                     copy(&proof)
    911                 )
    912                 .await
    913                 .unwrap(),
    914             ClaimAttemptOutcome::Retained(_)
    915         ));
    916         let second = claim(
    917             reopened
    918                 .claim_attempt(
    919                     selection(&binding, &prepared, digest, recipients[1]),
    920                     copy(&proof),
    921                 )
    922                 .await
    923                 .unwrap(),
    924         );
    925         let second_evidence = obtain(&second, false).await;
    926         captured(
    927             reopened
    928                 .capture_evidence(input, &proof, &second_evidence)
    929                 .await
    930                 .unwrap(),
    931         );
    932         reopened.close().await.unwrap();
    933         let mut db = fixture.database().await;
    934         let actual: i64 = sqlx::query_scalar("PRAGMA user_version")
    935             .fetch_one(&mut db)
    936             .await
    937             .unwrap();
    938         assert_eq!(actual, version);
    939         db.close().await.unwrap();
    940     }
    941 }