lib

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

plans.rs (11527B)


      1 //! Real synthetic peer/self NIP-44 and signed route inputs for T1 persistence.
      2 use super::{WorkspaceFixture, copied};
      3 use futures::FutureExt;
      4 use js_sys::Reflect;
      5 use nostr::{
      6     JsonUtil,
      7     nips::nip44,
      8     prelude::rand::{CryptoRng, Error, RngCore},
      9 };
     10 use radroots_domain::{EnvelopeEventId, UnixSeconds};
     11 use radroots_protocol::chat::{ChatRumor, ChatSeal, ChatSigningPlan};
     12 use radroots_protocol::nip59::{CapturedDmRoute};
     13 use radroots_protocol::intent::SigningReplay;
     14 use radroots_storage::command::{BoundSigningPlan, PlanBindingOutcome};
     15 use radroots_storage::workspace::WorkspaceStore;
     16 use wasm_bindgen::{JsCast, prelude::*};
     17 
     18 #[wasm_bindgen]
     19 extern "C" {
     20     #[wasm_bindgen(js_namespace = console, js_name = log)]
     21     fn fixture_panic(message: &str);
     22 }
     23 
     24 pub(super) struct BrowserRng;
     25 impl RngCore for BrowserRng {
     26     fn next_u32(&mut self) -> u32 {
     27         let mut bytes = [0; 4];
     28         self.fill_bytes(&mut bytes);
     29         u32::from_le_bytes(bytes)
     30     }
     31     fn next_u64(&mut self) -> u64 {
     32         let mut bytes = [0; 8];
     33         self.fill_bytes(&mut bytes);
     34         u64::from_le_bytes(bytes)
     35     }
     36     fn fill_bytes(&mut self, bytes: &mut [u8]) {
     37         Reflect::get(&js_sys::global(), &JsValue::from_str("crypto"))
     38             .unwrap()
     39             .dyn_into::<web_sys::Crypto>()
     40             .unwrap()
     41             .get_random_values_with_u8_array(bytes)
     42             .unwrap();
     43     }
     44     fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Error> {
     45         self.fill_bytes(bytes);
     46         Ok(())
     47     }
     48 }
     49 impl CryptoRng for BrowserRng {}
     50 pub(super) fn delivery_relays(large: bool) -> Vec<String> {
     51     if large {
     52         (0..16)
     53             .map(|index| format!("wss://plan.fixture.example/{index}/{}", "x".repeat(1900)))
     54             .collect()
     55     } else {
     56         vec![
     57             "wss://plan.fixture.example/a".into(),
     58             "wss://plan.fixture.example/b".into(),
     59         ]
     60     }
     61 }
     62 pub(super) fn summary(bound: BoundSigningPlan) -> Vec<u8> {
     63     let mut bytes = bound.transaction_id().as_bytes().to_vec();
     64     bytes.extend_from_slice(bound.plan().digest());
     65     bytes.extend_from_slice(&bound.bound_at().get().to_be_bytes());
     66     bytes.extend_from_slice(&(bound.plan().protected_wire().len() as u32).to_be_bytes());
     67     bytes.extend_from_slice(bound.prepared().transaction_id().as_bytes());
     68     bytes
     69 }
     70 impl WorkspaceFixture {
     71     async fn plan_with_relays(&self, n: u8, profile: u8) -> Result<Vec<u8>, JsValue> {
     72         std::panic::set_hook(Box::new(|info| fixture_panic(&format!("{info}"))));
     73         let request = self.request(n, false).await?;
     74         let command = request.chat_command().unwrap();
     75         let time = UnixSeconds::new(1000).unwrap();
     76         let rumor = ChatRumor::from_command(command, time).unwrap();
     77         let context = nostr::secp256k1::Secp256k1::new();
     78         let mut scalar = [0; 32];
     79         scalar[31] = 1;
     80         let sender =
     81             nostr::Keys::new_with_ctx(&context, nostr::SecretKey::from_slice(&scalar).unwrap());
     82         let mut seals = Vec::new();
     83         let mut routes = Vec::new();
     84         let mut rng = BrowserRng;
     85         for recipient in rumor.recipients() {
     86             let public = nostr::PublicKey::from_slice(recipient.as_bytes()).unwrap();
     87             let encrypted = nip44::encrypt_with_rng(
     88                 &mut rng,
     89                 sender.secret_key(),
     90                 &public,
     91                 rumor.json(),
     92                 nip44::Version::V2,
     93             )
     94             .unwrap();
     95             scalar[31] = if *recipient == super::participant() {
     96                 1
     97             } else {
     98                 2
     99             };
    100             let receiver =
    101                 nostr::Keys::new_with_ctx(&context, nostr::SecretKey::from_slice(&scalar).unwrap());
    102             assert_eq!(receiver.public_key(), public);
    103             assert_eq!(
    104                 nip44::decrypt(receiver.secret_key(), &sender.public_key(), &encrypted).unwrap(),
    105                 rumor.json()
    106             );
    107             seals.push(
    108                 ChatSeal::new(
    109                     &rumor,
    110                     *recipient,
    111                     UnixSeconds::new(999).unwrap(),
    112                     &encrypted,
    113                 )
    114                 .unwrap(),
    115             );
    116             let relays = if profile != 0 {
    117                 delivery_relays(profile == 2)
    118             } else {
    119                 vec![String::from("wss://plan.fixture.example/")]
    120             };
    121             let source = nostr::UnsignedEvent {
    122                 id: None,
    123                 pubkey: public,
    124                 created_at: nostr::Timestamp::from_secs(999),
    125                 kind: nostr::Kind::Custom(10050),
    126                 tags: nostr::Tags::from_list(
    127                     relays
    128                         .iter()
    129                         .map(|relay| nostr::Tag::parse(["relay", relay.as_str()]).unwrap())
    130                         .collect(),
    131                 ),
    132                 content: "synthetic public route metadata ".repeat(1000),
    133             }
    134             .sign_with_ctx(&context, &mut rng, &receiver)
    135             .unwrap();
    136             source.verify_with_ctx(&context).unwrap();
    137             routes.push(
    138                 CapturedDmRoute::from_observed_descriptor(
    139                     *recipient,
    140                     EnvelopeEventId::from_bytes(*source.id.as_bytes()),
    141                     &source.as_json(),
    142                     &relays,
    143                 )
    144                 .unwrap(),
    145             );
    146         }
    147         Ok(
    148             ChatSigningPlan::new(command, time, seals, routes, SigningReplay::NonReplayable)
    149                 .unwrap()
    150                 .protected_wire()
    151                 .to_vec(),
    152         )
    153     }
    154 }
    155 #[wasm_bindgen]
    156 impl WorkspaceFixture {
    157     pub async fn new_plan(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    158         self.plan_with_relays(n, 0).await
    159     }
    160     pub async fn new_delivery_plan(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    161         self.plan_with_relays(n, 1).await
    162     }
    163     pub async fn new_large_delivery_plan(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    164         self.plan_with_relays(n, 2).await
    165     }
    166     pub async fn bind_plan(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> {
    167         self.bind_plan_mode(n, wire, 0).await
    168     }
    169     pub async fn bind_plan_read_unknown(
    170         &self,
    171         n: u8,
    172         wire: Vec<u8>,
    173         hook: js_sys::Function,
    174     ) -> Result<Vec<u8>, JsValue> {
    175         let request = self.request(n, false).await?;
    176         let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire).unwrap();
    177         hook.call0(&JsValue::NULL)?;
    178         match self
    179             .journal()
    180             .bind_signing_intents(
    181                 request.binding().clone(),
    182                 (plan).into(),
    183                 copied(&self.proof),
    184             )
    185             .await
    186             .map_err(|e| JsValue::from_str(e.code()))?
    187         {
    188             PlanBindingOutcome::Committed(_) => Err(JsValue::from_str("unexpected_commit")),
    189             PlanBindingOutcome::Unknown(anchor) => {
    190                 assert_eq!(anchor.workspace_id(), self.input.workspace_id());
    191                 assert_eq!(
    192                     anchor.operation_id(),
    193                     request.command().context().operation_id()
    194                 );
    195                 assert_eq!(anchor.command_digest(), request.command().digest());
    196                 assert_eq!(anchor.transaction_id(), None);
    197                 let mut bytes = anchor.operation_id().as_bytes().to_vec();
    198                 bytes.extend_from_slice(anchor.command_digest().as_bytes());
    199                 Ok(bytes)
    200             }
    201         }
    202     }
    203     pub async fn bind_plan_foreign(&self, n: u8, wire: Vec<u8>) -> Result<(), JsValue> {
    204         let request = self.request(n, false).await?;
    205         let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire).unwrap();
    206         let sibling = self.sibling().await?;
    207         let foreign = sibling
    208             .owner
    209             .authenticate(sibling.input.clone(), copied(&sibling.proof))
    210             .await
    211             .map_err(super::fail)?;
    212         let result = self
    213             .journal()
    214             .bind_signing_intents(foreign, (plan).into(), copied(&self.proof))
    215             .await;
    216         sibling.close().await?;
    217         result.map(|_| ()).map_err(|e| JsValue::from_str(e.code()))
    218     }
    219     pub async fn bind_plan_expiring(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> {
    220         self.bind_plan_mode(n, wire, 1).await
    221     }
    222     pub async fn bind_plan_unknown(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> {
    223         self.bind_plan_mode(n, wire, 2).await
    224     }
    225     pub async fn bind_plan_bad_clock(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> {
    226         self.bind_plan_mode(n, wire, 3).await
    227     }
    228     pub async fn bind_plan_expired_grant(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> {
    229         self.bind_plan_mode(n, wire, 4).await
    230     }
    231     pub async fn abandon_plan(&self, n: u8, wire: Vec<u8>) -> Result<(), JsValue> {
    232         let request = self.request(n, false).await?;
    233         let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire).unwrap();
    234         if self
    235             .journal()
    236             .bind_signing_intents(
    237                 request.binding().clone(),
    238                 (plan).into(),
    239                 copied(&self.proof),
    240             )
    241             .now_or_never()
    242             .is_some()
    243         {
    244             return Err(JsValue::from_str("unexpected_immediate_plan"));
    245         }
    246         Ok(())
    247     }
    248     pub async fn plan_query(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    249         let request = self.request(n, false).await?;
    250         self.journal()
    251             .signing_plan(
    252                 request.binding().clone(),
    253                 request.command().context().operation_id(),
    254                 request.command().digest(),
    255                 copied(&self.proof),
    256             )
    257             .await
    258             .map(|bound| bound.map(summary).unwrap_or_default())
    259             .map_err(|e| JsValue::from_str(e.code()))
    260     }
    261 }
    262 impl WorkspaceFixture {
    263     async fn bind_plan_mode(&self, n: u8, wire: Vec<u8>, mode: u8) -> Result<Vec<u8>, JsValue> {
    264         let request = self.request(n, false).await?;
    265         let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire)
    266             .map_err(|_| JsValue::from_str("invalid_plan"))?;
    267         if mode == 1 {
    268             self.clock.after.set(Some(1500));
    269         }
    270         if mode == 3 {
    271             self.clock.after.set(Some(90));
    272         }
    273         if mode == 4 {
    274             self.clock.after.set(Some(2000));
    275         }
    276         let outcome = self
    277             .journal()
    278             .bind_signing_intents(
    279                 request.binding().clone(),
    280                 (plan).into(),
    281                 copied(&self.proof),
    282             )
    283             .await
    284             .map_err(|e| JsValue::from_str(e.code()))?;
    285         match outcome {
    286             PlanBindingOutcome::Committed(bound) => Ok(summary(bound)),
    287             PlanBindingOutcome::Unknown(anchor) => {
    288                 if mode != 2 {
    289                     return Err(JsValue::from_str("commit_unknown"));
    290                 }
    291                 assert_eq!(
    292                     anchor.operation_id(),
    293                     request.command().context().operation_id()
    294                 );
    295                 assert_eq!(anchor.command_digest(), request.command().digest());
    296                 let mut bytes = anchor.operation_id().as_bytes().to_vec();
    297                 bytes.extend_from_slice(anchor.transaction_id().unwrap().as_bytes());
    298                 Ok(bytes)
    299             }
    300         }
    301     }
    302 }