lib

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

native_commands.rs (12923B)


      1 use core::num::NonZeroU64;
      2 use radroots_domain::{PublicKey, UnixSeconds};
      3 use radroots_execution::session::{
      4     HostFuture,
      5     command::{CommandIo, capture_dm_route, selected_dm_targets},
      6 };
      7 use radroots_nostr::signing::{
      8     OsNonceSource,
      9     gift_wrap::{randomized_past_time, wrap_retained_seal},
     10 };
     11 use radroots_protocol::nip59::CapturedDmRoute;
     12 use radroots_signing::provider::NonceSource;
     13 use radroots_storage::command::{OperationError, PrivateEnvelopeCandidate};
     14 use radroots_transport::{
     15     EventSink, EventSource, TargetSet,
     16     policy::{SatisfactionClass, SatisfactionPolicy},
     17     source::{FetchBounds, FetchRequest, FetchSelector},
     18 };
     19 use radroots_transport_nostr::{Config, NostrTransport};
     20 use std::{
     21     sync::atomic::{AtomicU8, Ordering},
     22     time::{SystemTime, UNIX_EPOCH},
     23 };
     24 
     25 pub(crate) struct NativeCommands {
     26     transport: NostrTransport,
     27     read: TargetSet,
     28     write: TargetSet,
     29     policy: SatisfactionPolicy,
     30     mode: AtomicU8,
     31 }
     32 impl NativeCommands {
     33     pub(crate) fn new(config: Config, policy: SatisfactionPolicy) -> Result<Self, OperationError> {
     34         let read = TargetSet::new(
     35             config
     36                 .read_relays()
     37                 .map(|relay| relay.to_target())
     38                 .collect::<Result<_, _>>()
     39                 .map_err(|_| OperationError::InvalidCommand)?,
     40         )
     41         .map_err(|_| OperationError::InvalidCommand)?;
     42         let write = TargetSet::new(
     43             config
     44                 .write_relays()
     45                 .map(|relay| relay.to_target())
     46                 .collect::<Result<_, _>>()
     47                 .map_err(|_| OperationError::InvalidCommand)?,
     48         )
     49         .map_err(|_| OperationError::InvalidCommand)?;
     50         if policy.class() != SatisfactionClass::Accepted {
     51             return Err(OperationError::InvalidCommand);
     52         }
     53         policy
     54             .validate_for(&write)
     55             .map_err(|_| OperationError::InvalidCommand)?;
     56         Ok(Self {
     57             transport: radroots_transport_nostr_native::create_transport(config),
     58             read,
     59             write,
     60             policy,
     61             mode: AtomicU8::new(0),
     62         })
     63     }
     64     pub(crate) fn select(&self, online: bool) -> Result<(), OperationError> {
     65         let mode = if online { 2 } else { 1 };
     66         match self
     67             .mode
     68             .compare_exchange(0, mode, Ordering::AcqRel, Ordering::Acquire)
     69         {
     70             Ok(_) => Ok(()),
     71             Err(current) if current == mode => Ok(()),
     72             Err(_) => Err(OperationError::Unauthorized),
     73         }
     74     }
     75     pub(crate) async fn disconnect(&self) {
     76         self.transport.shutdown().await;
     77     }
     78     fn capture_route<'a>(
     79         &self,
     80         recipient: PublicKey,
     81         raw_sources: impl IntoIterator<Item = &'a str>,
     82     ) -> Result<CapturedDmRoute, OperationError> {
     83         capture_dm_route(recipient, raw_sources, &self.write)
     84     }
     85 }
     86 impl CommandIo for NativeCommands {
     87     fn enabled(&self) -> bool {
     88         self.mode.load(Ordering::Acquire) == 2
     89     }
     90     fn now(&self) -> Result<UnixSeconds, OperationError> {
     91         let now = SystemTime::now()
     92             .duration_since(UNIX_EPOCH)
     93             .map_err(|_| OperationError::RecoveryRequired)?
     94             .as_secs();
     95         UnixSeconds::new(now).map_err(|_| OperationError::RecoveryRequired)
     96     }
     97     fn public_targets(&self) -> Result<TargetSet, OperationError> {
     98         if !self.enabled() {
     99             return Err(OperationError::Unauthorized);
    100         }
    101         Ok(self.write.clone())
    102     }
    103     fn seal_time(&self, now: UnixSeconds) -> Result<UnixSeconds, OperationError> {
    104         let time = randomized_past_time(
    105             NonZeroU64::new(now.get()).ok_or(OperationError::RecoveryRequired)?,
    106             &OsNonceSource,
    107         )
    108         .map_err(|_| OperationError::RecoveryRequired)?;
    109         UnixSeconds::new(time.get()).map_err(|_| OperationError::RecoveryRequired)
    110     }
    111     fn route(
    112         &self,
    113         recipient: PublicKey,
    114         deadline: NonZeroU64,
    115     ) -> HostFuture<'_, Result<CapturedDmRoute, OperationError>> {
    116         Box::pin(async move {
    117             if !self.enabled() {
    118                 return Err(OperationError::Unauthorized);
    119             }
    120             let selector = FetchSelector::all()
    121                 .with_kinds(vec![10050])
    122                 .and_then(|selector| selector.with_authors(vec![recipient]))
    123                 .map_err(|_| OperationError::InvalidCommand)?;
    124             let bounds =
    125                 FetchBounds::new(2, deadline.get()).map_err(|_| OperationError::InvalidCommand)?;
    126             let request = FetchRequest::new(self.delivery_id()?, self.read.clone(), bounds)
    127                 .map_err(|_| OperationError::InvalidCommand)?
    128                 .with_selector(selector);
    129             let page = self
    130                 .transport
    131                 .fetch(request)
    132                 .await
    133                 .map_err(|_| OperationError::MissingHistory)?;
    134             self.capture_route(
    135                 recipient,
    136                 page.events()
    137                     .iter()
    138                     .map(|observed| observed.event().raw_json()),
    139             )
    140         })
    141     }
    142     fn targets(&self, route: &CapturedDmRoute) -> Result<TargetSet, OperationError> {
    143         selected_dm_targets(route, &self.write)
    144     }
    145     fn publication_policy(&self) -> SatisfactionPolicy {
    146         self.policy.clone()
    147     }
    148     fn private_envelope(
    149         &self,
    150         recipient: PublicKey,
    151         raw_seal: &str,
    152     ) -> Result<PrivateEnvelopeCandidate, OperationError> {
    153         let now = NonZeroU64::new(self.now()?.get()).ok_or(OperationError::RecoveryRequired)?;
    154         let wrapped = wrap_retained_seal(raw_seal, recipient, now, &OsNonceSource)
    155             .map_err(|_| OperationError::InvalidEvidence)?;
    156         wrapped.with_wrapping_key(|key| {
    157             PrivateEnvelopeCandidate::from_obtained(recipient, wrapped.signed_json(), key)
    158         })
    159     }
    160     fn delivery_id(&self) -> Result<String, OperationError> {
    161         let bytes = OsNonceSource
    162             .next_nonce()
    163             .map_err(|_| OperationError::RecoveryRequired)?;
    164         let mut output = String::with_capacity(64);
    165         const HEX: &[u8; 16] = b"0123456789abcdef";
    166         for byte in bytes {
    167             output.push(HEX[usize::from(byte >> 4)] as char);
    168             output.push(HEX[usize::from(byte & 15)] as char);
    169         }
    170         Ok(output)
    171     }
    172     fn publish(
    173         &self,
    174         request: radroots_transport::sink::DeliveryRequest,
    175         selected: TargetSet,
    176     ) -> HostFuture<'_, Result<radroots_transport::DeliveryReceipt, radroots_transport::SinkFailure>>
    177     {
    178         self.transport.deliver_selected(request, selected)
    179     }
    180 }
    181 
    182 #[cfg(test)]
    183 mod tests {
    184     use super::NativeCommands;
    185     use futures::executor::block_on;
    186     use nostr::JsonUtil;
    187     use radroots_domain::PublicKey;
    188     use radroots_execution::session::command::CommandIo;
    189     use radroots_storage::command::{OperationError, SignedDmRelaySource};
    190     use radroots_transport::policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy};
    191     use radroots_transport_nostr::{
    192         Config, RelayAccess, RelayEndpoint, RelayProfile, RelayProfileKind, RelayUrlPolicy,
    193     };
    194     use std::num::NonZeroU64;
    195 
    196     const URI: &str = "ws://127.0.0.1:1";
    197     fn config(access: RelayAccess) -> Config {
    198         Config::from_profile(
    199             RelayProfile::explicit(
    200                 RelayProfileKind::Simulator,
    201                 [RelayEndpoint::new(URI, RelayUrlPolicy::Local, access).unwrap()],
    202             )
    203             .unwrap(),
    204         )
    205     }
    206     fn io() -> NativeCommands {
    207         NativeCommands::new(
    208             config(RelayAccess::ReadWrite),
    209             SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()),
    210         )
    211         .unwrap()
    212     }
    213     fn source(author: u8, time: u64, content: &str, relays: &[&str]) -> String {
    214         let mut key = [0; 32];
    215         key[31] = author;
    216         let keys = nostr::Keys::new(nostr::SecretKey::from_slice(&key).unwrap());
    217         nostr::EventBuilder::new(nostr::Kind::Custom(10050), content)
    218             .tags(
    219                 relays
    220                     .iter()
    221                     .map(|uri| nostr::Tag::parse(["relay", *uri]).unwrap()),
    222             )
    223             .custom_created_at(nostr::Timestamp::from_secs(time))
    224             .sign_with_keys(&keys)
    225             .unwrap()
    226             .as_json()
    227     }
    228     fn key() -> PublicKey {
    229         PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")
    230             .unwrap()
    231     }
    232 
    233     #[tokio::test]
    234     async fn explicit_io_configuration_and_repeated_start_modes_never_imply_network_admission() {
    235         assert!(
    236             NativeCommands::new(
    237                 config(RelayAccess::ReadOnly),
    238                 SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all())
    239             )
    240             .is_err()
    241         );
    242         assert!(
    243             NativeCommands::new(
    244                 config(RelayAccess::ReadWrite),
    245                 SatisfactionPolicy::new(SatisfactionClass::Delivered, TargetPolicy::all())
    246             )
    247             .is_err()
    248         );
    249         let local = io();
    250         assert!(matches!(
    251             local.route(key(), NonZeroU64::new(1000).unwrap()).await,
    252             Err(OperationError::Unauthorized)
    253         ));
    254         local.select(false).unwrap();
    255         local.select(false).unwrap();
    256         assert!(local.select(true).is_err());
    257         let online = io();
    258         online.select(true).unwrap();
    259         online.select(true).unwrap();
    260         assert!(online.select(false).is_err());
    261         local.disconnect().await;
    262         online.disconnect().await;
    263         let preview = crate::Client::preview();
    264         assert!(preview.start(crate::StartMode::Online).await.is_err());
    265         preview.close().await.unwrap();
    266     }
    267 
    268     #[test]
    269     fn exact_signed_route_heads_are_order_independent_and_ties_use_the_original_event_id() {
    270         let io = io();
    271         let older = source(1, 100, "old", &[URI]);
    272         let newer = source(1, 101, "new", &[URI]);
    273         let expected = SignedDmRelaySource::verify(&newer).unwrap().event_id();
    274         for values in [
    275             [older.as_str(), newer.as_str()],
    276             [newer.as_str(), older.as_str()],
    277         ] {
    278             let route = io.capture_route(key(), values).unwrap();
    279             assert_eq!(route.source_id(), expected);
    280             assert_eq!(route.raw_json(), newer);
    281         }
    282         let a = source(1, 101, "a", &[URI]);
    283         let b = source(1, 101, "b", &[URI]);
    284         let a_id = SignedDmRelaySource::verify(&a).unwrap().event_id();
    285         let b_id = SignedDmRelaySource::verify(&b).unwrap().event_id();
    286         for values in [[a.as_str(), b.as_str()], [b.as_str(), a.as_str()]] {
    287             assert_eq!(
    288                 io.capture_route(key(), values).unwrap().source_id(),
    289                 a_id.min(b_id)
    290             );
    291         }
    292         assert!(matches!(
    293             io.capture_route(key(), []),
    294             Err(OperationError::MissingHistory)
    295         ));
    296         assert!(matches!(
    297             io.capture_route(key(), [older.as_str(), newer.as_str(), newer.as_str()]),
    298             Err(OperationError::InvalidEvidence)
    299         ));
    300         assert!(matches!(
    301             io.capture_route(key(), [source(2, 100, "foreign", &[URI]).as_str()]),
    302             Err(OperationError::InvalidEvidence)
    303         ));
    304     }
    305 
    306     #[test]
    307     fn signed_route_selection_keeps_exact_sources_and_deduplicates_only_approved_targets() {
    308         let io = io();
    309         let raw = format!(
    310             " \n{}\t",
    311             source(
    312                 1,
    313                 100,
    314                 "original",
    315                 &[URI, URI, "ws://127.0.0.1:1/", "wss://other.example"]
    316             )
    317         );
    318         let route = io.capture_route(key(), [raw.as_str()]).unwrap();
    319         assert_eq!(route.raw_json(), raw);
    320         assert_eq!(route.selected_relays().len(), 2);
    321         assert_eq!(io.targets(&route).unwrap().len(), 1);
    322         let changed = radroots_transport::TargetSet::new(vec![
    323             radroots_transport::Target::nostr_relay("wss://changed.example").unwrap(),
    324         ])
    325         .unwrap();
    326         assert!(matches!(
    327             radroots_execution::session::command::selected_dm_targets(&route, &changed),
    328             Err(OperationError::UnverifiedApproval)
    329         ));
    330         let refused = source(1, 100, "no approved target", &["wss://other.example"]);
    331         assert!(matches!(
    332             io.capture_route(key(), [refused.as_str()]),
    333             Err(OperationError::UnverifiedApproval)
    334         ));
    335         let no_targets = source(1, 100, "no advertised fallback", &[]);
    336         assert!(matches!(
    337             io.capture_route(key(), [no_targets.as_str()]),
    338             Err(OperationError::UnverifiedApproval)
    339         ));
    340         // The actual IO gate refuses before opening the configured local port.
    341         assert!(block_on(io.route(key(), NonZeroU64::new(1000).unwrap())).is_err());
    342     }
    343 }