lib

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

plan.rs (10502B)


      1 //! Immutable complete known-kind signing data, without execution authority.
      2 use super::{ChatRumor, ChatSeal};
      3 use crate::intent::SigningReplay;
      4 use crate::nip59::CapturedDmRoute;
      5 use crate::{command::CapturedChatCommand, nip01::WireError};
      6 use alloc::{boxed::Box, collections::BTreeSet, string::String, vec::Vec};
      7 use core::fmt;
      8 use radroots_domain::{
      9     CommandDigest, EnvelopeEventId, MessageId, OperationId, PublicKey, UnixSeconds,
     10 };
     11 use sha2::{Digest, Sha256};
     12 use zeroize::Zeroizing;
     13 
     14 /// Complete protected plan bound, including original signed route sources.
     15 pub const PLAN_MAX_BYTES: usize = 384 * 1024;
     16 const MAGIC: &[u8] = b"radroots.chat.signing_plan.v1\0";
     17 
     18 /// Complete sorted recipient set, exact seal preimages and retained route
     19 /// observations. Construction verifies structural provenance only: encryption
     20 /// authentication, signed route verification, network approval, provider
     21 /// capability and protected T1 commit remain execution obligations.
     22 pub struct ChatSigningPlan {
     23     operation_id: OperationId,
     24     command_digest: CommandDigest,
     25     message_id: MessageId,
     26     created_at: UnixSeconds,
     27     replay: SigningReplay,
     28     seals: Box<[ChatSeal]>,
     29     routes: Box<[CapturedDmRoute]>,
     30     wire: Zeroizing<Vec<u8>>,
     31     digest: [u8; 32],
     32 }
     33 impl ChatSigningPlan {
     34     /// Requires exactly one seal and observed route per sorted unique recipient.
     35     /// Combined selected targets cannot exceed the sixteen-relay session cap.
     36     pub fn new(
     37         command: &CapturedChatCommand,
     38         created_at: UnixSeconds,
     39         seals: Vec<ChatSeal>,
     40         routes: Vec<CapturedDmRoute>,
     41         replay: SigningReplay,
     42     ) -> Result<Self, WireError> {
     43         let rumor = ChatRumor::from_command(command, created_at)?;
     44         if seals.len() != rumor.recipients().len() || routes.len() != seals.len() {
     45             return Err(WireError::InvalidInput);
     46         }
     47         let mut targets = BTreeSet::new();
     48         for ((seal, route), recipient) in seals.iter().zip(&routes).zip(rumor.recipients()) {
     49             if seal.operation_id() != command.context().operation_id()
     50                 || seal.command_digest() != command.digest()
     51                 || seal.message_id() != rumor.message_id()
     52                 || seal.recipient() != *recipient
     53                 || route.participant() != *recipient
     54             {
     55                 return Err(WireError::InvalidInput);
     56             }
     57             for target in route.selected_relays() {
     58                 targets.insert(target.as_ref());
     59             }
     60         }
     61         if targets.len() > 16 {
     62             return Err(WireError::LimitExceeded);
     63         }
     64         // All variable fields are already bounded. Count the complete binary
     65         // representation before allocating its sole retained canonical buffer.
     66         let mut length = MAGIC.len() + 32 * 3 + 8 + 2;
     67         for (seal, route) in seals.iter().zip(&routes) {
     68             length += 32
     69                 + 32
     70                 + 4
     71                 + 1
     72                 + 1
     73                 + 32
     74                 + 8
     75                 + 4
     76                 + seal.fields().content.len()
     77                 + 32
     78                 + 4
     79                 + route.raw_json().len()
     80                 + 1;
     81             for target in route.selected_relays() {
     82                 length += 4 + target.len();
     83             }
     84         }
     85         if length > PLAN_MAX_BYTES {
     86             return Err(WireError::LimitExceeded);
     87         }
     88         let mut wire = Zeroizing::new(Vec::with_capacity(length));
     89         wire.extend_from_slice(MAGIC);
     90         wire.extend_from_slice(command.context().operation_id().as_bytes());
     91         wire.extend_from_slice(command.digest().as_bytes());
     92         wire.extend_from_slice(rumor.message_id().as_bytes());
     93         wire.extend_from_slice(&created_at.get().to_be_bytes());
     94         wire.push(replay.code());
     95         wire.push(seals.len() as u8);
     96         for (seal, route) in seals.iter().zip(&routes) {
     97             wire.extend_from_slice(seal.recipient().as_bytes());
     98             wire.extend_from_slice(seal.fields().author.as_bytes());
     99             wire.extend_from_slice(&13u32.to_be_bytes());
    100             wire.push(0); // Exact empty tag set.
    101             wire.push(1); // Exact BusinessSeal role.
    102             wire.extend_from_slice(&seal.event_id());
    103             wire.extend_from_slice(&seal.fields().created_at.to_be_bytes());
    104             put(&mut wire, seal.fields().content.as_bytes());
    105             wire.extend_from_slice(route.source_id().as_bytes());
    106             put(&mut wire, route.raw_json().as_bytes());
    107             wire.push(route.selected_relays().len() as u8);
    108             for target in route.selected_relays() {
    109                 put(&mut wire, target.as_bytes());
    110             }
    111         }
    112         let digest = Sha256::digest(wire.as_slice()).into();
    113         Ok(Self {
    114             operation_id: command.context().operation_id(),
    115             command_digest: command.digest(),
    116             message_id: rumor.message_id(),
    117             created_at,
    118             replay,
    119             seals: seals.into_boxed_slice(),
    120             routes: routes.into_boxed_slice(),
    121             wire,
    122             digest,
    123         })
    124     }
    125     /// Decodes only the bounded canonical profile and reconstructs every seal
    126     /// from the original command. It supplies no cryptographic route proof.
    127     pub fn parse(command: &CapturedChatCommand, wire: &[u8]) -> Result<Self, WireError> {
    128         if wire.len() > PLAN_MAX_BYTES {
    129             return Err(WireError::LimitExceeded);
    130         }
    131         let mut input = Input(wire);
    132         if input.take(MAGIC.len())? != MAGIC
    133             || input.take(32)? != command.context().operation_id().as_bytes()
    134             || input.take(32)? != command.digest().as_bytes()
    135         {
    136             return Err(WireError::InvalidInput);
    137         }
    138         let message_id = MessageId::from_bytes(input.array()?);
    139         let time = UnixSeconds::new(u64::from_be_bytes(input.array()?))
    140             .map_err(|_| WireError::InvalidInput)?;
    141         let rumor = ChatRumor::from_command(command, time)?;
    142         if message_id != rumor.message_id() {
    143             return Err(WireError::InvalidInput);
    144         }
    145         let replay = SigningReplay::from_code(input.byte()?)?;
    146         if usize::from(input.byte()?) != rumor.recipients().len() {
    147             return Err(WireError::InvalidInput);
    148         }
    149         let mut seals = Vec::new();
    150         let mut routes = Vec::new();
    151         for recipient in rumor.recipients() {
    152             let described =
    153                 PublicKey::from_bytes(input.array()?).map_err(|_| WireError::InvalidInput)?;
    154             if described != *recipient {
    155                 return Err(WireError::InvalidInput);
    156             }
    157             let author: [u8; 32] = input.array()?;
    158             let kind = u32::from_be_bytes(input.array()?);
    159             let tags = input.byte()?;
    160             let purpose = input.byte()?;
    161             let expected_id: [u8; 32] = input.array()?;
    162             if author != *rumor.author().as_bytes() || kind != 13 || tags != 0 || purpose != 1 {
    163                 return Err(WireError::InvalidInput);
    164             }
    165             let seal_time = UnixSeconds::new(u64::from_be_bytes(input.array()?))
    166                 .map_err(|_| WireError::InvalidInput)?;
    167             let ciphertext = input.text(super::SIGNED_MAX_BYTES)?;
    168             let seal = ChatSeal::new(&rumor, *recipient, seal_time, ciphertext)?;
    169             if seal.event_id() != expected_id {
    170                 return Err(WireError::InvalidInput);
    171             }
    172             seals.push(seal);
    173             let source_id = EnvelopeEventId::from_bytes(input.array()?);
    174             let raw_json = input.text(super::SIGNED_MAX_BYTES)?;
    175             let count = usize::from(input.byte()?);
    176             if count == 0 || count > 16 {
    177                 return Err(WireError::InvalidInput);
    178             }
    179             let mut selected = Vec::with_capacity(count);
    180             for _ in 0..count {
    181                 selected.push(String::from(input.text(2048)?));
    182             }
    183             routes.push(CapturedDmRoute::from_observed_descriptor(
    184                 *recipient, source_id, raw_json, &selected,
    185             )?);
    186         }
    187         if !input.0.is_empty() {
    188             return Err(WireError::InvalidInput);
    189         }
    190         let plan = Self::new(command, time, seals, routes, replay)?;
    191         if plan.protected_wire() != wire {
    192             return Err(WireError::InvalidInput);
    193         }
    194         Ok(plan)
    195     }
    196     pub const fn operation_id(&self) -> OperationId {
    197         self.operation_id
    198     }
    199     pub const fn command_digest(&self) -> CommandDigest {
    200         self.command_digest
    201     }
    202     pub const fn message_id(&self) -> MessageId {
    203         self.message_id
    204     }
    205     pub const fn created_at(&self) -> UnixSeconds {
    206         self.created_at
    207     }
    208     pub const fn replay(&self) -> SigningReplay {
    209         self.replay
    210     }
    211     pub fn seals(&self) -> &[ChatSeal] {
    212         &self.seals
    213     }
    214     pub fn routes(&self) -> &[CapturedDmRoute] {
    215         &self.routes
    216     }
    217     /// Borrows exact versioned bytes requiring protected at-rest handling.
    218     pub fn protected_wire(&self) -> &[u8] {
    219         &self.wire
    220     }
    221     /// Commits every exact preimage, route source, target and replay descriptor.
    222     pub const fn digest(&self) -> &[u8; 32] {
    223         &self.digest
    224     }
    225 }
    226 impl fmt::Debug for ChatSigningPlan {
    227     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    228         f.write_str("ChatSigningPlan(<redacted>)")
    229     }
    230 }
    231 fn put(out: &mut Vec<u8>, value: &[u8]) {
    232     // Every caller has bounded this field far below u32::MAX.
    233     out.extend_from_slice(&(value.len() as u32).to_be_bytes());
    234     out.extend_from_slice(value);
    235 }
    236 struct Input<'a>(&'a [u8]);
    237 impl<'a> Input<'a> {
    238     fn take(&mut self, size: usize) -> Result<&'a [u8], WireError> {
    239         let (value, rest) = self
    240             .0
    241             .split_at_checked(size)
    242             .ok_or(WireError::InvalidInput)?;
    243         self.0 = rest;
    244         Ok(value)
    245     }
    246     fn array<const N: usize>(&mut self) -> Result<[u8; N], WireError> {
    247         self.take(N)?
    248             .try_into()
    249             .map_err(|_| WireError::InvalidInput)
    250     }
    251     fn byte(&mut self) -> Result<u8, WireError> {
    252         Ok(self.array::<1>()?[0])
    253     }
    254     fn text(&mut self, max: usize) -> Result<&'a str, WireError> {
    255         let size = u32::from_be_bytes(self.array()?) as usize;
    256         if size > max {
    257             return Err(WireError::LimitExceeded);
    258         }
    259         core::str::from_utf8(self.take(size)?).map_err(|_| WireError::InvalidInput)
    260     }
    261 }