commit 2394cb4d5a4ae1d9891eeecd15c332937fb6cc5c
parent 73ec16a61178a23a06193cb2327f15a9beb4264a
Author: triesap <tyson@radroots.org>
Date: Sun, 18 Oct 2026 02:59:56 +0000
storage: retain complete protected native signing plans
- bind bounded exact chat seals to complete recipient and route descriptors
- verify signed DM advertisements and originating command provenance
- commit protected plan parts on the owned SQLite journal with bounded admission
- cover reopen replay corruption expiry and uncertain transaction completion
Diffstat:
31 files changed, 2905 insertions(+), 26 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
@@ -3647,9 +3647,11 @@ dependencies = [
"futures",
"getrandom 0.2.17",
"hex",
+ "nostr 0.44.7",
"radroots_domain",
"radroots_event",
"radroots_event_codec",
+ "radroots_protocol",
"radroots_secrets",
"radroots_storage",
"radroots_transport",
diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt
@@ -63,6 +63,19 @@ pub const radroots_protocol::capability::v1::SCHEMAS: &[radroots_protocol::schem
pub fn radroots_protocol::capability::v1::schema_registry() -> core::result::Result<radroots_protocol::schema::Registry, radroots_protocol::schema::Error>
pub fn radroots_protocol::capability::v1::validate_catalog(&[radroots_protocol::capability::v1::TransportDescriptor]) -> core::result::Result<(), radroots_protocol::capability::v1::Error>
pub mod radroots_protocol::chat
+pub enum radroots_protocol::chat::ChatReplay
+pub radroots_protocol::chat::ChatReplay::ExactReplayByRequestId
+pub radroots_protocol::chat::ChatReplay::LocalReplaySafe
+pub radroots_protocol::chat::ChatReplay::NonReplayable
+pub struct radroots_protocol::chat::CapturedDmRoute
+impl radroots_protocol::chat::CapturedDmRoute
+pub fn radroots_protocol::chat::CapturedDmRoute::from_observed_descriptor(radroots_identity::key::PublicKey, radroots_domain::identifier::EnvelopeEventId, &str, &[alloc::string::String]) -> core::result::Result<Self, radroots_protocol::nip01::WireError>
+pub const fn radroots_protocol::chat::CapturedDmRoute::participant(&self) -> radroots_identity::key::PublicKey
+pub fn radroots_protocol::chat::CapturedDmRoute::raw_json(&self) -> &str
+pub fn radroots_protocol::chat::CapturedDmRoute::selected_relays(&self) -> &[alloc::boxed::Box<str>]
+pub const fn radroots_protocol::chat::CapturedDmRoute::source_id(&self) -> radroots_domain::identifier::EnvelopeEventId
+impl core::fmt::Debug for radroots_protocol::chat::CapturedDmRoute
+pub fn radroots_protocol::chat::CapturedDmRoute::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_protocol::chat::ChatBudget
impl radroots_protocol::chat::ChatBudget
pub const fn radroots_protocol::chat::ChatBudget::envelope_ciphertext_max_bytes(self) -> usize
@@ -83,12 +96,39 @@ impl core::fmt::Debug for radroots_protocol::chat::ChatRumor
pub fn radroots_protocol::chat::ChatRumor::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_protocol::chat::ChatSeal
impl radroots_protocol::chat::ChatSeal
+pub const fn radroots_protocol::chat::ChatSeal::command_digest(&self) -> radroots_domain::identifier::CommandDigest
pub const fn radroots_protocol::chat::ChatSeal::event_id(&self) -> [u8; 32]
pub fn radroots_protocol::chat::ChatSeal::fields(&self) -> radroots_protocol::nip01::EventFields<'_>
+pub const fn radroots_protocol::chat::ChatSeal::message_id(&self) -> radroots_domain::identifier::MessageId
pub fn radroots_protocol::chat::ChatSeal::new(&radroots_protocol::chat::ChatRumor, radroots_identity::key::PublicKey, radroots_domain::context::UnixSeconds, &str) -> core::result::Result<Self, radroots_protocol::nip01::WireError>
+pub const fn radroots_protocol::chat::ChatSeal::operation_id(&self) -> radroots_domain::identifier::OperationId
pub const fn radroots_protocol::chat::ChatSeal::recipient(&self) -> radroots_identity::key::PublicKey
impl core::fmt::Debug for radroots_protocol::chat::ChatSeal
pub fn radroots_protocol::chat::ChatSeal::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub struct radroots_protocol::chat::ChatSigningPlan
+impl radroots_protocol::chat::ChatSigningPlan
+pub const fn radroots_protocol::chat::ChatSigningPlan::command_digest(&self) -> radroots_domain::identifier::CommandDigest
+pub const fn radroots_protocol::chat::ChatSigningPlan::created_at(&self) -> radroots_domain::context::UnixSeconds
+pub const fn radroots_protocol::chat::ChatSigningPlan::digest(&self) -> &[u8; 32]
+pub const fn radroots_protocol::chat::ChatSigningPlan::message_id(&self) -> radroots_domain::identifier::MessageId
+pub fn radroots_protocol::chat::ChatSigningPlan::new(&radroots_protocol::command::CapturedChatCommand, radroots_domain::context::UnixSeconds, alloc::vec::Vec<radroots_protocol::chat::ChatSeal>, alloc::vec::Vec<radroots_protocol::chat::CapturedDmRoute>, radroots_protocol::chat::ChatReplay) -> core::result::Result<Self, radroots_protocol::nip01::WireError>
+pub const fn radroots_protocol::chat::ChatSigningPlan::operation_id(&self) -> radroots_domain::identifier::OperationId
+pub fn radroots_protocol::chat::ChatSigningPlan::parse(&radroots_protocol::command::CapturedChatCommand, &[u8]) -> core::result::Result<Self, radroots_protocol::nip01::WireError>
+pub fn radroots_protocol::chat::ChatSigningPlan::protected_wire(&self) -> &[u8]
+pub const fn radroots_protocol::chat::ChatSigningPlan::replay(&self) -> radroots_protocol::chat::ChatReplay
+pub fn radroots_protocol::chat::ChatSigningPlan::routes(&self) -> &[radroots_protocol::chat::CapturedDmRoute]
+pub fn radroots_protocol::chat::ChatSigningPlan::seals(&self) -> &[radroots_protocol::chat::ChatSeal]
+impl core::fmt::Debug for radroots_protocol::chat::ChatSigningPlan
+pub fn radroots_protocol::chat::ChatSigningPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub struct radroots_protocol::chat::DmRelayAdvertisement
+impl radroots_protocol::chat::DmRelayAdvertisement
+pub fn radroots_protocol::chat::DmRelayAdvertisement::advertised_relays(&self) -> &[alloc::boxed::Box<str>]
+pub const fn radroots_protocol::chat::DmRelayAdvertisement::created_at(&self) -> radroots_domain::context::UnixSeconds
+pub fn radroots_protocol::chat::DmRelayAdvertisement::from_tags(radroots_identity::key::PublicKey, radroots_domain::context::UnixSeconds, &[alloc::vec::Vec<alloc::string::String>]) -> core::result::Result<Self, radroots_protocol::nip01::WireError>
+pub const fn radroots_protocol::chat::DmRelayAdvertisement::participant(&self) -> radroots_identity::key::PublicKey
+impl core::fmt::Debug for radroots_protocol::chat::DmRelayAdvertisement
+pub fn radroots_protocol::chat::DmRelayAdvertisement::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub const radroots_protocol::chat::PLAN_MAX_BYTES: usize
pub const radroots_protocol::chat::RUMOR_MAX_BYTES: usize
pub const radroots_protocol::chat::SIGNED_MAX_BYTES: usize
pub fn radroots_protocol::chat::nip44_v2_payload_len(usize) -> core::result::Result<usize, radroots_protocol::nip01::WireError>
diff --git a/contracts/api_baselines/radroots_signing.txt b/contracts/api_baselines/radroots_signing.txt
@@ -203,6 +203,15 @@ pub fn radroots_signing::issuance::SigningOutcome::into_parts(self) -> (radroots
pub const fn radroots_signing::issuance::SigningOutcome::kind(&self) -> &radroots_signing::issuance::OutcomeKind
pub const fn radroots_signing::issuance::SigningOutcome::not_dispatched(radroots_signing::issuance::IntentBinding, radroots_signing::provider::ProviderError) -> Self
pub const fn radroots_signing::issuance::SigningOutcome::unknown(radroots_signing::issuance::IntentBinding, radroots_signing::provider::ProviderError) -> Self
+pub struct radroots_signing::issuance::VerifiedDmRelayAdvertisement
+impl radroots_signing::issuance::VerifiedDmRelayAdvertisement
+pub const fn radroots_signing::issuance::VerifiedDmRelayAdvertisement::advertisement(&self) -> &radroots_protocol::chat::routes::DmRelayAdvertisement
+pub fn radroots_signing::issuance::VerifiedDmRelayAdvertisement::capture_route(&self, &[alloc::string::String]) -> core::result::Result<radroots_protocol::chat::routes::CapturedDmRoute, radroots_signing::provider::ProviderError>
+pub const fn radroots_signing::issuance::VerifiedDmRelayAdvertisement::event_id(&self) -> radroots_domain::identifier::EnvelopeEventId
+pub fn radroots_signing::issuance::VerifiedDmRelayAdvertisement::raw_json(&self) -> &str
+pub fn radroots_signing::issuance::VerifiedDmRelayAdvertisement::verify(&str, radroots_identity::key::PublicKey) -> core::result::Result<Self, radroots_signing::provider::ProviderError>
+impl core::fmt::Debug for radroots_signing::issuance::VerifiedDmRelayAdvertisement
+pub fn radroots_signing::issuance::VerifiedDmRelayAdvertisement::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const radroots_signing::issuance::MAX_EVENT_UNIX_SECONDS: u64
pub const radroots_signing::issuance::SIGNED_EVENT_MAX_BYTES: usize
pub mod radroots_signing::provider
diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt
@@ -757,6 +757,7 @@ pub fn radroots_storage::memory::MemoryStorage::transition_backup(&self, radroot
pub fn radroots_storage::memory::MemoryStorage::transition_restore(&self, radroots_storage::backup::BackupId, radroots_storage::backup::ReliabilityRevision, radroots_storage::backup::RestoreTransition, u64) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::backup::RestoreOperation, radroots_storage::Error>>
pub fn radroots_storage::memory::MemoryStorage::verify_backup(&self, radroots_storage::backup::BackupPlan, radroots_storage::backup::BackupManifest) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::backup::BackupCapabilityError>>
pub mod radroots_storage::command
+pub use radroots_storage::command::ChatSigningPlan
pub enum radroots_storage::command::AdmissionOutcome
pub radroots_storage::command::AdmissionOutcome::Committed(radroots_storage::command::PreparedOperation)
pub radroots_storage::command::AdmissionOutcome::Unknown(radroots_storage::command::CommitAttempt)
@@ -779,6 +780,11 @@ pub fn radroots_storage::command::OperationError::from(radroots_storage::workspa
impl core::error::Error for radroots_storage::command::OperationError
impl core::fmt::Display for radroots_storage::command::OperationError
pub fn radroots_storage::command::OperationError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub enum radroots_storage::command::PlanBindingOutcome
+pub radroots_storage::command::PlanBindingOutcome::Committed(radroots_storage::command::BoundSigningPlan)
+pub radroots_storage::command::PlanBindingOutcome::Unknown(radroots_storage::command::CommitAttempt)
+impl core::fmt::Debug for radroots_storage::command::PlanBindingOutcome
+pub fn radroots_storage::command::PlanBindingOutcome::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_storage::command::AdmissionRequest
impl radroots_storage::command::AdmissionRequest
pub const fn radroots_storage::command::AdmissionRequest::binding(&self) -> &radroots_storage::workspace::WorkspaceBinding
@@ -788,6 +794,16 @@ pub fn radroots_storage::command::AdmissionRequest::into_parts(self) -> (radroot
pub fn radroots_storage::command::AdmissionRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_protocol::command::CapturedChatCommand) -> core::result::Result<Self, radroots_storage::command::OperationError>
impl core::fmt::Debug for radroots_storage::command::AdmissionRequest
pub fn radroots_storage::command::AdmissionRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub struct radroots_storage::command::BoundSigningPlan
+impl radroots_storage::command::BoundSigningPlan
+pub const fn radroots_storage::command::BoundSigningPlan::bound_at(&self) -> radroots_domain::context::UnixSeconds
+pub fn radroots_storage::command::BoundSigningPlan::from_committed_store(radroots_storage::command::PreparedOperation, radroots_protocol::chat::plan::ChatSigningPlan, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError>
+pub fn radroots_storage::command::BoundSigningPlan::into_parts(self) -> (radroots_storage::command::PreparedOperation, radroots_protocol::chat::plan::ChatSigningPlan)
+pub const fn radroots_storage::command::BoundSigningPlan::plan(&self) -> &radroots_protocol::chat::plan::ChatSigningPlan
+pub const fn radroots_storage::command::BoundSigningPlan::prepared(&self) -> &radroots_storage::command::PreparedOperation
+pub const fn radroots_storage::command::BoundSigningPlan::transaction_id(&self) -> radroots_domain::identifier::TransactionId
+impl core::fmt::Debug for radroots_storage::command::BoundSigningPlan
+pub fn radroots_storage::command::BoundSigningPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_storage::command::CommitAttempt
impl radroots_storage::command::CommitAttempt
pub const fn radroots_storage::command::CommitAttempt::command_digest(self) -> radroots_domain::identifier::CommandDigest
@@ -807,7 +823,9 @@ 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 trait radroots_storage::command::OperationJournal: radroots_storage::workspace::WorkspaceStore
pub fn radroots_storage::command::OperationJournal::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError>>
+pub fn radroots_storage::command::OperationJournal::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError>>
pub fn radroots_storage::command::OperationJournal::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>>
+pub fn radroots_storage::command::OperationJournal::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>>
pub mod radroots_storage::event
pub use radroots_storage::event::BoxFuture
pub use radroots_storage::event::EventId
diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt
@@ -381,7 +381,9 @@ impl core::fmt::Debug for radroots_storage_sqlite::workspace::NativeWorkspace
pub fn radroots_storage_sqlite::workspace::NativeWorkspace::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl radroots_storage::command::OperationJournal for radroots_storage_sqlite::workspace::NativeWorkspace
pub fn radroots_storage_sqlite::workspace::NativeWorkspace::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError>>
+pub fn radroots_storage_sqlite::workspace::NativeWorkspace::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError>>
pub fn radroots_storage_sqlite::workspace::NativeWorkspace::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>>
+pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>>
impl radroots_storage::workspace::WorkspaceStore for radroots_storage_sqlite::workspace::NativeWorkspace
pub fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError>>
pub fn radroots_storage_sqlite::workspace::NativeWorkspace::close_workspace(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::workspace::WorkspaceError>>
diff --git a/contracts/protocol/chat.v1.json b/contracts/protocol/chat.v1.json
@@ -73,7 +73,33 @@
"59.md"
]
},
- "remaining": "Actual native T1 commit of complete plans, authenticated current access and advertised routes, issuance attempt ownership, obtained evidence capture, install/outbox, exact per-recipient wrapping/delivery, full receipts, browser/bindings and final acceptance",
+ "remaining": "Complete owned native execution route/capability approval, signer attempt ownership, obtained evidence capture, install/outbox, exact per-recipient wrapping/delivery, full receipts, browser/bindings and final acceptance",
"structured_commerce_authoring_enabled": false,
- "package_publication_authorized": false
+ "package_publication_authorized": false,
+ "recipient_dm_routes": {
+ "source_kind": 10050,
+ "source_max_bytes": 65536,
+ "source_verifier": "radroots_signing::issuance::VerifiedDmRelayAdvertisement",
+ "selected_uri_max_bytes": 2048,
+ "combined_session_max_relays": 16,
+ "empty_advertisement": "Explicit unavailable DM information; no fallback",
+ "data_constructor_authority": "No signature, source identity, configured/available transport, grant or consent proof; execution revalidates before dispatch"
+ },
+ "native_signing_plan": {
+ "state": "protected_native_transaction_component_implemented",
+ "codec_owner": "radroots_protocol::chat::ChatSigningPlan",
+ "complete_max_bytes": 393216,
+ "recipient_set": "Exactly sorted unique author and peer; no partial set",
+ "retained": "Original command and message commitments, exact per-recipient seal author/kind/time/tags/content/event ID/purpose, original signed route-source bytes, selected targets and explicit replay declaration",
+ "retained_memory": "Canonical buffer bounded before allocation; decoded recipient collections use boxed slices, not caller spare vector capacity",
+ "protected_data_part_max_bytes": 16384,
+ "max_data_parts": 24,
+ "protected_total_max_bytes": 2097152,
+ "native_workspace_schema": 4,
+ "predecessors": "Preserve and refuse; no inferred timestamps or automatic namespace rewrite",
+ "queue": "32 slots plus conservative queued and in-flight reservations under 4194304 bytes",
+ "transaction": "Current protected grant, original preparation, all indexed facts and fixed first-issue window rechecked under BEGIN IMMEDIATE; crypto work before transaction",
+ "completion": "Confirmed commit, known rollback and original anchored unknown are distinct; accepted owner work survives observer loss",
+ "remaining": "Execution route/capability approval, attempt ownership and S/T2/D, complete receipts, supported consumer adoption, browser/binding runtime and final acceptance"
+ }
}
diff --git a/crates/protocol/README.md b/crates/protocol/README.md
@@ -20,6 +20,8 @@ numbers embedded in wire and schema contracts.
| `radrootsd::transport_publish::v5` | daemon transport-publish request, job, outcome, and capability DTOs |
| `schema` | schema IDs, module generations, descriptors, and aggregate registries |
| `command` (`commands` feature) | bounded closed v1 inquiry/reply data codec and exact command/approval-intent hashes |
+| `nip01` (`nip01` feature) | exact bounded canonical preimages, IDs and complete-event sizes |
+| `chat` (`chat` feature) | bounded kind-14/13 data, complete immutable signing-plan codec and observed DM route descriptors |
Versioned DTOs live below an explicit generation module. The command codec
implements its fixed v1 profile without exposing automatic serialization of
@@ -35,6 +37,8 @@ they use.
| `std` | yes | implements standard-library error integration and enables `serde?/std` |
| `serde` | yes | derives serialization and deserialization for wire-contract types |
| `commands` | no | enables the portable closed chat codec, domain values, SHA-256 and zeroizing private command buffers |
+| `nip01` | no | enables pure exact NIP-01 serialization and complete byte counting |
+| `chat` | no | enables commands, NIP-01 and the bounded known-kind chat/plan data profile |
Disabling default features leaves the catalog and structural validation APIs
available with `alloc` only. Enable `serde` without `std` for portable encoded
@@ -90,3 +94,20 @@ The package charter is the
[Release V1 specification](../../contracts/crates/release_v1/radroots_crates_release_v1.toml).
The reviewed Rust surface is recorded in the
[public API baseline](../../contracts/api_baselines/radroots_protocol.txt).
+
+## Complete private signing-plan data
+
+`chat::ChatSigningPlan` retains the exact sorted unique peer/self recipient set,
+seal author/kind/time/empty tags/content/event ID/purpose, original signed DM
+route-source bytes, selected targets, logical message ID, command commitment and
+provider replay declaration. The closed binary profile is capped at 384 KiB;
+its decoded recipient collections discard caller spare capacity. Original route
+sources are each at most 64 KiB, selected URIs at most 2048 bytes, and the
+combined session selection at most sixteen distinct relays.
+
+Construction and decoding validate descriptors only. They verify no signature,
+MAC, grant, consent, route readiness or provider capability and create no durable
+commit. The executor must verify source evidence, approved targets and current
+access, then retain this complete plan through its qualified protected journal
+before any business signing invocation. A stored replay declaration alone never
+permits uncertain reissue.
diff --git a/crates/protocol/src/chat.rs b/crates/protocol/src/chat.rs
@@ -10,7 +10,7 @@ use alloc::{
vec::Vec,
};
use core::fmt;
-use radroots_domain::{MessageId, PublicKey, UnixSeconds};
+use radroots_domain::{CommandDigest, MessageId, OperationId, PublicKey, UnixSeconds};
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;
@@ -21,6 +21,11 @@ pub const SIGNED_MAX_BYTES: usize = 65_536;
const MAX_TIME: u64 = 253_402_300_799;
const RANDOMIZED_PAST_SECONDS: u64 = 172_800;
+mod plan;
+pub use plan::{ChatReplay, ChatSigningPlan, PLAN_MAX_BYTES};
+mod routes;
+pub use routes::{CapturedDmRoute, DmRelayAdvertisement};
+
fn payload_shape(plaintext_bytes: usize) -> Result<(usize, usize), WireError> {
// The qualified small-payload profile uses the two-byte length prefix.
// This does not claim support for the newer extended NIP-44 prefix.
@@ -111,6 +116,8 @@ impl ChatBudget {
/// Selectors and codec output authenticate no parent, source or participant.
pub struct ChatRumor {
event: UnsignedEvent,
+ operation_id: OperationId,
+ command_digest: CommandDigest,
author: PublicKey,
created_at: UnixSeconds,
recipients: Vec<PublicKey>,
@@ -166,6 +173,8 @@ impl ChatRumor {
recipients.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
Ok(Self {
event,
+ operation_id: command.context().operation_id(),
+ command_digest: command.digest(),
author,
created_at,
recipients,
@@ -236,6 +245,9 @@ fn ciphertext_shape(value: &str, plaintext_bytes: usize) -> Result<(), WireError
/// Bounded exact kind-13 data for one recipient, with no signature/authority.
pub struct ChatSeal {
+ operation_id: OperationId,
+ command_digest: CommandDigest,
+ message_id: MessageId,
author: PublicKey,
recipient: PublicKey,
created_at: UnixSeconds,
@@ -271,6 +283,9 @@ impl ChatSeal {
let preimage = crate::nip01::bounded_preimage(&fields, SIGNED_MAX_BYTES)?;
let event_id = Sha256::digest(preimage.as_bytes()).into();
Ok(Self {
+ operation_id: rumor.operation_id,
+ command_digest: rumor.command_digest,
+ message_id: rumor.message_id(),
author: rumor.author,
recipient,
created_at,
@@ -288,6 +303,19 @@ impl ChatSeal {
content: &self.ciphertext,
}
}
+ /// Returns the originating captured operation descriptor, without authority.
+ pub const fn operation_id(&self) -> OperationId {
+ self.operation_id
+ }
+ /// Returns the originating semantic command commitment.
+ pub const fn command_digest(&self) -> CommandDigest {
+ self.command_digest
+ }
+ /// Returns the exact unsigned rumor this seal was constructed to carry.
+ /// The qualified encryption provider must separately bind its plaintext.
+ pub const fn message_id(&self) -> MessageId {
+ self.message_id
+ }
/// Returns the exact recipient, separate from public seal tags.
pub const fn recipient(&self) -> PublicKey {
self.recipient
diff --git a/crates/protocol/src/chat/plan.rs b/crates/protocol/src/chat/plan.rs
@@ -0,0 +1,277 @@
+//! Immutable complete known-kind signing data, without execution authority.
+use super::{CapturedDmRoute, ChatRumor, ChatSeal};
+use crate::{command::CapturedChatCommand, nip01::WireError};
+use alloc::{boxed::Box, collections::BTreeSet, string::String, vec::Vec};
+use core::fmt;
+use radroots_domain::{
+ CommandDigest, EnvelopeEventId, MessageId, OperationId, PublicKey, UnixSeconds,
+};
+use sha2::{Digest, Sha256};
+use zeroize::Zeroizing;
+
+/// Complete protected plan bound, including original signed route sources.
+pub const PLAN_MAX_BYTES: usize = 384 * 1024;
+const MAGIC: &[u8] = b"radroots.chat.signing_plan.v1\0";
+
+/// Captured provider declaration. Data never establishes a provider guarantee
+/// or permits reissue after an uncertain effect; execution revalidates support.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ChatReplay {
+ NonReplayable,
+ LocalReplaySafe,
+ ExactReplayByRequestId,
+}
+
+/// Complete sorted recipient set, exact seal preimages and retained route
+/// observations. Construction verifies structural provenance only: encryption
+/// authentication, signed route verification, network approval, provider
+/// capability and protected T1 commit remain execution obligations.
+pub struct ChatSigningPlan {
+ operation_id: OperationId,
+ command_digest: CommandDigest,
+ message_id: MessageId,
+ created_at: UnixSeconds,
+ replay: ChatReplay,
+ seals: Box<[ChatSeal]>,
+ routes: Box<[CapturedDmRoute]>,
+ wire: Zeroizing<Vec<u8>>,
+ digest: [u8; 32],
+}
+impl ChatSigningPlan {
+ /// Requires exactly one seal and observed route per sorted unique recipient.
+ /// Combined selected targets cannot exceed the sixteen-relay session cap.
+ pub fn new(
+ command: &CapturedChatCommand,
+ created_at: UnixSeconds,
+ seals: Vec<ChatSeal>,
+ routes: Vec<CapturedDmRoute>,
+ replay: ChatReplay,
+ ) -> Result<Self, WireError> {
+ let rumor = ChatRumor::from_command(command, created_at)?;
+ if seals.len() != rumor.recipients().len() || routes.len() != seals.len() {
+ return Err(WireError::InvalidInput);
+ }
+ let mut targets = BTreeSet::new();
+ for ((seal, route), recipient) in seals.iter().zip(&routes).zip(rumor.recipients()) {
+ if seal.operation_id() != command.context().operation_id()
+ || seal.command_digest() != command.digest()
+ || seal.message_id() != rumor.message_id()
+ || seal.recipient() != *recipient
+ || route.participant() != *recipient
+ {
+ return Err(WireError::InvalidInput);
+ }
+ for target in route.selected_relays() {
+ targets.insert(target.as_ref());
+ }
+ }
+ if targets.len() > 16 {
+ return Err(WireError::LimitExceeded);
+ }
+ // All variable fields are already bounded. Count the complete binary
+ // representation before allocating its sole retained canonical buffer.
+ let mut length = MAGIC.len() + 32 * 3 + 8 + 2;
+ for (seal, route) in seals.iter().zip(&routes) {
+ length += 32
+ + 32
+ + 4
+ + 1
+ + 1
+ + 32
+ + 8
+ + 4
+ + seal.fields().content.len()
+ + 32
+ + 4
+ + route.raw_json().len()
+ + 1;
+ for target in route.selected_relays() {
+ length += 4 + target.len();
+ }
+ }
+ if length > PLAN_MAX_BYTES {
+ return Err(WireError::LimitExceeded);
+ }
+ let mut wire = Zeroizing::new(Vec::with_capacity(length));
+ wire.extend_from_slice(MAGIC);
+ wire.extend_from_slice(command.context().operation_id().as_bytes());
+ wire.extend_from_slice(command.digest().as_bytes());
+ wire.extend_from_slice(rumor.message_id().as_bytes());
+ wire.extend_from_slice(&created_at.get().to_be_bytes());
+ wire.push(match replay {
+ ChatReplay::NonReplayable => 0,
+ ChatReplay::LocalReplaySafe => 1,
+ ChatReplay::ExactReplayByRequestId => 2,
+ });
+ wire.push(seals.len() as u8);
+ for (seal, route) in seals.iter().zip(&routes) {
+ wire.extend_from_slice(seal.recipient().as_bytes());
+ wire.extend_from_slice(seal.fields().author.as_bytes());
+ wire.extend_from_slice(&13u32.to_be_bytes());
+ wire.push(0); // Exact empty tag set.
+ wire.push(1); // Exact BusinessSeal role.
+ wire.extend_from_slice(&seal.event_id());
+ wire.extend_from_slice(&seal.fields().created_at.to_be_bytes());
+ put(&mut wire, seal.fields().content.as_bytes());
+ wire.extend_from_slice(route.source_id().as_bytes());
+ put(&mut wire, route.raw_json().as_bytes());
+ wire.push(route.selected_relays().len() as u8);
+ for target in route.selected_relays() {
+ put(&mut wire, target.as_bytes());
+ }
+ }
+ let digest = Sha256::digest(wire.as_slice()).into();
+ Ok(Self {
+ operation_id: command.context().operation_id(),
+ command_digest: command.digest(),
+ message_id: rumor.message_id(),
+ created_at,
+ replay,
+ seals: seals.into_boxed_slice(),
+ routes: routes.into_boxed_slice(),
+ wire,
+ digest,
+ })
+ }
+ /// Decodes only the bounded canonical profile and reconstructs every seal
+ /// from the original command. It supplies no cryptographic route proof.
+ pub fn parse(command: &CapturedChatCommand, wire: &[u8]) -> Result<Self, WireError> {
+ if wire.len() > PLAN_MAX_BYTES {
+ return Err(WireError::LimitExceeded);
+ }
+ let mut input = Input(wire);
+ if input.take(MAGIC.len())? != MAGIC
+ || input.take(32)? != command.context().operation_id().as_bytes()
+ || input.take(32)? != command.digest().as_bytes()
+ {
+ return Err(WireError::InvalidInput);
+ }
+ let message_id = MessageId::from_bytes(input.array()?);
+ let time = UnixSeconds::new(u64::from_be_bytes(input.array()?))
+ .map_err(|_| WireError::InvalidInput)?;
+ let rumor = ChatRumor::from_command(command, time)?;
+ if message_id != rumor.message_id() {
+ return Err(WireError::InvalidInput);
+ }
+ let replay = match input.byte()? {
+ 0 => ChatReplay::NonReplayable,
+ 1 => ChatReplay::LocalReplaySafe,
+ 2 => ChatReplay::ExactReplayByRequestId,
+ _ => return Err(WireError::InvalidInput),
+ };
+ if usize::from(input.byte()?) != rumor.recipients().len() {
+ return Err(WireError::InvalidInput);
+ }
+ let mut seals = Vec::new();
+ let mut routes = Vec::new();
+ for recipient in rumor.recipients() {
+ let described =
+ PublicKey::from_bytes(input.array()?).map_err(|_| WireError::InvalidInput)?;
+ if described != *recipient {
+ return Err(WireError::InvalidInput);
+ }
+ let author: [u8; 32] = input.array()?;
+ let kind = u32::from_be_bytes(input.array()?);
+ let tags = input.byte()?;
+ let purpose = input.byte()?;
+ let expected_id: [u8; 32] = input.array()?;
+ if author != *rumor.author().as_bytes() || kind != 13 || tags != 0 || purpose != 1 {
+ return Err(WireError::InvalidInput);
+ }
+ let seal_time = UnixSeconds::new(u64::from_be_bytes(input.array()?))
+ .map_err(|_| WireError::InvalidInput)?;
+ let ciphertext = input.text(super::SIGNED_MAX_BYTES)?;
+ let seal = ChatSeal::new(&rumor, *recipient, seal_time, ciphertext)?;
+ if seal.event_id() != expected_id {
+ return Err(WireError::InvalidInput);
+ }
+ seals.push(seal);
+ let source_id = EnvelopeEventId::from_bytes(input.array()?);
+ let raw_json = input.text(super::SIGNED_MAX_BYTES)?;
+ let count = usize::from(input.byte()?);
+ if count == 0 || count > 16 {
+ return Err(WireError::InvalidInput);
+ }
+ let mut selected = Vec::with_capacity(count);
+ for _ in 0..count {
+ selected.push(String::from(input.text(2048)?));
+ }
+ routes.push(CapturedDmRoute::from_observed_descriptor(
+ *recipient, source_id, raw_json, &selected,
+ )?);
+ }
+ if !input.0.is_empty() {
+ return Err(WireError::InvalidInput);
+ }
+ let plan = Self::new(command, time, seals, routes, replay)?;
+ if plan.protected_wire() != wire {
+ return Err(WireError::InvalidInput);
+ }
+ Ok(plan)
+ }
+ pub const fn operation_id(&self) -> OperationId {
+ self.operation_id
+ }
+ pub const fn command_digest(&self) -> CommandDigest {
+ self.command_digest
+ }
+ pub const fn message_id(&self) -> MessageId {
+ self.message_id
+ }
+ pub const fn created_at(&self) -> UnixSeconds {
+ self.created_at
+ }
+ pub const fn replay(&self) -> ChatReplay {
+ self.replay
+ }
+ pub fn seals(&self) -> &[ChatSeal] {
+ &self.seals
+ }
+ pub fn routes(&self) -> &[CapturedDmRoute] {
+ &self.routes
+ }
+ /// Borrows exact versioned bytes requiring protected at-rest handling.
+ pub fn protected_wire(&self) -> &[u8] {
+ &self.wire
+ }
+ /// Commits every exact preimage, route source, target and replay descriptor.
+ pub const fn digest(&self) -> &[u8; 32] {
+ &self.digest
+ }
+}
+impl fmt::Debug for ChatSigningPlan {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("ChatSigningPlan(<redacted>)")
+ }
+}
+fn put(out: &mut Vec<u8>, value: &[u8]) {
+ // Every caller has bounded this field far below u32::MAX.
+ out.extend_from_slice(&(value.len() as u32).to_be_bytes());
+ out.extend_from_slice(value);
+}
+struct Input<'a>(&'a [u8]);
+impl<'a> Input<'a> {
+ fn take(&mut self, size: usize) -> Result<&'a [u8], WireError> {
+ let (value, rest) = self
+ .0
+ .split_at_checked(size)
+ .ok_or(WireError::InvalidInput)?;
+ self.0 = rest;
+ Ok(value)
+ }
+ fn array<const N: usize>(&mut self) -> Result<[u8; N], WireError> {
+ self.take(N)?
+ .try_into()
+ .map_err(|_| WireError::InvalidInput)
+ }
+ fn byte(&mut self) -> Result<u8, WireError> {
+ Ok(self.array::<1>()?[0])
+ }
+ fn text(&mut self, max: usize) -> Result<&'a str, WireError> {
+ let size = u32::from_be_bytes(self.array()?) as usize;
+ if size > max {
+ return Err(WireError::LimitExceeded);
+ }
+ core::str::from_utf8(self.take(size)?).map_err(|_| WireError::InvalidInput)
+ }
+}
diff --git a/crates/protocol/src/chat/routes.rs b/crates/protocol/src/chat/routes.rs
@@ -0,0 +1,160 @@
+use crate::nip01::{EventFields, WireError};
+use alloc::{boxed::Box, collections::BTreeSet, string::String, vec::Vec};
+use core::fmt;
+use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds};
+
+const MAX_TAGS: usize = 1024;
+const MAX_URI_BYTES: usize = 2048;
+
+/// Bounded kind-10050 tag projection. Construction authenticates no signature,
+/// route permission, transport availability or participant workspace authority.
+/// The advertised list is distinct from the sixteen-relay active-session cap.
+pub struct DmRelayAdvertisement {
+ participant: PublicKey,
+ created_at: UnixSeconds,
+ relays: Vec<Box<str>>,
+}
+impl DmRelayAdvertisement {
+ /// Projects exact relay tags after bounding their complete serialized size.
+ /// Additional signed tags are preserved by the caller's original event.
+ /// An empty list is explicit unavailable DM information, never a fallback.
+ pub fn from_tags(
+ participant: PublicKey,
+ created_at: UnixSeconds,
+ tags: &[Vec<String>],
+ ) -> Result<Self, WireError> {
+ if tags.len() > MAX_TAGS {
+ return Err(WireError::LimitExceeded);
+ }
+ let fields = EventFields {
+ author: participant,
+ created_at: created_at.get(),
+ kind: 10050,
+ tags,
+ content: "",
+ };
+ crate::nip01::signed_json_len(&fields, super::SIGNED_MAX_BYTES)?;
+ let mut relays = Vec::new();
+ let mut seen = BTreeSet::new();
+ for tag in tags {
+ if tag.first().is_none_or(|value| value != "relay") {
+ continue;
+ }
+ if tag.len() != 2 {
+ return Err(WireError::InvalidInput);
+ }
+ let value = tag[1].as_str();
+ if value.len() > MAX_URI_BYTES {
+ return Err(WireError::LimitExceeded);
+ }
+ if !(value.starts_with("wss://") || value.starts_with("ws://"))
+ || value.trim() != value
+ || value.chars().any(char::is_control)
+ {
+ return Err(WireError::InvalidInput);
+ }
+ if seen.insert(value) {
+ relays.push(Box::from(value));
+ }
+ }
+ Ok(Self {
+ participant,
+ created_at,
+ relays,
+ })
+ }
+ /// Returns the described participant, without proving ownership.
+ pub const fn participant(&self) -> PublicKey {
+ self.participant
+ }
+ /// Returns the author's claimed event time, not a trusted clock observation.
+ pub const fn created_at(&self) -> UnixSeconds {
+ self.created_at
+ }
+ /// Borrows unique advertised strings in their original preference order.
+ /// Actual URI syntax/network policy and session limits remain transport-owned.
+ pub fn advertised_relays(&self) -> &[Box<str>] {
+ &self.relays
+ }
+}
+impl fmt::Debug for DmRelayAdvertisement {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("DmRelayAdvertisement(<redacted>)")
+ }
+}
+
+/// Immutable captured route descriptors and original source bytes. This data
+/// constructor verifies neither signature, source identity, target approval nor
+/// transport availability. Execution must authenticate the source and enforce
+/// its exact selected subset before dispatch, including after store recovery.
+pub struct CapturedDmRoute {
+ participant: PublicKey,
+ source_id: EnvelopeEventId,
+ raw_json: Box<str>,
+ selected: Box<[Box<str>]>,
+}
+impl CapturedDmRoute {
+ /// Bounds the original JSON and complete selected strings before copying.
+ /// Session composition separately enforces its combined relay limit.
+ pub fn from_observed_descriptor(
+ participant: PublicKey,
+ source_id: EnvelopeEventId,
+ raw_json: &str,
+ selected: &[String],
+ ) -> Result<Self, WireError> {
+ if raw_json.len() > super::SIGNED_MAX_BYTES || selected.len() > 16 {
+ return Err(WireError::LimitExceeded);
+ }
+ if selected.is_empty() {
+ return Err(WireError::InvalidInput);
+ }
+ let root: &serde_json::value::RawValue =
+ serde_json::from_str(raw_json).map_err(|_| WireError::InvalidInput)?;
+ if !root.get().starts_with('{') {
+ return Err(WireError::InvalidInput);
+ }
+ let mut seen = BTreeSet::new();
+ for value in selected {
+ if value.len() > MAX_URI_BYTES {
+ return Err(WireError::LimitExceeded);
+ }
+ if !(value.starts_with("wss://") || value.starts_with("ws://"))
+ || value.trim() != value
+ || value.chars().any(char::is_control)
+ || !seen.insert(value.as_str())
+ {
+ return Err(WireError::InvalidInput);
+ }
+ }
+ Ok(Self {
+ participant,
+ source_id,
+ raw_json: Box::from(raw_json),
+ selected: selected
+ .iter()
+ .map(|value| Box::from(value.as_str()))
+ .collect(),
+ })
+ }
+ /// Returns the described recipient.
+ pub const fn participant(&self) -> PublicKey {
+ self.participant
+ }
+ /// Returns the reported source event identity; this getter supplies no proof.
+ pub const fn source_id(&self) -> EnvelopeEventId {
+ self.source_id
+ }
+ /// Borrows exact original bytes, including insignificant whitespace.
+ pub fn raw_json(&self) -> &str {
+ &self.raw_json
+ }
+ /// Borrows the frozen selected strings in preference order.
+ pub fn selected_relays(&self) -> &[Box<str>] {
+ &self.selected
+ }
+}
+impl fmt::Debug for CapturedDmRoute {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("CapturedDmRoute(<redacted>)")
+ }
+}
diff --git a/crates/protocol/tests/chat_wire.rs b/crates/protocol/tests/chat_wire.rs
@@ -241,3 +241,325 @@ fn rumor_and_seal_refuse_invalid_time_recipient_nested_size_and_ciphertext_shape
let bounded = CapturedChatCommand::parse(&serde_json::to_vec(&wire).unwrap()).unwrap();
assert!(ChatRumor::from_command(&bounded, time(1_700_000_000)).is_ok());
}
+
+fn plan_parts(row: &Value, command: &CapturedChatCommand) -> (Vec<ChatSeal>, Vec<CapturedDmRoute>) {
+ let rumor = ChatRumor::from_command(command, time(1_700_000_000)).unwrap();
+ let mut seals = Vec::new();
+ let mut routes = Vec::new();
+ for recipient in rumor.recipients() {
+ seals.push(
+ ChatSeal::new(
+ &rumor,
+ *recipient,
+ time(1_699_999_990),
+ text(row, "structural_ciphertext"),
+ )
+ .unwrap(),
+ );
+ routes.push(
+ CapturedDmRoute::from_observed_descriptor(
+ *recipient,
+ radroots_domain::EnvelopeEventId::from_bytes([9; 32]),
+ " { \"unverified\": true } ",
+ &["wss://route.example/".into()],
+ )
+ .unwrap(),
+ );
+ }
+ (seals, routes)
+}
+#[test]
+fn complete_plan_roundtrip_preserves_all_exact_descriptors_and_refuses_truncation_substitution() {
+ for row in vectors()["vectors"].as_array().unwrap() {
+ let command = CapturedChatCommand::parse(text(row, "wire").as_bytes()).unwrap();
+ for replay in [
+ ChatReplay::NonReplayable,
+ ChatReplay::LocalReplaySafe,
+ ChatReplay::ExactReplayByRequestId,
+ ] {
+ let (seals, routes) = plan_parts(row, &command);
+ let plan =
+ ChatSigningPlan::new(&command, time(1_700_000_000), seals, routes, replay).unwrap();
+ assert_eq!(plan.operation_id(), command.context().operation_id());
+ assert_eq!(plan.command_digest(), command.digest());
+ assert_eq!(plan.message_id().to_string(), text(row, "message_id"));
+ assert_eq!(plan.created_at(), time(1_700_000_000));
+ assert_eq!(plan.replay(), replay);
+ let recovered = ChatSigningPlan::parse(&command, plan.protected_wire()).unwrap();
+ assert_eq!(recovered.protected_wire(), plan.protected_wire());
+ assert_eq!(recovered.digest(), plan.digest());
+ assert_eq!(recovered.seals().len(), recovered.routes().len());
+ assert!(!format!("{plan:?}").contains("route.example"));
+ for size in 0..plan.protected_wire().len() {
+ assert!(
+ ChatSigningPlan::parse(&command, &plan.protected_wire()[..size]).is_err(),
+ "truncated at {size}"
+ );
+ }
+ let mut changed = plan.protected_wire().to_vec();
+ changed.push(0);
+ assert!(ChatSigningPlan::parse(&command, &changed).is_err());
+ // Prefix, original operation/digest/message and invalid replay code.
+ for offset in [0, 28, 60, 92, 132] {
+ let mut changed = plan.protected_wire().to_vec();
+ changed[offset] = 255;
+ assert!(
+ ChatSigningPlan::parse(&command, &changed).is_err(),
+ "offset {offset}"
+ );
+ }
+ }
+ let (mut seals, routes) = plan_parts(row, &command);
+ seals.pop();
+ assert!(
+ ChatSigningPlan::new(
+ &command,
+ time(1_700_000_000),
+ seals,
+ routes,
+ ChatReplay::NonReplayable
+ )
+ .is_err()
+ );
+ let (seals, mut routes) = plan_parts(row, &command);
+ routes.pop();
+ assert!(
+ ChatSigningPlan::new(
+ &command,
+ time(1_700_000_000),
+ seals,
+ routes,
+ ChatReplay::NonReplayable
+ )
+ .is_err()
+ );
+ if row["recipients"].as_array().unwrap().len() == 2 {
+ let (mut seals, routes) = plan_parts(row, &command);
+ seals.reverse();
+ assert!(
+ ChatSigningPlan::new(
+ &command,
+ time(1_700_000_000),
+ seals,
+ routes,
+ ChatReplay::NonReplayable
+ )
+ .is_err()
+ );
+ }
+ }
+ let data = vectors();
+ let command = CapturedChatCommand::parse(text(&data["vectors"][0], "wire").as_bytes()).unwrap();
+ assert!(matches!(
+ ChatSigningPlan::parse(&command, &vec![0; PLAN_MAX_BYTES + 1]),
+ Err(WireError::LimitExceeded)
+ ));
+}
+#[test]
+fn bounded_route_descriptors_refuse_invalid_shapes_before_copying_and_never_claim_verification() {
+ let data = vectors();
+ let command = CapturedChatCommand::parse(text(&data["vectors"][0], "wire").as_bytes()).unwrap();
+ let key = command.peer();
+ let source = radroots_domain::EnvelopeEventId::from_bytes([9; 32]);
+ for raw in ["", "[]", "false", "{", "null"] {
+ assert!(
+ CapturedDmRoute::from_observed_descriptor(
+ key,
+ source,
+ raw,
+ &["wss://route.example/".into()]
+ )
+ .is_err()
+ );
+ }
+ for selected in [
+ vec![],
+ vec!["https://wrong/".into()],
+ vec![" wss://wrong/".into()],
+ vec!["wss://wrong/\n".into()],
+ vec!["ws://same/".into(), "ws://same/".into()],
+ vec!["ws://same/".into(); 17],
+ vec![format!("wss://{}", "a".repeat(2048))],
+ ] {
+ assert!(CapturedDmRoute::from_observed_descriptor(key, source, "{}", &selected).is_err());
+ }
+ assert!(
+ CapturedDmRoute::from_observed_descriptor(
+ key,
+ source,
+ &"x".repeat(65537),
+ &["wss://route/".into()]
+ )
+ .is_err()
+ );
+ let tags = vec![
+ vec!["relay".into(), "ws://one/".into()],
+ vec!["relay".into(), "ws://one/".into()],
+ vec!["alt".into(), "not routing".into()],
+ ];
+ let projection = DmRelayAdvertisement::from_tags(key, time(0), &tags).unwrap();
+ assert_eq!(projection.advertised_relays().len(), 1);
+ assert_eq!(projection.participant(), key);
+ assert_eq!(projection.created_at(), time(0));
+ assert!(!format!("{projection:?}").contains("one/"));
+ for tags in [
+ vec![vec![]; 1025],
+ vec![vec!["relay".into()]],
+ vec![vec!["relay".into(), "https://wrong/".into()]],
+ vec![vec!["relay".into(), format!("wss://{}", "a".repeat(2048))]],
+ vec![vec!["alt".into(), "x".repeat(65536)]],
+ ] {
+ assert!(DmRelayAdvertisement::from_tags(key, time(0), &tags).is_err());
+ }
+}
+
+#[test]
+fn complete_plan_refuses_individual_provenance_field_and_combined_route_substitution() {
+ let data = vectors();
+ let row = &data["vectors"][0];
+ let command = CapturedChatCommand::parse(text(row, "wire").as_bytes()).unwrap();
+ let mut changed: Value = serde_json::from_slice(command.protected_wire()).unwrap();
+ changed["context"]["operation_id"] = "99".repeat(32).into();
+ let other_operation =
+ CapturedChatCommand::parse(&serde_json::to_vec(&changed).unwrap()).unwrap();
+ let (seals, routes) = plan_parts(row, &command);
+ assert!(
+ ChatSigningPlan::new(
+ &other_operation,
+ time(1_700_000_000),
+ seals,
+ routes,
+ ChatReplay::NonReplayable
+ )
+ .is_err()
+ );
+ changed = serde_json::from_slice(command.protected_wire()).unwrap();
+ changed["input"]["text"] = "same operation, different captured command".into();
+ let other_digest = CapturedChatCommand::parse(&serde_json::to_vec(&changed).unwrap()).unwrap();
+ let (seals, routes) = plan_parts(row, &command);
+ assert!(
+ ChatSigningPlan::new(
+ &other_digest,
+ time(1_700_000_000),
+ seals,
+ routes,
+ ChatReplay::NonReplayable
+ )
+ .is_err()
+ );
+ let (seals, routes) = plan_parts(row, &command);
+ assert!(
+ ChatSigningPlan::new(
+ &command,
+ time(1_700_000_001),
+ seals,
+ routes,
+ ChatReplay::NonReplayable
+ )
+ .is_err()
+ );
+ let (seals, mut routes) = plan_parts(row, &command);
+ routes.reverse();
+ assert!(
+ ChatSigningPlan::new(
+ &command,
+ time(1_700_000_000),
+ seals,
+ routes,
+ ChatReplay::NonReplayable
+ )
+ .is_err()
+ );
+ let (seals, routes) = plan_parts(row, &command);
+ let routes: Vec<_> = routes
+ .iter()
+ .enumerate()
+ .map(|(index, route)| {
+ CapturedDmRoute::from_observed_descriptor(
+ route.participant(),
+ route.source_id(),
+ route.raw_json(),
+ &(0..16)
+ .map(|n| format!("wss://route-{index}-{n}.example/"))
+ .collect::<Vec<_>>(),
+ )
+ .unwrap()
+ })
+ .collect();
+ assert!(matches!(
+ ChatSigningPlan::new(
+ &command,
+ time(1_700_000_000),
+ seals,
+ routes,
+ ChatReplay::NonReplayable
+ ),
+ Err(WireError::LimitExceeded)
+ ));
+ let (seals, routes) = plan_parts(row, &command);
+ let plan = ChatSigningPlan::new(
+ &command,
+ time(1_700_000_000),
+ seals,
+ routes,
+ ChatReplay::NonReplayable,
+ )
+ .unwrap();
+ let count = b"radroots.chat.signing_plan.v1\0".len() + 32 * 3 + 8 + 1;
+ let first = count + 1;
+ for (offset, value) in [
+ (count, 0),
+ (first + 32, 255),
+ (first + 64, 255),
+ (first + 68, 1),
+ (first + 69, 0),
+ (first + 70, 255),
+ (first + 110, 255),
+ ] {
+ let mut bytes = plan.protected_wire().to_vec();
+ bytes[offset] = value;
+ assert!(
+ ChatSigningPlan::parse(&command, &bytes).is_err(),
+ "field at {offset}"
+ );
+ }
+ let mut wrong_peer = plan.protected_wire().to_vec();
+ wrong_peer[first..first + 32].copy_from_slice(command.peer().as_bytes());
+ assert!(ChatSigningPlan::parse(&command, &wrong_peer).is_err());
+ let cipher_length = u32::from_be_bytes(
+ plan.protected_wire()[first + 110..first + 114]
+ .try_into()
+ .unwrap(),
+ ) as usize;
+ let raw_length_offset = first + 114 + cipher_length + 32;
+ let raw_length = u32::from_be_bytes(
+ plan.protected_wire()[raw_length_offset..raw_length_offset + 4]
+ .try_into()
+ .unwrap(),
+ ) as usize;
+ let route_count = raw_length_offset + 4 + raw_length;
+ for count in [0, 17] {
+ let mut bytes = plan.protected_wire().to_vec();
+ bytes[route_count] = count;
+ assert!(ChatSigningPlan::parse(&command, &bytes).is_err());
+ }
+ for bad in ["ws://leading/ ", "wss://internal/\u{0001}x"] {
+ assert!(
+ DmRelayAdvertisement::from_tags(
+ command.peer(),
+ time(0),
+ &[vec!["relay".into(), bad.into()]]
+ )
+ .is_err()
+ );
+ assert!(
+ CapturedDmRoute::from_observed_descriptor(
+ command.peer(),
+ radroots_domain::EnvelopeEventId::from_bytes([9; 32]),
+ "{}",
+ &[bad.into()]
+ )
+ .is_err()
+ );
+ }
+}
diff --git a/crates/protocol/tests/package_boundary.rs b/crates/protocol/tests/package_boundary.rs
@@ -17,6 +17,8 @@ const VERSIONED_SOURCES: &[&str] = &[
include_str!("../src/command.rs"),
include_str!("../src/nip01.rs"),
include_str!("../src/chat.rs"),
+ include_str!("../src/chat/routes.rs"),
+ include_str!("../src/chat/plan.rs"),
];
#[test]
diff --git a/crates/signing/README.md b/crates/signing/README.md
@@ -255,3 +255,12 @@ its safe journal boundary; dropping an observer cannot erase that responsibility
The legacy request/evidence API retains its existing callers while the
successor workers and providers migrate. Its sixteen-byte identities and
mandatory observation clock do not qualify the new execution contract.
+
+
+With `chat`, `issuance::VerifiedDmRelayAdvertisement` checks bounded exact
+kind-10050 fields, event ID, Schnorr signature and expected participant while
+retaining original bytes. Capturing an explicit advertised subset preserves
+that source observation; it establishes no global freshness, configured or
+available transport, workspace grant, consent or signing permission. Missing DM
+information supplies no fallback target. Exact seal conversion also compares the
+originating captured operation and command commitment before creating an intent.
diff --git a/crates/signing/src/issuance.rs b/crates/signing/src/issuance.rs
@@ -27,6 +27,11 @@ pub const MAX_EVENT_UNIX_SECONDS: u64 = 253_402_300_799;
const MAX_OBSERVATION_UNIX_MS: u64 = MAX_EVENT_UNIX_SECONDS * 1000 + 999;
const INTENT_DOMAIN: &[u8] = b"radroots.exact_signing_intent.v1\0";
+#[cfg(feature = "chat")]
+mod dm_relays;
+#[cfg(feature = "chat")]
+pub use dm_relays::VerifiedDmRelayAdvertisement;
+
/// Transport artifact role, separate from a participant's command permission.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
@@ -161,6 +166,9 @@ impl SigningIntent {
seal: &radroots_protocol::chat::ChatSeal,
call: ProviderCall,
) -> Result<Self, ProviderError> {
+ if seal.operation_id() != operation_id || seal.command_digest() != command_digest {
+ return Err(ProviderError::InvalidInput);
+ }
let fields = seal.fields();
let draft = radroots_event::GenericEventDraft::new(
"radroots.message.seal.v1",
diff --git a/crates/signing/src/issuance/dm_relays.rs b/crates/signing/src/issuance/dm_relays.rs
@@ -0,0 +1,110 @@
+use crate::provider::ProviderError;
+#[cfg(not(feature = "std"))]
+use alloc::string::String;
+use core::fmt;
+use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds};
+use radroots_event::{
+ SignedEvent,
+ wire::{EventWireLimits, Nip01EventWire},
+};
+use radroots_event_codec::verify::{self, Nip01SignatureVerifier, RawEvent};
+use radroots_protocol::chat::DmRelayAdvertisement;
+
+/// Actual ID/signature-verified kind-10050 observation. This verifies the
+/// participant's advertisement only, not its global freshness, routability,
+/// transport configuration, workspace grant or permission to issue a message.
+/// No public field constructor, serialization or automatic payload Debug exists.
+pub struct VerifiedDmRelayAdvertisement {
+ event_id: EnvelopeEventId,
+ advertisement: DmRelayAdvertisement,
+ raw_json: String,
+}
+impl VerifiedDmRelayAdvertisement {
+ /// Verifies bounded exact NIP-01 fields, event ID, expected participant and
+ /// Schnorr signature before returning retained routing data. The complete
+ /// raw budget is checked before any decoder-owned copy.
+ /// The caller retains unsupported/unverified input for its bounded evidence
+ /// policy; this borrowed-input validator never erases that original input.
+ pub fn verify(raw_json: &str, expected_participant: PublicKey) -> Result<Self, ProviderError> {
+ if raw_json.len() > super::SIGNED_EVENT_MAX_BYTES {
+ return Err(ProviderError::LimitExceeded);
+ }
+ let limits = EventWireLimits {
+ max_raw_json_bytes: super::SIGNED_EVENT_MAX_BYTES,
+ max_extra_fields: 0,
+ max_total_extra_json_bytes: 0,
+ ..EventWireLimits::default()
+ };
+ let wire = Nip01EventWire::parse_json_exact_with_limits(raw_json, limits)
+ .map_err(|_| ProviderError::AuthenticationFailed)?;
+ let event = SignedEvent::from_wire_verified_id(wire, raw_json)
+ .map_err(|_| ProviderError::AuthenticationFailed)?;
+ let verified = verify::id(RawEvent::new(event.envelope().clone()))
+ .map_err(|_| ProviderError::AuthenticationFailed)?;
+ verify::signature(verified, &Nip01SignatureVerifier)
+ .map_err(|_| ProviderError::AuthenticationFailed)?;
+ if event.wire().pubkey != expected_participant.to_hex() {
+ return Err(ProviderError::AuthenticationFailed);
+ }
+ if event.wire().kind != 10050 {
+ return Err(ProviderError::UnsupportedVersion);
+ }
+ let created_at =
+ UnixSeconds::new(event.wire().created_at).map_err(|_| ProviderError::InvalidInput)?;
+ let advertisement =
+ DmRelayAdvertisement::from_tags(expected_participant, created_at, &event.wire().tags)
+ .map_err(|error| match error {
+ radroots_protocol::nip01::WireError::LimitExceeded => ProviderError::LimitExceeded,
+ radroots_protocol::nip01::WireError::InvalidInput => ProviderError::InvalidInput,
+ })?;
+ Ok(Self {
+ event_id: EnvelopeEventId::from_bytes(*event.id().as_bytes()),
+ advertisement,
+ raw_json: String::from(raw_json),
+ })
+ }
+ /// Returns the authenticated NIP-01 source identity.
+ pub const fn event_id(&self) -> EnvelopeEventId {
+ self.event_id
+ }
+ /// Borrows the bounded authenticated tag projection.
+ pub const fn advertisement(&self) -> &DmRelayAdvertisement {
+ &self.advertisement
+ }
+ /// Borrows the exact original source bytes for retained plan evidence.
+ pub fn raw_json(&self) -> &str {
+ &self.raw_json
+ }
+ /// Freezes an explicit subset of this actual authenticated advertisement.
+ /// Native URI/network policy and runtime availability are still required;
+ /// this value supplies no workspace or signing permission.
+ pub fn capture_route(
+ &self,
+ selected: &[String],
+ ) -> Result<radroots_protocol::chat::CapturedDmRoute, ProviderError> {
+ if selected.iter().any(|target| {
+ !self
+ .advertisement
+ .advertised_relays()
+ .iter()
+ .any(|advertised| advertised.as_ref() == target)
+ }) {
+ return Err(ProviderError::InvalidInput);
+ }
+ radroots_protocol::chat::CapturedDmRoute::from_observed_descriptor(
+ self.advertisement.participant(),
+ self.event_id,
+ &self.raw_json,
+ selected,
+ )
+ .map_err(|error| match error {
+ radroots_protocol::nip01::WireError::LimitExceeded => ProviderError::LimitExceeded,
+ radroots_protocol::nip01::WireError::InvalidInput => ProviderError::InvalidInput,
+ })
+ }
+}
+impl fmt::Debug for VerifiedDmRelayAdvertisement {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("VerifiedDmRelayAdvertisement(<redacted>)")
+ }
+}
diff --git a/crates/signing/tests/chat_seal.rs b/crates/signing/tests/chat_seal.rs
@@ -173,4 +173,17 @@ fn known_seal_conversion_refuses_substituted_signer_identity() {
),
Err(ProviderError::InvalidInput)
));
+ assert_eq!(seal.message_id(), rumor.message_id());
+ for (operation, digest) in [
+ (OperationId::from_bytes([99; 32]), command.digest()),
+ (
+ command.context().operation_id(),
+ radroots_domain::CommandDigest::from_bytes([99; 32]),
+ ),
+ ] {
+ assert!(matches!(
+ SigningIntent::from_chat_seal(operation, digest, &seal, call(rumor.author())),
+ Err(ProviderError::InvalidInput)
+ ));
+ }
}
diff --git a/crates/signing/tests/dm_relays.rs b/crates/signing/tests/dm_relays.rs
@@ -0,0 +1,151 @@
+#![cfg(feature = "chat")]
+
+use nostr::JsonUtil;
+use radroots_domain::PublicKey;
+use radroots_signing::{issuance::VerifiedDmRelayAdvertisement, provider::ProviderError};
+
+fn key() -> nostr::Keys {
+ let mut scalar = [0; 32];
+ scalar[31] = 1; // Published synthetic identity, never host custody.
+ nostr::Keys::new(nostr::SecretKey::from_slice(&scalar).unwrap())
+}
+fn participant() -> PublicKey {
+ PublicKey::from_hex(&key().public_key().to_hex()).unwrap()
+}
+fn event(kind: u16, tags: Vec<Vec<String>>) -> String {
+ nostr::UnsignedEvent {
+ id: None,
+ pubkey: key().public_key(),
+ created_at: nostr::Timestamp::from_secs(1_700_000_000),
+ kind: nostr::Kind::Custom(kind),
+ tags: nostr::Tags::from_list(
+ tags.into_iter()
+ .map(|tag| nostr::Tag::parse(tag).unwrap())
+ .collect(),
+ ),
+ content: "Preserved signed metadata content does not supply a route.".into(),
+ }
+ .sign_with_keys(&key())
+ .unwrap()
+ .as_json()
+}
+
+#[test]
+fn actual_verified_advertisement_retains_original_evidence_and_preference_without_readiness_claims()
+{
+ let raw = event(
+ 10050,
+ vec![
+ vec!["relay".into(), "wss://first.example/".into()],
+ vec!["alt".into(), "public route information".into()],
+ vec!["relay".into(), "wss://second.example/".into()],
+ vec!["relay".into(), "wss://first.example/".into()],
+ ],
+ );
+ let verified = VerifiedDmRelayAdvertisement::verify(&raw, participant()).unwrap();
+ let decoded = nostr::Event::from_json(&raw).unwrap();
+ decoded.verify().unwrap();
+ assert_eq!(verified.event_id().as_bytes(), decoded.id.as_bytes());
+ assert_eq!(verified.raw_json(), raw);
+ assert_eq!(verified.advertisement().participant(), participant());
+ assert_eq!(verified.advertisement().created_at().get(), 1_700_000_000);
+ let urls: Vec<_> = verified
+ .advertisement()
+ .advertised_relays()
+ .iter()
+ .map(|url| url.as_ref())
+ .collect();
+ assert_eq!(urls, ["wss://first.example/", "wss://second.example/"]);
+ let selected = vec![String::from("wss://second.example/")];
+ let route = verified.capture_route(&selected).unwrap();
+ assert_eq!(route.participant(), participant());
+ assert_eq!(route.source_id(), verified.event_id());
+ assert_eq!(route.raw_json(), raw);
+ assert_eq!(route.selected_relays()[0].as_ref(), selected[0]);
+ assert!(!format!("{route:?}").contains("example"));
+ for refused in [
+ vec![],
+ vec![String::from("wss://unadvertised.example/")],
+ vec![selected[0].clone(), selected[0].clone()],
+ ] {
+ assert_eq!(
+ verified.capture_route(&refused).unwrap_err(),
+ ProviderError::InvalidInput
+ );
+ }
+ assert!(!format!("{verified:?} {:?}", verified.advertisement()).contains("example"));
+ let absent =
+ VerifiedDmRelayAdvertisement::verify(&event(10050, vec![]), participant()).unwrap();
+ assert!(absent.advertisement().advertised_relays().is_empty());
+ assert!(absent.capture_route(&selected).is_err());
+}
+
+#[test]
+fn correct_source_signature_is_required_for_the_exact_participant_and_profile() {
+ let raw = event(
+ 10050,
+ vec![vec!["relay".into(), "wss://first.example/".into()]],
+ );
+ let other =
+ PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")
+ .unwrap();
+ assert_eq!(
+ VerifiedDmRelayAdvertisement::verify(&raw, other).unwrap_err(),
+ ProviderError::AuthenticationFailed
+ );
+ assert_eq!(
+ VerifiedDmRelayAdvertisement::verify(&event(10051, vec![]), participant()).unwrap_err(),
+ ProviderError::UnsupportedVersion
+ );
+ let mut changed: serde_json::Value = serde_json::from_str(&raw).unwrap();
+ changed["sig"] = "00".repeat(64).into();
+ assert_eq!(
+ VerifiedDmRelayAdvertisement::verify(&changed.to_string(), participant()).unwrap_err(),
+ ProviderError::AuthenticationFailed
+ );
+ changed = serde_json::from_str(&raw).unwrap();
+ changed["id"] = "11".repeat(32).into();
+ assert_eq!(
+ VerifiedDmRelayAdvertisement::verify(&changed.to_string(), participant()).unwrap_err(),
+ ProviderError::AuthenticationFailed
+ );
+ let duplicate = format!("{{\"\\u0069d\":\"untrusted\",{}", &raw[1..]);
+ assert_eq!(
+ VerifiedDmRelayAdvertisement::verify(&duplicate, participant()).unwrap_err(),
+ ProviderError::AuthenticationFailed
+ );
+ assert_eq!(
+ VerifiedDmRelayAdvertisement::verify(&"x".repeat(65537), participant()).unwrap_err(),
+ ProviderError::LimitExceeded
+ );
+}
+
+#[test]
+fn authenticated_malformed_or_over_budget_relay_tags_never_supply_targets() {
+ for fields in [
+ vec!["relay".into()],
+ vec!["relay".into(), "https://wrong.example/".into()],
+ vec![
+ "relay".into(),
+ "wss://first.example/".into(),
+ "extra".into(),
+ ],
+ ] {
+ assert_eq!(
+ VerifiedDmRelayAdvertisement::verify(&event(10050, vec![fields]), participant())
+ .unwrap_err(),
+ ProviderError::InvalidInput
+ );
+ }
+ let raw = event(
+ 10050,
+ vec![vec![
+ "relay".into(),
+ format!("wss://host.example/{}", "a".repeat(2048)),
+ ]],
+ );
+ assert_eq!(
+ VerifiedDmRelayAdvertisement::verify(&raw, participant()).unwrap_err(),
+ ProviderError::LimitExceeded
+ );
+}
diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml
@@ -35,7 +35,7 @@ name = "radroots_storage"
[features]
default = ["memory", "serde"]
memory = []
-command_journal = ["radroots_protocol/commands"]
+command_journal = ["radroots_protocol/chat"]
serde = [
"dep:serde",
"radroots_domain/serde",
diff --git a/crates/storage/README.md b/crates/storage/README.md
@@ -234,12 +234,13 @@ remain owned by `radroots_protocol`.
| Feature | Default | Contract |
| --- | --- | --- |
+| `command_journal` | no | Enables typed protected command admission and complete chat-plan bind/query contracts through the portable Protocol profile. It starts no worker and grants no execution authority. |
| `memory` | yes | Enables the deterministic bounded in-memory reference backend. It installs no task, clock, entropy source, filesystem, or global state. |
| `serde` | yes | Adds validated serialization to passive storage values. It does not serialize backend handles, active secret capabilities, or transactions. |
Features are additive. `--no-default-features` exposes the backend-neutral SPI
without an implementation. `memory` and `serde` are supported independently,
-and `--all-features` enables both.
+and `--all-features` enables all declared features.
## Paired authored revisions
@@ -283,3 +284,13 @@ Except as otherwise noted, all files in the `radroots_storage` distribution are
For information on usage and redistribution, and for a DISCLAIMER OF ALL
WARRANTIES, see LICENSE included in the `radroots_storage` distribution.
+
+## Protected command and signing-plan transactions
+
+With `command_journal`, `command::OperationJournal` defines admission/query and
+complete immutable signing-plan bind/query transactions. Concrete adapters own
+current authentication, exact indexed-fact comparisons, fixed first-issue
+windows and observed commit/rollback completion. `PlanBindingOutcome::Unknown`
+retains the original workspace, operation and command anchor for reconciliation;
+a missing observer cannot establish rollback. `BoundSigningPlan` is a structural
+store report, separate from signature, business installation and delivery.
diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs
@@ -7,6 +7,7 @@ use core::fmt;
use radroots_domain::{
CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, WorkspaceId,
};
+pub use radroots_protocol::chat::ChatSigningPlan;
use radroots_protocol::command::CapturedChatCommand;
use radroots_transport::BoxFuture;
@@ -244,6 +245,23 @@ impl fmt::Debug for AdmissionOutcome {
/// Typed transaction port, implemented by actual shared storage adapters.
/// Applications do not implement a second orchestration or stock engine here.
pub trait OperationJournal: WorkspaceStore {
+ /// Atomically retains the complete immutable plan under current access and
+ /// the original first-issue window. No signer invocation happens here.
+ fn bind_signing_intents(
+ &self,
+ binding: WorkspaceBinding,
+ plan: ChatSigningPlan,
+ proof: AttachmentProof,
+ ) -> BoxFuture<'_, Result<PlanBindingOutcome, OperationError>>;
+ /// Queries original complete plan bytes under current access, including
+ /// after expiry. The returned value grants no permission to dispatch.
+ fn signing_plan(
+ &self,
+ binding: WorkspaceBinding,
+ operation_id: OperationId,
+ expected_digest: CommandDigest,
+ proof: AttachmentProof,
+ ) -> BoxFuture<'_, Result<Option<BoundSigningPlan>, OperationError>>;
/// Authenticates current grant/fences, checks the original operation first,
/// and confirms atomic retained preparation before any signing. Chat has no
/// physical hold. Only confirmed rollback may return a known-failure error.
@@ -262,3 +280,77 @@ pub trait OperationJournal: WorkspaceStore {
proof: AttachmentProof,
) -> BoxFuture<'_, Result<Option<PreparedOperation>, OperationError>>;
}
+
+/// Complete retained T1 observation, separate from issuance and installation.
+/// A custom adapter's structural report does not qualify durable execution.
+pub struct BoundSigningPlan {
+ prepared: PreparedOperation,
+ plan: ChatSigningPlan,
+ transaction_id: TransactionId,
+ bound_at: radroots_domain::UnixSeconds,
+}
+impl BoundSigningPlan {
+ /// Compares exact original command and fixed first-issue window.
+ pub fn from_committed_store(
+ prepared: PreparedOperation,
+ plan: ChatSigningPlan,
+ transaction_id: TransactionId,
+ bound_at: radroots_domain::UnixSeconds,
+ ) -> Result<Self, OperationError> {
+ if plan.operation_id() != prepared.identity().operation_id()
+ || plan.command_digest() != prepared.identity().command_digest()
+ || bound_at < prepared.issuance_window().prepared_at()
+ || bound_at >= prepared.issuance_window().first_issue_not_after()
+ || plan.created_at() < prepared.issuance_window().prepared_at()
+ || plan.created_at() > bound_at
+ {
+ return Err(OperationError::RecoveryRequired);
+ }
+ // Reconstruct against the actually retained command, rather than trust
+ // a matching digest descriptor attached to unrelated plan fields.
+ let checked = ChatSigningPlan::parse(prepared.request().command(), plan.protected_wire())
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ Ok(Self {
+ prepared,
+ plan: checked,
+ transaction_id,
+ bound_at,
+ })
+ }
+ /// Transfers retained command and exact plan without changing their identities.
+ pub fn into_parts(self) -> (PreparedOperation, ChatSigningPlan) {
+ (self.prepared, self.plan)
+ }
+ pub const fn prepared(&self) -> &PreparedOperation {
+ &self.prepared
+ }
+ pub const fn plan(&self) -> &ChatSigningPlan {
+ &self.plan
+ }
+ pub const fn transaction_id(&self) -> TransactionId {
+ self.transaction_id
+ }
+ /// Returns the checked observation captured before protection; this is not
+ /// an independently measured wall-clock commit or signing time.
+ pub const fn bound_at(&self) -> radroots_domain::UnixSeconds {
+ self.bound_at
+ }
+}
+impl fmt::Debug for BoundSigningPlan {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("BoundSigningPlan(<redacted>)")
+ }
+}
+/// Confirmed T1 completion or an original anchor requiring reconciliation.
+pub enum PlanBindingOutcome {
+ Committed(BoundSigningPlan),
+ Unknown(CommitAttempt),
+}
+impl fmt::Debug for PlanBindingOutcome {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(match self {
+ Self::Committed(_) => "PlanBindingOutcome::Committed(<redacted>)",
+ Self::Unknown(_) => "PlanBindingOutcome::Unknown(<retained>)",
+ })
+ }
+}
diff --git a/crates/storage_sqlite/Cargo.toml b/crates/storage_sqlite/Cargo.toml
@@ -60,6 +60,8 @@ zeroize = { workspace = true, features = ["alloc"] }
sqlx = { workspace = true, features = ["runtime-tokio", "sqlite-bundled"] }
[dev-dependencies]
+radroots_protocol = { workspace = true, default-features = false, features = ["chat"] }
+nostr = { workspace = true, default-features = false, features = ["std", "nip44"] }
futures = { workspace = true }
hex = { workspace = true }
radroots_secrets = { workspace = true, features = ["file", "memory"] }
diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md
@@ -203,5 +203,22 @@ authority. Close permanently stops admission, drains admitted requests, checks
the WAL checkpoint and awaits connection closure before releasing the lock.
Cancelled close can be awaited again. Dropping the handle is not close evidence.
Revocation commits a protected grant revision and survives reopening. This
-attachment boundary supplies no command journal, network pairing, firm stock,
-transfer, restore or browser qualification.
+attachment alone supplies no network pairing, firm stock, transfer, restore or
+browser qualification.
+
+
+The separate `OperationJournal` implementation durably admits non-stock chat
+preparations and binds complete immutable signing plans before dispatch. It
+rechecks the current protected grant, original preparation and all indexed facts
+under `BEGIN IMMEDIATE`, with provider work outside that transaction. A fixed
+first-issue window never restarts on replay. Already-bound bytes remain queryable
+and replayable after expiry under current access; this grants no new issuance.
+
+The current workspace schema is version 4. Older namespaces are preserved and
+refused for explicit cutover, without an automatic state rewrite. Complete plans
+use a protected manifest and at most twenty-four 16 KiB protected data parts,
+with context binding the full workspace/operation/plan identity and part index.
+Existing secret-material/envelope bounds remain intact. Queued and in-flight
+request reservations share a 4 MiB byte cap alongside the 32-slot queue limit.
+Known rollback, confirmed commit and unknown completion remain distinct.
+This component performs no signer dispatch, business installation or delivery.
diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs
@@ -1,10 +1,11 @@
use super::{
AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto,
- fs::Namespace, operation, record::GrantRecord, worker,
+ fs::Namespace, operation, plan, record::GrantRecord, worker,
};
use radroots_domain::{CommandDigest, IssuanceWindow, OperationId, TransactionId};
use radroots_storage::command::{
- AdmissionOutcome, AdmissionRequest, CommitAttempt, OperationError, PreparedOperation,
+ AdmissionOutcome, AdmissionRequest, BoundSigningPlan, ChatSigningPlan, CommitAttempt,
+ OperationError, PlanBindingOutcome, PreparedOperation,
};
use sqlx::{Connection, Sqlite, SqliteConnection, Transaction};
@@ -43,6 +44,198 @@ impl Journal<'_> {
Ok((record, protected, current))
}
+ pub(super) async fn bind_plan(
+ &mut self,
+ binding: WorkspaceBinding,
+ supplied: ChatSigningPlan,
+ proof: AttachmentProof,
+ ) -> Result<PlanBindingOutcome, OperationError> {
+ let (record, grant, current) = self.access(&binding, &proof).await?;
+ let (prepared, operation_protected) = operation::read(
+ self.connection,
+ self.selected,
+ supplied.operation_id(),
+ self.crypto,
+ )
+ .await?
+ .ok_or(OperationError::RecoveryRequired)?;
+ operation::check_digest(&prepared, binding.actor(), Some(supplied.command_digest()))?;
+ same_binding(prepared.request().binding(), &binding)?;
+ let anchor = prepared.identity();
+ let (prepared, existing) =
+ plan::read(self.connection, self.selected, prepared, self.crypto).await?;
+ let (plan, transaction_id, bound_at, protected, fresh) =
+ if let Some((plan, transaction, bound_at, protected)) = existing {
+ if plan.protected_wire() != supplied.protected_wire() {
+ return Err(OperationError::IdempotencyConflict);
+ }
+ (plan, transaction, bound_at, protected, false)
+ } else {
+ let window = prepared.issuance_window();
+ if current.observed_at() < window.prepared_at() {
+ return Err(super::WorkspaceError::Unavailable.into());
+ }
+ if current.observed_at() >= window.first_issue_not_after() {
+ return Err(OperationError::DeadlineExceeded);
+ }
+ let supplied =
+ ChatSigningPlan::parse(prepared.request().command(), supplied.protected_wire())
+ .map_err(|_| OperationError::InvalidCommand)?;
+ if supplied.created_at() < window.prepared_at()
+ || supplied.created_at() > current.observed_at()
+ {
+ return Err(OperationError::InvalidCommand);
+ }
+ let transaction = TransactionId::from_bytes(super::random()?);
+ let protected = plan::protect(
+ &prepared,
+ &supplied,
+ transaction,
+ current.observed_at(),
+ self.crypto,
+ )
+ .await?;
+ (
+ supplied,
+ transaction,
+ current.observed_at(),
+ protected,
+ true,
+ )
+ };
+ let attempt = CommitAttempt::new(
+ anchor.workspace_id(),
+ anchor.operation_id(),
+ anchor.command_digest(),
+ Some(transaction_id),
+ );
+ let mut transaction = self
+ .connection
+ .begin_with("BEGIN IMMEDIATE")
+ .await
+ .map_err(|_| OperationError::StorageFailure)?;
+ let changed = async {
+ let now = recheck(
+ &mut transaction,
+ self.namespace,
+ self.selected,
+ &grant,
+ &record,
+ &binding,
+ &proof,
+ self.clock,
+ )
+ .await?;
+ operation::unchanged(&mut transaction, &prepared, &operation_protected).await?;
+ if fresh {
+ if now.observed_at() < bound_at {
+ return Err(super::WorkspaceError::Unavailable.into());
+ }
+ if now.observed_at() >= prepared.issuance_window().first_issue_not_after() {
+ return Err(OperationError::DeadlineExceeded);
+ }
+ plan::unchanged(&mut transaction, &prepared, None).await?;
+ plan::insert(&mut transaction, &prepared, &protected).await?;
+ } else {
+ plan::unchanged(&mut transaction, &prepared, Some(&protected)).await?;
+ }
+ Ok(())
+ }
+ .await;
+ if let Err(error) = changed {
+ if transaction.rollback().await.is_err() {
+ *self.uncertain = true;
+ return Ok(PlanBindingOutcome::Unknown(attempt));
+ }
+ return Err(error);
+ }
+ let finished = if fresh {
+ transaction.commit().await
+ } else {
+ transaction.rollback().await
+ };
+ if finished.is_err() {
+ *self.uncertain = true;
+ return Ok(PlanBindingOutcome::Unknown(attempt));
+ }
+ Ok(PlanBindingOutcome::Committed(
+ BoundSigningPlan::from_committed_store(prepared, plan, transaction_id, bound_at)?,
+ ))
+ }
+
+ pub(super) async fn query_plan(
+ &mut self,
+ binding: WorkspaceBinding,
+ operation_id: OperationId,
+ digest: CommandDigest,
+ proof: AttachmentProof,
+ ) -> Result<Option<BoundSigningPlan>, OperationError> {
+ let (record, grant, _) = self.access(&binding, &proof).await?;
+ let operation =
+ operation::read(self.connection, self.selected, operation_id, self.crypto).await?;
+ let retained = if let Some((prepared, ciphertext)) = operation {
+ operation::check_digest(&prepared, binding.actor(), Some(digest))?;
+ same_binding(prepared.request().binding(), &binding)?;
+ let (prepared, plan) =
+ plan::read(self.connection, self.selected, prepared, self.crypto).await?;
+ Some((prepared, ciphertext, plan))
+ } else {
+ None
+ };
+ let mut transaction = self
+ .connection
+ .begin_with("BEGIN IMMEDIATE")
+ .await
+ .map_err(|_| OperationError::StorageFailure)?;
+ let checked = async {
+ recheck(
+ &mut transaction,
+ self.namespace,
+ self.selected,
+ &grant,
+ &record,
+ &binding,
+ &proof,
+ self.clock,
+ )
+ .await?;
+ if let Some((prepared, ciphertext, plan)) = &retained {
+ operation::unchanged(&mut transaction, prepared, ciphertext).await?;
+ plan::unchanged(
+ &mut transaction,
+ prepared,
+ plan.as_ref().map(|entry| &entry.3),
+ )
+ .await?;
+ } else {
+ let count: i64 = sqlx::query_scalar(
+ "SELECT (SELECT count(*) FROM operations WHERE workspace=?1 AND operation_id=?2)+(SELECT count(*) FROM signing_plans WHERE workspace=?1 AND operation_id=?2)+(SELECT count(*) FROM signing_plan_parts WHERE workspace=?1 AND operation_id=?2)",
+ )
+ .bind(self.selected.workspace_id().as_bytes().as_slice())
+ .bind(operation_id.as_bytes().as_slice())
+ .fetch_one(&mut *transaction)
+ .await
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ if count != 0 {
+ return Err(OperationError::RecoveryRequired);
+ }
+ }
+ Ok(())
+ }
+ .await;
+ if transaction.rollback().await.is_err() {
+ *self.uncertain = true;
+ return Err(OperationError::RecoveryRequired);
+ }
+ checked?;
+ match retained {
+ Some((prepared, _, Some((plan, transaction, bound_at, _)))) => Ok(Some(
+ BoundSigningPlan::from_committed_store(prepared, plan, transaction, bound_at)?,
+ )),
+ _ => Ok(None),
+ }
+ }
+
pub(super) async fn admit(
&mut self,
request: AdmissionRequest,
diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs
@@ -64,6 +64,36 @@ impl WorkspaceCrypto {
self.seal_bound(operation_context(workspace, operation)?, 65_536, plaintext)
.await
}
+ pub(super) async fn seal_plan_part(
+ &self,
+ workspace: WorkspaceId,
+ operation: OperationId,
+ digest: &[u8; 32],
+ part: u8,
+ plaintext: &[u8],
+ ) -> Result<Vec<u8>, WorkspaceError> {
+ self.seal_bound(
+ plan_context(workspace, operation, digest, part)?,
+ PRIVATE_PAYLOAD_MAX_BYTES,
+ plaintext,
+ )
+ .await
+ }
+ pub(super) async fn open_plan_part(
+ &self,
+ workspace: WorkspaceId,
+ operation: OperationId,
+ digest: &[u8; 32],
+ part: u8,
+ protected: &[u8],
+ ) -> Result<SecretMaterial, WorkspaceError> {
+ self.open_bound(
+ plan_context(workspace, operation, digest, part)?,
+ PRIVATE_PAYLOAD_MAX_BYTES,
+ protected,
+ )
+ .await
+ }
async fn seal_bound(
&self,
context: EnvelopeContext,
@@ -191,3 +221,27 @@ fn operation_context(
.map_err(|_| WorkspaceError::InvalidInput)?,
))
}
+
+fn plan_context(
+ workspace: WorkspaceId,
+ operation: OperationId,
+ digest: &[u8; 32],
+ part: u8,
+) -> Result<EnvelopeContext, WorkspaceError> {
+ use sha2::{Digest, Sha256};
+ let mut hash = Sha256::new();
+ hash.update(b"radroots.workspace.signing_plan.part.v1\0");
+ hash.update(workspace.as_bytes());
+ hash.update(operation.as_bytes());
+ hash.update(digest);
+ hash.update([part]);
+ let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into());
+ Ok(EnvelopeContext::new(
+ EnvelopePurpose::parse("radroots.workspace.signing_plan")
+ .map_err(|_| WorkspaceError::InvalidInput)?,
+ EnvelopeSubject::parse("workspace_plan_part", subject.to_string())
+ .map_err(|_| WorkspaceError::InvalidInput)?,
+ PayloadSchemaId::parse("radroots.workspace.signing_plan.v1")
+ .map_err(|_| WorkspaceError::InvalidInput)?,
+ ))
+}
diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs
@@ -9,6 +9,7 @@ mod admission;
mod crypto;
mod fs;
mod operation;
+mod plan;
mod record;
mod worker;
@@ -213,6 +214,38 @@ impl WorkspaceStore for NativeWorkspace {
}
}
impl radroots_storage::command::OperationJournal for NativeWorkspace {
+ fn bind_signing_intents(
+ &self,
+ binding: WorkspaceBinding,
+ plan: radroots_storage::command::ChatSigningPlan,
+ proof: AttachmentProof,
+ ) -> BoxFuture<
+ '_,
+ Result<
+ radroots_storage::command::PlanBindingOutcome,
+ radroots_storage::command::OperationError,
+ >,
+ > {
+ Box::pin(self.worker.bind_plan(binding, plan, proof))
+ }
+ fn signing_plan(
+ &self,
+ binding: WorkspaceBinding,
+ operation_id: radroots_domain::OperationId,
+ digest: radroots_domain::CommandDigest,
+ proof: AttachmentProof,
+ ) -> BoxFuture<
+ '_,
+ Result<
+ Option<radroots_storage::command::BoundSigningPlan>,
+ radroots_storage::command::OperationError,
+ >,
+ > {
+ Box::pin(
+ self.worker
+ .signing_plan(binding, operation_id, digest, proof),
+ )
+ }
fn admit_command_and_hold(
&self,
request: radroots_storage::command::AdmissionRequest,
diff --git a/crates/storage_sqlite/src/workspace/plan.rs b/crates/storage_sqlite/src/workspace/plan.rs
@@ -0,0 +1,312 @@
+//! Protected complete plan storage; all crypto runs outside write transactions.
+use super::{
+ AttachmentInput,
+ crypto::{PRIVATE_PAYLOAD_MAX_BYTES, WorkspaceCrypto},
+};
+use radroots_domain::{CommandDigest, OperationId, TransactionId, UnixSeconds};
+use radroots_storage::command::{
+ BoundSigningPlan, ChatSigningPlan, OperationError, PreparedOperation,
+};
+use serde::{Deserialize, Serialize};
+use sqlx::{Row, SqliteConnection};
+use zeroize::Zeroizing;
+
+pub(super) const TABLE: &str = "CREATE TABLE signing_plans (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), part_count INTEGER NOT NULL CHECK(part_count BETWEEN 1 AND 24), byte_count INTEGER NOT NULL CHECK(byte_count BETWEEN 1 AND 393216), 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 PARTS: &str = "CREATE TABLE signing_plan_parts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, part INTEGER NOT NULL CHECK(part BETWEEN 1 AND 24), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,part), FOREIGN KEY(workspace,operation_id) REFERENCES signing_plans(workspace,operation_id)) STRICT, WITHOUT ROWID";
+const MAX_PROTECTED_TOTAL: usize = 2 * 1024 * 1024;
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct Manifest {
+ version: u8,
+ workspace: radroots_domain::WorkspaceId,
+ operation_id: OperationId,
+ command_digest: CommandDigest,
+ preparation_transaction: TransactionId,
+ plan_digest: CommandDigest,
+ transaction_id: TransactionId,
+ bound_at: UnixSeconds,
+ part_count: usize,
+ byte_count: usize,
+}
+pub(super) struct ProtectedPlan {
+ pub digest: [u8; 32],
+ pub transaction: TransactionId,
+ pub manifest: Vec<u8>,
+ pub parts: Vec<Vec<u8>>,
+ pub bytes: usize,
+}
+pub(super) async fn protect(
+ prepared: &PreparedOperation,
+ plan: &ChatSigningPlan,
+ transaction: TransactionId,
+ bound_at: UnixSeconds,
+ crypto: &WorkspaceCrypto,
+) -> Result<ProtectedPlan, OperationError> {
+ let anchor = prepared.identity();
+ let chunks = plan.protected_wire().chunks(PRIVATE_PAYLOAD_MAX_BYTES);
+ let manifest = Manifest {
+ version: 1,
+ workspace: anchor.workspace_id(),
+ operation_id: anchor.operation_id(),
+ command_digest: anchor.command_digest(),
+ preparation_transaction: prepared.transaction_id(),
+ plan_digest: CommandDigest::from_bytes(*plan.digest()),
+ transaction_id: transaction,
+ bound_at,
+ part_count: chunks.len(),
+ byte_count: plan.protected_wire().len(),
+ };
+ let plaintext =
+ Zeroizing::new(serde_json::to_vec(&manifest).map_err(|_| OperationError::InvalidCommand)?);
+ let protected = crypto
+ .seal_plan_part(
+ anchor.workspace_id(),
+ anchor.operation_id(),
+ plan.digest(),
+ 0,
+ &plaintext,
+ )
+ .await?;
+ let mut total = protected.len();
+ let mut parts = Vec::new();
+ for (index, chunk) in chunks.enumerate() {
+ let part = crypto
+ .seal_plan_part(
+ anchor.workspace_id(),
+ anchor.operation_id(),
+ plan.digest(),
+ (index + 1) as u8,
+ chunk,
+ )
+ .await?;
+ total = total
+ .checked_add(part.len())
+ .filter(|size| *size <= MAX_PROTECTED_TOTAL)
+ .ok_or(OperationError::InvalidCommand)?;
+ parts.push(part);
+ }
+ Ok(ProtectedPlan {
+ digest: *plan.digest(),
+ transaction,
+ manifest: protected,
+ parts,
+ bytes: manifest.byte_count,
+ })
+}
+
+pub(super) async fn read(
+ connection: &mut SqliteConnection,
+ selected: &AttachmentInput,
+ prepared: PreparedOperation,
+ crypto: &WorkspaceCrypto,
+) -> Result<
+ (
+ PreparedOperation,
+ Option<(ChatSigningPlan, TransactionId, UnixSeconds, ProtectedPlan)>,
+ ),
+ OperationError,
+> {
+ let anchor = prepared.identity();
+ let row = sqlx::query("SELECT CASE WHEN length(plan_digest)=32 THEN plan_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,part_count,byte_count,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM signing_plans WHERE workspace=? AND operation_id=?")
+ .bind(selected.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?;
+ let Some(row) = row else {
+ return Ok((prepared, None));
+ };
+ let digest: Vec<u8> = row
+ .try_get::<Option<Vec<u8>>, _>(0)
+ .map_err(|_| OperationError::RecoveryRequired)?
+ .ok_or(OperationError::RecoveryRequired)?;
+ let digest: [u8; 32] = digest
+ .try_into()
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ let transaction: Vec<u8> = row
+ .try_get::<Option<Vec<u8>>, _>(1)
+ .map_err(|_| OperationError::RecoveryRequired)?
+ .ok_or(OperationError::RecoveryRequired)?;
+ let transaction = TransactionId::from_bytes(
+ transaction
+ .try_into()
+ .map_err(|_| OperationError::RecoveryRequired)?,
+ );
+ let part_count: i64 = row
+ .try_get(2)
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ let byte_count: i64 = row
+ .try_get(3)
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ if !(1..=24).contains(&part_count)
+ || !(1..=393216).contains(&byte_count)
+ || (byte_count as usize).div_ceil(PRIVATE_PAYLOAD_MAX_BYTES) != part_count as usize
+ {
+ return Err(OperationError::RecoveryRequired);
+ }
+ let manifest: Vec<u8> = row
+ .try_get::<Option<Vec<u8>>, _>(4)
+ .map_err(|_| OperationError::RecoveryRequired)?
+ .ok_or(OperationError::RecoveryRequired)?;
+ let decoded = crypto
+ .open_plan_part(
+ selected.workspace_id(),
+ anchor.operation_id(),
+ &digest,
+ 0,
+ &manifest,
+ )
+ .await?;
+ let decoded: Manifest = decoded
+ .expose_secret(|bytes| serde_json::from_slice(bytes))
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ if decoded.version != 1
+ || decoded.workspace != selected.workspace_id()
+ || decoded.operation_id != anchor.operation_id()
+ || decoded.command_digest != anchor.command_digest()
+ || decoded.preparation_transaction != prepared.transaction_id()
+ || decoded.plan_digest.as_bytes() != &digest
+ || decoded.transaction_id != transaction
+ || decoded.part_count != part_count as usize
+ || decoded.byte_count != byte_count as usize
+ {
+ return Err(OperationError::RecoveryRequired);
+ }
+ // SQL bounds aggregate/count before materializing any untrusted part set.
+ let (count, total): (i64, i64) = sqlx::query_as("SELECT count(*),coalesce(sum(length(protected)),0) FROM signing_plan_parts WHERE workspace=? AND operation_id=?")
+ .bind(selected.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?;
+ if count != part_count || total <= 0 || total > (MAX_PROTECTED_TOTAL - manifest.len()) as i64 {
+ return Err(OperationError::RecoveryRequired);
+ }
+ let rows = sqlx::query("SELECT part,CASE WHEN length(protected)>0 AND length(protected)<=262144 AND (SELECT coalesce(sum(length(p.protected)),0) FROM signing_plan_parts p WHERE p.workspace=signing_plan_parts.workspace AND p.operation_id=signing_plan_parts.operation_id)<=2097152 THEN protected END FROM signing_plan_parts WHERE workspace=? AND operation_id=? ORDER BY part LIMIT 25")
+ .bind(selected.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).fetch_all(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?;
+ if rows.len() != part_count as usize {
+ return Err(OperationError::RecoveryRequired);
+ }
+ let mut wire = Zeroizing::new(Vec::with_capacity(byte_count as usize));
+ let mut parts = Vec::new();
+ for (index, row) in rows.iter().enumerate() {
+ let part: i64 = row
+ .try_get(0)
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ if part != (index + 1) as i64 {
+ return Err(OperationError::RecoveryRequired);
+ }
+ let protected: Vec<u8> = row
+ .try_get::<Option<Vec<u8>>, _>(1)
+ .map_err(|_| OperationError::RecoveryRequired)?
+ .ok_or(OperationError::RecoveryRequired)?;
+ let plaintext = crypto
+ .open_plan_part(
+ selected.workspace_id(),
+ anchor.operation_id(),
+ &digest,
+ part as u8,
+ &protected,
+ )
+ .await?;
+ let expected = if index + 1 == rows.len() {
+ byte_count as usize - index * PRIVATE_PAYLOAD_MAX_BYTES
+ } else {
+ PRIVATE_PAYLOAD_MAX_BYTES
+ };
+ plaintext.expose_secret(|bytes| {
+ if bytes.len() != expected {
+ return Err(OperationError::RecoveryRequired);
+ }
+ wire.extend_from_slice(bytes);
+ Ok(())
+ })?;
+ parts.push(protected);
+ }
+ let plan = ChatSigningPlan::parse(prepared.request().command(), &wire)
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ if plan.digest() != &digest {
+ return Err(OperationError::RecoveryRequired);
+ }
+ let protected = ProtectedPlan {
+ digest,
+ transaction,
+ manifest,
+ parts,
+ bytes: byte_count as usize,
+ };
+ // Validate the original T1 observation before returning even to internal callers.
+ let bound =
+ BoundSigningPlan::from_committed_store(prepared, plan, transaction, decoded.bound_at)?;
+ let (prepared, plan) = bound.into_parts();
+ Ok((
+ prepared,
+ Some((plan, transaction, decoded.bound_at, protected)),
+ ))
+}
+
+pub(super) async fn insert(
+ connection: &mut SqliteConnection,
+ prepared: &PreparedOperation,
+ value: &ProtectedPlan,
+) -> Result<(), OperationError> {
+ let anchor = prepared.identity();
+ sqlx::query("INSERT INTO signing_plans(workspace,operation_id,plan_digest,transaction_id,part_count,byte_count,protected) VALUES(?,?,?,?,?,?,?)")
+ .bind(anchor.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).bind(value.digest.as_slice()).bind(value.transaction.as_bytes().as_slice()).bind(value.parts.len() as i64).bind(value.bytes as i64).bind(&value.manifest).execute(&mut *connection).await.map_err(|_| OperationError::StorageFailure)?;
+ for (index, part) in value.parts.iter().enumerate() {
+ sqlx::query(
+ "INSERT INTO signing_plan_parts(workspace,operation_id,part,protected) VALUES(?,?,?,?)",
+ )
+ .bind(anchor.workspace_id().as_bytes().as_slice())
+ .bind(anchor.operation_id().as_bytes().as_slice())
+ .bind((index + 1) as i64)
+ .bind(part)
+ .execute(&mut *connection)
+ .await
+ .map_err(|_| OperationError::StorageFailure)?;
+ }
+ Ok(())
+}
+pub(super) async fn unchanged(
+ connection: &mut SqliteConnection,
+ prepared: &PreparedOperation,
+ value: Option<&ProtectedPlan>,
+) -> Result<(), OperationError> {
+ let anchor = prepared.identity();
+ let count: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM signing_plans WHERE workspace=? AND operation_id=?",
+ )
+ .bind(anchor.workspace_id().as_bytes().as_slice())
+ .bind(anchor.operation_id().as_bytes().as_slice())
+ .fetch_one(&mut *connection)
+ .await
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ let Some(value) = value else {
+ let parts: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM signing_plan_parts WHERE workspace=? AND operation_id=?",
+ )
+ .bind(anchor.workspace_id().as_bytes().as_slice())
+ .bind(anchor.operation_id().as_bytes().as_slice())
+ .fetch_one(&mut *connection)
+ .await
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ return if count == 0 && parts == 0 {
+ Ok(())
+ } else {
+ Err(OperationError::RecoveryRequired)
+ };
+ };
+ let matched: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans WHERE workspace=? AND operation_id=? AND plan_digest=? AND transaction_id=? AND part_count=? AND byte_count=? AND protected=?")
+ .bind(anchor.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).bind(value.digest.as_slice()).bind(value.transaction.as_bytes().as_slice()).bind(value.parts.len() as i64).bind(value.bytes as i64).bind(&value.manifest).fetch_one(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?;
+ let parts: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM signing_plan_parts WHERE workspace=? AND operation_id=?",
+ )
+ .bind(anchor.workspace_id().as_bytes().as_slice())
+ .bind(anchor.operation_id().as_bytes().as_slice())
+ .fetch_one(&mut *connection)
+ .await
+ .map_err(|_| OperationError::RecoveryRequired)?;
+ if count != 1 || matched != 1 || parts != value.parts.len() as i64 {
+ return Err(OperationError::RecoveryRequired);
+ }
+ for (index, part) in value.parts.iter().enumerate() {
+ let matched: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plan_parts WHERE workspace=? AND operation_id=? AND part=? AND protected=?")
+ .bind(anchor.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).bind((index + 1) as i64).bind(part).fetch_one(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?;
+ if matched != 1 {
+ return Err(OperationError::RecoveryRequired);
+ }
+ }
+ Ok(())
+}
diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs
@@ -1,5 +1,6 @@
use super::*;
mod operation_records;
+mod plan_records;
use radroots_domain::{ActorRef, SourceId};
use radroots_secrets::{
EncryptedEnvelope, SecretId, SecretRef,
@@ -556,7 +557,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r
.await
.unwrap();
let statement = match fault {
- 0 => "PRAGMA user_version=4",
+ 0 => "PRAGMA user_version=5",
1 => "DELETE FROM workspace_grant",
2 => "UPDATE workspace_grant SET grant_id=zeroblob(31)",
3 => "UPDATE workspace_grant SET protected=zeroblob(0)",
@@ -602,7 +603,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 { 4 } else { 3 });
+ assert_eq!(version, if fault == 0 { 5 } else { 4 });
assert_eq!(rows, if fault == 1 { 0 } else { 1 });
if (3..=5).contains(&fault) {
let size: i64 = sqlx::query_scalar("SELECT length(protected) FROM workspace_grant")
diff --git a/crates/storage_sqlite/src/workspace/tests/plan_records.rs b/crates/storage_sqlite/src/workspace/tests/plan_records.rs
@@ -0,0 +1,374 @@
+use super::*;
+use crate::workspace::{operation, plan as plan_store};
+use nostr::{JsonUtil, nips::nip44};
+use radroots_domain::{CommandContextData, EnvelopeEventId, OperationId};
+use radroots_protocol::{
+ chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan},
+ command::{CapturedChatCommand, InquireInput},
+};
+use radroots_storage::command::{
+ AdmissionOutcome, AdmissionRequest, OperationJournal, PlanBindingOutcome,
+};
+use serde_json::{Value, json};
+use sqlx::{Connection, SqliteConnection};
+
+#[tokio::test]
+async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_each_inconsistency() {
+ let fixture = CryptoFixture::new();
+ let path = fixture
+ ._temp
+ .path()
+ .canonicalize()
+ .unwrap()
+ .join("plan-records");
+ let (store, selected, proof) = NativeWorkspace::initialize_local_outbox(
+ &path,
+ LocalOutboxConfig::new(
+ participant(),
+ participant(),
+ "device",
+ UnixSeconds::new(200).unwrap(),
+ )
+ .unwrap(),
+ fixture.crypto(),
+ Arc::new(FixedClock(100)),
+ )
+ .await
+ .unwrap();
+ let binding = store.authenticate(selected.clone(), &proof).await.unwrap();
+ let operation_id = OperationId::from_bytes([51; 32]);
+ let context = CommandContextData::new(
+ operation_id,
+ binding.actor(),
+ selected.workspace_id(),
+ selected.authority(),
+ selected.route_digest(),
+ None,
+ None,
+ UnixSeconds::new(150).unwrap(),
+ None,
+ )
+ .unwrap();
+ let command = CapturedChatCommand::inquire(
+ context,
+ InquireInput::new(
+ radroots_domain::ThreadId::from_bytes([6; 32]),
+ participant(),
+ None,
+ "protected native plan fixture",
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let rumor = ChatRumor::from_command(&command, UnixSeconds::new(100).unwrap()).unwrap();
+ let mut scalar = [0; 32];
+ scalar[31] = 1;
+ let keys = nostr::Keys::new(nostr::SecretKey::from_slice(&scalar).unwrap());
+ let ciphertext = nip44::encrypt(
+ keys.secret_key(),
+ &keys.public_key(),
+ rumor.json(),
+ nip44::Version::V2,
+ )
+ .unwrap();
+ let seal = ChatSeal::new(
+ &rumor,
+ participant(),
+ UnixSeconds::new(99).unwrap(),
+ &ciphertext,
+ )
+ .unwrap();
+ let source = nostr::UnsignedEvent {
+ id: None,
+ pubkey: keys.public_key(),
+ created_at: nostr::Timestamp::from_secs(99),
+ kind: nostr::Kind::Custom(10050),
+ tags: nostr::Tags::from_list(vec![
+ nostr::Tag::parse(["relay", "wss://route.example/"]).unwrap(),
+ ]),
+ content: "public route metadata ".repeat(1000),
+ }
+ .sign_with_keys(&keys)
+ .unwrap();
+ let route = CapturedDmRoute::from_observed_descriptor(
+ participant(),
+ EnvelopeEventId::from_bytes(*source.id.as_bytes()),
+ &source.as_json(),
+ &["wss://route.example/".into()],
+ )
+ .unwrap();
+ let plan = ChatSigningPlan::new(
+ &command,
+ UnixSeconds::new(100).unwrap(),
+ vec![seal],
+ vec![route],
+ ChatReplay::NonReplayable,
+ )
+ .unwrap();
+ let digest = *plan.digest();
+ let original_wire = plan.protected_wire().to_vec();
+ let copied =
+ || proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes).unwrap());
+ assert!(matches!(
+ store
+ .admit_command_and_hold(
+ AdmissionRequest::new(binding.clone(), command).unwrap(),
+ copied()
+ )
+ .await
+ .unwrap(),
+ AdmissionOutcome::Committed(_)
+ ));
+ assert!(matches!(
+ store
+ .bind_signing_intents(binding, plan, copied())
+ .await
+ .unwrap(),
+ PlanBindingOutcome::Committed(_)
+ ));
+ store.close().await.unwrap();
+ let mut database = SqliteConnection::connect_with(
+ &sqlx::sqlite::SqliteConnectOptions::new()
+ .filename(path.join("execution_v1.sqlite"))
+ .create_if_missing(false)
+ .foreign_keys(false),
+ )
+ .await
+ .unwrap();
+ sqlx::query("PRAGMA ignore_check_constraints=ON")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ let crypto = fixture.crypto();
+ let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM signing_plans")
+ .fetch_one(&mut database)
+ .await
+ .unwrap();
+ let manifest: Value = crypto
+ .open_plan_part(selected.workspace_id(), operation_id, &digest, 0, &original)
+ .await
+ .unwrap()
+ .expose_secret(|bytes| serde_json::from_slice(bytes).unwrap());
+ for (field, value) in [
+ ("version", json!(2)),
+ ("workspace", json!("99".repeat(32))),
+ ("operation_id", json!("99".repeat(32))),
+ ("command_digest", json!("99".repeat(32))),
+ ("preparation_transaction", json!("99".repeat(32))),
+ ("plan_digest", json!("99".repeat(32))),
+ ("transaction_id", json!("99".repeat(32))),
+ ("part_count", json!(24)),
+ ("byte_count", json!(1)),
+ ("bound_at", json!("0")),
+ ] {
+ let mut changed = manifest.clone();
+ changed[field] = value;
+ let protected = crypto
+ .seal_plan_part(
+ selected.workspace_id(),
+ operation_id,
+ &digest,
+ 0,
+ &serde_json::to_vec(&changed).unwrap(),
+ )
+ .await
+ .unwrap();
+ sqlx::query("UPDATE signing_plans SET protected=?")
+ .bind(&protected)
+ .execute(&mut database)
+ .await
+ .unwrap();
+ let prepared = operation::read(&mut database, &selected, operation_id, &crypto)
+ .await
+ .unwrap()
+ .unwrap()
+ .0;
+ let error = plan_store::read(&mut database, &selected, prepared, &crypto)
+ .await
+ .err()
+ .expect("inconsistent authenticated manifest must fail");
+ assert_eq!(error.code(), "recovery_required", "{field}");
+ let retained: Vec<u8> = sqlx::query_scalar("SELECT protected FROM signing_plans")
+ .fetch_one(&mut database)
+ .await
+ .unwrap();
+ assert_eq!(retained, protected);
+ }
+ sqlx::query("UPDATE signing_plans SET protected=?")
+ .bind(&original)
+ .execute(&mut database)
+ .await
+ .unwrap();
+ let original_parts: Vec<(i64, Vec<u8>)> =
+ sqlx::query_as("SELECT part,protected FROM signing_plan_parts ORDER BY part")
+ .fetch_all(&mut database)
+ .await
+ .unwrap();
+ assert!(original_parts.len() > 1);
+ for fault in 0..7 {
+ sqlx::query("DELETE FROM signing_plan_parts")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ for (part, protected) in &original_parts {
+ sqlx::query("INSERT INTO signing_plan_parts(workspace,operation_id,part,protected) VALUES(?,?,?,?)").bind(selected.workspace_id().as_bytes().as_slice()).bind(operation_id.as_bytes().as_slice()).bind(part).bind(protected).execute(&mut database).await.unwrap();
+ }
+ match fault {
+ 0 => {
+ sqlx::query("DELETE FROM signing_plan_parts WHERE part=1")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ 1 => {
+ sqlx::query("UPDATE signing_plan_parts SET protected=zeroblob(0)")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ 2 => {
+ sqlx::query(
+ "UPDATE signing_plan_parts SET protected=zeroblob(2097153) WHERE part=1",
+ )
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ 3 => {
+ sqlx::query("UPDATE signing_plan_parts SET part=0 WHERE part=1")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ 4 | 5 => {
+ let mut bytes = if fault == 4 {
+ vec![0]
+ } else {
+ original_wire[..16384].to_vec()
+ };
+ if fault == 5 {
+ bytes[b"radroots.chat.signing_plan.v1\0".len() + 32 * 3 + 8] = 1;
+ }
+ let protected = crypto
+ .seal_plan_part(selected.workspace_id(), operation_id, &digest, 1, &bytes)
+ .await
+ .unwrap();
+ sqlx::query("UPDATE signing_plan_parts SET protected=? WHERE part=1")
+ .bind(protected)
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ 6 => {
+ sqlx::query("UPDATE signing_plans SET byte_count=1")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ _ => unreachable!(),
+ }
+ let prepared = operation::read(&mut database, &selected, operation_id, &crypto)
+ .await
+ .unwrap()
+ .unwrap()
+ .0;
+ let error = plan_store::read(&mut database, &selected, prepared, &crypto)
+ .await
+ .err()
+ .expect("part inconsistency must fail");
+ assert_eq!(error.code(), "recovery_required", "part fault {fault}");
+ sqlx::query("UPDATE signing_plans SET byte_count=?")
+ .bind(original_wire.len() as i64)
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ sqlx::query("DELETE FROM signing_plan_parts")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ for (part, protected) in &original_parts {
+ sqlx::query(
+ "INSERT INTO signing_plan_parts(workspace,operation_id,part,protected) VALUES(?,?,?,?)",
+ )
+ .bind(selected.workspace_id().as_bytes().as_slice())
+ .bind(operation_id.as_bytes().as_slice())
+ .bind(part)
+ .bind(protected)
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ let prepared = operation::read(&mut database, &selected, operation_id, &crypto)
+ .await
+ .unwrap()
+ .unwrap()
+ .0;
+ let (prepared, value) = plan_store::read(&mut database, &selected, prepared, &crypto)
+ .await
+ .unwrap();
+ let (_, _, _, protected) = value.unwrap();
+ assert!(
+ plan_store::unchanged(&mut database, &prepared, None)
+ .await
+ .is_err()
+ );
+ for fault in 0..4 {
+ match fault {
+ 0 => {
+ sqlx::query("UPDATE signing_plans SET transaction_id=zeroblob(32)")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ 1 => {
+ sqlx::query("UPDATE signing_plan_parts SET protected=zeroblob(1) WHERE part=1")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ 2 => {
+ sqlx::query("DELETE FROM signing_plan_parts WHERE part=1")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ 3 => {
+ sqlx::query("DELETE FROM signing_plans")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ _ => unreachable!(),
+ }
+ assert!(
+ plan_store::unchanged(&mut database, &prepared, Some(&protected))
+ .await
+ .is_err(),
+ "transaction fault {fault}"
+ );
+ if fault == 0 {
+ sqlx::query("UPDATE signing_plans SET transaction_id=?")
+ .bind(protected.transaction.as_bytes().as_slice())
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ if fault == 1 {
+ sqlx::query("UPDATE signing_plan_parts SET protected=? WHERE part=1")
+ .bind(&original_parts[0].1)
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ if fault == 2 {
+ sqlx::query("INSERT INTO signing_plan_parts(workspace,operation_id,part,protected) VALUES(?,?,1,?)").bind(selected.workspace_id().as_bytes().as_slice()).bind(operation_id.as_bytes().as_slice()).bind(&original_parts[0].1).execute(&mut database).await.unwrap();
+ }
+ }
+ assert!(
+ plan_store::unchanged(&mut database, &prepared, None)
+ .await
+ .is_err()
+ );
+ database.close().await.unwrap();
+}
diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs
@@ -1,10 +1,11 @@
use super::{
AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto,
- WorkspaceError, admission::Journal, fs::Namespace, operation, record::GrantRecord,
+ WorkspaceError, admission::Journal, fs::Namespace, operation, plan, record::GrantRecord,
};
use radroots_domain::{CommandDigest, OperationId};
use radroots_storage::command::{
- AdmissionOutcome, AdmissionRequest, CommitAttempt, OperationError, PreparedOperation,
+ AdmissionOutcome, AdmissionRequest, BoundSigningPlan, ChatSigningPlan, CommitAttempt,
+ OperationError, PlanBindingOutcome, PreparedOperation,
};
use sqlx::{
Connection, Row, SqliteConnection,
@@ -14,6 +15,7 @@ use std::{
path::PathBuf,
sync::{
Arc, Mutex,
+ atomic::{AtomicUsize, Ordering},
mpsc::{self, SyncSender},
},
thread::JoinHandle,
@@ -21,14 +23,26 @@ use std::{
};
use tokio::sync::{oneshot, watch};
-// Each request holds bounded descriptors and one 32-byte proof. With 32
-// queued requests and a single in-flight request this is below the 4 MiB
-// contract. Command data has a 64 KiB canonical bound, 4 KiB decoded text and
-// bounded exact-sized descriptors; no unbounded event/SQL enters this queue.
+// Count conservative retained input bounds across queued and in-flight jobs.
+// Plan jobs retain both their canonical bytes and bounded decoded fields.
+const QUEUE_MAX_BYTES: usize = 4 * 1024 * 1024;
const QUEUE_CAPACITY: usize = 32;
const TABLE: &str = "CREATE TABLE workspace_grant (singleton INTEGER PRIMARY KEY CHECK(singleton=1), workspace BLOB NOT NULL CHECK(length(workspace)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT";
type Reply<T, E = WorkspaceError> = oneshot::Sender<Result<T, E>>;
enum Job {
+ BindPlan(
+ Box<WorkspaceBinding>,
+ ChatSigningPlan,
+ AttachmentProof,
+ Reply<PlanBindingOutcome, OperationError>,
+ ),
+ SigningPlan(
+ Box<WorkspaceBinding>,
+ OperationId,
+ CommandDigest,
+ AttachmentProof,
+ Reply<Option<BoundSigningPlan>, OperationError>,
+ ),
Authenticate(AttachmentInput, AttachmentProof, Reply<WorkspaceBinding>),
Revoke(AttachmentInput, AttachmentProof, Reply<()>),
Admit(
@@ -44,8 +58,22 @@ enum Job {
Reply<Option<PreparedOperation>, OperationError>,
),
}
+struct Budget {
+ used: Arc<AtomicUsize>,
+ bytes: usize,
+}
+impl Drop for Budget {
+ fn drop(&mut self) {
+ self.used.fetch_sub(self.bytes, Ordering::AcqRel);
+ }
+}
+struct Queued {
+ job: Job,
+ _budget: Budget,
+}
pub(super) struct Handle {
- sender: Mutex<Option<SyncSender<Job>>>,
+ sender: Mutex<Option<SyncSender<Queued>>>,
+ queued_bytes: Arc<AtomicUsize>,
completed: watch::Receiver<Option<Result<(), WorkspaceError>>>,
thread: Mutex<Option<JoinHandle<()>>>,
}
@@ -57,7 +85,8 @@ impl Handle {
crypto: WorkspaceCrypto,
clock: Arc<dyn WorkspaceClock>,
) -> Result<Self, WorkspaceError> {
- let (sender, requests) = mpsc::sync_channel(QUEUE_CAPACITY);
+ let (sender, requests) = mpsc::sync_channel::<Queued>(QUEUE_CAPACITY);
+ let queued_bytes = Arc::new(AtomicUsize::new(0));
let (ready, started) = oneshot::channel();
let (completion, completed) = watch::channel(None);
let thread = std::thread::Builder::new()
@@ -117,8 +146,34 @@ impl Handle {
}
let mut uncertain = false;
if ready.send(Ok(())).is_ok() {
- while let Ok(job) = requests.recv() {
+ while let Ok(Queued { job, _budget }) = requests.recv() {
match job {
+ Job::BindPlan(binding, plan, proof, reply) => {
+ let result = Journal {
+ connection: &mut connection,
+ namespace: &namespace,
+ selected: &input,
+ crypto: &crypto,
+ clock: clock.as_ref(),
+ uncertain: &mut uncertain,
+ }
+ .bind_plan(*binding, plan, proof)
+ .await;
+ let _ = reply.send(result);
+ }
+ Job::SigningPlan(binding, operation_id, digest, proof, reply) => {
+ let result = Journal {
+ connection: &mut connection,
+ namespace: &namespace,
+ selected: &input,
+ crypto: &crypto,
+ clock: clock.as_ref(),
+ uncertain: &mut uncertain,
+ }
+ .query_plan(*binding, operation_id, digest, proof)
+ .await;
+ let _ = reply.send(result);
+ }
Job::Authenticate(selected, proof, reply) => {
let result = authenticate(
&mut connection,
@@ -195,6 +250,7 @@ impl Handle {
.map_err(|_| WorkspaceError::Unavailable)?;
let handle = Self {
sender: Mutex::new(Some(sender)),
+ queued_bytes,
completed,
thread: Mutex::new(Some(thread)),
};
@@ -211,17 +267,71 @@ impl Handle {
}
}
fn send(&self, job: Job) -> Result<(), WorkspaceError> {
+ let bytes = match &job {
+ Job::BindPlan(..) => 1024 * 1024,
+ Job::Admit(..) => 96 * 1024,
+ _ => 16 * 1024,
+ };
+ self.queued_bytes
+ .try_update(Ordering::AcqRel, Ordering::Acquire, |used| {
+ used.checked_add(bytes)
+ .filter(|next| *next <= QUEUE_MAX_BYTES)
+ })
+ .map_err(|_| WorkspaceError::Unavailable)?;
+ let queued = Queued {
+ job,
+ _budget: Budget {
+ used: self.queued_bytes.clone(),
+ bytes,
+ },
+ };
self.sender
.lock()
.map_err(|_| WorkspaceError::Unavailable)?
.as_ref()
.ok_or(WorkspaceError::Closed)?
- .try_send(job)
+ .try_send(queued)
.map_err(|error| match error {
mpsc::TrySendError::Full(_) => WorkspaceError::Unavailable,
mpsc::TrySendError::Disconnected(_) => WorkspaceError::Closed,
})
}
+ pub(super) async fn bind_plan(
+ &self,
+ binding: WorkspaceBinding,
+ plan: ChatSigningPlan,
+ proof: AttachmentProof,
+ ) -> Result<PlanBindingOutcome, OperationError> {
+ let anchor = CommitAttempt::new(
+ binding.input().workspace_id(),
+ plan.operation_id(),
+ plan.command_digest(),
+ None,
+ );
+ let (reply, result) = oneshot::channel();
+ self.send(Job::BindPlan(Box::new(binding), plan, proof, reply))?;
+ match result.await {
+ Ok(result) => result,
+ Err(_) => Ok(PlanBindingOutcome::Unknown(anchor)),
+ }
+ }
+ pub(super) async fn signing_plan(
+ &self,
+ binding: WorkspaceBinding,
+ operation_id: OperationId,
+ digest: CommandDigest,
+ proof: AttachmentProof,
+ ) -> Result<Option<BoundSigningPlan>, OperationError> {
+ let (reply, result) = oneshot::channel();
+ self.send(Job::SigningPlan(
+ Box::new(binding),
+ operation_id,
+ digest,
+ proof,
+ reply,
+ ))?;
+ result.await.map_err(|_| OperationError::RecoveryRequired)?
+ }
pub(super) async fn authenticate(
&self,
input: AttachmentInput,
@@ -357,7 +467,15 @@ async fn initialize(
.execute(&mut *transaction)
.await
.map_err(|_| WorkspaceError::StorageFailure)?;
- sqlx::query("PRAGMA user_version=3")
+ sqlx::raw_sql(plan::TABLE)
+ .execute(&mut *transaction)
+ .await
+ .map_err(|_| WorkspaceError::StorageFailure)?;
+ sqlx::raw_sql(plan::PARTS)
+ .execute(&mut *transaction)
+ .await
+ .map_err(|_| WorkspaceError::StorageFailure)?;
+ sqlx::query("PRAGMA user_version=4")
.execute(&mut *transaction)
.await
.map_err(|_| WorkspaceError::StorageFailure)?;
@@ -379,11 +497,11 @@ async fn initialize(
.fetch_one(&mut *connection)
.await
.map_err(|_| WorkspaceError::RecoveryRequired)?;
- if version != 3 {
+ if version != 4 {
return Err(WorkspaceError::RecoveryRequired);
}
- let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=3 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='index' AND name='operation_transaction_identity' AND tbl_name='operations' AND sql=? THEN 1 ELSE 0 END)=3 THEN 1 ELSE 0 END FROM sqlite_schema")
- .bind(TABLE).bind(operation::TABLE).bind(operation::INDEX).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?;
+ let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=5 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='index' AND name='operation_transaction_identity' AND tbl_name='operations' AND sql=? THEN 1 ELSE 0 END)=5 THEN 1 ELSE 0 END FROM sqlite_schema")
+ .bind(TABLE).bind(operation::TABLE).bind(plan::TABLE).bind(plan::PARTS).bind(operation::INDEX).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?;
if catalog_matches != 1 {
return Err(WorkspaceError::RecoveryRequired);
}
diff --git a/crates/storage_sqlite/tests/support/workspace_plans.rs b/crates/storage_sqlite/tests/support/workspace_plans.rs
@@ -0,0 +1,471 @@
+//! Native storage tests use real synthetic NIP-44 data, never host custody.
+use super::*;
+use nostr::{JsonUtil, nips::nip44};
+use radroots_domain::EnvelopeEventId;
+use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan};
+use radroots_storage::command::{BoundSigningPlan, PlanBindingOutcome};
+fn keys(last: u8) -> nostr::Keys {
+ let mut bytes = [0; 32];
+ bytes[31] = last;
+ nostr::Keys::new(nostr::SecretKey::from_slice(&bytes).unwrap())
+}
+fn peer_request(binding: &WorkspaceBinding, id: u8) -> AdmissionRequest {
+ let request = request(binding, id, "protected complete private plan", "original");
+ let mut value: serde_json::Value =
+ serde_json::from_slice(request.command().protected_wire()).unwrap();
+ value["input"]["peer"] = keys(2).public_key().to_hex().into();
+ AdmissionRequest::from_protected_wire(binding.clone(), &serde_json::to_vec(&value).unwrap())
+ .unwrap()
+}
+fn plan(
+ command: &radroots_protocol::command::CapturedChatCommand,
+ created: u64,
+ suffix: &str,
+) -> ChatSigningPlan {
+ let rumor = ChatRumor::from_command(command, UnixSeconds::new(created).unwrap()).unwrap();
+ let author = keys(1);
+ let mut seals = Vec::new();
+ let mut routes = Vec::new();
+ for recipient in rumor.recipients() {
+ let target = nostr::PublicKey::from_slice(recipient.as_bytes()).unwrap();
+ let ciphertext = nip44::encrypt(
+ author.secret_key(),
+ &target,
+ rumor.json(),
+ nip44::Version::V2,
+ )
+ .unwrap();
+ seals.push(
+ ChatSeal::new(
+ &rumor,
+ *recipient,
+ UnixSeconds::new(created - 1).unwrap(),
+ &ciphertext,
+ )
+ .unwrap(),
+ );
+ let signer = if recipient == &key() {
+ keys(1)
+ } else {
+ keys(2)
+ };
+ let url = format!("wss://relay.example/{suffix}");
+ let source = nostr::UnsignedEvent {
+ id: None,
+ pubkey: signer.public_key(),
+ created_at: nostr::Timestamp::from_secs(created - 1),
+ kind: nostr::Kind::Custom(10050),
+ tags: nostr::Tags::from_list(vec![nostr::Tag::parse(["relay", &url]).unwrap()]),
+ content: "public signed route provenance ".repeat(1000),
+ }
+ .sign_with_keys(&signer)
+ .unwrap();
+ source.verify().unwrap();
+ routes.push(
+ CapturedDmRoute::from_observed_descriptor(
+ *recipient,
+ EnvelopeEventId::from_bytes(*source.id.as_bytes()),
+ &source.as_json(),
+ &[url],
+ )
+ .unwrap(),
+ );
+ }
+ ChatSigningPlan::new(
+ command,
+ UnixSeconds::new(created).unwrap(),
+ seals,
+ routes,
+ ChatReplay::NonReplayable,
+ )
+ .unwrap()
+}
+fn bound(outcome: PlanBindingOutcome) -> BoundSigningPlan {
+ match outcome {
+ PlanBindingOutcome::Committed(bound) => bound,
+ PlanBindingOutcome::Unknown(_) => panic!("fixture must confirm T1"),
+ }
+}
+#[tokio::test]
+async fn complete_private_plan_commits_reopens_and_replays_exact_original_bytes_after_expiry() {
+ let fixture = Fixture::new();
+ let (store, input, proof, binding) = fixture.create().await;
+ let prepared = committed(
+ store
+ .admit_command_and_hold(peer_request(&binding, 90), copy(&proof))
+ .await
+ .unwrap(),
+ );
+ let original = plan(prepared.request().command(), 100, "original");
+ let wire = original.protected_wire().to_vec();
+ let digest = prepared.identity().command_digest();
+ let operation = prepared.identity().operation_id();
+ assert!(
+ store
+ .signing_plan(binding.clone(), operation, digest, copy(&proof))
+ .await
+ .unwrap()
+ .is_none()
+ );
+ let retained = bound(
+ store
+ .bind_signing_intents(binding.clone(), original, copy(&proof))
+ .await
+ .unwrap(),
+ );
+ assert_eq!(retained.plan().seals().len(), 2);
+ assert_eq!(retained.plan().protected_wire(), wire);
+ assert_eq!(
+ retained.prepared().transaction_id(),
+ prepared.transaction_id()
+ );
+ let transaction = retained.transaction_id();
+ let altered = plan(prepared.request().command(), 100, "changed");
+ assert!(matches!(
+ store
+ .bind_signing_intents(binding.clone(), altered, copy(&proof))
+ .await,
+ Err(OperationError::IdempotencyConflict)
+ ));
+ fixture.clock.now.store(151, Ordering::SeqCst);
+ let replay = ChatSigningPlan::parse(prepared.request().command(), &wire).unwrap();
+ assert_eq!(
+ bound(
+ store
+ .bind_signing_intents(binding.clone(), replay, copy(&proof))
+ .await
+ .unwrap()
+ )
+ .transaction_id(),
+ transaction
+ );
+ store.close().await.unwrap();
+ let database_bytes = std::fs::read(fixture.path.join("execution_v1.sqlite")).unwrap();
+ assert!(
+ !database_bytes
+ .windows(wire.len())
+ .any(|bytes| bytes == wire)
+ );
+ assert!(
+ !database_bytes
+ .windows(31)
+ .any(|bytes| bytes == b"protected complete private plan")
+ );
+ let reopened = fixture.reopen(input).await;
+ let recovered = reopened
+ .signing_plan(binding.clone(), operation, digest, copy(&proof))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(recovered.plan().protected_wire(), wire);
+ assert_eq!(recovered.transaction_id(), transaction);
+ assert_eq!(recovered.bound_at().get(), 100);
+ assert!(matches!(
+ reopened
+ .signing_plan(
+ binding,
+ operation,
+ CommandDigest::from_bytes([0; 32]),
+ copy(&proof)
+ )
+ .await,
+ Err(OperationError::IdempotencyConflict)
+ ));
+ reopened.close().await.unwrap();
+}
+#[tokio::test]
+async fn no_new_plan_commits_after_window_or_after_current_grant_revocation() {
+ for revoked in [false, true] {
+ let fixture = Fixture::new();
+ let (store, input, proof, binding) = fixture.create().await;
+ let prepared = committed(
+ store
+ .admit_command_and_hold(peer_request(&binding, 91), copy(&proof))
+ .await
+ .unwrap(),
+ );
+ let supplied = plan(prepared.request().command(), 100, "one");
+ if revoked {
+ store.revoke(input, &proof).await.unwrap();
+ } else {
+ fixture.clock.now.store(150, Ordering::SeqCst);
+ }
+ let result = store
+ .bind_signing_intents(binding, supplied, copy(&proof))
+ .await;
+ assert!(if revoked {
+ matches!(
+ result,
+ Err(OperationError::Workspace(WorkspaceError::GrantRevoked))
+ )
+ } else {
+ matches!(result, Err(OperationError::DeadlineExceeded))
+ });
+ store.close().await.unwrap();
+ let mut database = fixture.database().await;
+ let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans")
+ .fetch_one(&mut database)
+ .await
+ .unwrap();
+ assert_eq!(count, 0);
+ database.close().await.unwrap();
+ }
+}
+#[tokio::test]
+async fn admitted_plan_outlives_its_observer_and_byte_budget_refuses_unadmitted_work() {
+ let fixture = Fixture::new();
+ let (store, _, proof, binding) = fixture.create().await;
+ let mut preparations = Vec::new();
+ for id in 100..105 {
+ preparations.push(committed(
+ store
+ .admit_command_and_hold(peer_request(&binding, id), copy(&proof))
+ .await
+ .unwrap(),
+ ));
+ }
+ let (arrived, resume) = fixture.clock.arm(0);
+ let mut first = store.bind_signing_intents(
+ binding.clone(),
+ plan(preparations[0].request().command(), 100, "one"),
+ copy(&proof),
+ );
+ assert!(futures::poll!(first.as_mut()).is_pending());
+ reached(arrived).await;
+ drop(first);
+ let mut accepted = Vec::new();
+ for prepared in &preparations[1..4] {
+ let mut next = store.bind_signing_intents(
+ binding.clone(),
+ plan(prepared.request().command(), 100, "one"),
+ copy(&proof),
+ );
+ assert!(futures::poll!(next.as_mut()).is_pending());
+ accepted.push(next);
+ }
+ assert!(matches!(
+ store
+ .bind_signing_intents(
+ binding.clone(),
+ plan(preparations[4].request().command(), 100, "one"),
+ copy(&proof)
+ )
+ .await,
+ Err(OperationError::Workspace(WorkspaceError::Unavailable))
+ ));
+ resume.send(()).unwrap();
+ for next in accepted {
+ bound(next.await.unwrap());
+ }
+ let recovered = store
+ .signing_plan(
+ binding.clone(),
+ preparations[0].identity().operation_id(),
+ preparations[0].identity().command_digest(),
+ copy(&proof),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ recovered.plan().operation_id(),
+ preparations[0].identity().operation_id()
+ );
+ assert!(
+ store
+ .signing_plan(
+ binding,
+ preparations[4].identity().operation_id(),
+ preparations[4].identity().command_digest(),
+ copy(&proof)
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+ store.close().await.unwrap();
+}
+#[tokio::test]
+async fn expiry_during_protection_and_known_sql_rollback_preserve_unbound_preparation() {
+ for expire in [false, true] {
+ let fixture = Fixture::new();
+ let (store, _, proof, binding) = fixture.create().await;
+ let prepared = committed(
+ store
+ .admit_command_and_hold(peer_request(&binding, 110), copy(&proof))
+ .await
+ .unwrap(),
+ );
+ let supplied = plan(prepared.request().command(), 100, "one");
+ let mut database = fixture.database().await;
+ if !expire {
+ sqlx::raw_sql("CREATE TRIGGER reject_plan BEFORE INSERT ON signing_plan_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ABORT,'synthetic storage failure'); END").execute(&mut database).await.unwrap();
+ }
+ let (arrived, resume) = fixture.clock.arm(1);
+ let mut call = store.bind_signing_intents(binding.clone(), supplied, copy(&proof));
+ assert!(futures::poll!(call.as_mut()).is_pending());
+ reached(arrived).await;
+ if expire {
+ fixture.clock.now.store(150, Ordering::SeqCst);
+ }
+ resume.send(()).unwrap();
+ let result = call.await;
+ assert!(if expire {
+ matches!(result, Err(OperationError::DeadlineExceeded))
+ } else {
+ matches!(result, Err(OperationError::StorageFailure))
+ });
+ let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans")
+ .fetch_one(&mut database)
+ .await
+ .unwrap();
+ assert_eq!(count, 0);
+ if !expire {
+ sqlx::raw_sql("DROP TRIGGER reject_plan")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ }
+ database.close().await.unwrap();
+ assert!(
+ store
+ .signing_plan(
+ binding,
+ prepared.identity().operation_id(),
+ prepared.identity().command_digest(),
+ copy(&proof)
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+ store.close().await.unwrap();
+ }
+}
+
+#[tokio::test]
+async fn unknown_plan_completion_latches_until_reopen_and_preserves_original_operation_anchor() {
+ let fixture = Fixture::new();
+ let (store, input, proof, binding) = fixture.create().await;
+ let prepared = committed(
+ store
+ .admit_command_and_hold(peer_request(&binding, 120), copy(&proof))
+ .await
+ .unwrap(),
+ );
+ let supplied = plan(prepared.request().command(), 100, "one");
+ let mut database = fixture.database().await;
+ sqlx::raw_sql("CREATE TRIGGER unknown_plan BEFORE INSERT ON signing_plan_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ROLLBACK,'synthetic unknown completion'); END").execute(&mut database).await.unwrap();
+ let outcome = store
+ .bind_signing_intents(binding.clone(), supplied, copy(&proof))
+ .await
+ .unwrap();
+ match outcome {
+ PlanBindingOutcome::Unknown(anchor) => {
+ assert_eq!(anchor.workspace_id(), prepared.identity().workspace_id());
+ assert_eq!(anchor.operation_id(), prepared.identity().operation_id());
+ assert_eq!(
+ anchor.command_digest(),
+ prepared.identity().command_digest()
+ );
+ assert!(anchor.transaction_id().is_some());
+ }
+ _ => panic!("uncertain rollback must remain unknown"),
+ }
+ assert!(matches!(
+ store
+ .signing_plan(
+ binding.clone(),
+ prepared.identity().operation_id(),
+ prepared.identity().command_digest(),
+ copy(&proof)
+ )
+ .await,
+ Err(OperationError::RecoveryRequired)
+ ));
+ sqlx::raw_sql("DROP TRIGGER unknown_plan")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ database.close().await.unwrap();
+ store.close().await.unwrap();
+ let reopened = fixture.reopen(input).await;
+ assert!(
+ reopened
+ .signing_plan(
+ binding,
+ prepared.identity().operation_id(),
+ prepared.identity().command_digest(),
+ copy(&proof)
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+ reopened.close().await.unwrap();
+}
+#[tokio::test]
+async fn retained_plan_refuses_index_manifest_and_part_substitution_without_repair() {
+ let fixture = Fixture::new();
+ let (store, _, proof, binding) = fixture.create().await;
+ let prepared = committed(
+ store
+ .admit_command_and_hold(peer_request(&binding, 121), copy(&proof))
+ .await
+ .unwrap(),
+ );
+ bound(
+ store
+ .bind_signing_intents(
+ binding.clone(),
+ plan(prepared.request().command(), 100, "one"),
+ copy(&proof),
+ )
+ .await
+ .unwrap(),
+ );
+ let mut database = fixture.database().await;
+ sqlx::query("PRAGMA ignore_check_constraints=ON")
+ .execute(&mut database)
+ .await
+ .unwrap();
+ let header: (Vec<u8>, Vec<u8>, i64, i64, Vec<u8>) = sqlx::query_as(
+ "SELECT plan_digest,transaction_id,part_count,byte_count,protected FROM signing_plans",
+ )
+ .fetch_one(&mut database)
+ .await
+ .unwrap();
+ let part: Vec<u8> = sqlx::query_scalar("SELECT protected FROM signing_plan_parts WHERE part=1")
+ .fetch_one(&mut database)
+ .await
+ .unwrap();
+ for change in [
+ "UPDATE signing_plans SET plan_digest=zeroblob(32)",
+ "UPDATE signing_plans SET transaction_id=zeroblob(32)",
+ "UPDATE signing_plans SET part_count=25",
+ "UPDATE signing_plans SET byte_count=393217",
+ "UPDATE signing_plans SET protected=zeroblob(262145)",
+ "UPDATE signing_plan_parts SET protected=zeroblob(262145) WHERE part=1",
+ "UPDATE signing_plan_parts SET protected=zeroblob(64) WHERE part=1",
+ ] {
+ sqlx::query("UPDATE signing_plans SET plan_digest=?,transaction_id=?,part_count=?,byte_count=?,protected=?").bind(&header.0).bind(&header.1).bind(header.2).bind(header.3).bind(&header.4).execute(&mut database).await.unwrap();
+ sqlx::query("UPDATE signing_plan_parts SET protected=? WHERE part=1")
+ .bind(&part)
+ .execute(&mut database)
+ .await
+ .unwrap();
+ sqlx::query(change).execute(&mut database).await.unwrap();
+ let error = store
+ .signing_plan(
+ binding.clone(),
+ prepared.identity().operation_id(),
+ prepared.identity().command_digest(),
+ copy(&proof),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.code(), "recovery_required", "{change}: {error:?}");
+ }
+ database.close().await.unwrap();
+ store.close().await.unwrap();
+}
diff --git a/crates/storage_sqlite/tests/workspace_admission.rs b/crates/storage_sqlite/tests/workspace_admission.rs
@@ -1,5 +1,8 @@
#![cfg(unix)]
+#[path = "support/workspace_plans.rs"]
+mod plans;
+
use radroots_domain::{
CommandContextData, CommandDigest, CorrelationId, OperationId, PublicKey, UnixSeconds,
};
@@ -760,7 +763,7 @@ async fn predecessor_grant_only_schema_is_preserved_for_explicit_cutover() {
store.close().await.unwrap();
let mut database = fixture.database().await;
sqlx::raw_sql(
- "DROP INDEX operation_transaction_identity; DROP TABLE operations; PRAGMA user_version=1",
+ "DROP TABLE signing_plan_parts; DROP TABLE signing_plans; DROP INDEX operation_transaction_identity; DROP TABLE operations; PRAGMA user_version=1",
)
.execute(&mut database)
.await