receipt_workflow.rs (11393B)
1 use super::*; 2 use futures::{SinkExt, StreamExt}; 3 use nostr::JsonUtil; 4 use radroots::{Client, NativeConfig, StartMode, inbox::InquireInput}; 5 use radroots_domain::ThreadId; 6 use radroots_nostr::{ 7 key::parse_secret_key, 8 signing::{LocalSigner, OsNonceSource}, 9 }; 10 use radroots_signing::{ 11 Signer, 12 provider::{ParticipantProvider, ProviderError, SignerCallbacks, SignerHandle}, 13 signer::BoxFuture, 14 }; 15 use radroots_storage::event::SourceGeneration; 16 use radroots_storage::workspace::WorkspaceStore; 17 use radroots_storage_sqlite::{OpenMode, OpenOptions, Paths}; 18 use radroots_transport::policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}; 19 use radroots_transport_nostr::{ 20 Config, RelayAccess, RelayEndpoint, RelayProfile, RelayProfileKind, RelayUrlPolicy, 21 }; 22 use tokio::{ 23 net::TcpListener, 24 sync::{mpsc as channel, oneshot}, 25 task::JoinSet, 26 }; 27 use tokio_tungstenite::{accept_async, tungstenite::Message}; 28 29 #[path = "receipt_workflow_faults.rs"] 30 mod faults; 31 #[path = "receipt_workflow_listing.rs"] 32 mod listing; 33 34 struct Callbacks; 35 impl SignerCallbacks for Callbacks { 36 fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>> { 37 Box::pin(async { Ok(()) }) 38 } 39 fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>> { 40 Box::pin(async { Ok(()) }) 41 } 42 } 43 fn now() -> u64 { 44 std::time::SystemTime::now() 45 .duration_since(std::time::UNIX_EPOCH) 46 .unwrap() 47 .as_secs() 48 } 49 fn route_key(last: u8) -> nostr::Keys { 50 let mut bytes = [0; 32]; 51 bytes[31] = last; 52 nostr::Keys::new(nostr::SecretKey::from_slice(&bytes).unwrap()) 53 } 54 fn advertisement(last: u8, url: &str) -> String { 55 let keys = route_key(last); 56 nostr::UnsignedEvent { 57 id: None, 58 pubkey: keys.public_key(), 59 created_at: nostr::Timestamp::from_secs(now() - 1), 60 kind: nostr::Kind::Custom(10050), 61 tags: nostr::Tags::from_list(vec![ 62 nostr::Tag::parse(["relay", url]).unwrap(), 63 nostr::Tag::parse(["client", "ordinary-test"]).unwrap(), 64 ]), 65 content: String::new(), 66 } 67 .sign_with_keys(&keys) 68 .unwrap() 69 .as_json() 70 } 71 struct Relay { 72 url: String, 73 events: channel::UnboundedReceiver<String>, 74 count: Arc<AtomicU64>, 75 requests: Arc<AtomicU64>, 76 accepting: Arc<AtomicBool>, 77 stop: oneshot::Sender<()>, 78 task: tokio::task::JoinHandle<()>, 79 } 80 impl Relay { 81 async fn new() -> Self { 82 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); 83 let url = format!("ws://{}", listener.local_addr().unwrap()); 84 let sources = Arc::new([advertisement(1, &url), advertisement(2, &url)]); 85 let count = Arc::new(AtomicU64::new(0)); 86 let counter = count.clone(); 87 let requests = Arc::new(AtomicU64::new(0)); 88 let read_counter = requests.clone(); 89 let accepting = Arc::new(AtomicBool::new(true)); 90 let acceptance = accepting.clone(); 91 let (send, events) = channel::unbounded_channel(); 92 let (stop, mut stopping) = oneshot::channel(); 93 let task = tokio::spawn(async move { 94 let mut clients = JoinSet::new(); 95 loop { 96 tokio::select! { 97 _ = &mut stopping => break, 98 accepted = listener.accept() => { 99 let (tcp, _) = accepted.unwrap(); 100 let sources = sources.clone(); let send = send.clone(); let count = counter.clone(); let acceptance = acceptance.clone();let requests=read_counter.clone(); 101 clients.spawn(async move { 102 let mut socket = accept_async(tcp).await.unwrap(); 103 while let Some(Ok(message)) = socket.next().await { 104 let Message::Text(raw) = message else {continue}; 105 let value: serde_json::Value = serde_json::from_str(&raw).unwrap(); 106 match value[0].as_str().unwrap() { 107 "REQ" => { 108 requests.fetch_add(1,Ordering::SeqCst); 109 let author = value[2]["authors"][0].as_str().unwrap(); 110 for source in sources.iter() { 111 let event: serde_json::Value = serde_json::from_str(source).unwrap(); 112 if event["pubkey"].as_str() == Some(author) { 113 socket.send(Message::Text(format!("[\"EVENT\",{}, {} ]", value[1], source).into())).await.unwrap(); 114 } 115 } 116 socket.send(Message::Text(json!(["EOSE", value[1]]).to_string().into())).await.unwrap(); 117 } 118 "EVENT" => { 119 let event = raw.strip_prefix("[\"EVENT\",").and_then(|raw| raw.strip_suffix(']')).unwrap().to_owned(); 120 nostr::Event::from_json(&event).unwrap().verify().unwrap(); 121 count.fetch_add(1, Ordering::SeqCst); 122 send.send(event).unwrap(); 123 socket.send(Message::Text(json!(["OK", value[1]["id"], acceptance.load(Ordering::SeqCst), ""]).to_string().into())).await.unwrap(); 124 } 125 "CLOSE" => {}, 126 other => panic!("unexpected relay command {other}"), 127 } 128 } 129 }); 130 } 131 } 132 } 133 clients.shutdown().await; 134 }); 135 Self { 136 url, 137 events, 138 count, 139 requests, 140 accepting, 141 stop, 142 task, 143 } 144 } 145 fn config(&self) -> Config { 146 Config::from_profile( 147 RelayProfile::explicit( 148 RelayProfileKind::Simulator, 149 [ 150 RelayEndpoint::new(&self.url, RelayUrlPolicy::Local, RelayAccess::ReadWrite) 151 .unwrap(), 152 ], 153 ) 154 .unwrap(), 155 ) 156 .with_timeouts(2_000, 2_000, 2_000) 157 .unwrap() 158 } 159 } 160 161 #[tokio::test] 162 async fn ordinary_online_inquiry_runs_t0_t1_sign_install_and_exact_peer_self_delivery_then_reopens() 163 { 164 let mut relay = Relay::new().await; 165 let fixture = Fixture::new(); 166 fixture.clock.live.store(true, Ordering::SeqCst); 167 let (store, input, proof, _) = fixture.create_with_expiry(now() + 600).await; 168 let cache = fixture.path.parent().unwrap().join("ordinary-cache"); 169 std::fs::create_dir(&cache).unwrap(); 170 let options = OpenOptions::new(Paths::from_directory(cache).unwrap(), OpenMode::Create) 171 .with_source_generation(SourceGeneration::new([18; 32]).unwrap(), 1) 172 .unwrap(); 173 let policy = SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()); 174 let client = Client::open( 175 NativeConfig::public_read(options) 176 .with_workspace(store.as_ref().clone()) 177 .with_nostr(relay.config(), policy) 178 .unwrap(), 179 ) 180 .await 181 .unwrap(); 182 let scope = client.attach(input.clone(), copy(&proof)).await.unwrap(); 183 let signer = LocalSigner::new( 184 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") 185 .unwrap(), 186 ) 187 .unwrap() 188 .with_nonce_source(Arc::new(OsNonceSource)); 189 client 190 .attach_signer(SignerHandle::new(Arc::new(signer), Arc::new(Callbacks))) 191 .await 192 .unwrap(); 193 client.start(StartMode::Online).await.unwrap(); 194 assert_eq!(relay.count.load(Ordering::SeqCst), 0); 195 let operation = OperationId::from_bytes([201; 32]); 196 let not_after = now() + 120; 197 let context = || { 198 scope 199 .command_context_with_correlation( 200 operation, 201 None, 202 None, 203 UnixSeconds::new(not_after).unwrap(), 204 Some(CorrelationId::new("ordinary-online").unwrap()), 205 ) 206 .unwrap() 207 }; 208 let inquire = || { 209 InquireInput::new( 210 ThreadId::from_bytes([33; 32]), 211 PublicKey::from_bytes(route_key(2).public_key().to_bytes()).unwrap(), 212 None, 213 "ordinary complete inquiry", 214 ) 215 .unwrap() 216 }; 217 let receipt = client.inbox().inquire(context(), inquire()).await.unwrap(); 218 assert!(receipt.durable()); 219 assert!(receipt.business_result().is_some(), "{receipt:?}"); 220 assert_eq!(relay.count.load(Ordering::SeqCst), 2); 221 let mut recipients = Vec::new(); 222 for _ in 0..2 { 223 let raw = tokio::time::timeout(Duration::from_secs(5), relay.events.recv()) 224 .await 225 .unwrap() 226 .unwrap(); 227 let outer = nostr::Event::from_json(raw).unwrap(); 228 let target = outer 229 .tags 230 .iter() 231 .find(|tag| tag.as_slice()[0] == "p") 232 .unwrap() 233 .as_slice()[1] 234 .clone(); 235 let key = if target == route_key(1).public_key().to_hex() { 236 1 237 } else { 238 2 239 }; 240 let message = nostr::nips::nip59::extract_rumor(&route_key(key), &outer) 241 .await 242 .unwrap(); 243 assert_eq!(message.sender, route_key(1).public_key()); 244 assert_eq!(message.rumor.content, "ordinary complete inquiry"); 245 assert_eq!( 246 message.rumor.id.unwrap().as_bytes(), 247 receipt.business_result().unwrap().id().as_bytes() 248 ); 249 recipients.push(key); 250 } 251 recipients.sort_unstable(); 252 assert_eq!(recipients, [1, 2]); 253 let snapshot = store 254 .operation_snapshot(scope.binding().clone(), operation, None, copy(&proof)) 255 .await 256 .unwrap() 257 .unwrap(); 258 assert!( 259 snapshot 260 .artifacts() 261 .iter() 262 .all(|recipient| recipient.obtained().is_some()) 263 ); 264 assert_eq!(snapshot.publications().len(), 2); 265 assert_eq!(snapshot.delivery_attempts().len(), 2); 266 assert!( 267 snapshot 268 .publications() 269 .iter() 270 .all(|work| snapshot.publication_accepted(*work).unwrap()) 271 ); 272 assert!(relay.requests.load(Ordering::SeqCst) > 0); 273 let original = receipt.operation_checkpoint(); 274 let replay = client.inbox().inquire(context(), inquire()).await.unwrap(); 275 assert_eq!(replay.operation_checkpoint(), original); 276 assert_eq!(relay.count.load(Ordering::SeqCst), 2); 277 client.close().await.unwrap(); 278 let reopened = fixture.reopen(input).await; 279 let snapshot = reopened 280 .operation_snapshot(scope.binding().clone(), operation, None, copy(&proof)) 281 .await 282 .unwrap() 283 .unwrap(); 284 assert_eq!( 285 radroots_execution::OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot( 286 &snapshot 287 ) 288 .unwrap() 289 .operation_checkpoint(), 290 original 291 ); 292 reopened.close_workspace().await.unwrap(); 293 relay.stop.send(()).unwrap(); 294 relay.task.await.unwrap(); 295 }