lib

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

commit 73ec16a61178a23a06193cb2327f15a9beb4264a
parent 0235b502a87b0cad0b3c90d65e04e800962594f5
Author: triesap <tyson@radroots.org>
Date:   Sun, 18 Oct 2026 01:30:22 +0000

protocol: own exact bounded private chat bytes

- move canonical event serialization into the shared protocol owner
- encode exact plaintext rumors and bound both private envelope layers
- convert known-kind seals through the exact signing contract
- verify independent bytes, real crypto, refusals and coverage gates

Diffstat:
MCargo.lock | 1+
Mcontracts/api_baselines/radroots_protocol.txt | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_signing.txt | 1+
Mcontracts/coverage-profiles.toml | 5++++-
Acontracts/protocol/chat.v1.json | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/event/Cargo.toml | 2+-
Mcrates/event/src/wire/v1.rs | 63++++++++++-----------------------------------------------------
Mcrates/event/tests/package_boundary.rs | 6+++---
Mcrates/protocol/Cargo.toml | 3+++
Acrates/protocol/src/chat.rs | 304+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/src/lib.rs | 8++++++++
Acrates/protocol/src/nip01.rs | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/chat_wire.rs | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/fixtures/chat_wire.v1.json | 224+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/tests/package_boundary.rs | 15+++++++++++++--
Acrates/protocol/tests/support/chat_wire_oracle.mjs | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/signing/Cargo.toml | 5+++--
Mcrates/signing/src/issuance.rs | 96+++++++++++++++++++++++++++++++++++++++----------------------------------------
Acrates/signing/tests/chat_seal.rs | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/signing/tests/issuance.rs | 22++++++++++++++++++++++
Mcrates/signing/tests/package_boundary.rs | 4++--
21 files changed, 1486 insertions(+), 113 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3289,6 +3289,7 @@ name = "radroots_protocol" version = "0.1.0-alpha" dependencies = [ "radroots_domain", + "radroots_identity", "serde", "serde_json", "sha2", diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -62,6 +62,36 @@ pub const radroots_protocol::capability::v1::MAX_TRANSPORT_KIND_BYTES: usize pub const radroots_protocol::capability::v1::SCHEMAS: &[radroots_protocol::schema::Metadata] 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 struct radroots_protocol::chat::ChatBudget +impl radroots_protocol::chat::ChatBudget +pub const fn radroots_protocol::chat::ChatBudget::envelope_ciphertext_max_bytes(self) -> usize +pub fn radroots_protocol::chat::ChatBudget::for_rumor(usize, radroots_identity::key::PublicKey) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub const fn radroots_protocol::chat::ChatBudget::rumor_ciphertext_bytes(self) -> usize +pub const fn radroots_protocol::chat::ChatBudget::signed_envelope_max_bytes(self) -> usize +pub const fn radroots_protocol::chat::ChatBudget::signed_seal_max_bytes(self) -> usize +pub struct radroots_protocol::chat::ChatRumor +impl radroots_protocol::chat::ChatRumor +pub const fn radroots_protocol::chat::ChatRumor::author(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_protocol::chat::ChatRumor::budget(&self) -> radroots_protocol::chat::ChatBudget +pub const fn radroots_protocol::chat::ChatRumor::created_at(&self) -> radroots_domain::context::UnixSeconds +pub fn radroots_protocol::chat::ChatRumor::from_command(&radroots_protocol::command::CapturedChatCommand, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub fn radroots_protocol::chat::ChatRumor::json(&self) -> &str +pub const fn radroots_protocol::chat::ChatRumor::message_id(&self) -> radroots_domain::identifier::MessageId +pub fn radroots_protocol::chat::ChatRumor::recipients(&self) -> &[radroots_identity::key::PublicKey] +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::event_id(&self) -> [u8; 32] +pub fn radroots_protocol::chat::ChatSeal::fields(&self) -> radroots_protocol::nip01::EventFields<'_> +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::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 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> pub mod radroots_protocol::command pub enum radroots_protocol::command::ChatKind pub radroots_protocol::command::ChatKind::Inquire @@ -375,6 +405,31 @@ pub const radroots_protocol::event::v1::TRADE_STATE_VOCABULARY: &[radroots_proto pub fn radroots_protocol::event::v1::schema_registry() -> core::result::Result<radroots_protocol::schema::Registry, radroots_protocol::schema::Error> pub fn radroots_protocol::event::v1::validate_catalog(&[radroots_protocol::event::v1::EventDescriptor]) -> core::result::Result<(), radroots_protocol::event::v1::Error> pub fn radroots_protocol::event::v1::validate_trade_state_vocabulary(&[radroots_protocol::event::v1::TradeState]) -> core::result::Result<(), radroots_protocol::event::v1::Error> +pub mod radroots_protocol::nip01 +pub enum radroots_protocol::nip01::WireError +pub radroots_protocol::nip01::WireError::InvalidInput +pub radroots_protocol::nip01::WireError::LimitExceeded +impl core::error::Error for radroots_protocol::nip01::WireError +impl core::fmt::Display for radroots_protocol::nip01::WireError +pub fn radroots_protocol::nip01::WireError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::nip01::EventFields<'a> +pub radroots_protocol::nip01::EventFields::author: radroots_identity::key::PublicKey +pub radroots_protocol::nip01::EventFields::content: &'a str +pub radroots_protocol::nip01::EventFields::created_at: u64 +pub radroots_protocol::nip01::EventFields::kind: u32 +pub radroots_protocol::nip01::EventFields::tags: &'a [alloc::vec::Vec<alloc::string::String>] +impl core::fmt::Debug for radroots_protocol::nip01::EventFields<'_> +pub fn radroots_protocol::nip01::EventFields<'_>::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::nip01::UnsignedEvent +impl radroots_protocol::nip01::UnsignedEvent +pub fn radroots_protocol::nip01::UnsignedEvent::encode(&radroots_protocol::nip01::EventFields<'_>, usize) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub const fn radroots_protocol::nip01::UnsignedEvent::event_id(&self) -> [u8; 32] +pub fn radroots_protocol::nip01::UnsignedEvent::json(&self) -> &str +impl core::fmt::Debug for radroots_protocol::nip01::UnsignedEvent +pub fn radroots_protocol::nip01::UnsignedEvent::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub fn radroots_protocol::nip01::canonical_preimage(&radroots_protocol::nip01::EventFields<'_>) -> alloc::string::String +pub fn radroots_protocol::nip01::preimage_len(&radroots_protocol::nip01::EventFields<'_>, usize) -> core::result::Result<usize, radroots_protocol::nip01::WireError> +pub fn radroots_protocol::nip01::signed_json_len(&radroots_protocol::nip01::EventFields<'_>, usize) -> core::result::Result<usize, radroots_protocol::nip01::WireError> pub mod radroots_protocol::radrootsd pub mod radroots_protocol::radrootsd::transport_publish pub mod radroots_protocol::radrootsd::transport_publish::v5 diff --git a/contracts/api_baselines/radroots_signing.txt b/contracts/api_baselines/radroots_signing.txt @@ -186,6 +186,7 @@ impl radroots_signing::issuance::SigningIntent pub const fn radroots_signing::issuance::SigningIntent::author(&self) -> radroots_identity::key::PublicKey pub const fn radroots_signing::issuance::SigningIntent::binding(&self) -> radroots_signing::issuance::IntentBinding pub fn radroots_signing::issuance::SigningIntent::check_before_effect(&self, radroots_identity::key::PublicKey, u64) -> core::result::Result<(), radroots_signing::provider::ProviderError> +pub fn radroots_signing::issuance::SigningIntent::from_chat_seal(radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, &radroots_protocol::chat::ChatSeal, radroots_signing::provider::ProviderCall) -> core::result::Result<Self, radroots_signing::provider::ProviderError> pub fn radroots_signing::issuance::SigningIntent::new(radroots_domain::identifier::OperationId, [u8; 32], radroots_event_codec::authoring::AuthoredEventPlan, radroots_signing::issuance::ArtifactRole, core::option::Option<radroots_identity::key::PublicKey>, radroots_signing::provider::ProviderCall) -> core::result::Result<Self, radroots_signing::provider::ProviderError> pub const fn radroots_signing::issuance::SigningIntent::recipient(&self) -> core::option::Option<radroots_identity::key::PublicKey> pub const fn radroots_signing::issuance::SigningIntent::role(&self) -> radroots_signing::issuance::ArtifactRole diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml @@ -9,7 +9,10 @@ features = ["session", "signer_session", "client_session", "workspace_session"] test_threads = 1 [profiles.crates."radroots_protocol"] -features = ["commands"] +features = ["chat"] + +[profiles.crates."radroots_signing"] +features = ["chat"] [profiles.crates."radroots"] no_default_features = false diff --git a/contracts/protocol/chat.v1.json b/contracts/protocol/chat.v1.json @@ -0,0 +1,79 @@ +{ + "schema_version": 1, + "contract_id": "radroots.protocol.chat.v1", + "state": "known_kind_codec_component_implemented", + "owner": "radroots_protocol", + "signing_conversion_owner": "radroots_signing", + "kinds": { + "rumor": 14, + "seal": 13, + "gift_wrap": 1059, + "recipient_dm_relays": 10050 + }, + "rumor": { + "content": "Exact plain UTF-8 text, never a JSON commerce record", + "required_tags_in_order": [ + [ + "p", + "peer" + ], + [ + "radroots", + "thread", + "thread_id" + ] + ], + "optional_tags_in_order": [ + [ + "radroots", + "source", + "30402", + "author", + "d", + "event_id" + ], + [ + "e", + "reply_parent_message_id" + ] + ], + "unsigned": true, + "complete_max_bytes": 24576, + "plain_text_max_bytes": 4096, + "recipient_set": "Sorted unique author and peer; one exact rumor for every per-recipient seal, including a deduplicated self-conversation", + "authorization": "Codec descriptors verify no source, parent, history, grant, consent, route or participant authority" + }, + "canonical": { + "preimage": "NIP-01 [0,pubkey,created_at,kind,tags,content], exact tag order and Unicode, lowercase control escapes, no Unicode normalization", + "legacy": "Event wire-v1 delegates canonical serialization while retaining its full accepted u64 timestamp/u32 kind range and public parse/error behavior", + "private_buffers": "Bound complete serialization before copying; clear owned rumor and temporary preimage text; no payload-bearing automatic diagnostics", + "unsigned_json": "Exact id/pubkey/created_at/kind/tags/content with no signature; complete unsigned length equals canonical preimage length plus 116 bytes", + "signed_json_length": "The supported exact complete signed object length equals canonical preimage length plus 253 bytes" + }, + "seal": { + "tags": [], + "timestamp": "Explicit positive time no later than rumor time and at most 172800 seconds earlier; runtime supplies checked randomized input", + "ciphertext": "Canonical base64 shape, version-2 prefix, exact predicted padded payload size; structural checks do not authenticate a MAC", + "complete_signed_max_bytes": 65536, + "signing": "Convert validated known-kind fields through the existing exact-intent signer; no command or durable-admission authority is created" + }, + "nested_budget": { + "profile": "Size calculations cover the standard two-byte NIP-44 v2 length prefix for lengths 1 through 65535; no extended-prefix support is claimed.", + "provider_caps": "A size calculation does not advertise encryption capability for every counted input. Both selected chat layers must fit the concrete provider's 65536-byte text/ciphertext boundary and the complete signed-event bounds.", + "measurement": "Before business seal signing, count complete rumor, padded/base64 rumor ciphertext, worst supported-timestamp signed seal, padded/base64 outer ciphertext and complete signed 1059 envelope", + "qualification": "Independent ECMAScript JSON/SHA-256/base64 vectors plus actual Rust encryption/signature/decryption conversion; structural vectors deliberately carry no valid MAC" + }, + "source": { + "repository": "https://github.com/nostr-protocol/nips", + "commit": "37db639582d857e12468dcccd99b2c7f1d657da9", + "documents": [ + "01.md", + "17.md", + "44.md", + "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", + "structured_commerce_authoring_enabled": false, + "package_publication_authorized": false +} diff --git a/crates/event/Cargo.toml b/crates/event/Cargo.toml @@ -51,7 +51,7 @@ serde = [ radroots_blossom = { workspace = true, default-features = false } radroots_core = { workspace = true, default-features = false } radroots_identity = { workspace = true, default-features = false } -radroots_protocol = { workspace = true, default-features = false } +radroots_protocol = { workspace = true, default-features = false, features = ["nip01"] } hex = { version = "0.4", default-features = false, features = ["alloc"] } jiff-tzdb = { workspace = true } serde = { workspace = true, default-features = false, features = [ diff --git a/crates/event/src/wire/v1.rs b/crates/event/src/wire/v1.rs @@ -410,33 +410,16 @@ pub fn canonical_nip01_event_id_preimage_v1( tags: &[Vec<String>], content: &str, ) -> Result<String, CanonicalEventIdError> { - let pubkey = parse_public_key(pubkey).map_err(CanonicalEventIdError::InvalidPubkey)?; - let pubkey = pubkey.to_hex(); - let mut preimage = String::new(); - preimage.push_str("[0,"); - push_canonical_json_string(&mut preimage, pubkey.as_str()); - preimage.push(','); - preimage.push_str(created_at.to_string().as_str()); - preimage.push(','); - preimage.push_str(kind.to_string().as_str()); - preimage.push_str(",["); - for (tag_index, tag) in tags.iter().enumerate() { - if tag_index > 0 { - preimage.push(','); - } - preimage.push('['); - for (value_index, value) in tag.iter().enumerate() { - if value_index > 0 { - preimage.push(','); - } - push_canonical_json_string(&mut preimage, value); - } - preimage.push(']'); - } - preimage.push_str("],"); - push_canonical_json_string(&mut preimage, content); - preimage.push(']'); - Ok(preimage) + let author = parse_public_key(pubkey).map_err(CanonicalEventIdError::InvalidPubkey)?; + Ok(radroots_protocol::nip01::canonical_preimage( + &radroots_protocol::nip01::EventFields { + author, + created_at, + kind, + tags, + content, + }, + )) } pub fn compute_canonical_nip01_event_id( @@ -650,32 +633,6 @@ fn serialized_json_value_len(value: &Value) -> usize { .len() } -fn push_canonical_json_string(target: &mut String, value: &str) { - target.push('"'); - for character in value.chars() { - match character { - '"' => target.push_str("\\\""), - '\\' => target.push_str("\\\\"), - '\n' => target.push_str("\\n"), - '\r' => target.push_str("\\r"), - '\t' => target.push_str("\\t"), - '\u{08}' => target.push_str("\\b"), - '\u{0c}' => target.push_str("\\f"), - '\u{00}'..='\u{1f}' => push_unicode_escape(target, character), - _ => target.push(character), - } - } - target.push('"'); -} - -fn push_unicode_escape(target: &mut String, character: char) { - const HEX: &[u8; 16] = b"0123456789abcdef"; - let value = character as u32; - target.push_str("\\u00"); - target.push(HEX[((value >> 4) & 0x0f) as usize] as char); - target.push(HEX[(value & 0x0f) as usize] as char); -} - // This policy guard does not interpret event values. The existing JSON and // event validators remain authoritative for syntax, types, budgets and ID. fn exact_event_json_shape(raw: &str) -> bool { diff --git a/crates/event/tests/package_boundary.rs b/crates/event/tests/package_boundary.rs @@ -44,9 +44,9 @@ fn manifest_has_final_identity_and_required_radroots_dependencies() { "radroots_protocol", ]) ); - assert!( - MANIFEST.contains("radroots_protocol = { workspace = true, default-features = false }") - ); + assert!(MANIFEST.contains( + "radroots_protocol = { workspace = true, default-features = false, features = [\"nip01\"] }" + )); assert_eq!( table_keys(MANIFEST, "[features]"), BTreeSet::from(["default", "knowledge", "serde", "std"]), diff --git a/crates/protocol/Cargo.toml b/crates/protocol/Cargo.toml @@ -35,8 +35,11 @@ default = ["std", "serde"] serde = ["dep:serde"] std = ["serde?/std"] commands = ["serde", "dep:radroots_domain", "dep:serde_json", "dep:sha2", "dep:zeroize"] +nip01 = ["dep:radroots_identity", "dep:sha2", "dep:zeroize"] +chat = ["commands", "nip01"] [dependencies] +radroots_identity = { workspace = true, default-features = false, optional = true } radroots_domain = { workspace = true, default-features = false, features = ["serde"], optional = true } serde_json = { workspace = true, default-features = false, features = ["alloc", "raw_value"], optional = true } sha2 = { workspace = true, default-features = false, optional = true } diff --git a/crates/protocol/src/chat.rs b/crates/protocol/src/chat.rs @@ -0,0 +1,304 @@ +//! Closed NIP-17/44/59 chat profile data. No signer, route or grant is invoked. + +use crate::{ + command::CapturedChatCommand, + nip01::{EventFields, UnsignedEvent, WireError}, +}; +use alloc::{ + string::{String, ToString}, + vec, + vec::Vec, +}; +use core::fmt; +use radroots_domain::{MessageId, PublicKey, UnixSeconds}; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; + +/// Complete unsigned-rumor byte limit, separate from plain chat text. +pub const RUMOR_MAX_BYTES: usize = 24_576; +/// Complete signed seal or gift-wrap limit. +pub const SIGNED_MAX_BYTES: usize = 65_536; +const MAX_TIME: u64 = 253_402_300_799; +const RANDOMIZED_PAST_SECONDS: u64 = 172_800; + +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. + if !(1..=65_535).contains(&plaintext_bytes) { + return Err(WireError::InvalidInput); + } + let padded = if plaintext_bytes <= 32 { + 32 + } else { + let power = plaintext_bytes.next_power_of_two(); + let chunk = if power <= 256 { 32 } else { power / 8 }; + plaintext_bytes.div_ceil(chunk) * chunk + }; + let raw = padded + 67; + Ok((raw.div_ceil(3) * 4, (3 - raw % 3) % 3)) +} +/// Exact encoded size of the qualified two-byte-prefix NIP-44 v2 payload. +/// This is a size calculation, without encryption or a MAC-validity claim. +pub fn nip44_v2_payload_len(plaintext_bytes: usize) -> Result<usize, WireError> { + Ok(payload_shape(plaintext_bytes)?.0) +} + +/// Conservative complete nested sizes using the largest supported timestamp. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ChatBudget { + rumor_ciphertext_bytes: usize, + signed_seal_max_bytes: usize, + envelope_ciphertext_max_bytes: usize, + signed_envelope_max_bytes: usize, +} +impl ChatBudget { + /// Measures both nesting layers before any business seal signing. + pub fn for_rumor(rumor_bytes: usize, participant: PublicKey) -> Result<Self, WireError> { + if rumor_bytes > RUMOR_MAX_BYTES { + return Err(WireError::LimitExceeded); + } + let rumor_ciphertext_bytes = nip44_v2_payload_len(rumor_bytes)?; + let fields = EventFields { + author: participant, + created_at: MAX_TIME, + kind: 13, + tags: &[], + content: "", + }; + let signed_seal_max_bytes = + crate::nip01::signed_json_len(&fields, SIGNED_MAX_BYTES)? + rumor_ciphertext_bytes; + let envelope_ciphertext_max_bytes = nip44_v2_payload_len(signed_seal_max_bytes)?; + let tags = [vec![String::from("p"), participant.to_hex()]]; + let fields = EventFields { + author: participant, + created_at: MAX_TIME, + kind: 1059, + tags: &tags, + content: "", + }; + let signed_envelope_max_bytes = crate::nip01::signed_json_len(&fields, SIGNED_MAX_BYTES)? + + envelope_ciphertext_max_bytes; + if signed_seal_max_bytes > SIGNED_MAX_BYTES || signed_envelope_max_bytes > SIGNED_MAX_BYTES + { + return Err(WireError::LimitExceeded); + } + Ok(Self { + rumor_ciphertext_bytes, + signed_seal_max_bytes, + envelope_ciphertext_max_bytes, + signed_envelope_max_bytes, + }) + } + /// Exact encoded rumor ciphertext size. + pub const fn rumor_ciphertext_bytes(self) -> usize { + self.rumor_ciphertext_bytes + } + /// Maximum complete seal JSON size. + pub const fn signed_seal_max_bytes(self) -> usize { + self.signed_seal_max_bytes + } + /// Maximum outer encoded ciphertext size. + pub const fn envelope_ciphertext_max_bytes(self) -> usize { + self.envelope_ciphertext_max_bytes + } + /// Maximum complete signed gift-wrap size. + pub const fn signed_envelope_max_bytes(self) -> usize { + self.signed_envelope_max_bytes + } +} + +/// One exact unsigned kind-14 message shared by the complete peer/self set. +/// Selectors and codec output authenticate no parent, source or participant. +pub struct ChatRumor { + event: UnsignedEvent, + author: PublicKey, + created_at: UnixSeconds, + recipients: Vec<PublicKey>, + budget: ChatBudget, +} +impl ChatRumor { + /// Encodes captured plain text and ordered profile tags, preserving Unicode. + /// Authoritative execution must separately verify captured scope/history and + /// bind this exact timestamp to its retained preparation. + pub fn from_command( + command: &CapturedChatCommand, + created_at: UnixSeconds, + ) -> Result<Self, WireError> { + if created_at.get() == 0 { + return Err(WireError::InvalidInput); + } + let author = command.context().actor().participant(); + let peer = command.peer(); + let mut tags = vec![ + vec![String::from("p"), peer.to_hex()], + vec![ + String::from("radroots"), + String::from("thread"), + command.thread_id().to_string(), + ], + ]; + if let Some(source) = command.source() { + tags.push(vec![ + String::from("radroots"), + String::from("source"), + String::from("30402"), + source.author().to_hex(), + String::from(source.d()), + source.event_id().to_string(), + ]); + } + if let Some(parent) = command.parent() { + tags.push(vec![String::from("e"), parent.to_string()]); + } + let fields = EventFields { + author, + created_at: created_at.get(), + kind: 14, + tags: &tags, + content: command.text(), + }; + let event = UnsignedEvent::encode(&fields, RUMOR_MAX_BYTES)?; + let budget = ChatBudget::for_rumor(event.json().len(), author)?; + let mut recipients = vec![author]; + if peer != author { + recipients.push(peer); + } + recipients.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + Ok(Self { + event, + author, + created_at, + recipients, + budget, + }) + } + /// Returns the logical message ID, independent of per-recipient wrapping. + pub const fn message_id(&self) -> MessageId { + MessageId::from_bytes(self.event.event_id()) + } + /// Borrows exact unsigned JSON for protected retention and encryption. + pub fn json(&self) -> &str { + self.event.json() + } + /// Returns the captured author, without proving authority. + pub const fn author(&self) -> PublicKey { + self.author + } + /// Returns the immutable rumor timestamp. + pub const fn created_at(&self) -> UnixSeconds { + self.created_at + } + /// Borrows the complete sorted, unique peer/self recipient set. + pub fn recipients(&self) -> &[PublicKey] { + &self.recipients + } + /// Returns pre-signing complete nesting bounds. + pub const fn budget(&self) -> ChatBudget { + self.budget + } +} +impl fmt::Debug for ChatRumor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ChatRumor(<redacted>)") + } +} + +fn sextet(byte: u8) -> Option<u8> { + match byte { + b'A'..=b'Z' => Some(byte - b'A'), + b'a'..=b'z' => Some(byte - b'a' + 26), + b'0'..=b'9' => Some(byte - b'0' + 52), + b'+' => Some(62), + b'/' => Some(63), + _ => None, + } +} +fn ciphertext_shape(value: &str, plaintext_bytes: usize) -> Result<(), WireError> { + let (size, padding) = payload_shape(plaintext_bytes)?; + if value.len() != size { + return Err(WireError::InvalidInput); + } + let bytes = value.as_bytes(); + let split = size - padding; + if !bytes[..split].iter().all(|b| sextet(*b).is_some()) + || !bytes[split..].iter().all(|b| *b == b'=') + || bytes[0] != b'A' + || !(b'g'..=b'v').contains(&bytes[1]) + { + return Err(WireError::InvalidInput); + } + let last = sextet(bytes[split - 1]).ok_or(WireError::InvalidInput)?; + if (padding == 1 && last & 3 != 0) || (padding == 2 && last & 15 != 0) { + return Err(WireError::InvalidInput); + } + Ok(()) +} + +/// Bounded exact kind-13 data for one recipient, with no signature/authority. +pub struct ChatSeal { + author: PublicKey, + recipient: PublicKey, + created_at: UnixSeconds, + ciphertext: Zeroizing<String>, + event_id: [u8; 32], +} +impl ChatSeal { + /// Validates the recipient, randomized past timestamp, complete nesting and + /// canonical encoded payload shape before copying ciphertext. MAC validity + /// belongs to qualified cryptography, not this structural constructor. + pub fn new( + rumor: &ChatRumor, + recipient: PublicKey, + created_at: UnixSeconds, + ciphertext: &str, + ) -> Result<Self, WireError> { + if !rumor.recipients.contains(&recipient) + || created_at.get() == 0 + || created_at > rumor.created_at + || rumor.created_at.get() - created_at.get() > RANDOMIZED_PAST_SECONDS + { + return Err(WireError::InvalidInput); + } + ciphertext_shape(ciphertext, rumor.json().len())?; + let fields = EventFields { + author: rumor.author, + created_at: created_at.get(), + kind: 13, + tags: &[], + content: ciphertext, + }; + crate::nip01::signed_json_len(&fields, SIGNED_MAX_BYTES)?; + let preimage = crate::nip01::bounded_preimage(&fields, SIGNED_MAX_BYTES)?; + let event_id = Sha256::digest(preimage.as_bytes()).into(); + Ok(Self { + author: rumor.author, + recipient, + created_at, + ciphertext: Zeroizing::new(String::from(ciphertext)), + event_id, + }) + } + /// Borrows the exact immutable fields; seal tags are always empty. + pub fn fields(&self) -> EventFields<'_> { + EventFields { + author: self.author, + created_at: self.created_at.get(), + kind: 13, + tags: &[], + content: &self.ciphertext, + } + } + /// Returns the exact recipient, separate from public seal tags. + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + /// Returns the exact expected signed event ID. + pub const fn event_id(&self) -> [u8; 32] { + self.event_id + } +} +impl fmt::Debug for ChatSeal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ChatSeal(<redacted>)") + } +} diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs @@ -9,6 +9,14 @@ extern crate alloc; #[cfg(feature = "commands")] pub mod command; +/// Exact canonical NIP-01 bytes and complete serialization budgets. +#[cfg(feature = "nip01")] +pub mod nip01; + +/// Bounded known-kind private-chat data; no admission or route authority. +#[cfg(feature = "chat")] +pub mod chat; + #[cfg(all(test, not(feature = "std")))] extern crate std; diff --git a/crates/protocol/src/nip01.rs b/crates/protocol/src/nip01.rs @@ -0,0 +1,226 @@ +//! Canonical NIP-01 bytes. These data codecs authenticate no event or command. + +use alloc::{ + string::{String, ToString}, + vec::Vec, +}; +use core::fmt; +use radroots_identity::PublicKey; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; + +/// Fixed codec failures, without private input in diagnostics. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum WireError { + /// Data does not fit the selected profile. + InvalidInput, + /// Complete serialized output exceeds its selected byte budget. + LimitExceeded, +} +impl fmt::Display for WireError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidInput => "invalid event profile", + Self::LimitExceeded => "event byte limit exceeded", + }) + } +} +impl core::error::Error for WireError {} + +/// Borrowed exact fields. No registry, clock, participant or grant is inferred. +pub struct EventFields<'a> { + /// Validated x-only author key. + pub author: PublicKey, + /// Exact NIP-01 integer timestamp; business profiles apply their own bounds. + pub created_at: u64, + /// Exact NIP-01 kind. + pub kind: u32, + /// Ordered tags and fields, without sorting or normalization. + pub tags: &'a [Vec<String>], + /// Exact UTF-8 content. + pub content: &'a str, +} +impl fmt::Debug for EventFields<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("EventFields(<redacted>)") + } +} + +fn add(total: &mut usize, amount: usize, limit: usize) -> Result<(), WireError> { + *total = total + .checked_add(amount) + .filter(|n| *n <= limit) + .ok_or(WireError::LimitExceeded)?; + Ok(()) +} +fn string_len(value: &str, total: &mut usize, limit: usize) -> Result<(), WireError> { + add(total, 2, limit)?; + for byte in value.bytes() { + add( + total, + match byte { + b'"' | b'\\' | b'\n' | b'\r' | b'\t' | 8 | 12 => 2, + 0..=31 => 6, + _ => 1, + }, + limit, + )?; + } + Ok(()) +} +/// Counts complete canonical preimage bytes before allocating the output. +pub fn preimage_len(fields: &EventFields<'_>, limit: usize) -> Result<usize, WireError> { + let mut size = 3 + 66 + 1; + add( + &mut size, + fields.created_at.checked_ilog10().unwrap_or(0) as usize + 1, + limit, + )?; + add( + &mut size, + 1 + fields.kind.checked_ilog10().unwrap_or(0) as usize + 1 + 2, + limit, + )?; + for (index, tag) in fields.tags.iter().enumerate() { + add(&mut size, 2 + usize::from(index != 0), limit)?; + for (index, value) in tag.iter().enumerate() { + add(&mut size, usize::from(index != 0), limit)?; + string_len(value, &mut size, limit)?; + } + } + add(&mut size, 2, limit)?; + string_len(fields.content, &mut size, limit)?; + add(&mut size, 1, limit)?; + Ok(size) +} + +fn push_string(target: &mut String, value: &str) { + target.push('"'); + const HEX: &[u8; 16] = b"0123456789abcdef"; + for character in value.chars() { + match character { + '"' => target.push_str("\\\""), + '\\' => target.push_str("\\\\"), + '\n' => target.push_str("\\n"), + '\r' => target.push_str("\\r"), + '\t' => target.push_str("\\t"), + '\u{08}' => target.push_str("\\b"), + '\u{0c}' => target.push_str("\\f"), + '\u{00}'..='\u{1f}' => { + let value = character as usize; + target.push_str("\\u00"); + target.push(HEX[value >> 4] as char); + target.push(HEX[value & 15] as char); + } + _ => target.push(character), + } + } + target.push('"'); +} +fn push_tags(target: &mut String, tags: &[Vec<String>]) { + target.push('['); + for (index, tag) in tags.iter().enumerate() { + if index != 0 { + target.push(','); + } + target.push('['); + for (index, value) in tag.iter().enumerate() { + if index != 0 { + target.push(','); + } + push_string(target, value); + } + target.push(']'); + } + target.push(']'); +} +fn append_preimage(target: &mut String, fields: &EventFields<'_>) { + target.push_str("[0,"); + push_string(target, &fields.author.to_hex()); + target.push(','); + target.push_str(&fields.created_at.to_string()); + target.push(','); + target.push_str(&fields.kind.to_string()); + target.push(','); + push_tags(target, fields.tags); + target.push(','); + push_string(target, fields.content); + target.push(']'); +} +/// Retains the original wire-v1 serialization semantics, including unrestricted +/// NIP-01 integer timestamps. Callers must bound their input; new private +/// profiles use the explicitly bounded encoder instead. +pub fn canonical_preimage(fields: &EventFields<'_>) -> String { + let mut target = String::new(); + append_preimage(&mut target, fields); + target +} +/// Checks the complete preimage before allocating private serialized bytes. +pub(crate) fn bounded_preimage( + fields: &EventFields<'_>, + limit: usize, +) -> Result<Zeroizing<String>, WireError> { + let size = preimage_len(fields, limit)?; + let mut target = Zeroizing::new(String::with_capacity(size)); + append_preimage(&mut target, fields); + Ok(target) +} +/// Counts complete signed JSON, including the exact ID and 64-byte signature. +pub fn signed_json_len(fields: &EventFields<'_>, limit: usize) -> Result<usize, WireError> { + let mut size = preimage_len(fields, limit)?; + add(&mut size, 253, limit)?; + Ok(size) +} +fn hex(bytes: &[u8; 32]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut output = String::with_capacity(64); + for byte in bytes { + output.push(HEX[(byte >> 4) as usize] as char); + output.push(HEX[(byte & 15) as usize] as char); + } + output +} +/// Owned exact unsigned JSON and its computed event ID; no signature or +/// authenticated participant claim is supplied by this value. +pub struct UnsignedEvent { + id: [u8; 32], + json: Zeroizing<String>, +} +impl UnsignedEvent { + /// Checks the complete rumor/object size before creating private output. + pub fn encode(fields: &EventFields<'_>, limit: usize) -> Result<Self, WireError> { + let preimage = bounded_preimage( + fields, + limit.checked_sub(116).ok_or(WireError::LimitExceeded)?, + )?; + let id = Sha256::digest(preimage.as_bytes()).into(); + let mut json = Zeroizing::new(String::with_capacity(preimage.len() + 116)); + json.push_str("{\"id\":"); + push_string(&mut json, &hex(&id)); + json.push_str(",\"pubkey\":"); + push_string(&mut json, &fields.author.to_hex()); + json.push_str(",\"created_at\":"); + json.push_str(&fields.created_at.to_string()); + json.push_str(",\"kind\":"); + json.push_str(&fields.kind.to_string()); + json.push_str(",\"tags\":"); + push_tags(&mut json, fields.tags); + json.push_str(",\"content\":"); + push_string(&mut json, fields.content); + json.push('}'); + Ok(Self { id, json }) + } + /// Returns the exact SHA-256 event ID. + pub const fn event_id(&self) -> [u8; 32] { + self.id + } + /// Borrows the exact unsigned JSON, without cloning private content. + pub fn json(&self) -> &str { + &self.json + } +} +impl fmt::Debug for UnsignedEvent { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("UnsignedEvent(<redacted>)") + } +} diff --git a/crates/protocol/tests/chat_wire.rs b/crates/protocol/tests/chat_wire.rs @@ -0,0 +1,243 @@ +#![cfg(feature = "chat")] + +use radroots_domain::{PublicKey, UnixSeconds}; +use radroots_protocol::{chat::*, command::CapturedChatCommand, nip01::*}; +use serde_json::Value; + +fn vectors() -> Value { + serde_json::from_str(include_str!("fixtures/chat_wire.v1.json")).unwrap() +} +fn time(value: u64) -> UnixSeconds { + UnixSeconds::new(value).unwrap() +} +fn text<'a>(row: &'a Value, key: &str) -> &'a str { + row[key].as_str().unwrap() +} + +#[test] +fn independent_wire_vectors_preserve_plaintext_tags_recipient_set_and_exact_seal() { + for row in vectors()["vectors"].as_array().unwrap() { + let command = CapturedChatCommand::parse(text(row, "wire").as_bytes()).unwrap(); + let rumor = ChatRumor::from_command(&command, time(1_700_000_000)).unwrap(); + assert_eq!(rumor.json(), text(row, "rumor")); + assert_eq!(rumor.message_id().to_string(), text(row, "message_id")); + assert_eq!(rumor.author(), command.context().actor().participant()); + assert_eq!(rumor.created_at(), time(1_700_000_000)); + let recipients: Vec<_> = rumor.recipients().iter().map(|key| key.to_hex()).collect(); + assert_eq!(serde_json::to_value(recipients).unwrap(), row["recipients"]); + let json: Value = serde_json::from_str(rumor.json()).unwrap(); + assert!(json.get("sig").is_none()); + assert_eq!(json["content"], command.text()); + for recipient in rumor.recipients() { + let seal = ChatSeal::new( + &rumor, + *recipient, + time(1_699_999_990), + text(row, "structural_ciphertext"), + ) + .unwrap(); + assert_eq!( + canonical_preimage(&seal.fields()), + text(row, "seal_preimage") + ); + assert_eq!( + signed_json_len(&seal.fields(), SIGNED_MAX_BYTES).unwrap() as u64, + row["signed_seal_bytes"].as_u64().unwrap() + ); + assert_eq!(seal.recipient(), *recipient); + let encoded = UnsignedEvent::encode(&seal.fields(), SIGNED_MAX_BYTES).unwrap(); + assert_eq!(seal.event_id(), encoded.event_id()); + assert_eq!( + serde_json::from_str::<Value>(encoded.json()).unwrap()["id"], + row["seal_id"] + ); + assert!(!format!("{seal:?}").contains(text(row, "structural_ciphertext"))); + } + assert!(!format!("{rumor:?}").contains(command.text())); + } +} + +#[test] +fn complete_nested_budget_and_padding_match_independent_serialized_objects() { + let data = vectors(); + let key = PublicKey::from_hex(text(&data["canonical"][0], "author")).unwrap(); + for row in data["budgets"].as_array().unwrap() { + let budget = + ChatBudget::for_rumor(row["rumor_bytes"].as_u64().unwrap() as usize, key).unwrap(); + assert_eq!( + budget.rumor_ciphertext_bytes() as u64, + row["rumor_ciphertext_bytes"].as_u64().unwrap() + ); + assert_eq!( + budget.signed_seal_max_bytes() as u64, + row["signed_seal_max_bytes"].as_u64().unwrap() + ); + assert_eq!( + budget.envelope_ciphertext_max_bytes() as u64, + row["envelope_ciphertext_max_bytes"].as_u64().unwrap() + ); + assert_eq!( + budget.signed_envelope_max_bytes() as u64, + row["signed_envelope_max_bytes"].as_u64().unwrap() + ); + } + for row in data["padding"].as_array().unwrap() { + assert_eq!( + nip44_v2_payload_len(row["plaintext_bytes"].as_u64().unwrap() as usize).unwrap() as u64, + row["encoded_bytes"].as_u64().unwrap() + ); + } + for size in [0, 65_536, usize::MAX] { + assert_eq!(nip44_v2_payload_len(size), Err(WireError::InvalidInput)); + } + assert_eq!(ChatBudget::for_rumor(0, key), Err(WireError::InvalidInput)); + assert_eq!( + ChatBudget::for_rumor(RUMOR_MAX_BYTES + 1, key), + Err(WireError::LimitExceeded) + ); +} + +#[test] +fn canonical_wire_preserves_original_escaping_and_full_legacy_integer_range() { + for row in vectors()["canonical"].as_array().unwrap() { + let tags: Vec<Vec<String>> = serde_json::from_value(row["tags"].clone()).unwrap(); + let fields = EventFields { + author: PublicKey::from_hex(text(row, "author")).unwrap(), + created_at: text(row, "created_at").parse().unwrap(), + kind: row["kind"].as_u64().unwrap() as u32, + tags: &tags, + content: text(row, "content"), + }; + let expected = text(row, "preimage"); + assert_eq!(canonical_preimage(&fields), expected); + assert_eq!( + preimage_len(&fields, expected.len()).unwrap(), + expected.len() + ); + assert_eq!( + preimage_len(&fields, expected.len() - 1), + Err(WireError::LimitExceeded) + ); + let signed_size = row["signed_json_bytes"].as_u64().unwrap() as usize; + assert_eq!(signed_json_len(&fields, signed_size).unwrap(), signed_size); + assert_eq!( + signed_json_len(&fields, signed_size - 1), + Err(WireError::LimitExceeded) + ); + let unsigned = UnsignedEvent::encode(&fields, expected.len() + 116).unwrap(); + assert_eq!(unsigned.json().len(), expected.len() + 116); + assert_eq!( + serde_json::from_str::<Value>(unsigned.json()).unwrap()["id"], + row["event_id"] + ); + assert!(matches!( + UnsignedEvent::encode(&fields, expected.len() + 115), + Err(WireError::LimitExceeded) + )); + assert!(matches!( + UnsignedEvent::encode(&fields, 0), + Err(WireError::LimitExceeded) + )); + assert!( + !format!("{fields:?} {unsigned:?}").contains(fields.content) + || fields.content.is_empty() + ); + } +} + +#[test] +fn noncanonical_base64_padding_version_and_alphabet_are_refused_before_seal_capture() { + for row in vectors()["vectors"].as_array().unwrap() { + let command = CapturedChatCommand::parse(text(row, "wire").as_bytes()).unwrap(); + let rumor = ChatRumor::from_command(&command, time(1_700_000_000)).unwrap(); + let original = text(row, "structural_ciphertext").as_bytes(); + let mut changes = Vec::new(); + let mut invalid = original.to_vec(); + invalid[2] = b'!'; + changes.push(invalid); + let mut wrong_version = original.to_vec(); + wrong_version[1] = b'Q'; + changes.push(wrong_version); + let padding = original + .iter() + .rev() + .take_while(|byte| **byte == b'=') + .count(); + if padding != 0 { + let mut missing_padding = original.to_vec(); + *missing_padding.last_mut().unwrap() = b'A'; + changes.push(missing_padding); + let mut nonzero_tail = original.to_vec(); + nonzero_tail[original.len() - padding - 1] = b'B'; + changes.push(nonzero_tail); + } + for changed in changes { + assert!(matches!( + ChatSeal::new( + &rumor, + rumor.recipients()[0], + time(1_699_999_990), + core::str::from_utf8(&changed).unwrap() + ), + Err(WireError::InvalidInput) + )); + } + } +} + +#[test] +fn rumor_and_seal_refuse_invalid_time_recipient_nested_size_and_ciphertext_shape() { + let data = vectors(); + let row = &data["vectors"][0]; + let command = CapturedChatCommand::parse(text(row, "wire").as_bytes()).unwrap(); + assert!(matches!( + ChatRumor::from_command(&command, time(0)), + Err(WireError::InvalidInput) + )); + let rumor = ChatRumor::from_command(&command, time(1_700_000_000)).unwrap(); + let peer = rumor.recipients()[0]; + for timestamp in [0, 1_700_000_001, 1_700_000_000 - 172_801] { + assert!(matches!( + ChatSeal::new( + &rumor, + peer, + time(timestamp), + text(row, "structural_ciphertext") + ), + Err(WireError::InvalidInput) + )); + } + let stranger = + PublicKey::from_hex("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9") + .unwrap(); + assert!(matches!( + ChatSeal::new( + &rumor, + stranger, + time(1_699_999_990), + text(row, "structural_ciphertext") + ), + Err(WireError::InvalidInput) + )); + for change in [ + "", + "#unsupported", + "AA", + &"A".repeat(text(row, "structural_ciphertext").len()), + ] { + assert!(matches!( + ChatSeal::new(&rumor, peer, time(1_699_999_990), change), + Err(WireError::InvalidInput) + )); + } + let mut wire: Value = serde_json::from_str(text(row, "wire")).unwrap(); + wire["input"]["text"] = Value::String("\u{0000}".repeat(4096)); + let expanded = CapturedChatCommand::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + assert!(matches!( + ChatRumor::from_command(&expanded, time(1_700_000_000)), + Err(WireError::LimitExceeded) + )); + wire["input"]["text"] = Value::String("a".repeat(4096)); + let bounded = CapturedChatCommand::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + assert!(ChatRumor::from_command(&bounded, time(1_700_000_000)).is_ok()); +} diff --git a/crates/protocol/tests/fixtures/chat_wire.v1.json b/crates/protocol/tests/fixtures/chat_wire.v1.json @@ -0,0 +1,224 @@ +{ + "schema": "radroots.chat_wire_vectors.v1", + "producer": "Node.js 26.10.0; independent ECMAScript JSON/SHA-256/base64", + "structural_payloads_are_unauthenticated": true, + "vectors": [ + { + "name": "inquiry_unicode", + "wire": "{\"context\":{\"actor\":{\"grant_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"buyer\"},\"approval\":null,\"authority\":{\"executor_id\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"generation\":\"9007199254740993\"},\"correlation_id\":\"first-observer\",\"expected\":null,\"not_after\":\"200\",\"operation_id\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"route_digest\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"workspace_id\":\"0303030303030303030303030303030303030303030303030303030303030303\"},\"input\":{\"peer\":\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"source\":null,\"text\":\"private 🥬 \\u000f \\n Å Å 
 🧺\",\"thread_id\":\"0606060606060606060606060606060606060606060606060606060606060606\"},\"type\":\"inbox.inquire\"}", + "preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",1700000000,14,[[\"p\",\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\"],[\"radroots\",\"thread\",\"0606060606060606060606060606060606060606060606060606060606060606\"]],\"private 🥬 \\u000f \\n Å Å 
 🧺\"]", + "rumor": "{\"id\":\"e5b879b60760f36c51395c24bddf454f508b81f51373de1dc75211cede535363\",\"pubkey\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"created_at\":1700000000,\"kind\":14,\"tags\":[[\"p\",\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\"],[\"radroots\",\"thread\",\"0606060606060606060606060606060606060606060606060606060606060606\"]],\"content\":\"private 🥬 \\u000f \\n Å Å 
 🧺\"}", + "message_id": "e5b879b60760f36c51395c24bddf454f508b81f51373de1dc75211cede535363", + "recipients": [ + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5" + ], + "structural_ciphertext": "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", + "seal_preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",1699999990,13,[],\"AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"]", + "seal_id": "a69029d41dcd5a0ba1c44fd6ff4c5b9aa41988a4a3aa4b3ee542ff3ddffb8f1a", + "signed_seal_bytes": 1031 + }, + { + "name": "inquiry_source_expected", + "wire": "{\"context\":{\"actor\":{\"grant_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"buyer\"},\"approval\":null,\"authority\":{\"executor_id\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"generation\":\"9007199254740993\"},\"correlation_id\":\"first-observer\",\"expected\":{\"agreement\":null,\"buyer_head\":null,\"checkpoint\":{\"coverage\":\"partial\",\"digest\":\"0808080808080808080808080808080808080808080808080808080808080808\",\"missing\":[\"0909090909090909090909090909090909090909090909090909090909090909\"],\"sequence\":\"9007199254740993\"},\"order_id\":\"0707070707070707070707070707070707070707070707070707070707070707\",\"seller_sequence\":\"9007199254740993\"},\"not_after\":\"200\",\"operation_id\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"route_digest\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"workspace_id\":\"0303030303030303030303030303030303030303030303030303030303030303\"},\"input\":{\"peer\":\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"source\":{\"coordinate\":{\"author\":\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"d\":\"55555555555555555555555555555555\",\"kind\":30402},\"event_id\":\"0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a\"},\"text\":\"A public reference does not prove terms or stock.\",\"thread_id\":\"0606060606060606060606060606060606060606060606060606060606060606\"},\"type\":\"inbox.inquire\"}", + "preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",1700000000,14,[[\"p\",\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\"],[\"radroots\",\"thread\",\"0606060606060606060606060606060606060606060606060606060606060606\"],[\"radroots\",\"source\",\"30402\",\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"55555555555555555555555555555555\",\"0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a\"]],\"A public reference does not prove terms or stock.\"]", + "rumor": "{\"id\":\"87ef1e8f05137848323d95ea44f9d12148eb36f94d7d08bec12a3c5757694bfd\",\"pubkey\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"created_at\":1700000000,\"kind\":14,\"tags\":[[\"p\",\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\"],[\"radroots\",\"thread\",\"0606060606060606060606060606060606060606060606060606060606060606\"],[\"radroots\",\"source\",\"30402\",\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"55555555555555555555555555555555\",\"0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a\"]],\"content\":\"A public reference does not prove terms or stock.\"}", + "message_id": "87ef1e8f05137848323d95ea44f9d12148eb36f94d7d08bec12a3c5757694bfd", + "recipients": [ + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5" + ], + "structural_ciphertext": "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", + "seal_preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",1699999990,13,[],\"AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"]", + "seal_id": "4d8a27e6d22027eed214055d931d58fcc03f31afdec002ed107172b12bcce96f", + "signed_seal_bytes": 1287 + }, + { + "name": "reply", + "wire": "{\"context\":{\"actor\":{\"grant_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"buyer\"},\"approval\":null,\"authority\":{\"executor_id\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"generation\":\"9007199254740993\"},\"correlation_id\":null,\"expected\":null,\"not_after\":\"200\",\"operation_id\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"route_digest\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"workspace_id\":\"0303030303030303030303030303030303030303030303030303030303030303\"},\"input\":{\"parent\":\"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\",\"peer\":\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"text\":\"reply\",\"thread_id\":\"0606060606060606060606060606060606060606060606060606060606060606\"},\"type\":\"inbox.reply\"}", + "preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",1700000000,14,[[\"p\",\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\"],[\"radroots\",\"thread\",\"0606060606060606060606060606060606060606060606060606060606060606\"],[\"e\",\"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\"]],\"reply\"]", + "rumor": "{\"id\":\"4d1680b430b9efa51ed1dfc97783a4624f51f91a6ced924284b31a42e77b8213\",\"pubkey\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"created_at\":1700000000,\"kind\":14,\"tags\":[[\"p\",\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\"],[\"radroots\",\"thread\",\"0606060606060606060606060606060606060606060606060606060606060606\"],[\"e\",\"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\"]],\"content\":\"reply\"}", + "message_id": "4d1680b430b9efa51ed1dfc97783a4624f51f91a6ced924284b31a42e77b8213", + "recipients": [ + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5" + ], + "structural_ciphertext": "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", + "seal_preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",1699999990,13,[],\"AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"]", + "seal_id": "a69029d41dcd5a0ba1c44fd6ff4c5b9aa41988a4a3aa4b3ee542ff3ddffb8f1a", + "signed_seal_bytes": 1031 + }, + { + "name": "self_chat", + "wire": "{\"context\":{\"actor\":{\"grant_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"buyer\"},\"approval\":null,\"authority\":{\"executor_id\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"generation\":\"9007199254740993\"},\"correlation_id\":\"first-observer\",\"expected\":null,\"not_after\":\"200\",\"operation_id\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"route_digest\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"workspace_id\":\"0303030303030303030303030303030303030303030303030303030303030303\"},\"input\":{\"peer\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"source\":null,\"text\":\"private 🥬 \\u000f \\n Å Å 
 🧺\",\"thread_id\":\"0606060606060606060606060606060606060606060606060606060606060606\"},\"type\":\"inbox.inquire\"}", + "preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",1700000000,14,[[\"p\",\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\"],[\"radroots\",\"thread\",\"0606060606060606060606060606060606060606060606060606060606060606\"]],\"private 🥬 \\u000f \\n Å Å 
 🧺\"]", + "rumor": "{\"id\":\"836309fc7a3b433934dac0391d97218ac7e8f6398c4cd4a5c44a41b456122e8d\",\"pubkey\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"created_at\":1700000000,\"kind\":14,\"tags\":[[\"p\",\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\"],[\"radroots\",\"thread\",\"0606060606060606060606060606060606060606060606060606060606060606\"]],\"content\":\"private 🥬 \\u000f \\n Å Å 
 🧺\"}", + "message_id": "836309fc7a3b433934dac0391d97218ac7e8f6398c4cd4a5c44a41b456122e8d", + "recipients": [ + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + ], + "structural_ciphertext": "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", + "seal_preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",1699999990,13,[],\"AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"]", + "seal_id": "a69029d41dcd5a0ba1c44fd6ff4c5b9aa41988a4a3aa4b3ee542ff3ddffb8f1a", + "signed_seal_bytes": 1031 + } + ], + "budgets": [ + { + "rumor_bytes": 1, + "rumor_ciphertext_bytes": 132, + "signed_seal_max_bytes": 477, + "envelope_ciphertext_max_bytes": 772, + "signed_envelope_max_bytes": 1191 + }, + { + "rumor_bytes": 32, + "rumor_ciphertext_bytes": 132, + "signed_seal_max_bytes": 477, + "envelope_ciphertext_max_bytes": 772, + "signed_envelope_max_bytes": 1191 + }, + { + "rumor_bytes": 33, + "rumor_ciphertext_bytes": 176, + "signed_seal_max_bytes": 521, + "envelope_ciphertext_max_bytes": 944, + "signed_envelope_max_bytes": 1363 + }, + { + "rumor_bytes": 256, + "rumor_ciphertext_bytes": 432, + "signed_seal_max_bytes": 777, + "envelope_ciphertext_max_bytes": 1284, + "signed_envelope_max_bytes": 1703 + }, + { + "rumor_bytes": 257, + "rumor_ciphertext_bytes": 516, + "signed_seal_max_bytes": 861, + "envelope_ciphertext_max_bytes": 1284, + "signed_envelope_max_bytes": 1703 + }, + { + "rumor_bytes": 1024, + "rumor_ciphertext_bytes": 1456, + "signed_seal_max_bytes": 1801, + "envelope_ciphertext_max_bytes": 2820, + "signed_envelope_max_bytes": 3239 + }, + { + "rumor_bytes": 16384, + "rumor_ciphertext_bytes": 21936, + "signed_seal_max_bytes": 22281, + "envelope_ciphertext_max_bytes": 32860, + "signed_envelope_max_bytes": 33279 + }, + { + "rumor_bytes": 24576, + "rumor_ciphertext_bytes": 32860, + "signed_seal_max_bytes": 33205, + "envelope_ciphertext_max_bytes": 54704, + "signed_envelope_max_bytes": 55123 + } + ], + "padding": [ + { + "plaintext_bytes": 1, + "encoded_bytes": 132 + }, + { + "plaintext_bytes": 2, + "encoded_bytes": 132 + }, + { + "plaintext_bytes": 31, + "encoded_bytes": 132 + }, + { + "plaintext_bytes": 32, + "encoded_bytes": 132 + }, + { + "plaintext_bytes": 33, + "encoded_bytes": 176 + }, + { + "plaintext_bytes": 64, + "encoded_bytes": 176 + }, + { + "plaintext_bytes": 65, + "encoded_bytes": 220 + }, + { + "plaintext_bytes": 255, + "encoded_bytes": 432 + }, + { + "plaintext_bytes": 256, + "encoded_bytes": 432 + }, + { + "plaintext_bytes": 257, + "encoded_bytes": 516 + }, + { + "plaintext_bytes": 65535, + "encoded_bytes": 87472 + } + ], + "canonical": [ + { + "created_at": "0", + "kind": 0, + "tags": [], + "content": "", + "author": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",0,0,[],\"\"]", + "event_id": "438633166bd72a6b099ca89b06018a96fc9a175ce81b44a853b1242fcca7ae0b", + "signed_json_bytes": 333 + }, + { + "created_at": "9", + "kind": 9, + "tags": [ + [], + [ + "p", + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + ] + ], + "content": "🥬 Å Å 
 
", + "author": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",9,9,[[],[\"p\",\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\"]],\"🥬 Å Å 
 
\"]", + "event_id": "5e3cd969d7d1618f1dd98f049658788620459a35bbf56c0baff9d3be045d73e2", + "signed_json_bytes": 427 + }, + { + "created_at": "10", + "kind": 10, + "tags": [ + [ + "quoted\"", + "slash\\", + "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f" + ] + ], + "content": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f", + "author": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",10,10,[[\"quoted\\\"\",\"slash\\\\\",\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\"]],\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\"]", + "event_id": "86eccb0cf6286909533edab14c842e22462a05bde663f94bb7782592ad515025", + "signed_json_bytes": 704 + }, + { + "created_at": "18446744073709551615", + "kind": 4294967295, + "tags": [], + "content": "largest legacy integers", + "author": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "preimage": "[0,\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",18446744073709551615,4294967295,[],\"largest legacy integers\"]", + "event_id": "ee201ba5f37fd64968403b9abaf3b3c720a49d5ab487ddcbc735995dc40dd145", + "signed_json_bytes": 384 + } + ] +} diff --git a/crates/protocol/tests/package_boundary.rs b/crates/protocol/tests/package_boundary.rs @@ -15,6 +15,8 @@ const VERSIONED_SOURCES: &[&str] = &[ include_str!("../src/runtime/v1.rs"), include_str!("../src/schema.rs"), include_str!("../src/command.rs"), + include_str!("../src/nip01.rs"), + include_str!("../src/chat.rs"), ]; #[test] @@ -26,11 +28,18 @@ fn manifest_has_approved_data_only_features_and_dependencies() { assert!(MANIFEST.contains("default = [\"std\", \"serde\"]")); assert_eq!( table_keys(MANIFEST, "[features]"), - BTreeSet::from(["commands", "default", "serde", "std"]) + BTreeSet::from(["chat", "commands", "default", "nip01", "serde", "std"]) ); assert_eq!( table_keys(MANIFEST, "[dependencies]"), - BTreeSet::from(["radroots_domain", "serde", "serde_json", "sha2", "zeroize"]) + BTreeSet::from([ + "radroots_domain", + "radroots_identity", + "serde", + "serde_json", + "sha2", + "zeroize" + ]) ); assert_eq!( table_keys(MANIFEST, "[dev-dependencies]"), @@ -45,9 +54,11 @@ fn crate_root_exposes_only_the_approved_versioned_skeleton() { root_declarations("pub mod "), BTreeSet::from([ "capability", + "chat", "command", "error", "event", + "nip01", "radrootsd", "runtime", "schema" diff --git a/crates/protocol/tests/support/chat_wire_oracle.mjs b/crates/protocol/tests/support/chat_wire_oracle.mjs @@ -0,0 +1,61 @@ +// Independent ECMAScript/Node oracle. Zero-filled payload frames below prove +// structure and byte counts only; they deliberately contain no valid MAC. +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; + +const inputs = JSON.parse(readFileSync(new URL("../fixtures/chat_commands.v1.json", import.meta.url), "utf8")); +const hash = (value) => createHash("sha256").update(value, "utf8").digest("hex"); +const bytes = (value) => Buffer.byteLength(value, "utf8"); +const padded = (length) => { + if (length <= 32) return 32; + const next = 2 ** Math.ceil(Math.log2(length)); + const chunk = next <= 256 ? 32 : next / 8; + return Math.ceil(length / chunk) * chunk; +}; +const frame = (length) => { + const buffer = Buffer.alloc(padded(length) + 67); + buffer[0] = 2; + return buffer.toString("base64"); +}; +const encodedLength = (length) => Math.ceil((padded(length) + 67) / 3) * 4; +const preimage = (event) => JSON.stringify([0, event.pubkey, event.created_at, event.kind, event.tags, event.content]); +const unsigned = (event) => ({ id: hash(preimage(event)), ...event }); +const signedLength = (event) => bytes(JSON.stringify({ ...unsigned(event), sig: "0".repeat(128) })); +const commands = inputs.vectors.map(({ name, wire }) => ({ name, command: JSON.parse(wire) })); +const self = structuredClone(commands[0]); +self.name = "self_chat"; +self.command.input.peer = self.command.context.actor.participant; +commands.push(self); +const vectors = commands.map(({ name, command }) => { + const input = command.input; + const author = command.context.actor.participant; + const tags = [["p", input.peer], ["radroots", "thread", input.thread_id]]; + if (input.source) tags.push(["radroots", "source", "30402", input.source.coordinate.author, input.source.coordinate.d, input.source.event_id]); + if (input.parent) tags.push(["e", input.parent]); + const event = { pubkey: author, created_at: 1700000000, kind: 14, tags, content: input.text }; + const rumor = JSON.stringify(unsigned(event)); + const ciphertext = frame(bytes(rumor)); + const seal = { pubkey: author, created_at: 1699999990, kind: 13, tags: [], content: ciphertext }; + return { name, wire: JSON.stringify(command), preimage: preimage(event), rumor, message_id: hash(preimage(event)), recipients: [...new Set([author, input.peer])].sort(), structural_ciphertext: ciphertext, seal_preimage: preimage(seal), seal_id: hash(preimage(seal)), signed_seal_bytes: signedLength(seal) }; +}); +const author = commands[0].command.context.actor.participant; +const budgets = [1, 32, 33, 256, 257, 1024, 16384, 24576].map((length) => { + const ciphertext = frame(length); + const seal = { pubkey: author, created_at: 253402300799, kind: 13, tags: [], content: ciphertext }; + const sealBytes = signedLength(seal); + const outer = { pubkey: author, created_at: 253402300799, kind: 1059, tags: [["p", author]], content: frame(sealBytes) }; + return { rumor_bytes: length, rumor_ciphertext_bytes: bytes(ciphertext), signed_seal_max_bytes: sealBytes, envelope_ciphertext_max_bytes: encodedLength(sealBytes), signed_envelope_max_bytes: signedLength(outer) }; +}); +const padding = [1, 2, 31, 32, 33, 64, 65, 255, 256, 257, 65535].map((length) => ({ plaintext_bytes: length, encoded_bytes: encodedLength(length) })); +const allControls = Array.from({ length: 32 }, (_, index) => String.fromCharCode(index)).join(""); +const canonical = [ + { created_at: "0", kind: 0, tags: [], content: "" }, + { created_at: "9", kind: 9, tags: [[], ["p", author]], content: "🥬 Å A\u030a \u2028 \u2029" }, + { created_at: "10", kind: 10, tags: [["quoted\"", "slash\\", allControls]], content: allControls }, + { created_at: "18446744073709551615", kind: 4294967295, tags: [], content: "largest legacy integers" }, +].map((value) => { + // Decimal integer text preserves the legacy u64 case beyond JS Number. + const exact = `[0,${JSON.stringify(author)},${value.created_at},${value.kind},${JSON.stringify(value.tags)},${JSON.stringify(value.content)}]`; + return { ...value, author, preimage: exact, event_id: hash(exact), signed_json_bytes: bytes(exact) + 253 }; +}); +process.stdout.write(JSON.stringify({ schema: "radroots.chat_wire_vectors.v1", producer: `Node.js ${process.versions.node}; independent ECMAScript JSON/SHA-256/base64`, structural_payloads_are_unauthenticated: true, vectors, budgets, padding, canonical }, null, 2) + "\n"); diff --git a/crates/signing/Cargo.toml b/crates/signing/Cargo.toml @@ -32,6 +32,7 @@ name = "radroots_signing" [features] default = ["std", "serde"] +chat = ["radroots_protocol/chat"] std = [ "radroots_domain/std", "radroots_event/std", @@ -52,7 +53,7 @@ radroots_domain = { workspace = true, default-features = false } radroots_event = { workspace = true, default-features = false } radroots_event_codec = { workspace = true, default-features = false } radroots_identity = { workspace = true, default-features = false } -radroots_protocol = { workspace = true, default-features = false } +radroots_protocol = { workspace = true, default-features = false, features = ["nip01"] } hex = { version = "0.4", default-features = false, features = ["alloc"] } sha2 = { workspace = true, default-features = false } zeroize = { workspace = true, default-features = false, features = ["alloc"] } @@ -66,7 +67,7 @@ radroots_blossom = { workspace = true, default-features = false, features = [ "std", ] } serde_json = { workspace = true, features = ["std"] } -nostr = { workspace = true, features = ["std"] } +nostr = { workspace = true, features = ["std", "nip44"] } [lints] workspace = true diff --git a/crates/signing/src/issuance.rs b/crates/signing/src/issuance.rs @@ -151,6 +151,40 @@ impl SigningIntent { signed_json_bytes, }) } + /// Converts one bounded known-kind seal into the existing exact signer + /// contract. This codec conversion grants no command, route or journal + /// authority; the executor must retain the full plan before dispatch. + #[cfg(feature = "chat")] + pub fn from_chat_seal( + operation_id: OperationId, + command_digest: radroots_domain::CommandDigest, + seal: &radroots_protocol::chat::ChatSeal, + call: ProviderCall, + ) -> Result<Self, ProviderError> { + let fields = seal.fields(); + let draft = radroots_event::GenericEventDraft::new( + "radroots.message.seal.v1", + fields.kind, + fields.created_at, + core::iter::empty().collect(), + fields.content, + fields.author.to_hex(), + ) + .map_err(|_| ProviderError::InvalidInput)?; + let plan = + AuthoredEventPlan::from_generic(draft).map_err(|_| ProviderError::InvalidInput)?; + if plan.expected_event_id().as_bytes() != &seal.event_id() { + return Err(ProviderError::InvalidInput); + } + Self::new( + operation_id, + *command_digest.as_bytes(), + plan, + ArtifactRole::BusinessSeal, + Some(seal.recipient()), + call, + ) + } /// Returns the original immutable binding. pub const fn binding(&self) -> IntentBinding { self.binding @@ -185,31 +219,6 @@ impl SigningIntent { } } -struct Size(usize); -impl Size { - fn add(&mut self, n: usize) -> Result<(), ProviderError> { - self.0 = self - .0 - .checked_add(n) - .filter(|n| *n <= SIGNED_EVENT_MAX_BYTES) - .ok_or(ProviderError::LimitExceeded)?; - Ok(()) - } - fn string(&mut self, value: &str) -> Result<(), ProviderError> { - self.add(2)?; - if value.len() > SIGNED_EVENT_MAX_BYTES { - return Err(ProviderError::LimitExceeded); - } - for byte in value.bytes() { - self.add(match byte { - b'"' | b'\\' | b'\n' | b'\r' | b'\t' | 8 | 12 => 2, - 0..=31 => 6, - _ => 1, - })?; - } - Ok(()) - } -} fn signed_json_len(plan: &AuthoredEventPlan) -> Result<usize, ProviderError> { if plan.body().kind() > u32::from(u16::MAX) { return Err(ProviderError::UnsupportedVersion); @@ -220,26 +229,12 @@ fn signed_json_len(plan: &AuthoredEventPlan) -> Result<usize, ProviderError> { if plan.body().tags().len() > limits.max_tag_count { return Err(ProviderError::LimitExceeded); } - let mut size = Size(0); - size.add(b"{\"id\":".len() + 66 + b",\"pubkey\":".len() + 66 + b",\"created_at\":".len())?; - size.add(plan.created_at().checked_ilog10().unwrap_or(0) as usize + 1)?; - size.add( - b",\"kind\":".len() - + plan.body().kind().checked_ilog10().unwrap_or(0) as usize - + 1 - + b",\"tags\":".len() - + 2, - )?; - for (index, tag) in plan.body().tags().iter().enumerate() { - if index != 0 { - size.add(1)?; - } - size.add(2)?; + for tag in plan.body().tags() { elements = elements .checked_add(tag.len()) .filter(|n| *n <= limits.max_total_tag_elements) .ok_or(ProviderError::LimitExceeded)?; - for (index, field) in tag.iter().enumerate() { + for field in tag { if field.len() > limits.max_tag_element_bytes { return Err(ProviderError::LimitExceeded); } @@ -247,16 +242,19 @@ fn signed_json_len(plan: &AuthoredEventPlan) -> Result<usize, ProviderError> { .checked_add(field.len()) .filter(|n| *n <= limits.max_total_tag_bytes) .ok_or(ProviderError::LimitExceeded)?; - if index != 0 { - size.add(1)?; - } - size.string(field)?; } } - size.add(b",\"content\":".len())?; - size.string(plan.body().content())?; - size.add(b",\"sig\":".len() + 130 + 1)?; - Ok(size.0) + radroots_protocol::nip01::signed_json_len( + &radroots_protocol::nip01::EventFields { + author: *plan.author(), + created_at: plan.created_at(), + kind: plan.body().kind(), + tags: plan.body().tags(), + content: plan.body().content(), + }, + SIGNED_EVENT_MAX_BYTES, + ) + .map_err(|_| ProviderError::LimitExceeded) } /// Scope of a forensic digest. A prefix digest never claims full coverage. diff --git a/crates/signing/tests/chat_seal.rs b/crates/signing/tests/chat_seal.rs @@ -0,0 +1,176 @@ +#![cfg(feature = "chat")] + +use nostr::{JsonUtil, nips::nip44}; +use radroots_domain::{ + ActorRef, ActorRole, AuthorityRef, CommandContextData, ExecutorId, Generation, GrantId, + OperationId, PublicKey, RouteDigest, ThreadId, UnixSeconds, WorkspaceId, +}; +use radroots_protocol::{ + chat::{ChatRumor, ChatSeal}, + command::{CapturedChatCommand, InquireInput}, +}; +use radroots_signing::{ + issuance::{ArtifactRole, OutcomeKind, SigningIntent, SigningOutcome}, + provider::{ProviderCall, ProviderError}, + request::CancellationSignal, +}; +use std::num::NonZeroU64; + +const NOW: u64 = 1_700_000_000; +fn keys(last: u8) -> nostr::Keys { + // Published synthetic test identities, isolated from all host custody. + let mut bytes = [0; 32]; + bytes[31] = last; + nostr::Keys::new(nostr::SecretKey::from_slice(&bytes).unwrap()) +} +fn call(author: PublicKey) -> ProviderCall { + ProviderCall::new( + author, + NonZeroU64::new((NOW + 120) * 1000).unwrap(), + CancellationSignal::new(), + ) +} +fn command() -> CapturedChatCommand { + let author = PublicKey::from_hex(&keys(1).public_key().to_hex()).unwrap(); + let peer = PublicKey::from_hex(&keys(2).public_key().to_hex()).unwrap(); + let context = CommandContextData::new( + OperationId::from_bytes([1; 32]), + ActorRef::new( + author, + ActorRole::Buyer, + None, + Some(GrantId::from_bytes([2; 32])), + ), + WorkspaceId::from_bytes([3; 32]), + AuthorityRef::new(ExecutorId::from_bytes([4; 32]), Generation::new(1).unwrap()), + RouteDigest::from_bytes([5; 32]), + None, + None, + UnixSeconds::new(NOW + 120).unwrap(), + None, + ) + .unwrap(); + CapturedChatCommand::inquire( + context, + InquireInput::new( + ThreadId::from_bytes([6; 32]), + peer, + None, + "private 🥬 Å A\u{030a}\n", + ) + .unwrap(), + ) + .unwrap() +} + +#[test] +fn known_kind_conversion_signs_and_authenticates_the_same_rumor_for_peer_and_self() { + let author = keys(1); + let peer = keys(2); + let command = command(); + let rumor = ChatRumor::from_command(&command, UnixSeconds::new(NOW).unwrap()).unwrap(); + let mut sealed = Vec::new(); + for recipient in rumor.recipients() { + let receiver = if recipient == &rumor.author() { + &author + } else { + &peer + }; + let encrypted = nip44::encrypt( + author.secret_key(), + &receiver.public_key(), + rumor.json(), + nip44::Version::V2, + ) + .unwrap(); + assert_eq!(encrypted.len(), rumor.budget().rumor_ciphertext_bytes()); + let seal = ChatSeal::new( + &rumor, + *recipient, + UnixSeconds::new(NOW - 10).unwrap(), + &encrypted, + ) + .unwrap(); + let intent = SigningIntent::from_chat_seal( + command.context().operation_id(), + command.digest(), + &seal, + call(rumor.author()), + ) + .unwrap(); + assert_eq!(intent.role(), ArtifactRole::BusinessSeal); + assert_eq!(intent.recipient(), Some(*recipient)); + assert_eq!(intent.author(), rumor.author()); + assert_eq!( + intent.binding().command_digest(), + command.digest().as_bytes() + ); + intent + .check_before_effect(rumor.author(), NOW * 1000) + .unwrap(); + let event = intent.with_plan(|plan| { + nostr::UnsignedEvent { + id: Some(nostr::EventId::from_slice(plan.expected_event_id().as_bytes()).unwrap()), + pubkey: author.public_key(), + created_at: nostr::Timestamp::from_secs(plan.created_at()), + kind: nostr::Kind::Custom(plan.body().kind() as u16), + tags: nostr::Tags::new(), + content: plan.body().content().into(), + } + .sign_with_keys(&author) + .unwrap() + }); + event.verify().unwrap(); + let raw = event.as_json(); + assert_eq!(raw.len(), intent.signed_json_bytes()); + assert!(raw.len() <= rumor.budget().signed_seal_max_bytes()); + assert_eq!(event.id.as_bytes(), &seal.event_id()); + assert!(event.tags.is_empty()); + assert_eq!( + nip44::decrypt(receiver.secret_key(), &author.public_key(), &event.content).unwrap(), + rumor.json() + ); + let captured = SigningOutcome::capture(&intent, raw, None); + match captured.kind() { + OutcomeKind::Obtained(artifact) => { + assert_eq!(artifact.event_id().as_bytes(), &seal.event_id()); + assert_eq!(artifact.observed_at_unix_ms(), None); + sealed.push(artifact.event_id()); + } + _ => panic!("real exact seal must verify"), + } + } + assert_eq!(sealed.len(), 2); + assert_ne!(sealed[0], sealed[1]); +} + +#[test] +fn known_seal_conversion_refuses_substituted_signer_identity() { + let command = command(); + let author = keys(1); + let peer = keys(2); + let rumor = ChatRumor::from_command(&command, UnixSeconds::new(NOW).unwrap()).unwrap(); + let encrypted = nip44::encrypt( + author.secret_key(), + &peer.public_key(), + rumor.json(), + nip44::Version::V2, + ) + .unwrap(); + let seal = ChatSeal::new( + &rumor, + command.peer(), + UnixSeconds::new(NOW - 10).unwrap(), + &encrypted, + ) + .unwrap(); + assert!(matches!( + SigningIntent::from_chat_seal( + command.context().operation_id(), + command.digest(), + &seal, + call(command.peer()) + ), + Err(ProviderError::InvalidInput) + )); +} diff --git a/crates/signing/tests/issuance.rs b/crates/signing/tests/issuance.rs @@ -160,6 +160,10 @@ fn malformed_wrong_field_signature_and_oversized_output_are_bounded_forensics() let raw = signed(&intent); let mut signature: serde_json::Value = serde_json::from_str(&raw).unwrap(); signature["sig"] = "00".repeat(64).into(); + // The callback can preserve every expected field while substituting only + // the returned event ID. That response is not authenticated exact evidence. + let mut wrong_id: serde_json::Value = serde_json::from_str(&raw).unwrap(); + wrong_id["id"] = "11".repeat(32).into(); let different = signed(&self::intent("other", vec![], 1, 2)); for (raw, reason) in [ ( @@ -167,6 +171,7 @@ fn malformed_wrong_field_signature_and_oversized_output_are_bounded_forensics() RejectionReason::InvalidArtifact, ), (different, RejectionReason::InvalidArtifact), + (wrong_id.to_string(), RejectionReason::InvalidArtifact), (signature.to_string(), RejectionReason::InvalidSignature), ( "x".repeat(SIGNED_EVENT_MAX_BYTES + 1), @@ -380,6 +385,23 @@ fn intent_binding_preserves_low_operation_bytes_deadline_role_and_recipient() { .unwrap(), ) .unwrap(); + // A valid private carrier still requires its separate exact recipient + // binding; public seal bytes deliberately contain no recipient tag. + assert!(matches!( + SigningIntent::new( + OperationId::from_bytes([1; 32]), + [2; 32], + opaque.clone(), + role, + None, + ProviderCall::new( + PublicKey::from_str(AUTHOR).unwrap(), + NonZeroU64::new(CREATED * 1000 + 10_000).unwrap(), + CancellationSignal::new(), + ), + ), + Err(ProviderError::InvalidInput) + )); let input = SigningIntent::new( OperationId::from_bytes([1; 32]), [2; 32], diff --git a/crates/signing/tests/package_boundary.rs b/crates/signing/tests/package_boundary.rs @@ -24,7 +24,7 @@ fn manifest_has_final_identity_features_and_dependencies() { "radroots_event = { workspace = true, default-features = false }", "radroots_event_codec = { workspace = true, default-features = false }", "radroots_identity = { workspace = true, default-features = false }", - "radroots_protocol = { workspace = true, default-features = false }", + "radroots_protocol = { workspace = true, default-features = false, features = [\"nip01\"] }", ] { assert!( MANIFEST.contains(required), @@ -33,7 +33,7 @@ fn manifest_has_final_identity_features_and_dependencies() { } assert_eq!( table_keys(MANIFEST, "[features]"), - BTreeSet::from(["default", "serde", "std"]) + BTreeSet::from(["chat", "default", "serde", "std"]) ); assert_eq!( table_keys(MANIFEST, "[dependencies]"),