1use std::time::Duration;
15
16use async_stream::stream;
17use futures::pin_mut;
18use futures::select;
19use futures::FutureExt;
20use futures::Stream;
21use rings_rpc::jsonrpc::Client as RpcClient;
22use rings_rpc::protos::rings_node::AcceptAnswerRequest;
23use rings_rpc::protos::rings_node::AnswerOfferRequest;
24use rings_rpc::protos::rings_node::ConnectPeerViaHttpRequest;
25use rings_rpc::protos::rings_node::ConnectWithDidRequest;
26use rings_rpc::protos::rings_node::CreateOfferRequest;
27use rings_rpc::protos::rings_node::DisconnectRequest;
28use rings_rpc::protos::rings_node::FetchTopicMessagesRequest;
29use rings_rpc::protos::rings_node::ListPeersRequest;
30use rings_rpc::protos::rings_node::LookupServiceRequest;
31use rings_rpc::protos::rings_node::NodeInfoRequest;
32use rings_rpc::protos::rings_node::PublishMessageToTopicRequest;
33use rings_rpc::protos::rings_node::RegisterServiceRequest;
34use rings_rpc::protos::rings_node::SendBackendMessageRequest;
35use rings_rpc::protos::rings_node::SwarmInfo;
36
37pub use crate::processor::handshake::OfferReplyKind;
38use crate::seed::Seed;
39use crate::util::loader::ResourceLoader;
40
41type Output<T> = anyhow::Result<ClientOutput<T>>;
43
44pub struct Client {
46 client: RpcClient,
47}
48
49pub struct ClientOutput<T> {
51 pub result: T,
53 display: String,
54 stderr_notice: Option<String>,
55}
56
57impl OfferReplyKind {
58 pub const fn stderr_notice(self) -> &'static str {
60 match self {
61 Self::Answer => {
62 "Answered peer's offer (answer); return this payload to the offerer for `rings connect accept`."
63 }
64 Self::CounterOffer => {
65 "Counter-offer (offer, answered: false): this node's pending offer prevailed on the DID tie-break. \
66 Pass this counter-offer to the peer for `rings connect answer`, then complete on this node with `rings connect accept`."
67 }
68 }
69 }
70}
71
72pub fn format_answer_offer_output(reply: String) -> Output<String> {
74 let notice = match OfferReplyKind::from_encoded_reply(reply.as_str()) {
75 Ok(kind) => kind.stderr_notice().to_owned(),
76 Err(_) => OfferReplyKind::Answer.stderr_notice().to_owned(),
77 };
78 ClientOutput::ok_with_stderr(reply.clone(), reply, notice)
79}
80
81pub fn ensure_accept_answer_is_not_counter_offer(answer: &str) -> anyhow::Result<()> {
84 if matches!(
85 OfferReplyKind::from_encoded_reply(answer),
86 Ok(OfferReplyKind::CounterOffer)
87 ) {
88 anyhow::bail!(
89 "payload is a counter-offer (`ConnectNodeSend`), not an answer (`ConnectNodeReport`); \
90 answer it with `rings connect answer <counter_offer>` and pass the resulting answer \
91 to the peer's `rings connect accept`"
92 );
93 }
94 Ok(())
95}
96
97impl Client {
98 pub fn new(endpoint_url: &str) -> anyhow::Result<Self> {
100 let rpc_client =
101 RpcClient::new(endpoint_url).map_err(|error| anyhow::anyhow!("{error}"))?;
102 Ok(Self { client: rpc_client })
103 }
104
105 pub fn with_api_token(endpoint_url: &str, api_token: String) -> anyhow::Result<Self> {
107 let rpc_client = RpcClient::new(endpoint_url)
108 .and_then(|client| client.with_bearer_token(api_token))
109 .map_err(|error| anyhow::anyhow!("{error}"))?;
110 Ok(Self { client: rpc_client })
111 }
112
113 pub async fn connect_peer_via_http(&mut self, url: &str) -> Output<String> {
122 self.connect_peer_via_http_with_token(url, None).await
123 }
124
125 pub async fn connect_peer_via_http_with_token(
128 &mut self,
129 url: &str,
130 remote_api_token: Option<String>,
131 ) -> Output<String> {
132 let peer_did = self
133 .client
134 .connect_peer_via_http(&ConnectPeerViaHttpRequest {
135 url: url.to_string(),
136 api_token: remote_api_token,
137 })
138 .await
139 .map_err(|e| anyhow::anyhow!("{}", e))?
140 .did;
141
142 ClientOutput::ok(format!("Remote did: {peer_did}"), peer_did)
143 }
144
145 pub async fn connect_with_seed(&mut self, source: &str) -> Output<()> {
147 let seed = Seed::load(source).await?;
148 let req = seed.into_connect_with_seed_request();
149
150 self.client
151 .connect_with_seed(&req)
152 .await
153 .map_err(|e| anyhow::anyhow!("{}", e))?;
154
155 ClientOutput::ok("Successful!".to_string(), ())
156 }
157
158 pub async fn connect_with_did(&mut self, did: &str) -> Output<()> {
160 self.client
161 .connect_with_did(&ConnectWithDidRequest {
162 did: did.to_string(),
163 })
164 .await
165 .map_err(|e| anyhow::anyhow!("{}", e))?;
166 ClientOutput::ok("Successful!".to_owned(), ())
167 }
168
169 pub async fn create_offer(&mut self, did: &str) -> Output<String> {
175 let offer = self
176 .client
177 .create_offer(&CreateOfferRequest {
178 did: did.to_string(),
179 })
180 .await
181 .map_err(|e| anyhow::anyhow!("{}", e))?
182 .offer;
183
184 ClientOutput::ok(offer.clone(), offer)
185 }
186
187 pub async fn answer_offer(&mut self, offer: &str) -> Output<String> {
196 let answer = self
197 .client
198 .answer_offer(&AnswerOfferRequest {
199 offer: offer.to_string(),
200 })
201 .await
202 .map_err(|e| anyhow::anyhow!("{}", e))?
203 .answer;
204
205 format_answer_offer_output(answer)
206 }
207
208 pub async fn accept_answer(&mut self, answer: &str) -> Output<()> {
214 ensure_accept_answer_is_not_counter_offer(answer)?;
215 self.client
216 .accept_answer(&AcceptAnswerRequest {
217 answer: answer.to_string(),
218 })
219 .await
220 .map_err(|e| anyhow::anyhow!("{}", e))?;
221
222 ClientOutput::ok("Done.".into(), ())
223 }
224
225 pub async fn list_peers(&mut self) -> Output<()> {
229 let peers = self
230 .client
231 .list_peers(&ListPeersRequest {})
232 .await
233 .map_err(|e| anyhow::anyhow!("{}", e))?
234 .peers;
235
236 let mut display = String::new();
237 display.push_str("Did, TransportId, Status\n");
238 display.push_str(
239 peers
240 .iter()
241 .map(|peer| format!("{}, {}, {}", peer.did, peer.did, peer.state))
242 .collect::<Vec<_>>()
243 .join("\n")
244 .as_str(),
245 );
246
247 ClientOutput::ok(display, ())
248 }
249
250 pub async fn disconnect(&mut self, did: &str) -> Output<()> {
252 self.client
253 .disconnect(&DisconnectRequest {
254 did: did.to_string(),
255 })
256 .await
257 .map_err(|e| anyhow::anyhow!("{}", e))?;
258
259 ClientOutput::ok("Done.".into(), ())
260 }
261
262 pub async fn send_message(&self, did: &str, namespace: &str, data: &str) -> Output<()> {
265 self.client
266 .send_backend_message(&SendBackendMessageRequest {
267 destination_did: did.to_string(),
268 namespace: namespace.to_string(),
269 data: base64::encode(data.as_bytes()),
271 })
272 .await
273 .map_err(|e| anyhow::anyhow!("{}", e))?;
274 ClientOutput::ok("Done.".into(), ())
275 }
276
277 pub async fn register_service(&self, name: &str) -> Output<()> {
279 self.client
280 .register_service(&RegisterServiceRequest {
281 name: name.to_string(),
282 })
283 .await
284 .map_err(|e| anyhow::anyhow!("{}", e))?;
285 ClientOutput::ok("Done.".into(), ())
286 }
287
288 pub async fn lookup_service(&self, name: &str) -> Output<()> {
290 let dids = self
291 .client
292 .lookup_service(&LookupServiceRequest {
293 name: name.to_string(),
294 })
295 .await
296 .map_err(|e| anyhow::anyhow!("{}", e))?
297 .dids;
298
299 ClientOutput::ok(dids.join("\n"), ())
300 }
301
302 pub async fn publish_message_to_topic(&self, topic: &str, data: &str) -> Output<()> {
304 self.client
305 .publish_message_to_topic(&PublishMessageToTopicRequest {
306 topic: topic.to_string(),
307 data: data.to_string(),
308 })
309 .await
310 .map_err(|e| anyhow::anyhow!("{}", e))?;
311 ClientOutput::ok("Done.".into(), ())
312 }
313
314 pub async fn subscribe_topic<'a, 'b>(
316 &'a self,
317 topic: String,
318 ) -> impl Stream<Item = String> + 'b
319 where
320 'a: 'b,
321 {
322 let mut skip = 0usize;
323
324 stream! {
325 loop {
326 let timeout = rings_runtime::sleep(Duration::from_secs(5)).fuse();
327 pin_mut!(timeout);
328
329 select! {
330 _ = timeout => {
331 let result = self
332 .client
333 .fetch_topic_messages(&FetchTopicMessagesRequest {
334 topic: topic.clone(),
335 skip: skip as i64,
336 })
337 .await;
338
339 let messages = match result {
340 Ok(result) => result.data,
341 Err(e) => {
342 tracing::error!("Failed to fetch messages of topic: {}, {}", topic, e);
343 continue;
344 }
345 };
346 for msg in messages.iter().cloned() {
347 yield msg
348 }
349 skip += messages.len();
350 }
351 }
352 }
353 }
354 }
355
356 pub async fn inspect(&self) -> Output<SwarmInfo> {
358 let swarm_info = self
359 .client
360 .node_info(&NodeInfoRequest {})
361 .await
362 .map_err(|e| anyhow::anyhow!("{}", e))?
363 .swarm
364 .ok_or_else(|| anyhow::anyhow!("node_info response did not include swarm info"))?;
365
366 let display =
367 serde_json::to_string_pretty(&swarm_info).map_err(|e| anyhow::anyhow!("{}", e))?;
368
369 ClientOutput::ok(display, swarm_info)
370 }
371}
372
373impl<T> ClientOutput<T> {
374 pub fn ok(display: String, result: T) -> anyhow::Result<Self> {
376 Ok(Self {
377 result,
378 display,
379 stderr_notice: None,
380 })
381 }
382
383 pub fn ok_with_stderr(
385 display: String,
386 result: T,
387 stderr_notice: String,
388 ) -> anyhow::Result<Self> {
389 Ok(Self {
390 result,
391 display,
392 stderr_notice: Some(stderr_notice),
393 })
394 }
395
396 pub fn display_text(&self) -> &str {
398 self.display.as_str()
399 }
400
401 pub fn stderr_notice(&self) -> Option<&str> {
403 self.stderr_notice.as_deref()
404 }
405
406 pub fn display(&self) {
409 if let Some(notice) = &self.stderr_notice {
410 eprintln!("{notice}");
411 }
412 println!("{}", self.display);
413 }
414}
415
416#[cfg(test)]
418mod credential_transport_tests {
419 use rings_core::delegation::DelegateeKey;
420 use rings_core::dht::delivery::NextHop;
421 use rings_core::dht::Did;
422 use rings_core::dht::RelayCustody;
423 use rings_core::ecc::SecretKey;
424 use rings_core::message::ConnectNodeReport;
425 use rings_core::message::ConnectNodeSend;
426 use rings_core::message::DhtProtocolMode;
427 use rings_core::message::Encoder;
428 use rings_core::message::Message;
429 use rings_core::message::MessagePayload;
430 use rings_core::message::MessageSigner;
431
432 use super::ensure_accept_answer_is_not_counter_offer;
433 use super::format_answer_offer_output;
434 use super::Client;
435 use super::OfferReplyKind;
436
437 fn encoded_handshake_payload(message: Message) -> String {
438 let key = SecretKey::random();
439 let delegatee_key = DelegateeKey::new_with_seckey(&key).expect("test delegatee key");
440 let signer = MessageSigner::new(&delegatee_key, 1);
441 let destination: Did = SecretKey::random().address().into();
442 let payload = MessagePayload::new_send_with_sequence(
443 message,
444 signer,
445 NextHop::toward(destination),
446 destination,
447 0,
448 None,
449 )
450 .expect("signed handshake payload");
451 payload.encode().expect("encoded payload").to_string()
452 }
453
454 fn encoded_answer_fixture() -> String {
455 encoded_handshake_payload(Message::ConnectNodeReport(ConnectNodeReport {
456 step_index: 1,
457 final_step: true,
458 session_id: None,
459 handshake: bytes::Bytes::from_static(b"{\"type\":\"answer\"}"),
460 dht_protocol_mode: DhtProtocolMode::new(1, 1, 1),
461 relay_custody: RelayCustody::Holds,
462 }))
463 }
464
465 fn encoded_counter_offer_fixture() -> String {
466 encoded_handshake_payload(Message::ConnectNodeSend(ConnectNodeSend {
467 step_index: 0,
468 final_step: false,
469 session_id: None,
470 handshake: bytes::Bytes::from_static(b"{\"type\":\"offer\"}"),
471 dht_protocol_mode: DhtProtocolMode::new(1, 1, 1),
472 relay_custody: RelayCustody::Holds,
473 }))
474 }
475
476 #[test]
478 fn authenticated_cli_rejects_remote_http() {
479 for endpoint in [
480 "http://example.com",
481 "http://localhost.example.com",
482 "http://127.0.0.1.example.com",
483 ] {
484 assert!(Client::with_api_token(endpoint, "fixture-token".to_owned()).is_err());
485 }
486 }
487
488 #[test]
490 fn authenticated_cli_accepts_https_and_literal_loopback() {
491 for endpoint in [
492 "https://example.com",
493 "http://127.0.0.1:50000",
494 "http://[::1]:50000",
495 ] {
496 assert!(Client::with_api_token(endpoint, "fixture-token".to_owned()).is_ok());
497 }
498 }
499
500 #[test]
503 fn answer_offer_formats_answer_reply() {
504 let answer = encoded_answer_fixture();
505 assert_eq!(
506 OfferReplyKind::from_encoded_reply(answer.as_str()).expect("classify answer"),
507 OfferReplyKind::Answer
508 );
509
510 let output = format_answer_offer_output(answer.clone()).expect("format answer output");
511 assert_eq!(output.result, answer);
512 assert_eq!(output.display_text(), answer);
513 let notice = output.stderr_notice().expect("stderr notice for answer");
514 assert!(notice.contains("answer"), "unexpected notice: {notice}");
515 assert!(
516 notice.contains("rings connect accept"),
517 "unexpected notice: {notice}"
518 );
519 }
520
521 #[test]
525 fn answer_offer_formats_counter_offer_reply() {
526 let counter_offer = encoded_counter_offer_fixture();
527 assert_eq!(
528 OfferReplyKind::from_encoded_reply(counter_offer.as_str())
529 .expect("classify counter-offer"),
530 OfferReplyKind::CounterOffer
531 );
532
533 let output =
534 format_answer_offer_output(counter_offer.clone()).expect("format counter-offer output");
535 assert_eq!(output.result, counter_offer);
536 assert_eq!(output.display_text(), counter_offer);
537 let notice = output
538 .stderr_notice()
539 .expect("stderr notice for counter-offer");
540 assert!(
541 notice.contains("Counter-offer"),
542 "unexpected notice: {notice}"
543 );
544 assert!(
545 notice.contains("answered: false"),
546 "unexpected notice: {notice}"
547 );
548 assert!(
549 notice.contains("rings connect answer"),
550 "unexpected notice: {notice}"
551 );
552 assert!(
553 notice.contains("rings connect accept"),
554 "unexpected notice: {notice}"
555 );
556 }
557
558 #[test]
561 fn accept_answer_refuses_counter_offer_with_clear_instruction() {
562 let answer = encoded_answer_fixture();
563 assert!(ensure_accept_answer_is_not_counter_offer(answer.as_str()).is_ok());
564
565 let counter_offer = encoded_counter_offer_fixture();
566 let err = ensure_accept_answer_is_not_counter_offer(counter_offer.as_str())
567 .expect_err("counter-offer must be refused by connect accept");
568 let msg = err.to_string();
569 assert!(msg.contains("counter-offer"), "unexpected error: {msg}");
570 assert!(
571 msg.contains("rings connect answer"),
572 "unexpected error: {msg}"
573 );
574 assert!(
575 msg.contains("rings connect accept"),
576 "unexpected error: {msg}"
577 );
578 }
579}