lib

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

issuance.rs (19872B)


      1 //! Exact attempt and independently verified obtained-artifact data. Constructors
      2 //! provide no proof that a backend retained a claim or authorized dispatch.
      3 use super::{BoundSigningPlan, CommitAttempt, OperationError};
      4 use crate::workspace::WorkspaceBinding;
      5 use core::{fmt, num::NonZeroU64};
      6 use radroots_domain::{
      7     CommandDigest, EnvelopeEventId, OperationId, PublicKey, SigningAttemptId, TransactionId,
      8     UnixSeconds, WorkspaceId,
      9 };
     10 use radroots_event::{
     11     GenericEventDraft,
     12     wire::{EventWireLimits, Nip01EventWire},
     13 };
     14 use radroots_event_codec::{
     15     authoring::AuthoredEventPlan,
     16     verify::{self, Nip01SignatureVerifier, RawEvent},
     17 };
     18 use radroots_protocol::{
     19     chat::ChatSeal,
     20     intent::IntentBinding,
     21     plan::{SigningArtifact, SigningTarget},
     22 };
     23 use sha2::{Digest, Sha256};
     24 use zeroize::Zeroizing;
     25 
     26 /// Frozen selectors for claiming one retained recipient intent. No constructor
     27 /// authenticates a principal, approves a route or permits a signer invocation.
     28 pub struct ClaimAttemptRequest {
     29     binding: WorkspaceBinding,
     30     operation_id: OperationId,
     31     command_digest: CommandDigest,
     32     plan_digest: [u8; 32],
     33     target: SigningTarget,
     34 }
     35 impl ClaimAttemptRequest {
     36     pub const fn new(
     37         binding: WorkspaceBinding,
     38         operation_id: OperationId,
     39         command_digest: CommandDigest,
     40         plan_digest: [u8; 32],
     41         recipient: PublicKey,
     42     ) -> Self {
     43         Self::for_artifact(
     44             binding,
     45             operation_id,
     46             command_digest,
     47             plan_digest,
     48             SigningTarget::BusinessSeal(recipient),
     49         )
     50     }
     51     pub const fn for_artifact(
     52         binding: WorkspaceBinding,
     53         operation_id: OperationId,
     54         command_digest: CommandDigest,
     55         plan_digest: [u8; 32],
     56         target: SigningTarget,
     57     ) -> Self {
     58         Self {
     59             binding,
     60             operation_id,
     61             command_digest,
     62             plan_digest,
     63             target,
     64         }
     65     }
     66     pub const fn binding(&self) -> &WorkspaceBinding {
     67         &self.binding
     68     }
     69     pub const fn operation_id(&self) -> OperationId {
     70         self.operation_id
     71     }
     72     pub const fn command_digest(&self) -> CommandDigest {
     73         self.command_digest
     74     }
     75     pub const fn plan_digest(&self) -> &[u8; 32] {
     76         &self.plan_digest
     77     }
     78     pub const fn target(&self) -> SigningTarget {
     79         self.target
     80     }
     81     /// Private-only projection; a public artifact has no recipient.
     82     pub fn recipient(&self) -> Result<PublicKey, OperationError> {
     83         self.target
     84             .recipient()
     85             .ok_or(OperationError::UnsupportedOperation)
     86     }
     87     pub fn identity(&self) -> CommitAttempt {
     88         CommitAttempt::new(
     89             self.binding.input().workspace_id(),
     90             self.operation_id,
     91             self.command_digest,
     92             None,
     93         )
     94     }
     95 }
     96 impl fmt::Debug for ClaimAttemptRequest {
     97     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     98         f.write_str("ClaimAttemptRequest(<redacted>)")
     99     }
    100 }
    101 
    102 /// Actual store report of an immutable first claim. Construction remains
    103 /// structural. Only an actual newly committed claim may be dispatched once;
    104 /// retrieving this snapshot never proves a previous invocation did not begin.
    105 pub struct SigningAttempt {
    106     bound: BoundSigningPlan,
    107     target: SigningTarget,
    108     attempt_id: SigningAttemptId,
    109     transaction_id: TransactionId,
    110     claimed_at: UnixSeconds,
    111     binding: IntentBinding,
    112     deadline: NonZeroU64,
    113 }
    114 impl SigningAttempt {
    115     pub fn from_committed_store(
    116         bound: BoundSigningPlan,
    117         target: impl Into<SigningTarget>,
    118         attempt_id: SigningAttemptId,
    119         transaction_id: TransactionId,
    120         claimed_at: UnixSeconds,
    121     ) -> Result<Self, OperationError> {
    122         let window = bound.prepared().issuance_window();
    123         if claimed_at < bound.bound_at() || claimed_at >= window.first_issue_not_after() {
    124             return Err(OperationError::RecoveryRequired);
    125         }
    126         let target = target.into();
    127         if matches!(target, SigningTarget::PublicEvent) && bound.plan().listing().is_none()
    128             || matches!(target, SigningTarget::BusinessSeal(_)) && bound.plan().chat().is_none()
    129         {
    130             return Err(OperationError::UnsupportedOperation);
    131         }
    132         let artifact = bound
    133             .plan()
    134             .artifact(target)
    135             .map_err(|_| OperationError::InvalidCommand)?;
    136         let deadline = NonZeroU64::new(
    137             window
    138                 .first_issue_not_after()
    139                 .get()
    140                 .checked_mul(1000)
    141                 .ok_or(OperationError::RecoveryRequired)?,
    142         )
    143         .ok_or(OperationError::RecoveryRequired)?;
    144         let preimage_digest = match target {
    145             SigningTarget::PublicEvent => *bound.plan().digest(),
    146             SigningTarget::BusinessSeal(_) => {
    147                 let fields = artifact.fields();
    148                 // Internal reuse of the qualified v1 authored-plan hash. No predecessor
    149                 // event model escapes this new API; downward parser retirement remains
    150                 // separately governed by the shared target architecture.
    151                 let draft = GenericEventDraft::new(
    152                     "radroots.message.seal.v1",
    153                     fields.kind,
    154                     fields.created_at,
    155                     fields.tags.to_vec(),
    156                     fields.content,
    157                     fields.author.to_hex(),
    158                 )
    159                 .map_err(|_| OperationError::InvalidCommand)?;
    160                 let plan = AuthoredEventPlan::from_generic(draft)
    161                     .map_err(|_| OperationError::InvalidCommand)?;
    162                 if plan.expected_event_id().as_bytes() != &artifact.event_id() {
    163                     return Err(OperationError::RecoveryRequired);
    164                 }
    165                 *plan.digest().as_bytes()
    166             }
    167         };
    168         let binding = IntentBinding::from_components(
    169             bound.plan().operation_id(),
    170             *bound.plan().command_digest().as_bytes(),
    171             preimage_digest,
    172             target.role(),
    173             target.recipient(),
    174             deadline,
    175         )
    176         .map_err(|_| OperationError::InvalidCommand)?;
    177         Ok(Self {
    178             bound,
    179             target,
    180             attempt_id,
    181             transaction_id,
    182             claimed_at,
    183             binding,
    184             deadline,
    185         })
    186     }
    187     /// Transfers the immutable retained plan without creating another claim.
    188     pub fn into_bound_plan(self) -> BoundSigningPlan {
    189         self.bound
    190     }
    191     pub const fn bound_plan(&self) -> &BoundSigningPlan {
    192         &self.bound
    193     }
    194     /// Exact retained artifact, with no private projection for public events.
    195     pub fn artifact(&self) -> Result<SigningArtifact<'_>, OperationError> {
    196         self.bound
    197             .plan()
    198             .artifact(self.target)
    199             .map_err(|_| OperationError::RecoveryRequired)
    200     }
    201     pub const fn target(&self) -> SigningTarget {
    202         self.target
    203     }
    204     /// Borrows a private seal only when this attempt actually selected one.
    205     pub fn seal(&self) -> Result<&ChatSeal, OperationError> {
    206         match self.artifact()? {
    207             SigningArtifact::Seal(seal) => Ok(seal),
    208             _ => Err(OperationError::UnsupportedOperation),
    209         }
    210     }
    211     pub const fn attempt_id(&self) -> SigningAttemptId {
    212         self.attempt_id
    213     }
    214     pub const fn transaction_id(&self) -> TransactionId {
    215         self.transaction_id
    216     }
    217     pub const fn claimed_at(&self) -> UnixSeconds {
    218         self.claimed_at
    219     }
    220     pub const fn binding(&self) -> IntentBinding {
    221         self.binding
    222     }
    223     pub const fn deadline_unix_ms(&self) -> NonZeroU64 {
    224         self.deadline
    225     }
    226     pub fn identity(&self) -> CommitAttempt {
    227         let original = self.bound.prepared().identity();
    228         CommitAttempt::new(
    229             original.workspace_id(),
    230             original.operation_id(),
    231             original.command_digest(),
    232             Some(self.transaction_id),
    233         )
    234     }
    235 }
    236 impl fmt::Debug for SigningAttempt {
    237     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    238         f.write_str("SigningAttempt(<redacted>)")
    239     }
    240 }
    241 
    242 /// Confirmed new claim, retained potential issuance, or anchored uncertainty.
    243 /// A data variant alone cannot qualify a custom adapter's commit or dispatch.
    244 pub enum ClaimAttemptOutcome {
    245     /// Only this actual newly committed store result permits its owning
    246     /// executor to proceed once after route/provider/current-access checks.
    247     Claimed(SigningAttempt),
    248     /// Never dispatch again merely because this original record was found.
    249     Retained(SigningAttempt),
    250     /// Reconcile the original identity; never infer rollback/nonissuance.
    251     Unknown(CommitAttempt),
    252 }
    253 impl fmt::Debug for ClaimAttemptOutcome {
    254     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    255         f.write_str(match self {
    256             Self::Claimed(_) => "ClaimAttemptOutcome::Claimed(<redacted>)",
    257             Self::Retained(_) => "ClaimAttemptOutcome::Retained(<redacted>)",
    258             Self::Unknown(_) => "ClaimAttemptOutcome::Unknown(<retained>)",
    259         })
    260     }
    261 }
    262 
    263 /// Independently authenticated exact obtained bytes, bound to reported claim
    264 /// data but not proof of the backend's actual retained attempt. Concrete capture
    265 /// must compare its own protected claim and plan before appending this evidence.
    266 pub struct ArtifactEvidence {
    267     workspace_id: WorkspaceId,
    268     operation_id: OperationId,
    269     command_digest: CommandDigest,
    270     plan_digest: [u8; 32],
    271     target: SigningTarget,
    272     attempt_id: SigningAttemptId,
    273     intent: IntentBinding,
    274     event_id: EnvelopeEventId,
    275     raw: Zeroizing<String>,
    276     digest: [u8; 32],
    277     observed_at: Option<NonZeroU64>,
    278 }
    279 impl ArtifactEvidence {
    280     /// Bounds before copying and verifies ID/signature/every signed field.
    281     /// No clock, grant-expiry or cancellation lookup may discard obtained bytes.
    282     pub fn verify(
    283         attempt: &SigningAttempt,
    284         raw: &str,
    285         observed_at: Option<NonZeroU64>,
    286     ) -> Result<Self, OperationError> {
    287         if raw.len() > 65536 {
    288             return Err(OperationError::InvalidEvidence);
    289         }
    290         let limits = if attempt.target() == SigningTarget::PublicEvent {
    291             EventWireLimits {
    292                 max_raw_json_bytes: 65536,
    293                 max_content_bytes: 65536,
    294                 max_tag_count: radroots_protocol::listing::LISTING_TAG_MAX_COUNT,
    295                 max_total_tag_elements:
    296                     radroots_protocol::listing::LISTING_TAG_TOTAL_ELEMENT_MAX_COUNT,
    297                 max_tag_element_bytes: 65536,
    298                 max_total_tag_bytes: 65536,
    299                 max_extra_fields: 0,
    300                 max_total_extra_json_bytes: 0,
    301             }
    302         } else {
    303             EventWireLimits {
    304                 max_raw_json_bytes: 65536,
    305                 max_extra_fields: 0,
    306                 max_total_extra_json_bytes: 0,
    307                 ..EventWireLimits::default()
    308             }
    309         };
    310         let wire = Nip01EventWire::parse_json_exact_with_limits(raw, limits)
    311             .map_err(|_| OperationError::InvalidEvidence)?;
    312         let artifact = attempt.artifact()?;
    313         let fields = artifact.fields();
    314         let event_id = EnvelopeEventId::from_bytes(artifact.event_id());
    315         if wire.id != event_id.to_string()
    316             || wire.pubkey != fields.author.to_hex()
    317             || wire.kind != fields.kind
    318             || wire.created_at != fields.created_at
    319             || wire.tags != fields.tags
    320             || wire.content != fields.content
    321         {
    322             return Err(OperationError::InvalidEvidence);
    323         }
    324         let envelope =
    325             checked_envelope(wire, limits).map_err(|_| OperationError::InvalidEvidence)?;
    326         let id =
    327             verify::id(RawEvent::new(envelope)).map_err(|_| OperationError::InvalidEvidence)?;
    328         verify::signature(id, &Nip01SignatureVerifier)
    329             .map_err(|_| OperationError::InvalidEvidence)?;
    330         let original = attempt.bound_plan().prepared().identity();
    331         Ok(Self {
    332             workspace_id: original.workspace_id(),
    333             operation_id: original.operation_id(),
    334             command_digest: original.command_digest(),
    335             plan_digest: *attempt.bound_plan().plan().digest(),
    336             target: attempt.target(),
    337             attempt_id: attempt.attempt_id(),
    338             intent: attempt.binding(),
    339             event_id,
    340             raw: Zeroizing::new(String::from(raw)),
    341             digest: Sha256::digest(raw.as_bytes()).into(),
    342             observed_at: observed_at.filter(|time| time.get() <= 253_402_300_799_999),
    343         })
    344     }
    345     /// Explicitly copies a bounded already-verified value for the store owner;
    346     /// the caller keeps its sole original through actual durable completion.
    347     pub fn retained_copy(&self) -> Self {
    348         Self {
    349             workspace_id: self.workspace_id,
    350             operation_id: self.operation_id,
    351             command_digest: self.command_digest,
    352             plan_digest: self.plan_digest,
    353             target: self.target,
    354             attempt_id: self.attempt_id,
    355             intent: self.intent,
    356             event_id: self.event_id,
    357             raw: Zeroizing::new(self.raw.to_string()),
    358             digest: self.digest,
    359             observed_at: self.observed_at,
    360         }
    361     }
    362     pub fn matches_attempt(&self, attempt: &SigningAttempt) -> bool {
    363         let Ok(artifact) = attempt.artifact() else {
    364             return false;
    365         };
    366         self.workspace_id == attempt.bound_plan().prepared().identity().workspace_id()
    367             && self.attempt_id == attempt.attempt_id()
    368             && self.intent == attempt.binding()
    369             && self.operation_id == attempt.bound_plan().prepared().identity().operation_id()
    370             && self.command_digest == attempt.bound_plan().prepared().identity().command_digest()
    371             && &self.plan_digest == attempt.bound_plan().plan().digest()
    372             && self.target == attempt.target()
    373             && self.event_id.as_bytes() == &artifact.event_id()
    374     }
    375     pub const fn workspace_id(&self) -> WorkspaceId {
    376         self.workspace_id
    377     }
    378     pub const fn operation_id(&self) -> OperationId {
    379         self.operation_id
    380     }
    381     pub const fn command_digest(&self) -> CommandDigest {
    382         self.command_digest
    383     }
    384     pub const fn plan_digest(&self) -> &[u8; 32] {
    385         &self.plan_digest
    386     }
    387     pub const fn target(&self) -> SigningTarget {
    388         self.target
    389     }
    390     /// Private-only projection; a public artifact has no recipient.
    391     pub fn recipient(&self) -> Result<PublicKey, OperationError> {
    392         self.target
    393             .recipient()
    394             .ok_or(OperationError::UnsupportedOperation)
    395     }
    396     pub const fn attempt_id(&self) -> SigningAttemptId {
    397         self.attempt_id
    398     }
    399     pub const fn intent(&self) -> IntentBinding {
    400         self.intent
    401     }
    402     pub const fn event_id(&self) -> EnvelopeEventId {
    403         self.event_id
    404     }
    405     pub fn raw_json(&self) -> &str {
    406         &self.raw
    407     }
    408     pub const fn digest(&self) -> &[u8; 32] {
    409         &self.digest
    410     }
    411     pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> {
    412         self.observed_at
    413     }
    414 }
    415 impl fmt::Debug for ArtifactEvidence {
    416     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    417         f.write_str("ArtifactEvidence(<redacted>)")
    418     }
    419 }
    420 
    421 /// Fixed reference to exact retained obtained bytes. Data construction alone
    422 /// supplies no proof of capture, business installation or delivery.
    423 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    424 pub struct EvidenceReceipt {
    425     workspace_id: WorkspaceId,
    426     operation_id: OperationId,
    427     command_digest: CommandDigest,
    428     attempt_id: SigningAttemptId,
    429     target: SigningTarget,
    430     event_id: EnvelopeEventId,
    431     digest: [u8; 32],
    432     transaction_id: TransactionId,
    433     observed_at: Option<NonZeroU64>,
    434 }
    435 impl EvidenceReceipt {
    436     pub const fn from_committed_store(
    437         evidence: &ArtifactEvidence,
    438         transaction_id: TransactionId,
    439     ) -> Self {
    440         Self {
    441             workspace_id: evidence.workspace_id,
    442             operation_id: evidence.operation_id,
    443             command_digest: evidence.command_digest,
    444             attempt_id: evidence.attempt_id,
    445             target: evidence.target,
    446             event_id: evidence.event_id,
    447             digest: evidence.digest,
    448             transaction_id,
    449             observed_at: evidence.observed_at,
    450         }
    451     }
    452     pub const fn workspace_id(&self) -> WorkspaceId {
    453         self.workspace_id
    454     }
    455     pub const fn operation_id(&self) -> OperationId {
    456         self.operation_id
    457     }
    458     pub const fn command_digest(&self) -> CommandDigest {
    459         self.command_digest
    460     }
    461     pub const fn attempt_id(&self) -> SigningAttemptId {
    462         self.attempt_id
    463     }
    464     pub const fn target(&self) -> SigningTarget {
    465         self.target
    466     }
    467     /// Private-only projection; a public artifact has no recipient.
    468     pub fn recipient(&self) -> Result<PublicKey, OperationError> {
    469         self.target
    470             .recipient()
    471             .ok_or(OperationError::UnsupportedOperation)
    472     }
    473     pub const fn event_id(&self) -> EnvelopeEventId {
    474         self.event_id
    475     }
    476     pub const fn digest(&self) -> &[u8; 32] {
    477         &self.digest
    478     }
    479     pub const fn transaction_id(&self) -> TransactionId {
    480         self.transaction_id
    481     }
    482     pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> {
    483         self.observed_at
    484     }
    485 }
    486 /// Actual capture completion, separate from installing or sending a record.
    487 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    488 pub enum EvidenceCaptureOutcome {
    489     Committed(EvidenceReceipt),
    490     Unknown(CommitAttempt),
    491 }
    492 /// An original protected obtained record read under current workspace access.
    493 /// Advanced adapter construction remains a structural report, not qualification.
    494 pub struct CapturedArtifact {
    495     attempt: SigningAttempt,
    496     evidence: ArtifactEvidence,
    497     receipt: EvidenceReceipt,
    498 }
    499 impl CapturedArtifact {
    500     pub fn from_committed_store(
    501         attempt: SigningAttempt,
    502         evidence: ArtifactEvidence,
    503         transaction_id: TransactionId,
    504     ) -> Result<Self, OperationError> {
    505         if !evidence.matches_attempt(&attempt) {
    506             return Err(OperationError::RecoveryRequired);
    507         }
    508         let receipt = EvidenceReceipt::from_committed_store(&evidence, transaction_id);
    509         Ok(Self {
    510             attempt,
    511             evidence,
    512             receipt,
    513         })
    514     }
    515     pub const fn attempt(&self) -> &SigningAttempt {
    516         &self.attempt
    517     }
    518     pub const fn evidence(&self) -> &ArtifactEvidence {
    519         &self.evidence
    520     }
    521     pub const fn receipt(&self) -> EvidenceReceipt {
    522         self.receipt
    523     }
    524 }
    525 impl fmt::Debug for CapturedArtifact {
    526     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    527         f.write_str("CapturedArtifact(<redacted>)")
    528     }
    529 }
    530 
    531 fn checked_envelope(
    532     wire: Nip01EventWire,
    533     limits: EventWireLimits,
    534 ) -> Result<radroots_event::envelope::EventEnvelope, radroots_event::envelope::EventEnvelopeError> {
    535     use radroots_event::envelope::{EventEnvelope, EventEnvelopeLimits, EventEnvelopeParts};
    536     EventEnvelope::new_with_limits(
    537         EventEnvelopeParts {
    538             id: wire.id,
    539             author: wire.pubkey,
    540             created_at: wire.created_at,
    541             kind: wire.kind,
    542             tags: wire.tags,
    543             content: wire.content,
    544             sig: wire.sig,
    545         },
    546         EventEnvelopeLimits {
    547             max_content_bytes: limits.max_content_bytes,
    548             max_tag_count: limits.max_tag_count,
    549             max_total_tag_elements: limits.max_total_tag_elements,
    550             max_tag_element_bytes: limits.max_tag_element_bytes,
    551             max_total_tag_bytes: limits.max_total_tag_bytes,
    552         },
    553     )
    554 }