lib

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

signing_plan.rs (9272B)


      1 //! Complete immutable private signing data. No store or provider fact is implied.
      2 use super::{CommerceSeal, EncodedCommerceRumor};
      3 use crate::{
      4     intent::SigningReplay,
      5     nip01::WireError,
      6     nip59::{CapturedDmRoute, SIGNED_MAX_BYTES},
      7 };
      8 use alloc::{collections::BTreeSet, string::String, vec::Vec};
      9 use core::fmt;
     10 use radroots_domain::{CommandDigest, EnvelopeEventId, OperationId, UnixSeconds};
     11 use sha2::{Digest, Sha256};
     12 use zeroize::Zeroizing;
     13 
     14 /// Includes both complete original route advertisements and exact seal fields.
     15 pub const SIGNING_PLAN_MAX_BYTES: usize = 256 * 1024;
     16 const MAGIC: &[u8] = b"radroots.commerce.signing_plan.v1\0";
     17 
     18 /// Complete peer/self plan tied to one exact original record and rumor.
     19 /// Construction supplies data only. The host must verify encryption, signed
     20 /// route sources, selected targets, current consent and actual durable T1.
     21 pub struct CommerceSigningPlan {
     22     operation: OperationId,
     23     command: CommandDigest,
     24     seals: [CommerceSeal; 2],
     25     routes: [CapturedDmRoute; 2],
     26     replay: SigningReplay,
     27     wire: Zeroizing<Vec<u8>>,
     28     digest: [u8; 32],
     29 }
     30 impl CommerceSigningPlan {
     31     /// Requires the complete sorted bilateral set and one original route for
     32     /// each recipient. Combined selected relays cannot exceed sixteen.
     33     pub fn new(
     34         operation: OperationId,
     35         command: CommandDigest,
     36         rumor: &EncodedCommerceRumor,
     37         seals: [CommerceSeal; 2],
     38         routes: [CapturedDmRoute; 2],
     39         replay: SigningReplay,
     40     ) -> Result<Self, WireError> {
     41         let mut targets = BTreeSet::new();
     42         let mut length = MAGIC.len() + 32 * 4 + 8 + 2;
     43         for ((seal, route), recipient) in seals.iter().zip(&routes).zip(rumor.recipients()) {
     44             if seal.operation_id() != operation
     45                 || seal.command_digest() != command
     46                 || seal.record_id() != rumor.record_id()
     47                 || seal.rumor_id() != rumor.event_id()
     48                 || seal.fields().author != rumor.author()
     49                 || seal.recipient() != *recipient
     50                 || route.participant() != *recipient
     51             {
     52                 return Err(WireError::InvalidInput);
     53             }
     54             length += 32
     55                 + 32
     56                 + 4
     57                 + 1
     58                 + 1
     59                 + 32
     60                 + 8
     61                 + 4
     62                 + seal.fields().content.len()
     63                 + 32
     64                 + 4
     65                 + route.raw_json().len()
     66                 + 1;
     67             for target in route.selected_relays() {
     68                 length += 4 + target.len();
     69                 targets.insert(target.as_ref());
     70             }
     71         }
     72         if length > SIGNING_PLAN_MAX_BYTES || targets.len() > 16 {
     73             return Err(WireError::LimitExceeded);
     74         }
     75         let mut wire = Zeroizing::new(Vec::with_capacity(length));
     76         wire.extend_from_slice(MAGIC);
     77         wire.extend_from_slice(operation.as_bytes());
     78         wire.extend_from_slice(command.as_bytes());
     79         wire.extend_from_slice(rumor.record_id().as_bytes());
     80         wire.extend_from_slice(rumor.event_id().as_bytes());
     81         wire.extend_from_slice(&rumor.created_at().get().to_be_bytes());
     82         wire.push(replay.code());
     83         wire.push(2);
     84         for (seal, route) in seals.iter().zip(&routes) {
     85             wire.extend_from_slice(seal.recipient().as_bytes());
     86             wire.extend_from_slice(seal.fields().author.as_bytes());
     87             wire.extend_from_slice(&13u32.to_be_bytes());
     88             wire.push(0);
     89             wire.push(1);
     90             wire.extend_from_slice(&seal.event_id());
     91             wire.extend_from_slice(&seal.fields().created_at.to_be_bytes());
     92             put(&mut wire, seal.fields().content.as_bytes());
     93             wire.extend_from_slice(route.source_id().as_bytes());
     94             put(&mut wire, route.raw_json().as_bytes());
     95             wire.push(route.selected_relays().len() as u8);
     96             for target in route.selected_relays() {
     97                 put(&mut wire, target.as_bytes());
     98             }
     99         }
    100         let digest = Sha256::digest(wire.as_slice()).into();
    101         Ok(Self {
    102             operation,
    103             command,
    104             seals,
    105             routes,
    106             replay,
    107             wire,
    108             digest,
    109         })
    110     }
    111     /// Reconstructs every intent against the independently supplied original
    112     /// T0 rumor. A stored ID alone cannot substitute for its exact contents.
    113     pub fn parse(
    114         operation: OperationId,
    115         command: CommandDigest,
    116         rumor: &EncodedCommerceRumor,
    117         wire: &[u8],
    118     ) -> Result<Self, WireError> {
    119         if wire.len() > SIGNING_PLAN_MAX_BYTES {
    120             return Err(WireError::LimitExceeded);
    121         }
    122         let mut input = Input(wire);
    123         if input.take(MAGIC.len())? != MAGIC
    124             || input.take(32)? != operation.as_bytes()
    125             || input.take(32)? != command.as_bytes()
    126             || input.take(32)? != rumor.record_id().as_bytes()
    127             || input.take(32)? != rumor.event_id().as_bytes()
    128             || u64::from_be_bytes(input.array()?) != rumor.created_at().get()
    129         {
    130             return Err(WireError::InvalidInput);
    131         }
    132         let replay = SigningReplay::from_code(input.byte()?)?;
    133         if input.byte()? != 2 {
    134             return Err(WireError::InvalidInput);
    135         }
    136         let mut seals = Vec::with_capacity(2);
    137         let mut routes = Vec::with_capacity(2);
    138         for recipient in rumor.recipients() {
    139             if input.take(32)? != recipient.as_bytes()
    140                 || input.take(32)? != rumor.author().as_bytes()
    141                 || u32::from_be_bytes(input.array()?) != 13
    142                 || input.byte()? != 0
    143                 || input.byte()? != 1
    144             {
    145                 return Err(WireError::InvalidInput);
    146             }
    147             let id: [u8; 32] = input.array()?;
    148             let time = UnixSeconds::new(u64::from_be_bytes(input.array()?))
    149                 .map_err(|_| WireError::InvalidInput)?;
    150             let ciphertext = input.text(SIGNED_MAX_BYTES)?;
    151             let seal = CommerceSeal::new(operation, command, rumor, *recipient, time, ciphertext)?;
    152             if seal.event_id() != id {
    153                 return Err(WireError::InvalidInput);
    154             }
    155             seals.push(seal);
    156             let source = EnvelopeEventId::from_bytes(input.array()?);
    157             let raw = input.text(SIGNED_MAX_BYTES)?;
    158             let count = usize::from(input.byte()?);
    159             if !(1..=16).contains(&count) {
    160                 return Err(WireError::InvalidInput);
    161             }
    162             let mut selected = Vec::with_capacity(count);
    163             for _ in 0..count {
    164                 selected.push(String::from(input.text(2048)?));
    165             }
    166             routes.push(CapturedDmRoute::from_observed_descriptor(
    167                 *recipient, source, raw, &selected,
    168             )?);
    169         }
    170         if !input.0.is_empty() {
    171             return Err(WireError::InvalidInput);
    172         }
    173         let plan = Self::new(
    174             operation,
    175             command,
    176             rumor,
    177             seals.try_into().map_err(|_| WireError::InvalidInput)?,
    178             routes.try_into().map_err(|_| WireError::InvalidInput)?,
    179             replay,
    180         )?;
    181         if plan.protected_wire() != wire {
    182             return Err(WireError::InvalidInput);
    183         }
    184         Ok(plan)
    185     }
    186     pub const fn operation_id(&self) -> OperationId {
    187         self.operation
    188     }
    189     pub const fn command_digest(&self) -> CommandDigest {
    190         self.command
    191     }
    192     pub const fn seals(&self) -> &[CommerceSeal; 2] {
    193         &self.seals
    194     }
    195     pub const fn routes(&self) -> &[CapturedDmRoute; 2] {
    196         &self.routes
    197     }
    198     pub const fn replay(&self) -> SigningReplay {
    199         self.replay
    200     }
    201     /// Original private data requiring protected at-rest handling.
    202     pub fn protected_wire(&self) -> &[u8] {
    203         &self.wire
    204     }
    205     /// Exact commitment of every original intent, route and replay descriptor.
    206     pub const fn digest(&self) -> &[u8; 32] {
    207         &self.digest
    208     }
    209 }
    210 impl fmt::Debug for CommerceSigningPlan {
    211     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    212         f.write_str("CommerceSigningPlan(<redacted>)")
    213     }
    214 }
    215 fn put(out: &mut Vec<u8>, value: &[u8]) {
    216     out.extend_from_slice(&(value.len() as u32).to_be_bytes());
    217     out.extend_from_slice(value);
    218 }
    219 struct Input<'a>(&'a [u8]);
    220 impl<'a> Input<'a> {
    221     fn take(&mut self, size: usize) -> Result<&'a [u8], WireError> {
    222         let (value, rest) = self
    223             .0
    224             .split_at_checked(size)
    225             .ok_or(WireError::InvalidInput)?;
    226         self.0 = rest;
    227         Ok(value)
    228     }
    229     fn array<const N: usize>(&mut self) -> Result<[u8; N], WireError> {
    230         self.take(N)?
    231             .try_into()
    232             .map_err(|_| WireError::InvalidInput)
    233     }
    234     fn byte(&mut self) -> Result<u8, WireError> {
    235         Ok(self.array::<1>()?[0])
    236     }
    237     fn text(&mut self, max: usize) -> Result<&'a str, WireError> {
    238         let size = u32::from_be_bytes(self.array()?) as usize;
    239         if size > max {
    240             return Err(WireError::LimitExceeded);
    241         }
    242         core::str::from_utf8(self.take(size)?).map_err(|_| WireError::InvalidInput)
    243     }
    244 }