commit dbd5245699aab199db35dda2421c2c28a102693f parent 9e9ce7d9f38d20f419a494d6083463a97a3726ff Author: triesap <tyson@radroots.org> Date: Tue, 20 Oct 2026 16:24:25 +0000 storage: install original listing revisions with public outbox work - Fence initial coordinates in retained creation transactions. - Install verified public revisions and publication links atomically. - Preserve private flows and exact retained catalog recovery. - Verify native faults, browser recovery and generated API boundaries. Diffstat:
24 files changed, 1802 insertions(+), 63 deletions(-)
diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -837,6 +837,7 @@ pub radroots_storage::command::EvidenceCaptureOutcome::Committed(radroots_storag pub radroots_storage::command::EvidenceCaptureOutcome::Unknown(radroots_storage::command::CommitAttempt) pub enum radroots_storage::command::InstallationOutcome pub radroots_storage::command::InstallationOutcome::Committed(alloc::boxed::Box<radroots_storage::command::ChatInstallation>) +pub radroots_storage::command::InstallationOutcome::ListingCommitted(alloc::boxed::Box<radroots_storage::command::ListingInstallation>) pub radroots_storage::command::InstallationOutcome::Unknown(radroots_storage::command::CommitAttempt) impl core::fmt::Debug for radroots_storage::command::InstallationOutcome pub fn radroots_storage::command::InstallationOutcome::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result @@ -848,6 +849,7 @@ pub radroots_storage::command::OperationError::InvalidCommand pub radroots_storage::command::OperationError::InvalidEvidence pub radroots_storage::command::OperationError::MissingHistory pub radroots_storage::command::OperationError::RecoveryRequired +pub radroots_storage::command::OperationError::StaleState pub radroots_storage::command::OperationError::StorageFailure pub radroots_storage::command::OperationError::Unauthorized pub radroots_storage::command::OperationError::UnsupportedOperation @@ -1084,6 +1086,23 @@ pub const fn radroots_storage::command::InstallationRequest::operation_id(&self) pub const fn radroots_storage::command::InstallationRequest::plan_digest(&self) -> &[u8; 32] impl core::fmt::Debug for radroots_storage::command::InstallationRequest pub fn radroots_storage::command::InstallationRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::ListingInstallation +impl radroots_storage::command::ListingInstallation +pub const fn radroots_storage::command::ListingInstallation::author(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage::command::ListingInstallation::basis(&self) -> radroots_storage::command::EvidenceReceipt +pub const fn radroots_storage::command::ListingInstallation::command_digest(&self) -> radroots_domain::identifier::CommandDigest +pub fn radroots_storage::command::ListingInstallation::from_committed_store(&radroots_storage::command::BoundSigningPlan, radroots_storage::command::EvidenceReceipt, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::command::ListingInstallation::installed_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage::command::ListingInstallation::listing_id(&self) -> radroots_domain::listing::ListingId +pub const fn radroots_storage::command::ListingInstallation::operation_id(&self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage::command::ListingInstallation::plan_digest(&self) -> &[u8; 32] +pub const fn radroots_storage::command::ListingInstallation::plan_transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub const fn radroots_storage::command::ListingInstallation::preparation_transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub const fn radroots_storage::command::ListingInstallation::revision(&self) -> radroots_domain::identifier::EnvelopeEventId +pub const fn radroots_storage::command::ListingInstallation::transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub const fn radroots_storage::command::ListingInstallation::workspace_id(&self) -> radroots_domain::identifier::WorkspaceId +impl core::fmt::Debug for radroots_storage::command::ListingInstallation +pub fn radroots_storage::command::ListingInstallation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::OperationSnapshot impl radroots_storage::command::OperationSnapshot pub fn radroots_storage::command::OperationSnapshot::artifacts(&self) -> &[radroots_storage::command::ArtifactSnapshot] @@ -1094,13 +1113,16 @@ pub fn radroots_storage::command::OperationSnapshot::delivery_observations(&self pub fn radroots_storage::command::OperationSnapshot::from_store_report(radroots_storage::command::RetainedOperation, alloc::vec::Vec<radroots_storage::command::ArtifactSnapshot>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> pub const fn radroots_storage::command::OperationSnapshot::installation(&self) -> core::option::Option<radroots_storage::command::ChatInstallation> pub fn radroots_storage::command::OperationSnapshot::installed_message(&self) -> core::option::Option<&radroots_domain::message::ChatMessage> +pub const fn radroots_storage::command::OperationSnapshot::listing_installation(&self) -> core::option::Option<radroots_storage::command::ListingInstallation> pub fn radroots_storage::command::OperationSnapshot::message_id(&self) -> core::option::Option<radroots_domain::identifier::MessageId> pub const fn radroots_storage::command::OperationSnapshot::observed_at(&self) -> radroots_domain::context::UnixSeconds pub fn radroots_storage::command::OperationSnapshot::prepared(&self) -> &radroots_storage::command::PreparedOperation +pub fn radroots_storage::command::OperationSnapshot::public_publications(&self) -> &[radroots_storage::command::PublicPublicationWork] pub fn radroots_storage::command::OperationSnapshot::publication_accepted(&self, radroots_storage::command::PublicationWork) -> core::result::Result<bool, radroots_storage::command::OperationError> pub fn radroots_storage::command::OperationSnapshot::publications(&self) -> &[radroots_storage::command::PublicationWork] pub fn radroots_storage::command::OperationSnapshot::with_delivery(self, alloc::vec::Vec<radroots_storage::command::DeliveryAttemptSummary>, alloc::vec::Vec<radroots_storage::command::DeliveryObservation>) -> core::result::Result<Self, radroots_storage::command::OperationError> pub fn radroots_storage::command::OperationSnapshot::with_installation(self, core::option::Option<radroots_storage::command::ChatInstallation>, alloc::vec::Vec<radroots_storage::command::PublicationWork>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::OperationSnapshot::with_public_installation(self, core::option::Option<radroots_storage::command::ListingInstallation>, alloc::vec::Vec<radroots_storage::command::PublicPublicationWork>) -> core::result::Result<Self, radroots_storage::command::OperationError> impl core::fmt::Debug for radroots_storage::command::OperationSnapshot pub fn radroots_storage::command::OperationSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::PreparedOperation @@ -1113,6 +1135,16 @@ pub const fn radroots_storage::command::PreparedOperation::revision(&self) -> ra pub const fn radroots_storage::command::PreparedOperation::transaction_id(&self) -> radroots_domain::identifier::TransactionId impl core::fmt::Debug for radroots_storage::command::PreparedOperation pub fn radroots_storage::command::PreparedOperation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::PublicPublicationWork +impl radroots_storage::command::PublicPublicationWork +pub const fn radroots_storage::command::PublicPublicationWork::evidence(&self) -> radroots_storage::command::EvidenceReceipt +pub fn radroots_storage::command::PublicPublicationWork::from_committed_store(&radroots_storage::command::BoundSigningPlan, radroots_storage::command::ListingInstallation, radroots_storage::command::EvidenceReceipt, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::command::PublicPublicationWork::installation_transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub const fn radroots_storage::command::PublicPublicationWork::plan_digest(&self) -> &[u8; 32] +pub const fn radroots_storage::command::PublicPublicationWork::queued_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage::command::PublicPublicationWork::transaction_id(&self) -> radroots_domain::identifier::TransactionId +impl core::fmt::Debug for radroots_storage::command::PublicPublicationWork +pub fn radroots_storage::command::PublicPublicationWork::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::PublicationWork impl radroots_storage::command::PublicationWork pub const fn radroots_storage::command::PublicationWork::evidence(&self) -> radroots_storage::command::EvidenceReceipt diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs @@ -224,6 +224,7 @@ impl Error { O::InvalidEvidence => (Code::RecoveryRequired, RetryClass::ManualReconciliation), O::Unauthorized | O::UnverifiedApproval => (Code::Unauthorized, RetryClass::Never), O::UnsupportedOperation => (Code::CapabilityUnavailable, RetryClass::Never), + O::StaleState => (Code::StaleState, RetryClass::AfterStateRefresh), O::MissingHistory => (Code::MissingHistory, RetryClass::AfterStateRefresh), O::DeadlineExceeded => (Code::DeadlineExceeded, RetryClass::AfterStateRefresh), O::IdempotencyConflict => (Code::IdempotencyConflict, RetryClass::Never), diff --git a/crates/radroots/tests/support/receipt_delivery.rs b/crates/radroots/tests/support/receipt_delivery.rs @@ -442,7 +442,7 @@ async fn predecessor_schema_six_preserves_original_installation_and_seal_without let ready = Ready::new(&[String::from("ws://127.0.0.1:9")], 236).await; ready.store.close().await.unwrap(); let mut database = ready.fixture.database().await; - sqlx::raw_sql("DROP TABLE chat_delivery_observations; DROP TABLE chat_delivery_parts; DROP TABLE chat_delivery_attempts; PRAGMA user_version=6").execute(&mut database).await.unwrap(); + sqlx::raw_sql("DROP TABLE public_publication_work; DROP TABLE listing_installations; DROP TABLE listing_creations; DROP TABLE chat_delivery_observations; DROP TABLE chat_delivery_parts; DROP TABLE chat_delivery_attempts; PRAGMA user_version=6").execute(&mut database).await.unwrap(); let counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM sqlite_schema),(SELECT count(*) FROM chat_messages),(SELECT count(*) FROM artifact_evidence)").fetch_one(&mut database).await.unwrap(); assert_eq!(counts, (16, 1, 1)); database.close().await.unwrap(); diff --git a/crates/radroots/tests/support/receipt_installation.rs b/crates/radroots/tests/support/receipt_installation.rs @@ -27,6 +27,9 @@ fn request_install( fn installed(outcome: InstallationOutcome) -> ChatInstallation { match outcome { InstallationOutcome::Committed(value) => *value, + InstallationOutcome::ListingCommitted(_) => { + panic!("chat fixture must not install a listing") + } InstallationOutcome::Unknown(_) => panic!("fixture must observe confirmed T2"), } } @@ -484,7 +487,7 @@ async fn predecessor_schema_five_retains_actual_claims_and_obtained_bytes_withou store.close().await.unwrap(); let mut database = fixture.database().await; sqlx::raw_sql( - "DROP TABLE chat_delivery_observations; DROP TABLE chat_delivery_parts; DROP TABLE chat_delivery_attempts; DROP TABLE chat_publication_work; DROP TABLE chat_messages; PRAGMA user_version=5", + "DROP TABLE public_publication_work; DROP TABLE listing_installations; DROP TABLE listing_creations; DROP TABLE chat_delivery_observations; DROP TABLE chat_delivery_parts; DROP TABLE chat_delivery_attempts; DROP TABLE chat_publication_work; DROP TABLE chat_messages; PRAGMA user_version=5", ) .execute(&mut database) .await diff --git a/crates/storage/README.md b/crates/storage/README.md @@ -353,6 +353,13 @@ command and plan, with validated installation/basis/work reports. Structural constructors supply no authentication or persistence guarantee. Uncertain T2 completion never releases claims or obtained evidence. +Public T2 reports use `ListingInstallation` and `PublicPublicationWork`. The +snapshot exposes the original coordinate/revision and exact evidence/work +references without inventing a message or private recipient. Concrete owners +must fence the initial coordinate before issuance and atomically retain the +revision and work once. First-issue expiry does not erase authenticated obtained +evidence or impose a new T2 deadline; current access still gates installation. + Delivery preparation retains an exact outer representation and complete bounded target intent against actual original publication work before transport. Only an actual fresh confirmed claim may proceed once through its qualified owner; diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -29,7 +29,8 @@ pub use delivery::{ pub use delivery_summary::DeliveryAttemptSummary; pub use dm_source::SignedDmRelaySource; pub use installation::{ - ChatInstallation, InstallationOutcome, InstallationRequest, PublicationWork, + ChatInstallation, InstallationOutcome, InstallationRequest, ListingInstallation, + PublicPublicationWork, PublicationWork, }; pub use issuance::{ ArtifactEvidence, CapturedArtifact, ClaimAttemptOutcome, ClaimAttemptRequest, @@ -60,6 +61,8 @@ pub enum OperationError { DeadlineExceeded, /// The retained operation identity binds a different command commitment. IdempotencyConflict, + /// The selected publication coordinate has another retained decision/head. + StaleState, /// A known storage failure preceded writes or had confirmed rollback. StorageFailure, /// State, completion or decoding requires explicit reconciliation. @@ -80,6 +83,7 @@ impl OperationError { Self::UnverifiedApproval => "unverified_approval", Self::DeadlineExceeded => "deadline_exceeded", Self::IdempotencyConflict => "idempotency_conflict", + Self::StaleState => "stale_state", Self::StorageFailure => "storage_failure", Self::RecoveryRequired => "recovery_required", Self::DeliveryAttemptLimit => "delivery_attempt_limit", @@ -364,9 +368,10 @@ pub trait OperationJournal: WorkspaceStore { request: radroots_transport::sink::DeliveryRequestId, proof: AttachmentProof, ) -> BoxFuture<'_, Result<Option<DeliveryAttempt>, OperationError>>; - /// Atomically installs the original logical chat result and retains distinct - /// publication work for actual obtained recipients. No signing or transport - /// occurs here; unknown completion retains all original claims and evidence. + /// Atomically installs the original chat result or initial listing revision + /// with publication work for actual obtained artifacts. Concrete hosts must + /// enforce the command's retained decision and current access. No signing or + /// transport occurs here; unknown completion retains claims and evidence. fn install_transition_and_outbox( &self, request: InstallationRequest, diff --git a/crates/storage/src/command/installation.rs b/crates/storage/src/command/installation.rs @@ -3,9 +3,12 @@ use super::{BoundSigningPlan, CommitAttempt, EvidenceReceipt, OperationError}; use crate::workspace::WorkspaceBinding; use core::fmt; +use radroots_domain::listing::ListingId; use radroots_domain::{ - CommandDigest, EnvelopeEventId, MessageId, OperationId, TransactionId, UnixSeconds, WorkspaceId, + CommandDigest, EnvelopeEventId, MessageId, OperationId, PublicKey, TransactionId, UnixSeconds, + WorkspaceId, }; +use radroots_protocol::plan::SigningTarget; use std::boxed::Box; /// Original-operation selectors for native installation. The concrete owner @@ -226,6 +229,9 @@ impl fmt::Debug for PublicationWork { pub enum InstallationOutcome { /// The logical installation and eligible publication links are confirmed. Committed(Box<ChatInstallation>), + /// Original public listing revision and direct-publication work, confirmed + /// together by the actual authoritative transaction. No delivery is implied. + ListingCommitted(Box<ListingInstallation>), /// Completion is unknown; retained claims/evidence are never discarded. Unknown(CommitAttempt), } @@ -233,6 +239,7 @@ impl fmt::Debug for InstallationOutcome { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::Committed(_) => "InstallationOutcome::Committed(<redacted>)", + Self::ListingCommitted(_) => "InstallationOutcome::ListingCommitted(<redacted>)", Self::Unknown(_) => "InstallationOutcome::Unknown(<retained>)", }) } @@ -258,3 +265,192 @@ fn check_evidence( } Ok(()) } + +/// Original confirmed public listing revision, without a private message or +/// participant placeholder. Data construction does not qualify a transaction. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct ListingInstallation { + plan: [u8; 32], + author: PublicKey, + listing: ListingId, + preparation_transaction: TransactionId, + plan_transaction: TransactionId, + transaction: TransactionId, + installed_at: UnixSeconds, + basis: EvidenceReceipt, +} +impl ListingInstallation { + /// Checks exact original scope and public artifact identity. The backend + /// must also authenticate its actual evidence, creation fence and rows. + pub fn from_committed_store( + bound: &BoundSigningPlan, + basis: EvidenceReceipt, + transaction: TransactionId, + installed_at: UnixSeconds, + ) -> Result<Self, OperationError> { + check_public_evidence(bound, basis)?; + if installed_at < bound.bound_at() { + return Err(OperationError::RecoveryRequired); + } + let command = bound + .prepared() + .request() + .command() + .listing() + .ok_or(OperationError::UnsupportedOperation)?; + let event = bound + .plan() + .listing() + .ok_or(OperationError::UnsupportedOperation)? + .event(); + Ok(Self { + plan: *bound.plan().digest(), + author: event.fields().author, + listing: command.input().id(), + preparation_transaction: bound.prepared().transaction_id(), + plan_transaction: bound.transaction_id(), + transaction, + installed_at, + basis, + }) + } + /// Original workspace. + pub const fn workspace_id(&self) -> WorkspaceId { + self.basis.workspace_id() + } + /// Original operation. + pub const fn operation_id(&self) -> OperationId { + self.basis.operation_id() + } + /// Original complete command commitment. + pub const fn command_digest(&self) -> CommandDigest { + self.basis.command_digest() + } + /// Exact retained complete plan commitment. + pub const fn plan_digest(&self) -> &[u8; 32] { + &self.plan + } + /// Actual author of this fixed listing coordinate. + pub const fn author(&self) -> PublicKey { + self.author + } + /// Stable128-bit discriminator; parsing never proves novelty. + pub const fn listing_id(&self) -> ListingId { + self.listing + } + /// Original actual signed event ID for this immutable revision. + pub const fn revision(&self) -> EnvelopeEventId { + self.basis.event_id() + } + /// Original T0 transaction. + pub const fn preparation_transaction_id(&self) -> TransactionId { + self.preparation_transaction + } + /// Original T1 transaction. + pub const fn plan_transaction_id(&self) -> TransactionId { + self.plan_transaction + } + /// Actual original installation transaction. + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + /// Original installation observation; it never renews an issuance window. + pub const fn installed_at(&self) -> UnixSeconds { + self.installed_at + } + /// Exact original retained evidence reference. + pub const fn basis(&self) -> EvidenceReceipt { + self.basis + } +} +impl fmt::Debug for ListingInstallation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ListingInstallation(<redacted>)") + } +} +/// Pending direct public work, referencing retained original signed bytes. It +/// carries no private recipient, wrapping key, new signature or relay outcome. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct PublicPublicationWork { + installation: TransactionId, + plan: [u8; 32], + evidence: EvidenceReceipt, + transaction: TransactionId, + queued_at: UnixSeconds, +} +impl PublicPublicationWork { + /// Checks structural scope only. Concrete hosts must authenticate actual + /// original evidence and link this work atomically with the installation. + pub fn from_committed_store( + bound: &BoundSigningPlan, + installation: ListingInstallation, + evidence: EvidenceReceipt, + transaction: TransactionId, + queued_at: UnixSeconds, + ) -> Result<Self, OperationError> { + check_public_evidence(bound, evidence)?; + let checked = ListingInstallation::from_committed_store( + bound, + installation.basis(), + installation.transaction_id(), + installation.installed_at(), + )?; + if checked != installation + || installation.basis() != evidence + || queued_at < installation.installed_at() + { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { + installation: installation.transaction_id(), + plan: *bound.plan().digest(), + evidence, + transaction, + queued_at, + }) + } + /// Original installation transaction. + pub const fn installation_transaction_id(&self) -> TransactionId { + self.installation + } + /// Original complete plan with its captured target descriptors. + pub const fn plan_digest(&self) -> &[u8; 32] { + &self.plan + } + /// Original exact public signed artifact reference. + pub const fn evidence(&self) -> EvidenceReceipt { + self.evidence + } + /// Actual first work-retention transaction. + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + /// Original work observation, not an issuance or delivery deadline. + pub const fn queued_at(&self) -> UnixSeconds { + self.queued_at + } +} +impl fmt::Debug for PublicPublicationWork { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PublicPublicationWork(<redacted>)") + } +} +fn check_public_evidence( + bound: &BoundSigningPlan, + evidence: EvidenceReceipt, +) -> Result<(), OperationError> { + let identity = bound.prepared().identity(); + let public = bound + .plan() + .listing() + .ok_or(OperationError::UnsupportedOperation)?; + if evidence.target() != SigningTarget::PublicEvent + || evidence.workspace_id() != identity.workspace_id() + || evidence.operation_id() != identity.operation_id() + || evidence.command_digest() != identity.command_digest() + || evidence.event_id().as_bytes() != public.event().event_id() + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage/src/command/snapshot.rs b/crates/storage/src/command/snapshot.rs @@ -2,7 +2,8 @@ //! dispatch permission; concrete owners must authenticate and compare all facts. use super::{ BoundSigningPlan, ChatInstallation, DeliveryAttemptSummary, DeliveryObservation, - EvidenceReceipt, OperationError, PreparedOperation, PublicationWork, SigningAttempt, + EvidenceReceipt, ListingInstallation, OperationError, PreparedOperation, PublicPublicationWork, + PublicationWork, SigningAttempt, }; use core::fmt; use radroots_domain::{ @@ -193,6 +194,8 @@ pub struct OperationSnapshot { installation: Option<ChatInstallation>, message: Option<ChatMessage>, publications: Box<[PublicationWork]>, + listing_installation: Option<ListingInstallation>, + public_publications: Box<[PublicPublicationWork]>, deliveries: Box<[DeliveryAttemptSummary]>, observations: Box<[DeliveryObservation]>, } @@ -279,6 +282,20 @@ impl OperationSnapshot { digest.update(work.transaction_id().as_bytes()); digest.update(work.queued_at().get().to_be_bytes()); } + if let Some(installed) = self.listing_installation() { + // Preserve original private checkpoint bytes exactly. The public + // extension binds actual installation/work, never a message ID. + digest.update(b"radroots.operation.public_installation.v1\0"); + digest.update(installed.author().as_bytes()); + digest.update(installed.listing_id().as_bytes()); + digest.update(installed.revision().as_bytes()); + digest.update(installed.transaction_id().as_bytes()); + digest.update(installed.installed_at().get().to_be_bytes()); + for work in self.public_publications() { + digest.update(work.transaction_id().as_bytes()); + digest.update(work.queued_at().get().to_be_bytes()); + } + } for attempt in self.delivery_attempts() { digest.update(attempt.work().evidence().target().key()); digest.update(attempt.intent().digest()); @@ -419,6 +436,8 @@ impl OperationSnapshot { installation: None, message: None, publications: Vec::new().into_boxed_slice(), + listing_installation: None, + public_publications: Vec::new().into_boxed_slice(), deliveries: Vec::new().into_boxed_slice(), observations: Vec::new().into_boxed_slice(), }) @@ -431,7 +450,11 @@ impl OperationSnapshot { installation: Option<ChatInstallation>, publications: Vec<PublicationWork>, ) -> Result<Self, OperationError> { - if !self.deliveries.is_empty() || !self.observations.is_empty() { + if self.listing_installation.is_some() + || !self.public_publications.is_empty() + || !self.deliveries.is_empty() + || !self.observations.is_empty() + { return Err(OperationError::RecoveryRequired); } let Some(installed) = installation else { @@ -507,6 +530,67 @@ impl OperationSnapshot { self.publications = publications.into_boxed_slice(); Ok(self) } + /// Adds structurally checked public T2 facts. The concrete store must + /// authenticate the creation decision and atomically retain both records. + pub fn with_public_installation( + mut self, + installation: Option<ListingInstallation>, + publications: Vec<PublicPublicationWork>, + ) -> Result<Self, OperationError> { + let Some(installed) = installation else { + if !publications.is_empty() { + return Err(OperationError::RecoveryRequired); + } + self.listing_installation = None; + self.public_publications = Vec::new().into_boxed_slice(); + return Ok(self); + }; + if self.installation.is_some() + || self.message.is_some() + || !self.publications.is_empty() + || !self.deliveries.is_empty() + || !self.observations.is_empty() + { + return Err(OperationError::RecoveryRequired); + } + let bound = self.bound_plan().ok_or(OperationError::RecoveryRequired)?; + if ListingInstallation::from_committed_store( + bound, + installed.basis(), + installed.transaction_id(), + installed.installed_at(), + )? != installed + || self.artifacts().len() != 1 + || self.artifacts()[0].obtained() != Some(installed.basis()) + || publications.len() != 1 + { + return Err(OperationError::RecoveryRequired); + } + let work = publications[0]; + if PublicPublicationWork::from_committed_store( + bound, + installed, + work.evidence(), + work.transaction_id(), + work.queued_at(), + )? != work + || work.transaction_id() != installed.transaction_id() + || work.queued_at() != installed.installed_at() + { + return Err(OperationError::RecoveryRequired); + } + self.listing_installation = Some(installed); + self.public_publications = publications.into_boxed_slice(); + Ok(self) + } + /// Actual original listing installation, when retained by the owner. + pub const fn listing_installation(&self) -> Option<ListingInstallation> { + self.listing_installation + } + /// Original pending direct-publication references, without wrapping or ACK. + pub fn public_publications(&self) -> &[PublicPublicationWork] { + &self.public_publications + } /// Actual retained installation report, when supplied by the concrete owner. pub const fn installation(&self) -> Option<ChatInstallation> { self.installation diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/installation.rs b/crates/storage_indexeddb/tests/browser/src/workspace/installation.rs @@ -53,6 +53,9 @@ impl WorkspaceFixture { .map_err(|e| JsValue::from_str(e.code()))? { InstallationOutcome::Committed(value) => Ok(installation(*value).to_string()), + InstallationOutcome::ListingCommitted(_) => { + Err(JsValue::from_str("unexpected_listing_installation")) + } InstallationOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), } } diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -1,12 +1,19 @@ # radroots_storage_sqlite -The separate execution-workspace database creates exact schema generation 8 -for shared chat/public non-stock preparation. `listing.publish` uses the same -operation identity, protected preparation, bounded worker and confirmed commit -classification as chat. Current seller authentication is required. T0 retains -data only; public signing, installation and delivery are separate stages. -The exact generation 7 catalog remains accepted for original chat recovery and -continuation. It refuses public admission without rewriting its catalog. +The separate execution-workspace database creates exact schema generation 10. +Chat and initial `listing.publish` share the operation journal, protected +preparation and owned bounded worker. Seller authentication and a retained T0 +coordinate decision precede public issuance. A conflicting initial publish +cannot replace that decision or reach a new signature. T2 rechecks the original +T0/T1/claim/obtained graph, then atomically retains its exact signed listing +revision and pending direct-publication work. It creates no private message, +recipient, wrapping identity, stock allocation or relay acknowledgement. + +Exact generation 7/8/9 catalogs preserve their original encrypted records and +private continuation without catalog rewrites. Original public T1/S remains +readable where supported. Unsupported new public admission, binding, issuance +or installation refuses explicitly; retained claims never permit reissue. +Actual transport dispatch and ordinary listing execution are separate stages. SQLite storage backend for Radroots. diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -71,6 +71,10 @@ impl Journal<'_> { } (plan, transaction, bound_at, protected, false) } else { + if supplied.listing().is_some() && !super::listing::current(self.connection).await? + { + return Err(OperationError::UnsupportedOperation); + } let window = prepared.issuance_window(); if current.observed_at() < window.prepared_at() { return Err(super::WorkspaceError::Unavailable.into()); @@ -234,15 +238,6 @@ impl Journal<'_> { proof: AttachmentProof, ) -> Result<AdmissionOutcome, OperationError> { let (record, grant, observed) = self.access(request.binding(), &proof).await?; - if request.command().listing().is_some() { - let version: i64 = sqlx::query_scalar("PRAGMA user_version") - .fetch_one(&mut *self.connection) - .await - .map_err(|_| OperationError::RecoveryRequired)?; - if !matches!(version, 8 | 9) { - return Err(OperationError::UnsupportedOperation); - } - } let context = request.command().context(); let workspace = context.workspace_id(); let operation_id = context.operation_id(); @@ -282,6 +277,12 @@ impl Journal<'_> { return Ok(AdmissionOutcome::Committed(snapshot)); } + if request.command().listing().is_some() + && !super::listing::current(self.connection).await? + { + return Err(OperationError::UnsupportedOperation); + } + // This fresh local outbox has no authenticated parent/order // history or protected approval origin. Selectors cannot create either. request.validate_fresh(observed.observed_at())?; @@ -294,6 +295,8 @@ impl Journal<'_> { let anchor = CommitAttempt::new(workspace, operation_id, digest, Some(transaction_id)); // Encryption/provider work finishes before opening the write transaction. let protected = operation::protect(&request, transaction_id, window, self.crypto).await?; + let creation = + super::listing::Creation::protect(&request, transaction_id, self.crypto).await?; let mut transaction = self .connection .begin_with("BEGIN IMMEDIATE") @@ -320,7 +323,11 @@ impl Journal<'_> { return Err(OperationError::DeadlineExceeded); } operation::absent(&mut transaction, self.selected, operation_id).await?; - operation::insert(&mut transaction, &request, transaction_id, &protected).await + operation::insert(&mut transaction, &request, transaction_id, &protected).await?; + if let Some(creation) = &creation { + creation.insert(&mut transaction).await?; + } + Ok(()) } .await; if let Err(error) = inserted { diff --git a/crates/storage_sqlite/src/workspace/attempt.rs b/crates/storage_sqlite/src/workspace/attempt.rs @@ -150,7 +150,7 @@ pub(super) async fn sql( .map_err(|_| OperationError::RecoveryRequired)?; match version { 7 | 8 => Ok(sqlx::AssertSqlSafe(legacy.to_owned())), - 9 => Ok(sqlx::AssertSqlSafe( + 9 | 10 => Ok(sqlx::AssertSqlSafe( legacy .replace("seal_evidence", "artifact_evidence") .replace("recipient", "artifact_key"), @@ -167,7 +167,7 @@ pub(super) async fn require_target( .fetch_one(connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - if version != 9 { + if !matches!(version, 9 | 10) { return Err(OperationError::UnsupportedOperation); } } diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -28,6 +28,7 @@ pub(super) enum IssuancePayload { Attempt, Evidence, Publication, + ListingInstallation, } #[derive(Clone, Copy)] @@ -181,6 +182,30 @@ impl WorkspaceCrypto { ) .await } + pub(super) async fn seal_listing( + &self, + scope: ListingScope, + plaintext: &[u8], + ) -> Result<Vec<u8>, WorkspaceError> { + self.seal_bound( + listing_context(scope)?, + PRIVATE_PAYLOAD_MAX_BYTES, + plaintext, + ) + .await + } + pub(super) async fn open_listing( + &self, + scope: ListingScope, + protected: &[u8], + ) -> Result<SecretMaterial, WorkspaceError> { + self.open_bound( + listing_context(scope)?, + PRIVATE_PAYLOAD_MAX_BYTES, + protected, + ) + .await + } pub(super) async fn seal_issuance( &self, scope: IssuanceScope, @@ -415,6 +440,11 @@ fn issuance_context( "radroots.workspace.chat_publication_work", "radroots.workspace.chat_publication_work.v1", ), + IssuancePayload::ListingInstallation => ( + 3u8, + "radroots.workspace.listing_installation", + "radroots.workspace.listing_installation.v1", + ), }; let mut hash = Sha256::new(); hash.update(b"radroots.workspace.issuance.context.v1\0"); @@ -425,19 +455,29 @@ fn issuance_context( hash.update(scope.attempt.as_bytes()); match scope.target { radroots_storage::command::SigningTarget::BusinessSeal(recipient) => { + if matches!(payload, IssuancePayload::ListingInstallation) { + return Err(WorkspaceError::InvalidInput); + } hash.update(recipient.as_bytes()) } radroots_storage::command::SigningTarget::PublicEvent => { - if matches!(payload, IssuancePayload::Publication) { - return Err(WorkspaceError::InvalidInput); - } - purpose = match payload { - IssuancePayload::Attempt => "radroots.workspace.public_signing_attempt", - _ => "radroots.workspace.public_artifact_evidence", - }; - schema = match payload { - IssuancePayload::Attempt => "radroots.workspace.public_signing_attempt.v1", - _ => "radroots.workspace.public_artifact_evidence.v1", + (purpose, schema) = match payload { + IssuancePayload::Attempt => ( + "radroots.workspace.public_signing_attempt", + "radroots.workspace.public_signing_attempt.v1", + ), + IssuancePayload::Evidence => ( + "radroots.workspace.public_artifact_evidence", + "radroots.workspace.public_artifact_evidence.v1", + ), + IssuancePayload::Publication => ( + "radroots.workspace.public_publication_work", + "radroots.workspace.public_publication_work.v1", + ), + IssuancePayload::ListingInstallation => ( + "radroots.workspace.listing_installation", + "radroots.workspace.listing_installation.v1", + ), }; hash.update(b"public_event.no_recipient.v1\0"); } @@ -472,3 +512,37 @@ fn message_context( .map_err(|_| WorkspaceError::InvalidInput)?, )) } + +#[derive(Clone, Copy)] +pub(super) enum ListingScope { + Decision { + workspace: WorkspaceId, + operation: OperationId, + }, +} +fn listing_context(scope: ListingScope) -> Result<EnvelopeContext, WorkspaceError> { + use sha2::{Digest, Sha256}; + let mut hash = Sha256::new(); + hash.update(b"radroots.workspace.listing.state.context.v1\0"); + let (purpose, schema) = match scope { + ListingScope::Decision { + workspace, + operation, + } => { + hash.update([0]); + hash.update(workspace.as_bytes()); + hash.update(operation.as_bytes()); + ( + "radroots.workspace.listing_decision", + "radroots.workspace.listing_decision.v1", + ) + } + }; + let digest = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse(purpose).map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("workspace_listing", digest.to_string()) + .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse(schema).map_err(|_| WorkspaceError::InvalidInput)?, + )) +} diff --git a/crates/storage_sqlite/src/workspace/installation.rs b/crates/storage_sqlite/src/workspace/installation.rs @@ -382,6 +382,14 @@ impl Journal<'_> { self.crypto, ) .await?; + if graph + .bound_plan() + .is_some_and(|bound| bound.plan().listing().is_some()) + { + return self + .install_listing(request, proof, record, grant, current, graph) + .await; + } let bound = graph.bound_plan().ok_or(OperationError::RecoveryRequired)?; if bound.plan().digest() != request.plan_digest() { return Err(OperationError::IdempotencyConflict); diff --git a/crates/storage_sqlite/src/workspace/issuance.rs b/crates/storage_sqlite/src/workspace/issuance.rs @@ -18,7 +18,7 @@ use sqlx::{Connection, SqliteConnection}; struct Loaded { bound: BoundSigningPlan, - operation: Vec<u8>, + operation: operation::ProtectedOperation, plan: plan::ProtectedPlan, } impl Journal<'_> { @@ -115,6 +115,11 @@ impl Journal<'_> { false, ) } else { + if request.target() == SigningTarget::PublicEvent + && !super::listing::current(self.connection).await? + { + return Err(OperationError::UnsupportedOperation); + } if current.observed_at() < bound.bound_at() { return Err(WorkspaceError::Unavailable.into()); } diff --git a/crates/storage_sqlite/src/workspace/listing.rs b/crates/storage_sqlite/src/workspace/listing.rs @@ -0,0 +1,172 @@ +//! Retained initial-coordinate decisions. Updates have separate expected-head +//! commands; another initial publish never overwrites this creation decision. +use super::{ + AttachmentInput, + crypto::{ListingScope, WorkspaceCrypto}, +}; +use radroots_domain::{ + CommandDigest, OperationId, PublicKey, TransactionId, WorkspaceId, listing::ListingId, +}; +use radroots_storage::command::{AdmissionRequest, OperationError, PreparedOperation}; +use serde::{Deserialize, Serialize}; +use sqlx::{Row, SqliteConnection}; +use zeroize::Zeroizing; + +pub(super) const CREATIONS: &str = "CREATE TABLE listing_creations (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, author BLOB NOT NULL CHECK(length(author)=32), listing_id BLOB NOT NULL CHECK(length(listing_id)=16), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id), FOREIGN KEY(workspace,operation_id) REFERENCES operations(workspace,operation_id)) STRICT, WITHOUT ROWID"; +pub(super) const COORDINATE_INDEX: &str = "CREATE UNIQUE INDEX listing_coordinate_identity ON listing_creations(workspace,author,listing_id)"; +#[derive(Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +struct DecisionRecord { + version: u8, + workspace: WorkspaceId, + operation: OperationId, + command: CommandDigest, + author: PublicKey, + listing: ListingId, + transaction: TransactionId, +} +impl DecisionRecord { + fn new(request: &AdmissionRequest, transaction: TransactionId) -> Result<Self, OperationError> { + let command = request + .command() + .listing() + .ok_or(OperationError::UnsupportedOperation)?; + let context = request.command().context(); + Ok(Self { + version: 1, + workspace: context.workspace_id(), + operation: context.operation_id(), + command: request.command().digest(), + author: context.actor().participant(), + listing: command.input().id(), + transaction, + }) + } + fn scope(&self) -> ListingScope { + ListingScope::Decision { + workspace: self.workspace, + operation: self.operation, + } + } +} +pub(super) struct Creation { + record: DecisionRecord, + protected: Vec<u8>, +} +impl Creation { + pub(super) async fn protect( + request: &AdmissionRequest, + transaction: TransactionId, + crypto: &WorkspaceCrypto, + ) -> Result<Option<Self>, OperationError> { + if request.command().listing().is_none() { + return Ok(None); + } + let record = DecisionRecord::new(request, transaction)?; + let raw = Zeroizing::new( + serde_json::to_vec(&record).map_err(|_| OperationError::InvalidCommand)?, + ); + let protected = crypto.seal_listing(record.scope(), &raw).await?; + Ok(Some(Self { record, protected })) + } + pub(super) async fn read( + connection: &mut SqliteConnection, + prepared: &PreparedOperation, + crypto: &WorkspaceCrypto, + ) -> Result<Option<Self>, OperationError> { + if !current(connection).await? { + return Ok(None); + } + let request = prepared.request(); + let context = request.command().context(); + let row=sqlx::query("SELECT CASE WHEN length(author)=32 THEN author END,CASE WHEN length(listing_id)=16 THEN listing_id END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM listing_creations WHERE workspace=? AND operation_id=?") + .bind(context.workspace_id().as_bytes().as_slice()).bind(context.operation_id().as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(row) = row else { + return if request.command().listing().is_some() { + Err(OperationError::RecoveryRequired) + } else { + Ok(None) + }; + }; + let bytes = |i| -> Result<Vec<u8>, OperationError> { + row.try_get::<Option<Vec<u8>>, _>(i) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired) + }; + let expected = DecisionRecord::new(request, prepared.transaction_id()) + .map_err(|_| OperationError::RecoveryRequired)?; + let protected = bytes(3)?; + let raw = crypto.open_listing(expected.scope(), &protected).await?; + let record: DecisionRecord = raw + .expose_secret(|raw| serde_json::from_slice(raw)) + .map_err(|_| OperationError::RecoveryRequired)?; + if record != expected + || bytes(0)? != record.author.as_bytes() + || bytes(1)? != record.listing.as_bytes() + || bytes(2)? != record.transaction.as_bytes() + { + return Err(OperationError::RecoveryRequired); + } + Ok(Some(Self { record, protected })) + } + pub(super) async fn insert( + &self, + connection: &mut SqliteConnection, + ) -> Result<(), OperationError> { + let r = &self.record; + // This check is inside the same BEGIN IMMEDIATE as T0 insertion. A + // competing operation cannot reach its first signing claim. + let exists:bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM listing_creations WHERE workspace=? AND author=? AND listing_id=?)") + .bind(r.workspace.as_bytes().as_slice()).bind(r.author.as_bytes().as_slice()).bind(r.listing.as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if exists { + return Err(OperationError::StaleState); + } + sqlx::query("INSERT INTO listing_creations(workspace,operation_id,author,listing_id,transaction_id,protected) VALUES(?,?,?,?,?,?)") + .bind(r.workspace.as_bytes().as_slice()).bind(r.operation.as_bytes().as_slice()).bind(r.author.as_bytes().as_slice()).bind(r.listing.as_bytes().as_slice()).bind(r.transaction.as_bytes().as_slice()).bind(&self.protected).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; + Ok(()) + } + pub(super) async fn unchanged( + &self, + connection: &mut SqliteConnection, + ) -> Result<(), OperationError> { + let r = &self.record; + let count:i64=sqlx::query_scalar("SELECT count(*) FROM listing_creations WHERE workspace=? AND operation_id=? AND author=? AND listing_id=? AND transaction_id=? AND protected=?") + .bind(r.workspace.as_bytes().as_slice()).bind(r.operation.as_bytes().as_slice()).bind(r.author.as_bytes().as_slice()).bind(r.listing.as_bytes().as_slice()).bind(r.transaction.as_bytes().as_slice()).bind(&self.protected).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 1 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} +pub(super) async fn current(connection: &mut SqliteConnection) -> Result<bool, OperationError> { + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + match version { + 7..=9 => Ok(false), + 10 => Ok(true), + _ => Err(OperationError::RecoveryRequired), + } +} +pub(super) async fn absent( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, +) -> Result<(), OperationError> { + if !current(connection).await? { + return Ok(()); + } + let found: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM listing_creations WHERE workspace=? AND operation_id=?)", + ) + .bind(selected.workspace_id().as_bytes().as_slice()) + .bind(operation.as_bytes().as_slice()) + .fetch_one(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if found { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/listing_installation.rs b/crates/storage_sqlite/src/workspace/listing_installation.rs @@ -0,0 +1,444 @@ +//! Atomic initial-listing revision and exact public-work retention. No signer, +//! provider, transport or stock allocator runs inside the write transaction. +use super::{ + AttachmentInput, AttachmentProof, + admission::{Journal, recheck}, + crypto::{IssuancePayload, IssuanceScope, WorkspaceCrypto}, + listing, + snapshot::{RetainedFacts, RetainedGraph}, +}; +use radroots_domain::{ + CommandDigest, EnvelopeEventId, OperationId, SigningAttemptId, TransactionId, UnixSeconds, + WorkspaceId, +}; +use radroots_storage::command::{ + BoundSigningPlan, CommitAttempt, EvidenceReceipt, InstallationOutcome, InstallationRequest, + ListingInstallation, OperationError, PublicPublicationWork, SigningTarget, +}; +use serde::{Deserialize, Serialize}; +use sqlx::{Connection, Row, SqliteConnection}; +use zeroize::Zeroizing; + +pub(super) const TABLE: &str = "CREATE TABLE listing_installations (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), event_id BLOB NOT NULL CHECK(length(event_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id), FOREIGN KEY(workspace,operation_id) REFERENCES listing_creations(workspace,operation_id)) STRICT, WITHOUT ROWID"; +pub(super) const WORK: &str = "CREATE TABLE public_publication_work (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), event_id BLOB NOT NULL CHECK(length(event_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), artifact_key BLOB NOT NULL CHECK(length(artifact_key)=1 AND hex(artifact_key)='00'), PRIMARY KEY(workspace,operation_id), FOREIGN KEY(workspace,operation_id) REFERENCES listing_installations(workspace,operation_id), FOREIGN KEY(workspace,operation_id,artifact_key) REFERENCES artifact_evidence(workspace,operation_id,artifact_key)) STRICT, WITHOUT ROWID"; +pub(super) const TX_INDEX: &str = "CREATE UNIQUE INDEX listing_installation_transaction_identity ON listing_installations(workspace,transaction_id)"; +#[derive(Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +struct PublicEvidenceRef { + workspace: WorkspaceId, + operation: OperationId, + command: CommandDigest, + attempt: SigningAttemptId, + event: EnvelopeEventId, + digest: [u8; 32], + transaction: TransactionId, + observed_at: Option<u64>, +} +impl PublicEvidenceRef { + fn new(e: EvidenceReceipt) -> Self { + Self { + workspace: e.workspace_id(), + operation: e.operation_id(), + command: e.command_digest(), + attempt: e.attempt_id(), + event: e.event_id(), + digest: *e.digest(), + transaction: e.transaction_id(), + observed_at: e.observed_at_unix_ms().map(core::num::NonZeroU64::get), + } + } +} +#[derive(Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +struct InstallationRecord { + version: u8, + plan: [u8; 32], + preparation: TransactionId, + plan_transaction: TransactionId, + transaction: TransactionId, + installed_at: UnixSeconds, + evidence: PublicEvidenceRef, +} +impl InstallationRecord { + fn new(i: ListingInstallation) -> Self { + Self { + version: 1, + plan: *i.plan_digest(), + preparation: i.preparation_transaction_id(), + plan_transaction: i.plan_transaction_id(), + transaction: i.transaction_id(), + installed_at: i.installed_at(), + evidence: PublicEvidenceRef::new(i.basis()), + } + } +} +#[derive(Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +struct WorkRecord { + version: u8, + installation: TransactionId, + plan: [u8; 32], + transaction: TransactionId, + queued_at: UnixSeconds, + evidence: PublicEvidenceRef, +} +impl WorkRecord { + fn new(w: PublicPublicationWork) -> Self { + Self { + version: 1, + installation: w.installation_transaction_id(), + plan: *w.plan_digest(), + transaction: w.transaction_id(), + queued_at: w.queued_at(), + evidence: PublicEvidenceRef::new(w.evidence()), + } + } +} +fn scope(bound: &BoundSigningPlan, evidence: EvidenceReceipt) -> IssuanceScope { + IssuanceScope { + workspace: evidence.workspace_id(), + operation: evidence.operation_id(), + plan_digest: *bound.plan().digest(), + attempt: evidence.attempt_id(), + target: SigningTarget::PublicEvent, + } +} +struct Protected<T> { + report: T, + protected: Vec<u8>, +} +pub(super) struct Records { + installation: Option<Protected<ListingInstallation>>, + work: Option<Protected<PublicPublicationWork>>, +} +impl Records { + pub(super) fn installation(&self) -> Option<ListingInstallation> { + self.installation.as_ref().map(|v| v.report) + } + pub(super) fn work(&self) -> Option<PublicPublicationWork> { + self.work.as_ref().map(|v| v.report) + } + pub(super) async fn read( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, + graph: &RetainedGraph, + crypto: &WorkspaceCrypto, + ) -> Result<Self, OperationError> { + let empty = Self { + installation: None, + work: None, + }; + if !listing::current(connection).await? { + return Ok(empty); + } + let installation = read_row(connection, selected, operation, Kind::Installation).await?; + let work = read_row(connection, selected, operation, Kind::Work).await?; + if installation.is_none() && work.is_none() { + return Ok(empty); + } + let bound = graph.bound_plan().ok_or(OperationError::RecoveryRequired)?; + if bound.plan().listing().is_none() { + return Err(OperationError::RecoveryRequired); + } + let evidence = graph + .reports() + .find(|r| r.target() == SigningTarget::PublicEvent) + .and_then(|r| r.obtained()) + .ok_or(OperationError::RecoveryRequired)?; + let installation = installation.ok_or(OperationError::RecoveryRequired)?; + let work = work.ok_or(OperationError::RecoveryRequired)?; + let raw = crypto + .open_issuance( + scope(bound, evidence), + IssuancePayload::ListingInstallation, + 0, + &installation.protected, + ) + .await?; + let encoded: InstallationRecord = raw + .expose_secret(|raw| serde_json::from_slice(raw)) + .map_err(|_| OperationError::RecoveryRequired)?; + let installed = ListingInstallation::from_committed_store( + bound, + evidence, + encoded.transaction, + encoded.installed_at, + )?; + if encoded != InstallationRecord::new(installed) + || !installation.matches( + installed.transaction_id(), + installed.plan_digest(), + installed.revision(), + ) + { + return Err(OperationError::RecoveryRequired); + } + let raw = crypto + .open_issuance( + scope(bound, evidence), + IssuancePayload::Publication, + 0, + &work.protected, + ) + .await?; + let encoded: WorkRecord = raw + .expose_secret(|raw| serde_json::from_slice(raw)) + .map_err(|_| OperationError::RecoveryRequired)?; + let queued = PublicPublicationWork::from_committed_store( + bound, + installed, + evidence, + encoded.transaction, + encoded.queued_at, + )?; + if encoded != WorkRecord::new(queued) + || !work.matches( + queued.transaction_id(), + queued.plan_digest(), + evidence.event_id(), + ) + || queued.transaction_id() != installed.transaction_id() + || queued.queued_at() != installed.installed_at() + { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { + installation: Some(Protected { + report: installed, + protected: installation.protected, + }), + work: Some(Protected { + report: queued, + protected: work.protected, + }), + }) + } + pub(super) async fn unchanged( + &self, + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, + ) -> Result<(), OperationError> { + if !listing::current(connection).await? { + return Ok(()); + } + let current = read_row(connection, selected, operation, Kind::Installation).await?; + match (&self.installation, current) { + (None, None) => (), + (Some(a), Some(b)) + if b.matches( + a.report.transaction_id(), + a.report.plan_digest(), + a.report.revision(), + ) && a.protected == b.protected => {} + _ => return Err(OperationError::RecoveryRequired), + } + let current = read_row(connection, selected, operation, Kind::Work).await?; + match (&self.work, current) { + (None, None) => (), + (Some(a), Some(b)) + if b.matches( + a.report.transaction_id(), + a.report.plan_digest(), + a.report.evidence().event_id(), + ) && a.protected == b.protected => {} + _ => return Err(OperationError::RecoveryRequired), + } + Ok(()) + } +} +enum Kind { + Installation, + Work, +} +struct RowFacts { + transaction: Vec<u8>, + plan: Vec<u8>, + event: Vec<u8>, + protected: Vec<u8>, +} +impl RowFacts { + fn matches(&self, tx: TransactionId, plan: &[u8; 32], event: EnvelopeEventId) -> bool { + self.transaction == tx.as_bytes() && self.plan == plan && self.event == event.as_bytes() + } +} +async fn read_row( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, + kind: Kind, +) -> Result<Option<RowFacts>, OperationError> { + let query = match kind { + Kind::Installation => { + "SELECT CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(plan_digest)=32 THEN plan_digest END,CASE WHEN length(event_id)=32 THEN event_id END,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM listing_installations WHERE workspace=? AND operation_id=?" + } + Kind::Work => { + "SELECT CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(plan_digest)=32 THEN plan_digest END,CASE WHEN length(event_id)=32 THEN event_id END,CASE WHEN length(protected)>0 AND length(protected)<=262144 AND length(artifact_key)=1 AND hex(artifact_key)='00' THEN protected END FROM public_publication_work WHERE workspace=? AND operation_id=?" + } + }; + let row = sqlx::query(query) + .bind(selected.workspace_id().as_bytes().as_slice()) + .bind(operation.as_bytes().as_slice()) + .fetch_optional(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + row.map(|r| { + let bytes = |i| -> Result<Vec<u8>, OperationError> { + r.try_get::<Option<Vec<u8>>, _>(i) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired) + }; + Ok(RowFacts { + transaction: bytes(0)?, + plan: bytes(1)?, + event: bytes(2)?, + protected: bytes(3)?, + }) + }) + .transpose() +} +pub(super) async fn absent( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, +) -> Result<(), OperationError> { + if !listing::current(connection).await? { + return Ok(()); + } + if read_row(connection, selected, operation, Kind::Installation) + .await? + .is_some() + || read_row(connection, selected, operation, Kind::Work) + .await? + .is_some() + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} +impl Journal<'_> { + pub(super) async fn install_listing( + &mut self, + request: InstallationRequest, + proof: AttachmentProof, + record: super::record::GrantRecord, + grant: Vec<u8>, + current: super::WorkspaceBinding, + graph: RetainedGraph, + ) -> Result<InstallationOutcome, OperationError> { + if !listing::current(self.connection).await? { + return Err(OperationError::UnsupportedOperation); + } + let facts = RetainedFacts::from_graph( + self.connection, + self.selected, + request.operation_id(), + graph, + self.crypto, + ) + .await?; + let bound = facts + .graph() + .bound_plan() + .ok_or(OperationError::RecoveryRequired)?; + if bound.plan().digest() != request.plan_digest() { + return Err(OperationError::IdempotencyConflict); + } + let retained = facts.listing(); + let evidence = facts + .graph() + .reports() + .find(|r| r.target() == SigningTarget::PublicEvent) + .and_then(|r| r.obtained()) + .ok_or(OperationError::InvalidEvidence)?; + let fresh = retained.installation().is_none(); + let installed = match retained.installation() { + Some(v) => v, + None => ListingInstallation::from_committed_store( + bound, + evidence, + TransactionId::from_bytes(super::random()?), + current.observed_at(), + )?, + }; + let prepared = if fresh { + let work = PublicPublicationWork::from_committed_store( + bound, + installed, + evidence, + installed.transaction_id(), + installed.installed_at(), + )?; + let raw = Zeroizing::new( + serde_json::to_vec(&InstallationRecord::new(installed)) + .map_err(|_| OperationError::InvalidCommand)?, + ); + let installation = self + .crypto + .seal_issuance( + scope(bound, evidence), + IssuancePayload::ListingInstallation, + 0, + &raw, + ) + .await?; + let raw = Zeroizing::new( + serde_json::to_vec(&WorkRecord::new(work)) + .map_err(|_| OperationError::InvalidCommand)?, + ); + let work = self + .crypto + .seal_issuance( + scope(bound, evidence), + IssuancePayload::Publication, + 0, + &raw, + ) + .await?; + Some((installation, work)) + } else { + None + }; + let anchor = CommitAttempt::new( + installed.workspace_id(), + installed.operation_id(), + installed.command_digest(), + Some(installed.transaction_id()), + ); + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked=async { + let now=recheck(&mut transaction,self.namespace,self.selected,&grant,&record,request.binding(),&proof,self.clock).await?; + facts.unchanged(&mut transaction,self.selected,request.operation_id()).await?; + if fresh && now.observed_at()<current.observed_at(){return Err(super::WorkspaceError::Unavailable.into());} + if let Some((installation,work))=&prepared { + sqlx::query("INSERT INTO listing_installations(workspace,operation_id,transaction_id,plan_digest,event_id,protected) VALUES(?,?,?,?,?,?)") + .bind(installed.workspace_id().as_bytes().as_slice()).bind(installed.operation_id().as_bytes().as_slice()).bind(installed.transaction_id().as_bytes().as_slice()).bind(installed.plan_digest().as_slice()).bind(installed.revision().as_bytes().as_slice()).bind(installation).execute(&mut *transaction).await.map_err(|_|OperationError::StorageFailure)?; + sqlx::query("INSERT INTO public_publication_work(workspace,operation_id,transaction_id,plan_digest,event_id,protected,artifact_key) VALUES(?,?,?,?,?,?,X'00')") + .bind(installed.workspace_id().as_bytes().as_slice()).bind(installed.operation_id().as_bytes().as_slice()).bind(installed.transaction_id().as_bytes().as_slice()).bind(installed.plan_digest().as_slice()).bind(installed.revision().as_bytes().as_slice()).bind(work).execute(&mut *transaction).await.map_err(|_|OperationError::StorageFailure)?; + } + Ok::<_,OperationError>(()) + }.await; + if let Err(error) = checked { + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Ok(InstallationOutcome::Unknown(anchor)); + } + return Err(error); + } + let completed = if fresh { + transaction.commit().await + } else { + transaction.rollback().await + }; + if completed.is_err() { + *self.uncertain = true; + return Ok(InstallationOutcome::Unknown(anchor)); + } + Ok(InstallationOutcome::ListingCommitted(Box::new(installed))) + } +} diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -13,6 +13,8 @@ mod evidence; mod fs; mod installation; mod issuance; +mod listing; +mod listing_installation; mod operation; mod plan; mod record; diff --git a/crates/storage_sqlite/src/workspace/operation.rs b/crates/storage_sqlite/src/workspace/operation.rs @@ -1,6 +1,6 @@ //! Retained non-stock command preparation. No signing or delivery occurs here. -use super::{AttachmentInput, crypto::WorkspaceCrypto}; +use super::{AttachmentInput, crypto::WorkspaceCrypto, listing}; use radroots_domain::{IssuanceWindow, OperationId, TransactionId}; use radroots_storage::command::{AdmissionRequest, OperationError, PreparedOperation}; use sqlx::{Row, SqliteConnection}; @@ -10,6 +10,11 @@ pub(super) const TABLE: &str = "CREATE TABLE operations (workspace BLOB NOT NULL pub(super) const INDEX: &str = "CREATE UNIQUE INDEX operation_transaction_identity ON operations(workspace,transaction_id)"; +pub(super) struct ProtectedOperation { + pub bytes: Vec<u8>, + pub creation: Option<listing::Creation>, +} + pub(super) async fn protect( request: &AdmissionRequest, transaction_id: TransactionId, @@ -31,7 +36,7 @@ pub(super) async fn read( selected: &AttachmentInput, operation_id: OperationId, crypto: &WorkspaceCrypto, -) -> Result<Option<(PreparedOperation, Vec<u8>)>, OperationError> { +) -> Result<Option<(PreparedOperation, ProtectedOperation)>, OperationError> { let row = sqlx::query("SELECT CASE WHEN length(actor)=32 THEN actor END,CASE WHEN length(grant_id)=32 THEN grant_id END,CASE WHEN length(command_type)<=80 THEN command_type END,CASE WHEN length(command_digest)=32 THEN command_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(phase)<=32 THEN phase END,revision,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM operations WHERE workspace=? AND operation_id=?") .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation_id.as_bytes().as_slice()) .fetch_optional(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; @@ -77,7 +82,14 @@ pub(super) async fn read( { return Err(OperationError::RecoveryRequired); } - Ok(Some((snapshot, protected))) + let creation = listing::Creation::read(connection, &snapshot, crypto).await?; + Ok(Some(( + snapshot, + ProtectedOperation { + bytes: protected, + creation, + }, + ))) } pub(super) async fn insert( @@ -101,7 +113,7 @@ pub(super) async fn insert( pub(super) async fn unchanged( connection: &mut SqliteConnection, snapshot: &PreparedOperation, - expected: &[u8], + expected: &ProtectedOperation, ) -> Result<(), OperationError> { let request = snapshot.request(); let context = request.command().context(); @@ -111,11 +123,24 @@ pub(super) async fn unchanged( .bind(request.command().kind().as_str()).bind(request.command().digest().as_bytes().as_slice()) .bind(snapshot.transaction_id().as_bytes().as_slice()) // Sequence construction enforces the signed 64-bit storage bound. - .bind(snapshot.revision().get() as i64).bind(expected) - .fetch_one(connection).await.map_err(|_| OperationError::RecoveryRequired)?; + .bind(snapshot.revision().get() as i64).bind(&expected.bytes) + .fetch_one(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; if matched != 1 { return Err(OperationError::RecoveryRequired); } + if let Some(creation) = &expected.creation { + creation.unchanged(connection).await?; + } else if listing::current(connection).await? { + if snapshot.request().command().listing().is_some() { + return Err(OperationError::RecoveryRequired); + } + listing::absent( + connection, + snapshot.request().binding().input(), + context.operation_id(), + ) + .await?; + } Ok(()) } @@ -132,7 +157,9 @@ pub(super) async fn absent( let retained: bool = sqlx::query_scalar(super::attempt::sql(connection, "SELECT EXISTS(SELECT 1 FROM operations WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM signing_plans WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM signing_plan_parts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM signing_attempts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM seal_evidence WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM seal_evidence_parts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_messages WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_publication_work WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_delivery_attempts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_delivery_parts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_delivery_observations WHERE workspace=?1 AND operation_id=?2)").await?) .bind(selected.workspace_id().as_bytes().as_slice()) .bind(operation.as_bytes().as_slice()) - .fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + .fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + listing::absent(connection, selected, operation).await?; + super::listing_installation::absent(connection, selected, operation).await?; if retained { return Err(OperationError::RecoveryRequired); } diff --git a/crates/storage_sqlite/src/workspace/snapshot.rs b/crates/storage_sqlite/src/workspace/snapshot.rs @@ -26,7 +26,7 @@ struct SeenArtifact { obtained: Option<ArtifactEvidence>, } pub(super) struct RetainedGraph { - retained: Option<(RetainedOperation, Vec<u8>)>, + retained: Option<(RetainedOperation, operation::ProtectedOperation)>, protected_plan: Option<ProtectedPlan>, artifacts: Vec<SeenArtifact>, } @@ -217,10 +217,18 @@ impl RetainedGraph { pub(super) struct RetainedFacts { graph: RetainedGraph, records: Records, + listing: super::listing_installation::Records, deliveries: DeliveryGraph, observations: Observations, } impl RetainedFacts { + pub(super) fn graph(&self) -> &RetainedGraph { + &self.graph + } + pub(super) fn listing(&self) -> &super::listing_installation::Records { + &self.listing + } + pub(super) async fn read( connection: &mut SqliteConnection, selected: &AttachmentInput, @@ -231,7 +239,20 @@ impl RetainedFacts { ) -> Result<Self, OperationError> { let graph = RetainedGraph::read(connection, selected, binding, operation, digest, crypto).await?; + Self::from_graph(connection, selected, operation, graph, crypto).await + } + pub(super) async fn from_graph( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, + graph: RetainedGraph, + crypto: &WorkspaceCrypto, + ) -> Result<Self, OperationError> { let records = Records::read(connection, selected, operation, &graph, crypto).await?; + let listing = super::listing_installation::Records::read( + connection, selected, operation, &graph, crypto, + ) + .await?; let deliveries = DeliveryGraph::read(connection, selected, operation, &graph, &records, crypto).await?; let observations = @@ -239,6 +260,7 @@ impl RetainedFacts { Ok(Self { graph, records, + listing, deliveries, observations, }) @@ -255,6 +277,9 @@ impl RetainedFacts { self.records .unchanged(connection, selected, operation) .await?; + self.listing + .unchanged(connection, selected, operation) + .await?; self.deliveries .unchanged(connection, selected, operation) .await?; @@ -278,6 +303,10 @@ impl RetainedFacts { .map(|value| value.report) .collect(), )? + .with_public_installation( + self.listing.installation(), + self.listing.work().into_iter().collect(), + )? .with_delivery( self.deliveries .attempts diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -686,7 +686,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r WorkspaceError::RecoveryRequired }; let statement = match fault { - 0 => "PRAGMA user_version=10", + 0 => "PRAGMA user_version=11", 1 => "DELETE FROM workspace_grant", 2 => "UPDATE workspace_grant SET grant_id=zeroblob(31)", 3 => "UPDATE workspace_grant SET protected=zeroblob(0)", @@ -732,7 +732,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .fetch_one(&mut connection) .await .unwrap(); - assert_eq!(version, if fault == 0 { 10 } else { 9 }); + assert_eq!(version, if fault == 0 { 11 } else { 10 }); assert_eq!(rows, if fault == 1 { 0 } else { 1 }); if let Some(expected) = retained_protected { let actual: Vec<u8> = sqlx::query_scalar("SELECT protected FROM workspace_grant") diff --git a/crates/storage_sqlite/src/workspace/tests/operation_records.rs b/crates/storage_sqlite/src/workspace/tests/operation_records.rs @@ -101,7 +101,7 @@ async fn protected_operation_read_refuses_each_inconsistent_payload_and_sql_proj recovered.request().binding().scope(), radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox ); - assert_eq!(legacy_retained, legacy); + assert_eq!(legacy_retained.bytes, legacy); assert_eq!( sqlx::query_scalar::<_, Vec<u8>>("SELECT protected FROM operations") .fetch_one(&mut database) @@ -189,7 +189,15 @@ async fn protected_operation_read_refuses_each_inconsistent_payload_and_sql_proj } let mut transaction = database.begin_with("BEGIN IMMEDIATE").await.unwrap(); assert!(matches!( - operation::unchanged(&mut transaction, &retained, &original).await, + operation::unchanged( + &mut transaction, + &retained, + &operation::ProtectedOperation { + bytes: original.clone(), + creation: None + } + ) + .await, Err(OperationError::RecoveryRequired) )); transaction.rollback().await.unwrap(); @@ -219,7 +227,15 @@ async fn protected_operation_read_refuses_each_inconsistent_payload_and_sql_proj .await .unwrap(); let mut transaction = database.begin_with("BEGIN IMMEDIATE").await.unwrap(); - let checked = operation::unchanged(&mut transaction, &retained, &original).await; + let checked = operation::unchanged( + &mut transaction, + &retained, + &operation::ProtectedOperation { + bytes: original.clone(), + creation: None, + }, + ) + .await; transaction.rollback().await.unwrap(); database.close().await.unwrap(); assert!( diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -1,7 +1,7 @@ use super::{ AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, WorkspaceError, admission::Journal, attempt, delivery, evidence, fs::Namespace, installation, - operation, plan, record::GrantRecord, + listing, operation, plan, record::GrantRecord, }; use radroots_domain::{CommandDigest, OperationId, PublicKey}; use radroots_storage::command::{ @@ -1007,13 +1007,18 @@ pub(super) async fn initialize( delivery::PARTS, delivery::TX_INDEX, delivery::OBSERVATIONS, + listing::CREATIONS, + listing::COORDINATE_INDEX, + super::listing_installation::TABLE, + super::listing_installation::TX_INDEX, + super::listing_installation::WORK, ] { sqlx::raw_sql(definition) .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=9") + sqlx::query("PRAGMA user_version=10") .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; @@ -1035,16 +1040,32 @@ pub(super) async fn initialize( .fetch_one(&mut *connection) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; - if !matches!(version, 7..=9) { + if !matches!(version, 7..=10) { return Err(WorkspaceError::RecoveryRequired); } let catalog_sql = "SELECT CASE WHEN count(*)=20 AND sum(CASE WHEN type='table' AND name='workspace_grant' AND tbl_name='workspace_grant' AND sql=? THEN 1 WHEN type='table' AND name='operations' AND tbl_name='operations' AND sql=? THEN 1 WHEN type='table' AND name='signing_plans' AND tbl_name='signing_plans' AND sql=? THEN 1 WHEN type='table' AND name='signing_plan_parts' AND tbl_name='signing_plan_parts' AND sql=? THEN 1 WHEN type='table' AND name='signing_attempts' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='index' AND name='signing_attempt_identity' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='index' AND name='signing_attempt_transaction_identity' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='table' AND name='seal_evidence' AND tbl_name='seal_evidence' AND sql=? THEN 1 WHEN type='table' AND name='seal_evidence_parts' AND tbl_name='seal_evidence_parts' AND sql=? THEN 1 WHEN type='index' AND name='seal_evidence_transaction_identity' AND tbl_name='seal_evidence' AND sql=? THEN 1 WHEN type='index' AND name='operation_transaction_identity' AND tbl_name='operations' AND sql=? THEN 1 WHEN type='table' AND name='chat_messages' AND tbl_name='chat_messages' AND sql=? THEN 1 WHEN type='index' AND name='chat_message_operation_identity' AND tbl_name='chat_messages' AND sql=? THEN 1 WHEN type='index' AND name='chat_message_transaction_identity' AND tbl_name='chat_messages' AND sql=? THEN 1 WHEN type='index' AND name='chat_message_thread' AND tbl_name='chat_messages' AND sql=? THEN 1 WHEN type='table' AND name='chat_publication_work' AND tbl_name='chat_publication_work' AND sql=? THEN 1 WHEN type='table' AND name='chat_delivery_attempts' AND tbl_name='chat_delivery_attempts' AND sql=? THEN 1 WHEN type='table' AND name='chat_delivery_parts' AND tbl_name='chat_delivery_parts' AND sql=? THEN 1 WHEN type='index' AND name='chat_delivery_transaction_identity' AND tbl_name='chat_delivery_attempts' AND sql=? THEN 1 WHEN type='table' AND name='chat_delivery_observations' AND tbl_name='chat_delivery_observations' AND sql=? THEN 1 ELSE 0 END)=20 THEN 1 ELSE 0 END FROM sqlite_schema"; - let catalog_sql = if version == 9 { + let catalog_sql = if matches!(version, 9 | 10) { catalog_sql.replace("seal_evidence", "artifact_evidence") } else { catalog_sql.to_owned() }; - let catalog_matches: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(catalog_sql)) + let catalog_sql = if version == 10 { + catalog_sql.replace("count(*)=20", "count(*)=25").replace("END)=20", "END)=25").replace("WHEN type='table' AND name='workspace_grant'", "WHEN type='table' AND name='listing_creations' AND tbl_name='listing_creations' AND sql=? THEN 1 WHEN type='index' AND name='listing_coordinate_identity' AND tbl_name='listing_creations' AND sql=? THEN 1 WHEN type='table' AND name='listing_installations' AND tbl_name='listing_installations' AND sql=? THEN 1 WHEN type='index' AND name='listing_installation_transaction_identity' AND tbl_name='listing_installations' AND sql=? THEN 1 WHEN type='table' AND name='public_publication_work' AND tbl_name='public_publication_work' AND sql=? THEN 1 WHEN type='table' AND name='workspace_grant'") + } else { + catalog_sql + }; + let catalog_query = sqlx::query_scalar(sqlx::AssertSqlSafe(catalog_sql)); + let catalog_query = if version == 10 { + catalog_query + .bind(listing::CREATIONS) + .bind(listing::COORDINATE_INDEX) + .bind(super::listing_installation::TABLE) + .bind(super::listing_installation::TX_INDEX) + .bind(super::listing_installation::WORK) + } else { + catalog_query + }; + let catalog_matches: i64 = catalog_query .bind(TABLE) .bind(if version == 7 { operation::TABLE_V7 @@ -1053,24 +1074,24 @@ pub(super) async fn initialize( }) .bind(plan::TABLE) .bind(plan::PARTS) - .bind(if version == 9 { + .bind(if matches!(version, 9 | 10) { attempt::TABLE } else { attempt::TABLE_V8 }) .bind(attempt::ID_INDEX) .bind(attempt::TX_INDEX) - .bind(if version == 9 { + .bind(if matches!(version, 9 | 10) { evidence::TABLE } else { evidence::TABLE_V8 }) - .bind(if version == 9 { + .bind(if matches!(version, 9 | 10) { evidence::PARTS } else { evidence::PARTS_V8 }) - .bind(if version == 9 { + .bind(if matches!(version, 9 | 10) { evidence::TX_INDEX } else { evidence::TX_INDEX_V8 @@ -1080,7 +1101,7 @@ pub(super) async fn initialize( .bind(installation::OP_INDEX) .bind(installation::TX_INDEX) .bind(installation::THREAD_INDEX) - .bind(if version == 9 { + .bind(if matches!(version, 9 | 10) { installation::WORK } else { installation::WORK_V8 diff --git a/crates/storage_sqlite/tests/support/public_admission.rs b/crates/storage_sqlite/tests/support/public_admission.rs @@ -249,7 +249,7 @@ fn public_request( ) .unwrap(); let wire = json!({"type":"listing.publish", "context":context,"input":{ - "id":"01".repeat(16),"title":title,"summary":"Quote required","description_markdown":"Public terms", + "id":format!("{id:02x}").repeat(16),"title":title,"summary":"Quote required","description_markdown":"Public terms", "published_at":"100","profile":{"profile":"radroots.listing","version":1,"state":"active", "product":{"name":"Carrots","description":"Public description","producer":null,"origin_summary":null}, "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch", @@ -1101,9 +1101,605 @@ mod public_issuance { assert_eq!(captured.evidence().raw_json(), evidence.raw_json()); reopened.close().await.unwrap(); } + fn install_request( + binding: &WorkspaceBinding, + prepared: &PreparedOperation, + digest: [u8; 32], + ) -> radroots_storage::command::InstallationRequest { + radroots_storage::command::InstallationRequest::new( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + digest, + ) + } + fn installed( + outcome: radroots_storage::command::InstallationOutcome, + ) -> radroots_storage::command::ListingInstallation { + match outcome { + radroots_storage::command::InstallationOutcome::ListingCommitted(v) => *v, + _ => panic!("public T2 must confirm original listing installation"), + } + } + async fn signed( + fixture: &Fixture, + store: &NativeWorkspace, + binding: &WorkspaceBinding, + input: &AttachmentInput, + proof: &AttachmentProof, + id: u8, + ) -> (PreparedOperation, [u8; 32], ArtifactEvidence) { + let (prepared, digest) = prepared(fixture, store, binding, proof, id).await; + let attempt = claimed( + store + .claim_attempt(selection(binding, &prepared, digest), copy(proof)) + .await + .unwrap(), + ); + let evidence = obtain(&attempt).await; + captured( + store + .capture_evidence(input.clone(), proof, &evidence) + .await + .unwrap(), + ); + (prepared, digest, evidence) + } + async fn t2_counts(fixture: &Fixture) -> (i64, i64, i64) { + let mut db = fixture.database().await; + 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(); + db.close().await.unwrap(); + counts + } + #[tokio::test] + async fn public_t2_requires_actual_obtained_evidence_then_installs_once_after_first_issue_expiry() + { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (prepared, digest) = prepared(&fixture, &store, &binding, &proof, 170).await; + assert!(matches!( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof) + ) + .await, + Err(OperationError::InvalidEvidence) + )); + let attempt = claimed( + store + .claim_attempt(selection(&binding, &prepared, digest), copy(&proof)) + .await + .unwrap(), + ); + assert!(matches!( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof) + ) + .await, + Err(OperationError::InvalidEvidence) + )); + assert_eq!(t2_counts(&fixture).await, (1, 0, 0)); + let evidence = obtain(&attempt).await; + let receipt = captured( + store + .capture_evidence(input.clone(), &proof, &evidence) + .await + .unwrap(), + ); + let before = store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(&proof), + ) + .await + .unwrap() + .unwrap() + .checkpoint_digest(); + fixture.clock.now.store(160, Ordering::SeqCst); + let result = installed( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(result.basis(), receipt); + assert_eq!(result.revision(), receipt.event_id()); + assert_eq!(result.author(), key()); + assert_eq!(result.installed_at().get(), 160); + assert_eq!( + result.listing_id(), + prepared.request().command().listing().unwrap().input().id() + ); + assert_eq!(t2_counts(&fixture).await, (1, 1, 1)); + let snapshot = store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(snapshot.listing_installation(), Some(result)); + assert!(snapshot.installation().is_none()); + assert!(snapshot.installed_message().is_none()); + assert!(snapshot.publications().is_empty()); + assert!(snapshot.delivery_attempts().is_empty()); + assert_eq!(snapshot.public_publications().len(), 1); + let work = snapshot.public_publications()[0]; + assert_eq!(work.evidence().target(), SigningTarget::PublicEvent); + assert_eq!(work.evidence().target().recipient(), None); + assert_eq!(work.transaction_id(), result.transaction_id()); + assert_eq!(work.queued_at(), result.installed_at()); + let checkpoint = snapshot.checkpoint_digest(); + assert_ne!(checkpoint, before); + store.close().await.unwrap(); + fixture.clock.now.store(170, Ordering::SeqCst); + let reopened = fixture.reopen(input).await; + let replay = installed( + reopened + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(replay, result); + let snapshot = reopened + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(snapshot.checkpoint_digest(), checkpoint); + let retained = reopened + .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.evidence().raw_json(), evidence.raw_json()); + assert_eq!(t2_counts(&fixture).await, (1, 1, 1)); + reopened.close().await.unwrap(); + } + #[tokio::test] + async fn another_initial_publish_cannot_claim_same_coordinate_before_any_signing() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create_scoped(200, true).await; + let first = committed( + store + .admit_command_and_hold( + public_request(&binding, 171, "first coordinate", "one"), + copy(&proof), + ) + .await + .unwrap(), + ); + let second = public_request(&binding, 172, "other operation", "two"); + let mut wire: serde_json::Value = + serde_json::from_slice(second.command().protected_wire()).unwrap(); + wire["input"]["id"] = json!(first.request().command().listing().unwrap().input().id()); + let second = AdmissionRequest::from_protected_wire( + binding.clone(), + &serde_json::to_vec(&wire).unwrap(), + ) + .unwrap(); + assert!(matches!( + store.admit_command_and_hold(second, copy(&proof)).await, + Err(OperationError::StaleState) + )); + assert_eq!(count(&fixture).await, 1); + assert_eq!(t2_counts(&fixture).await, (1, 0, 0)); + let mut db = fixture.database().await; + let claims: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_attempts") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(claims, 0); + db.close().await.unwrap(); + store.close().await.unwrap(); + } + #[tokio::test] + async fn public_t2_refuses_wrong_proof_digest_and_clock_rollback_without_partial_rows() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 173).await; + let wrong = AttachmentProof::from_protected_input(&[0x19; 32]).unwrap(); + assert!(matches!( + store + .install_transition_and_outbox(install_request(&binding, &prepared, digest), wrong) + .await, + Err(OperationError::Workspace(WorkspaceError::Unauthorized)) + )); + assert!(matches!( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, [9; 32]), + copy(&proof) + ) + .await, + Err(OperationError::IdempotencyConflict) + )); + let (arrived, resume) = fixture.clock.arm(1); + let mut pending = store.install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + reached(arrived).await; + fixture.clock.now.store(99, Ordering::SeqCst); + resume.send(()).unwrap(); + assert!(matches!( + pending.await, + Err(OperationError::Workspace(WorkspaceError::Unavailable)) + )); + assert_eq!(t2_counts(&fixture).await, (1, 0, 0)); + fixture.clock.now.store(100, Ordering::SeqCst); + installed( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap(), + ); + store.close().await.unwrap(); + } + #[tokio::test] + async fn public_work_insertion_fault_rolls_back_revision_and_preserves_original_signature() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (prepared, digest, evidence) = + signed(&fixture, &store, &binding, &input, &proof, 174).await; + let mut db = fixture.database().await; + 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(); + assert!(matches!( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof) + ) + .await, + Err(OperationError::StorageFailure) + )); + assert_eq!(t2_counts(&fixture).await, (1, 0, 0)); + let retained = store + .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.evidence().raw_json(), evidence.raw_json()); + sqlx::query("DROP TRIGGER fail_public_work") + .execute(&mut db) + .await + .unwrap(); + db.close().await.unwrap(); + installed( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(t2_counts(&fixture).await, (1, 1, 1)); + store.close().await.unwrap(); + } + #[tokio::test] + async fn public_t2_observer_loss_drains_and_reopens_original_installation() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 175).await; + let (arrived, resume) = fixture.clock.arm(1); + let mut pending = store.install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + reached(arrived).await; + drop(pending); + resume.send(()).unwrap(); + store.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + let snapshot = reopened + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + let original = snapshot.listing_installation().unwrap(); + assert_eq!( + installed( + reopened + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof) + ) + .await + .unwrap() + ), + original + ); + assert_eq!(t2_counts(&fixture).await, (1, 1, 1)); + reopened.close().await.unwrap(); + } + #[tokio::test] + async fn public_t2_actual_commit_failure_is_unknown_and_blocks_until_reopen() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 176).await; + let mut db = fixture.database().await; + 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(); + let radroots_storage::command::InstallationOutcome::Unknown(anchor) = store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap() + else { + panic!("actual failed COMMIT must remain unknown") + }; + assert_eq!(anchor.operation_id(), prepared.identity().operation_id()); + assert!(anchor.transaction_id().is_some()); + assert!(matches!( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fail_public_commit; DROP TABLE deferred_fault") + .execute(&mut db) + .await + .unwrap(); + db.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + assert_eq!(t2_counts(&fixture).await, (1, 0, 0)); + installed( + reopened + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap(), + ); + reopened.close().await.unwrap(); + } + #[tokio::test] + async fn exact_generation_nine_preserves_public_s_and_refuses_unfenced_new_effects() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (prepared, digest, evidence) = + signed(&fixture, &store, &binding, &input, &proof, 177).await; + store.close().await.unwrap(); + let mut db = fixture.database().await; + 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(); + db.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + let retained = reopened + .obtained_evidence(selection(&binding, &prepared, digest), copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.evidence().raw_json(), evidence.raw_json()); + assert!(matches!( + reopened + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof) + ) + .await, + Err(OperationError::UnsupportedOperation) + )); + assert!(matches!( + reopened + .admit_command_and_hold( + public_request(&binding, 178, "fresh unsupported", "new"), + copy(&proof) + ) + .await, + Err(OperationError::UnsupportedOperation) + )); + assert!(matches!( + reopened + .admit_command_and_hold( + public_request(&binding, 177, "changed terms", "replay"), + copy(&proof) + ) + .await, + Err(OperationError::IdempotencyConflict) + )); + let replay = AdmissionRequest::from_protected_wire( + binding.clone(), + prepared.request().command().protected_wire(), + ) + .unwrap(); + assert_eq!( + committed( + reopened + .admit_command_and_hold(replay, copy(&proof)) + .await + .unwrap() + ) + .identity(), + prepared.identity() + ); + assert!(matches!( + reopened + .claim_attempt(selection(&binding, &prepared, digest), copy(&proof)) + .await + .unwrap(), + ClaimAttemptOutcome::Retained(_) + )); + committed( + reopened + .admit_command_and_hold( + request(&binding, 179, "legacy private continuation", "private"), + copy(&proof), + ) + .await + .unwrap(), + ); + reopened.close().await.unwrap(); + } + #[tokio::test] + async fn public_t2_requires_current_grant_even_after_obtained_capture() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 180).await; + store.revoke(input, &proof).await.unwrap(); + assert!(matches!( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof) + ) + .await, + Err(OperationError::Workspace(WorkspaceError::GrantRevoked)) + )); + assert_eq!(t2_counts(&fixture).await, (1, 0, 0)); + store.close().await.unwrap(); + } + #[tokio::test] + async fn retained_listing_graph_refuses_changed_decision_and_orphaned_installation_without_repair() + { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (prepared, digest, _) = signed(&fixture, &store, &binding, &input, &proof, 181).await; + installed( + store + .install_transition_and_outbox( + install_request(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap(), + ); + let mut db = fixture.database().await; + sqlx::query("PRAGMA foreign_keys=OFF") + .execute(&mut db) + .await + .unwrap(); + let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM listing_creations") + .fetch_one(&mut db) + .await + .unwrap(); + sqlx::query("UPDATE listing_creations SET transaction_id=zeroblob(32)") + .execute(&mut db) + .await + .unwrap(); + assert!(matches!( + store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + sqlx::query("UPDATE listing_creations SET transaction_id=?,protected=?") + .bind(prepared.transaction_id().as_bytes().as_slice()) + .bind(&original) + .execute(&mut db) + .await + .unwrap(); + let event: Vec<u8> = sqlx::query_scalar("SELECT event_id FROM listing_installations") + .fetch_one(&mut db) + .await + .unwrap(); + let installed_row: Vec<u8> = + sqlx::query_scalar("SELECT protected FROM listing_installations") + .fetch_one(&mut db) + .await + .unwrap(); + for update in [ + "UPDATE listing_installations SET event_id=zeroblob(32)", + "UPDATE public_publication_work SET plan_digest=zeroblob(32)", + ] { + sqlx::query(update).execute(&mut db).await.unwrap(); + assert!(matches!( + store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + sqlx::query("UPDATE listing_installations SET event_id=?,protected=?") + .bind(&event) + .bind(&installed_row) + .execute(&mut db) + .await + .unwrap(); + sqlx::query("UPDATE public_publication_work SET plan_digest=?") + .bind(digest.as_slice()) + .execute(&mut db) + .await + .unwrap(); + } + sqlx::query("DELETE FROM listing_installations") + .execute(&mut db) + .await + .unwrap(); + assert!(matches!( + store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + 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(); + assert!(matches!( + store + .operation( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + db.close().await.unwrap(); + store.close().await.unwrap(); + } } pub(super) async fn retain_legacy_issuance_catalog(db: &mut SqliteConnection) { + sqlx::raw_sql("DROP TABLE public_publication_work; DROP TABLE listing_installations; DROP TABLE listing_creations").execute(&mut *db).await.unwrap(); use sqlx::Row; 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(); let definitions = rows