issuance.rs (22895B)
1 //! Exact-intent signature facts with nullable observation and no durable claim. 2 3 use crate::provider::{ProviderCall, ProviderError}; 4 #[cfg(not(feature = "std"))] 5 use alloc::string::String; 6 use core::{fmt, num::NonZeroU64}; 7 use radroots_domain::OperationId; 8 use radroots_event::{ 9 id::EventId, 10 wire::{EventWireLimits, Nip01EventWire}, 11 }; 12 use radroots_event_codec::{ 13 authoring::AuthoredEventPlan, 14 verify::{self, Nip01SignatureVerifier, RawEvent}, 15 }; 16 use radroots_identity::PublicKey; 17 use sha2::{Digest, Sha256}; 18 #[cfg(feature = "std")] 19 use std::string::String; 20 use zeroize::Zeroizing; 21 22 /// Maximum complete serialized event, including keys, tags and signature. 23 pub const SIGNED_EVENT_MAX_BYTES: usize = 65_536; 24 /// Maximum supported authored timestamp in seconds (year 9999). 25 pub const MAX_EVENT_UNIX_SECONDS: u64 = 253_402_300_799; 26 const MAX_OBSERVATION_UNIX_MS: u64 = MAX_EVENT_UNIX_SECONDS * 1000 + 999; 27 28 #[cfg(any(feature = "chat", feature = "commerce"))] 29 mod dm_relays; 30 #[cfg(any(feature = "chat", feature = "commerce"))] 31 pub use dm_relays::VerifiedDmRelayAdvertisement; 32 33 pub use radroots_protocol::intent::{ArtifactRole, IntentBinding}; 34 mod exact_recovery; 35 pub use exact_recovery::{ 36 ExactRecoveryCapability, ExactRecoveryKind, ExactRecoveryOutcome, ExactRecoveryRequest, 37 }; 38 39 /// Narrow exact-signature IO boundary, with native or browser-local futures. 40 /// Implementations must preserve obtained material and honestly distinguish a 41 /// pre-dispatch refusal from uncertainty. The port and its response confer no 42 /// first-dispatch authority, durable evidence or adapter qualification. 43 pub trait ExactIssuer: crate::host::HostBound { 44 fn issue_exact(&self, intent: SigningIntent) -> crate::signer::BoxFuture<'_, SigningOutcome>; 45 } 46 impl<T: crate::provider::ParticipantProvider + ?Sized> ExactIssuer for T { 47 fn issue_exact(&self, intent: SigningIntent) -> crate::signer::BoxFuture<'_, SigningOutcome> { 48 crate::provider::ParticipantProvider::sign_exact(self, intent) 49 } 50 } 51 52 /// Bounded exact preimage and immutable provenance. It is neither an 53 /// authenticated command context nor evidence of T0/T1 admission. 54 /// It has no automatic input-bearing diagnostics or serialization. 55 pub struct SigningIntent { 56 binding: IntentBinding, 57 plan: ExactPreimage, 58 role: ArtifactRole, 59 recipient: Option<PublicKey>, 60 call: ProviderCall, 61 signed_json_bytes: usize, 62 } 63 enum ExactPreimage { 64 Authored(AuthoredEventPlan), 65 #[cfg(feature = "artifacts")] 66 Listing(radroots_protocol::listing::ListingEvent), 67 } 68 impl ExactPreimage { 69 fn fields(&self) -> radroots_protocol::nip01::EventFields<'_> { 70 match self { 71 Self::Authored(plan) => radroots_protocol::nip01::EventFields { 72 author: *plan.author(), 73 created_at: plan.created_at(), 74 kind: plan.body().kind(), 75 tags: plan.body().tags(), 76 content: plan.body().content(), 77 }, 78 #[cfg(feature = "artifacts")] 79 Self::Listing(event) => event.fields(), 80 } 81 } 82 fn event_id(&self) -> radroots_event::id::EventId { 83 match self { 84 Self::Authored(plan) => *plan.expected_event_id(), 85 #[cfg(feature = "artifacts")] 86 Self::Listing(event) => radroots_event::id::EventId::from_bytes(*event.event_id()), 87 } 88 } 89 } 90 impl fmt::Debug for SigningIntent { 91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 92 f.write_str("SigningIntent(<redacted>)") 93 } 94 } 95 impl SigningIntent { 96 /// Converts one exact retained-plan artifact to the existing signing port. 97 /// This verifies structural identity only; actual T1/first-claim commits, 98 /// current grant, destination policy and provider support remain required. 99 #[cfg(feature = "artifacts")] 100 pub fn from_plan( 101 plan: &radroots_protocol::plan::CapturedSigningPlan, 102 target: radroots_protocol::plan::SigningTarget, 103 call: ProviderCall, 104 ) -> Result<Self, ProviderError> { 105 use radroots_protocol::plan::SigningArtifact; 106 match plan 107 .artifact(target) 108 .map_err(|_| ProviderError::InvalidInput)? 109 { 110 SigningArtifact::Seal(seal) => { 111 Self::from_chat_seal(plan.operation_id(), plan.command_digest(), seal, call) 112 } 113 SigningArtifact::Public(event) => { 114 let fields = event.fields(); 115 if fields.author != call.identity() 116 || fields.created_at > MAX_EVENT_UNIX_SECONDS 117 || call.deadline_unix_ms().get() > MAX_OBSERVATION_UNIX_MS 118 { 119 return Err(ProviderError::InvalidInput); 120 } 121 let signed_json_bytes = signed_json_len(&fields, public_event_limits())?; 122 let binding = IntentBinding::from_components( 123 plan.operation_id(), 124 *plan.command_digest().as_bytes(), 125 *plan.digest(), 126 ArtifactRole::PublicEvent, 127 None, 128 call.deadline_unix_ms(), 129 ) 130 .map_err(|_| ProviderError::InvalidInput)?; 131 Ok(Self { 132 binding, 133 plan: ExactPreimage::Listing(event.clone()), 134 role: ArtifactRole::PublicEvent, 135 recipient: None, 136 call, 137 signed_json_bytes, 138 }) 139 } 140 } 141 } 142 /// Freezes an already validated authored preimage and its captured context. 143 /// Complete-event and parser budgets are checked without serializing or 144 /// cloning the plan. A tighter business profile remains executor-owned. 145 pub fn new( 146 operation_id: OperationId, 147 command_digest: [u8; 32], 148 plan: AuthoredEventPlan, 149 role: ArtifactRole, 150 recipient: Option<PublicKey>, 151 call: ProviderCall, 152 ) -> Result<Self, ProviderError> { 153 if plan.author() != &call.identity() 154 || plan.created_at() > MAX_EVENT_UNIX_SECONDS 155 || call.deadline_unix_ms().get() > MAX_OBSERVATION_UNIX_MS 156 { 157 return Err(ProviderError::InvalidInput); 158 } 159 let kind = plan.body().kind(); 160 let role_valid = match role { 161 ArtifactRole::PublicEvent => recipient.is_none() && !matches!(kind, 13 | 14 | 1059), 162 ArtifactRole::BusinessSeal => { 163 kind == 13 && recipient.is_some() && plan.body().tags().is_empty() 164 } 165 ArtifactRole::GiftWrap => { 166 kind == 1059 167 && recipient.is_some_and(|peer| { 168 let tags = plan.body().tags(); 169 let mut recipients = tags 170 .iter() 171 .filter(|tag| tag.first().is_some_and(|field| field == "p")); 172 recipients 173 .next() 174 .is_some_and(|tag| tag.len() == 2 && tag[1] == peer.to_hex()) 175 && recipients.next().is_none() 176 }) 177 } 178 _ => return Err(ProviderError::UnsupportedVersion), 179 }; 180 if !role_valid { 181 return Err(ProviderError::InvalidInput); 182 } 183 let signed_json_bytes = signed_json_len( 184 &radroots_protocol::nip01::EventFields { 185 author: *plan.author(), 186 created_at: plan.created_at(), 187 kind: plan.body().kind(), 188 tags: plan.body().tags(), 189 content: plan.body().content(), 190 }, 191 EventWireLimits::default(), 192 )?; 193 let binding = IntentBinding::from_components( 194 operation_id, 195 command_digest, 196 *plan.digest().as_bytes(), 197 role, 198 recipient, 199 call.deadline_unix_ms(), 200 ) 201 .map_err(|_| ProviderError::InvalidInput)?; 202 Ok(Self { 203 binding, 204 plan: ExactPreimage::Authored(plan), 205 role, 206 recipient, 207 call, 208 signed_json_bytes, 209 }) 210 } 211 /// Converts one bounded known-kind seal into the existing exact signer 212 /// contract. This codec conversion grants no command, route or journal 213 /// authority; the executor must retain the full plan before dispatch. 214 #[cfg(any(feature = "chat", feature = "artifacts"))] 215 pub fn from_chat_seal( 216 operation_id: OperationId, 217 command_digest: radroots_domain::CommandDigest, 218 seal: &radroots_protocol::chat::ChatSeal, 219 call: ProviderCall, 220 ) -> Result<Self, ProviderError> { 221 if seal.operation_id() != operation_id || seal.command_digest() != command_digest { 222 return Err(ProviderError::InvalidInput); 223 } 224 Self::from_seal( 225 operation_id, 226 command_digest, 227 seal.fields(), 228 seal.recipient(), 229 seal.event_id(), 230 call, 231 ) 232 } 233 /// Converts exact structured-commerce seal data without granting any 234 /// command, store, provider or dispatch authority. 235 #[cfg(feature = "commerce")] 236 pub fn from_commerce_seal( 237 seal: &radroots_protocol::commerce::CommerceSeal, 238 call: ProviderCall, 239 ) -> Result<Self, ProviderError> { 240 Self::from_seal( 241 seal.operation_id(), 242 seal.command_digest(), 243 seal.fields(), 244 seal.recipient(), 245 seal.event_id(), 246 call, 247 ) 248 } 249 #[cfg(any(feature = "chat", feature = "artifacts", feature = "commerce"))] 250 fn from_seal( 251 operation_id: OperationId, 252 command_digest: radroots_domain::CommandDigest, 253 fields: radroots_protocol::nip01::EventFields<'_>, 254 recipient: PublicKey, 255 event_id: [u8; 32], 256 call: ProviderCall, 257 ) -> Result<Self, ProviderError> { 258 let draft = radroots_event::GenericEventDraft::new( 259 "radroots.message.seal.v1", 260 fields.kind, 261 fields.created_at, 262 core::iter::empty().collect(), 263 fields.content, 264 fields.author.to_hex(), 265 ) 266 .map_err(|_| ProviderError::InvalidInput)?; 267 let plan = 268 AuthoredEventPlan::from_generic(draft).map_err(|_| ProviderError::InvalidInput)?; 269 if plan.expected_event_id().as_bytes() != &event_id { 270 return Err(ProviderError::InvalidInput); 271 } 272 Self::new( 273 operation_id, 274 *command_digest.as_bytes(), 275 plan, 276 ArtifactRole::BusinessSeal, 277 Some(recipient), 278 call, 279 ) 280 } 281 /// Returns the original immutable binding. 282 pub const fn binding(&self) -> IntentBinding { 283 self.binding 284 } 285 /// Returns the exact authored-event byte count under the supported serializer. 286 pub const fn signed_json_bytes(&self) -> usize { 287 self.signed_json_bytes 288 } 289 /// Returns the expected author, independently of any business actor claim. 290 pub fn author(&self) -> PublicKey { 291 self.plan.fields().author 292 } 293 /// Returns the exact artifact role. 294 pub const fn role(&self) -> ArtifactRole { 295 self.role 296 } 297 /// Returns the exact recipient for a private carrier. 298 pub const fn recipient(&self) -> Option<PublicKey> { 299 self.recipient 300 } 301 /// Borrows exact NIP-01 fields and ID for one concrete conversion. The 302 /// typed public profile does not pass through a predecessor generic registry. 303 pub fn with_event<T>( 304 &self, 305 use_event: impl FnOnce( 306 radroots_protocol::nip01::EventFields<'_>, 307 radroots_event::id::EventId, 308 ) -> T, 309 ) -> T { 310 use_event(self.plan.fields(), self.plan.event_id()) 311 } 312 /// Checks scheduling before effects. Never repeat this after obtaining bytes. 313 pub fn check_before_effect( 314 &self, 315 identity: PublicKey, 316 now_unix_ms: u64, 317 ) -> Result<(), ProviderError> { 318 self.call.check_before_effect(identity, now_unix_ms) 319 } 320 } 321 322 fn signed_json_len( 323 fields: &radroots_protocol::nip01::EventFields<'_>, 324 limits: EventWireLimits, 325 ) -> Result<usize, ProviderError> { 326 if fields.kind > u32::from(u16::MAX) { 327 return Err(ProviderError::UnsupportedVersion); 328 } 329 let mut elements = 0usize; 330 let mut tag_bytes = 0usize; 331 if fields.tags.len() > limits.max_tag_count { 332 return Err(ProviderError::LimitExceeded); 333 } 334 for tag in fields.tags { 335 elements = elements 336 .checked_add(tag.len()) 337 .filter(|n| *n <= limits.max_total_tag_elements) 338 .ok_or(ProviderError::LimitExceeded)?; 339 for field in tag { 340 if field.len() > limits.max_tag_element_bytes { 341 return Err(ProviderError::LimitExceeded); 342 } 343 tag_bytes = tag_bytes 344 .checked_add(field.len()) 345 .filter(|n| *n <= limits.max_total_tag_bytes) 346 .ok_or(ProviderError::LimitExceeded)?; 347 } 348 } 349 radroots_protocol::nip01::signed_json_len(fields, SIGNED_EVENT_MAX_BYTES) 350 .map_err(|_| ProviderError::LimitExceeded) 351 } 352 353 /// Scope of a forensic digest. A prefix digest never claims full coverage. 354 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 355 pub struct ArtifactFingerprint { 356 sha256: [u8; 32], 357 covered_bytes: usize, 358 total_bytes: usize, 359 } 360 impl ArtifactFingerprint { 361 fn of(raw: &[u8]) -> Self { 362 let covered_bytes = raw.len().min(SIGNED_EVENT_MAX_BYTES); 363 Self { 364 sha256: Sha256::digest(&raw[..covered_bytes]).into(), 365 covered_bytes, 366 total_bytes: raw.len(), 367 } 368 } 369 /// Returns the SHA-256 of exactly the reported covered prefix. 370 pub const fn sha256(&self) -> &[u8; 32] { 371 &self.sha256 372 } 373 /// Returns the number of bytes included in the digest. 374 pub const fn covered_bytes(self) -> usize { 375 self.covered_bytes 376 } 377 /// Returns the original response size, without retaining its payload. 378 pub const fn total_bytes(self) -> usize { 379 self.total_bytes 380 } 381 } 382 /// A fixed classification of untrusted signer output. 383 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 384 #[non_exhaustive] 385 pub enum RejectionReason { 386 /// The response exceeds the complete-event budget. 387 TooLarge, 388 /// Structural decoding, exact fields or the supported profile do not match. 389 InvalidArtifact, 390 /// Cryptographic verification failed. 391 InvalidSignature, 392 /// The returned provenance belongs to another captured intent. 393 BindingMismatch, 394 } 395 /// Input-free forensic metadata. This supplies no authenticated business fact. 396 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 397 pub struct RejectedArtifact { 398 reason: RejectionReason, 399 fingerprint: Option<ArtifactFingerprint>, 400 } 401 impl RejectedArtifact { 402 /// Returns the fixed classification. 403 pub const fn reason(self) -> RejectionReason { 404 self.reason 405 } 406 /// Returns exact digest scope when response bytes were available. 407 pub const fn fingerprint(self) -> Option<ArtifactFingerprint> { 408 self.fingerprint 409 } 410 } 411 /// Authenticated exact bytes, without a durable-admission or business claim. 412 /// No automatic serialization, cloning or payload-bearing diagnostics exists. 413 pub struct SignedArtifact { 414 raw_json: Zeroizing<String>, 415 event_id: EventId, 416 observed_at_unix_ms: Option<NonZeroU64>, 417 } 418 impl fmt::Debug for SignedArtifact { 419 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 420 f.write_str("SignedArtifact(<redacted>)") 421 } 422 } 423 impl SignedArtifact { 424 /// Returns the exact authenticated event identity. 425 pub const fn event_id(&self) -> EventId { 426 self.event_id 427 } 428 /// Returns a checked positive observation, or explicit unknown time. 429 pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> { 430 self.observed_at_unix_ms 431 } 432 /// Exposes original bytes only for explicit capture/transport work. 433 pub fn with_json<T>(&self, use_json: impl FnOnce(&str) -> T) -> T { 434 use_json(&self.raw_json) 435 } 436 } 437 /// What a qualified provider reports, separately from durable capture. 438 #[derive(Debug)] 439 #[non_exhaustive] 440 pub enum OutcomeKind { 441 /// This provider proves its invocation did not dispatch signing. 442 NotDispatched(ProviderError), 443 /// Exact authenticated bytes were obtained; scheduling may have stopped. 444 Obtained(SignedArtifact), 445 /// No conclusive issuance result is available; retain uncertainty. 446 Unknown(ProviderError), 447 /// Untrusted output is not a business success or proof of no issuance. 448 Rejected(RejectedArtifact), 449 } 450 /// One result bound to the original captured intent. It is not an operation receipt. 451 #[derive(Debug)] 452 pub struct SigningOutcome { 453 binding: IntentBinding, 454 kind: OutcomeKind, 455 } 456 impl SigningOutcome { 457 /// Reports a qualified pre-dispatch refusal, without effects or legacy fallback. 458 pub const fn not_dispatched(binding: IntentBinding, reason: ProviderError) -> Self { 459 Self { 460 binding, 461 kind: OutcomeKind::NotDispatched(reason), 462 } 463 } 464 /// Reports uncertainty, which never permits blind reissue or hold release. 465 pub const fn unknown(binding: IntentBinding, reason: ProviderError) -> Self { 466 Self { 467 binding, 468 kind: OutcomeKind::Unknown(reason), 469 } 470 } 471 /// Verifies an obtained response without consulting scheduling or clocks. 472 /// Malformed output retains only bounded forensic metadata. Valid bytes are 473 /// preserved even with unavailable, expired or cancelled observation state. 474 pub fn capture( 475 intent: &SigningIntent, 476 raw_json: String, 477 observed_at_unix_ms: Option<NonZeroU64>, 478 ) -> Self { 479 let raw = Zeroizing::new(raw_json); 480 let fingerprint = ArtifactFingerprint::of(raw.as_bytes()); 481 let reject = |reason| Self { 482 binding: intent.binding(), 483 kind: OutcomeKind::Rejected(RejectedArtifact { 484 reason, 485 fingerprint: Some(fingerprint), 486 }), 487 }; 488 if raw.len() > SIGNED_EVENT_MAX_BYTES { 489 return reject(RejectionReason::TooLarge); 490 } 491 let limits = match &intent.plan { 492 #[cfg(feature = "artifacts")] 493 ExactPreimage::Listing(_) => public_event_limits(), 494 _ => EventWireLimits { 495 max_raw_json_bytes: SIGNED_EVENT_MAX_BYTES, 496 max_extra_fields: 0, 497 max_total_extra_json_bytes: 0, 498 ..EventWireLimits::default() 499 }, 500 }; 501 let Ok(wire) = Nip01EventWire::parse_json_exact_with_limits(&raw, limits) else { 502 return reject(RejectionReason::InvalidArtifact); 503 }; 504 let fields = intent.plan.fields(); 505 if wire.pubkey != fields.author.to_hex() 506 || wire.created_at != fields.created_at 507 || wire.kind != fields.kind 508 || wire.tags != fields.tags 509 || wire.content != fields.content 510 || wire.id != intent.plan.event_id().to_hex() 511 { 512 return reject(RejectionReason::InvalidArtifact); 513 } 514 let Ok(envelope) = checked_envelope(wire, limits) else { 515 return reject(RejectionReason::InvalidArtifact); 516 }; 517 let Ok(verified_id) = verify::id(RawEvent::new(envelope)) else { 518 return reject(RejectionReason::InvalidArtifact); 519 }; 520 if verify::signature(verified_id, &Nip01SignatureVerifier).is_err() { 521 return reject(RejectionReason::InvalidSignature); 522 } 523 Self { 524 binding: intent.binding(), 525 kind: OutcomeKind::Obtained(SignedArtifact { 526 raw_json: raw, 527 event_id: intent.plan.event_id(), 528 observed_at_unix_ms: observed_at_unix_ms 529 .filter(|at| at.get() <= MAX_OBSERVATION_UNIX_MS), 530 }), 531 } 532 } 533 /// Returns the exact captured provenance. 534 pub const fn binding(&self) -> IntentBinding { 535 self.binding 536 } 537 /// Borrows the classified result without cloning private bytes. 538 pub const fn kind(&self) -> &OutcomeKind { 539 &self.kind 540 } 541 /// Transfers the original binding and classified owned result. 542 pub fn into_parts(self) -> (IntentBinding, OutcomeKind) { 543 (self.binding, self.kind) 544 } 545 /// Refuses cross-intent callback results without promoting them to success 546 /// or proof of no issuance. Any available bytes retain scoped forensics. 547 pub fn enforce_binding(self, expected: IntentBinding) -> Self { 548 if self.binding == expected { 549 return self; 550 } 551 let fingerprint = match &self.kind { 552 OutcomeKind::Obtained(artifact) => { 553 Some(artifact.with_json(|raw| ArtifactFingerprint::of(raw.as_bytes()))) 554 } 555 OutcomeKind::Rejected(rejected) => rejected.fingerprint, 556 _ => None, 557 }; 558 Self { 559 binding: expected, 560 kind: OutcomeKind::Rejected(RejectedArtifact { 561 reason: RejectionReason::BindingMismatch, 562 fingerprint, 563 }), 564 } 565 } 566 } 567 568 #[cfg(feature = "artifacts")] 569 fn public_event_limits() -> EventWireLimits { 570 EventWireLimits { 571 max_raw_json_bytes: SIGNED_EVENT_MAX_BYTES, 572 max_content_bytes: SIGNED_EVENT_MAX_BYTES, 573 max_tag_count: radroots_protocol::listing::LISTING_TAG_MAX_COUNT, 574 max_total_tag_elements: radroots_protocol::listing::LISTING_TAG_TOTAL_ELEMENT_MAX_COUNT, 575 max_tag_element_bytes: SIGNED_EVENT_MAX_BYTES, 576 max_total_tag_bytes: SIGNED_EVENT_MAX_BYTES, 577 max_extra_fields: 0, 578 max_total_extra_json_bytes: 0, 579 } 580 } 581 582 fn checked_envelope( 583 wire: Nip01EventWire, 584 limits: EventWireLimits, 585 ) -> Result<radroots_event::envelope::EventEnvelope, radroots_event::envelope::EventEnvelopeError> { 586 use radroots_event::envelope::{EventEnvelope, EventEnvelopeLimits, EventEnvelopeParts}; 587 EventEnvelope::new_with_limits( 588 EventEnvelopeParts { 589 id: wire.id, 590 author: wire.pubkey, 591 created_at: wire.created_at, 592 kind: wire.kind, 593 tags: wire.tags, 594 content: wire.content, 595 sig: wire.sig, 596 }, 597 EventEnvelopeLimits { 598 max_content_bytes: limits.max_content_bytes, 599 max_tag_count: limits.max_tag_count, 600 max_total_tag_elements: limits.max_total_tag_elements, 601 max_tag_element_bytes: limits.max_tag_element_bytes, 602 max_total_tag_bytes: limits.max_total_tag_bytes, 603 }, 604 ) 605 }