use std::time::Duration;
use async_stream::stream;
use futures::pin_mut;
use futures::select;
use futures::FutureExt;
use futures::Stream;
use rings_rpc::jsonrpc::Client as RpcClient;
use rings_rpc::protos::rings_node::AcceptAnswerRequest;
use rings_rpc::protos::rings_node::AnswerOfferRequest;
use rings_rpc::protos::rings_node::ConnectPeerViaHttpRequest;
use rings_rpc::protos::rings_node::ConnectWithDidRequest;
use rings_rpc::protos::rings_node::CreateOfferRequest;
use rings_rpc::protos::rings_node::DisconnectRequest;
use rings_rpc::protos::rings_node::FetchTopicMessagesRequest;
use rings_rpc::protos::rings_node::ListPeersRequest;
use rings_rpc::protos::rings_node::LookupServiceRequest;
use rings_rpc::protos::rings_node::NodeInfoRequest;
use rings_rpc::protos::rings_node::PublishMessageToTopicRequest;
use rings_rpc::protos::rings_node::RegisterServiceRequest;
use rings_rpc::protos::rings_node::SendBackendMessageRequest;
use rings_rpc::protos::rings_node::SwarmInfo;
pub use crate::processor::handshake::OfferReplyKind;
use crate::seed::Seed;
use crate::util::loader::ResourceLoader;
type Output<T> = anyhow::Result<ClientOutput<T>>;
pub struct Client {
client: RpcClient,
}
pub struct ClientOutput<T> {
pub result: T,
display: String,
stderr_notice: Option<String>,
}
impl OfferReplyKind {
pub const fn stderr_notice(self) -> &'static str {
match self {
Self::Answer => {
"Answered peer's offer (answer); return this payload to the offerer for `rings connect accept`."
}
Self::CounterOffer => {
"Counter-offer (offer, answered: false): this node's pending offer prevailed on the DID tie-break. \
Pass this counter-offer to the peer for `rings connect answer`, then complete on this node with `rings connect accept`."
}
}
}
}
pub fn format_answer_offer_output(reply: String) -> Output<String> {
let notice = match OfferReplyKind::from_encoded_reply(reply.as_str()) {
Ok(kind) => kind.stderr_notice().to_owned(),
Err(_) => OfferReplyKind::Answer.stderr_notice().to_owned(),
};
ClientOutput::ok_with_stderr(reply.clone(), reply, notice)
}
pub fn ensure_accept_answer_is_not_counter_offer(answer: &str) -> anyhow::Result<()> {
if matches!(
OfferReplyKind::from_encoded_reply(answer),
Ok(OfferReplyKind::CounterOffer)
) {
anyhow::bail!(
"payload is a counter-offer (`ConnectNodeSend`), not an answer (`ConnectNodeReport`); \
answer it with `rings connect answer <counter_offer>` and pass the resulting answer \
to the peer's `rings connect accept`"
);
}
Ok(())
}
impl Client {
pub fn new(endpoint_url: &str) -> anyhow::Result<Self> {
let rpc_client =
RpcClient::new(endpoint_url).map_err(|error| anyhow::anyhow!("{error}"))?;
Ok(Self { client: rpc_client })
}
pub fn with_api_token(endpoint_url: &str, api_token: String) -> anyhow::Result<Self> {
let rpc_client = RpcClient::new(endpoint_url)
.and_then(|client| client.with_bearer_token(api_token))
.map_err(|error| anyhow::anyhow!("{error}"))?;
Ok(Self { client: rpc_client })
}
pub async fn connect_peer_via_http(&mut self, url: &str) -> Output<String> {
self.connect_peer_via_http_with_token(url, None).await
}
pub async fn connect_peer_via_http_with_token(
&mut self,
url: &str,
remote_api_token: Option<String>,
) -> Output<String> {
let peer_did = self
.client
.connect_peer_via_http(&ConnectPeerViaHttpRequest {
url: url.to_string(),
api_token: remote_api_token,
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?
.did;
ClientOutput::ok(format!("Remote did: {peer_did}"), peer_did)
}
pub async fn connect_with_seed(&mut self, source: &str) -> Output<()> {
let seed = Seed::load(source).await?;
let req = seed.into_connect_with_seed_request();
self.client
.connect_with_seed(&req)
.await
.map_err(|e| anyhow::anyhow!("{}", e))?;
ClientOutput::ok("Successful!".to_string(), ())
}
pub async fn connect_with_did(&mut self, did: &str) -> Output<()> {
self.client
.connect_with_did(&ConnectWithDidRequest {
did: did.to_string(),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?;
ClientOutput::ok("Successful!".to_owned(), ())
}
pub async fn create_offer(&mut self, did: &str) -> Output<String> {
let offer = self
.client
.create_offer(&CreateOfferRequest {
did: did.to_string(),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?
.offer;
ClientOutput::ok(offer.clone(), offer)
}
pub async fn answer_offer(&mut self, offer: &str) -> Output<String> {
let answer = self
.client
.answer_offer(&AnswerOfferRequest {
offer: offer.to_string(),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?
.answer;
format_answer_offer_output(answer)
}
pub async fn accept_answer(&mut self, answer: &str) -> Output<()> {
ensure_accept_answer_is_not_counter_offer(answer)?;
self.client
.accept_answer(&AcceptAnswerRequest {
answer: answer.to_string(),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?;
ClientOutput::ok("Done.".into(), ())
}
pub async fn list_peers(&mut self) -> Output<()> {
let peers = self
.client
.list_peers(&ListPeersRequest {})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?
.peers;
let mut display = String::new();
display.push_str("Did, TransportId, Status\n");
display.push_str(
peers
.iter()
.map(|peer| format!("{}, {}, {}", peer.did, peer.did, peer.state))
.collect::<Vec<_>>()
.join("\n")
.as_str(),
);
ClientOutput::ok(display, ())
}
pub async fn disconnect(&mut self, did: &str) -> Output<()> {
self.client
.disconnect(&DisconnectRequest {
did: did.to_string(),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?;
ClientOutput::ok("Done.".into(), ())
}
pub async fn send_message(&self, did: &str, namespace: &str, data: &str) -> Output<()> {
self.client
.send_backend_message(&SendBackendMessageRequest {
destination_did: did.to_string(),
namespace: namespace.to_string(),
data: base64::encode(data.as_bytes()),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?;
ClientOutput::ok("Done.".into(), ())
}
pub async fn register_service(&self, name: &str) -> Output<()> {
self.client
.register_service(&RegisterServiceRequest {
name: name.to_string(),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?;
ClientOutput::ok("Done.".into(), ())
}
pub async fn lookup_service(&self, name: &str) -> Output<()> {
let dids = self
.client
.lookup_service(&LookupServiceRequest {
name: name.to_string(),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?
.dids;
ClientOutput::ok(dids.join("\n"), ())
}
pub async fn publish_message_to_topic(&self, topic: &str, data: &str) -> Output<()> {
self.client
.publish_message_to_topic(&PublishMessageToTopicRequest {
topic: topic.to_string(),
data: data.to_string(),
})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?;
ClientOutput::ok("Done.".into(), ())
}
pub async fn subscribe_topic<'a, 'b>(
&'a self,
topic: String,
) -> impl Stream<Item = String> + 'b
where
'a: 'b,
{
let mut skip = 0usize;
stream! {
loop {
let timeout = rings_runtime::sleep(Duration::from_secs(5)).fuse();
pin_mut!(timeout);
select! {
_ = timeout => {
let result = self
.client
.fetch_topic_messages(&FetchTopicMessagesRequest {
topic: topic.clone(),
skip: skip as i64,
})
.await;
let messages = match result {
Ok(result) => result.data,
Err(e) => {
tracing::error!("Failed to fetch messages of topic: {}, {}", topic, e);
continue;
}
};
for msg in messages.iter().cloned() {
yield msg
}
skip += messages.len();
}
}
}
}
}
pub async fn inspect(&self) -> Output<SwarmInfo> {
let swarm_info = self
.client
.node_info(&NodeInfoRequest {})
.await
.map_err(|e| anyhow::anyhow!("{}", e))?
.swarm
.ok_or_else(|| anyhow::anyhow!("node_info response did not include swarm info"))?;
let display =
serde_json::to_string_pretty(&swarm_info).map_err(|e| anyhow::anyhow!("{}", e))?;
ClientOutput::ok(display, swarm_info)
}
}
impl<T> ClientOutput<T> {
pub fn ok(display: String, result: T) -> anyhow::Result<Self> {
Ok(Self {
result,
display,
stderr_notice: None,
})
}
pub fn ok_with_stderr(
display: String,
result: T,
stderr_notice: String,
) -> anyhow::Result<Self> {
Ok(Self {
result,
display,
stderr_notice: Some(stderr_notice),
})
}
pub fn display_text(&self) -> &str {
self.display.as_str()
}
pub fn stderr_notice(&self) -> Option<&str> {
self.stderr_notice.as_deref()
}
pub fn display(&self) {
if let Some(notice) = &self.stderr_notice {
eprintln!("{notice}");
}
println!("{}", self.display);
}
}
#[cfg(test)]
mod credential_transport_tests {
use rings_core::delegation::DelegateeKey;
use rings_core::dht::delivery::NextHop;
use rings_core::dht::Did;
use rings_core::dht::RelayCustody;
use rings_core::ecc::SecretKey;
use rings_core::message::ConnectNodeReport;
use rings_core::message::ConnectNodeSend;
use rings_core::message::DhtProtocolMode;
use rings_core::message::Encoder;
use rings_core::message::Message;
use rings_core::message::MessagePayload;
use rings_core::message::MessageSigner;
use super::ensure_accept_answer_is_not_counter_offer;
use super::format_answer_offer_output;
use super::Client;
use super::OfferReplyKind;
fn encoded_handshake_payload(message: Message) -> String {
let key = SecretKey::random();
let delegatee_key = DelegateeKey::new_with_seckey(&key).expect("test delegatee key");
let signer = MessageSigner::new(&delegatee_key, 1);
let destination: Did = SecretKey::random().address().into();
let payload = MessagePayload::new_send_with_sequence(
message,
signer,
NextHop::toward(destination),
destination,
0,
None,
)
.expect("signed handshake payload");
payload.encode().expect("encoded payload").to_string()
}
fn encoded_answer_fixture() -> String {
encoded_handshake_payload(Message::ConnectNodeReport(ConnectNodeReport {
sdp: "{\"type\":\"answer\"}".to_owned(),
dht_protocol_mode: DhtProtocolMode::new(1, 1, 1),
relay_custody: RelayCustody::Holds,
}))
}
fn encoded_counter_offer_fixture() -> String {
encoded_handshake_payload(Message::ConnectNodeSend(ConnectNodeSend {
sdp: "{\"type\":\"offer\"}".to_owned(),
dht_protocol_mode: DhtProtocolMode::new(1, 1, 1),
relay_custody: RelayCustody::Holds,
}))
}
#[test]
fn authenticated_cli_rejects_remote_http() {
for endpoint in [
"http://example.com",
"http://localhost.example.com",
"http://127.0.0.1.example.com",
] {
assert!(Client::with_api_token(endpoint, "fixture-token".to_owned()).is_err());
}
}
#[test]
fn authenticated_cli_accepts_https_and_literal_loopback() {
for endpoint in [
"https://example.com",
"http://127.0.0.1:50000",
"http://[::1]:50000",
] {
assert!(Client::with_api_token(endpoint, "fixture-token".to_owned()).is_ok());
}
}
#[test]
fn answer_offer_formats_answer_reply() {
let answer = encoded_answer_fixture();
assert_eq!(
OfferReplyKind::from_encoded_reply(answer.as_str()).expect("classify answer"),
OfferReplyKind::Answer
);
let output = format_answer_offer_output(answer.clone()).expect("format answer output");
assert_eq!(output.result, answer);
assert_eq!(output.display_text(), answer);
let notice = output.stderr_notice().expect("stderr notice for answer");
assert!(notice.contains("answer"), "unexpected notice: {notice}");
assert!(
notice.contains("rings connect accept"),
"unexpected notice: {notice}"
);
}
#[test]
fn answer_offer_formats_counter_offer_reply() {
let counter_offer = encoded_counter_offer_fixture();
assert_eq!(
OfferReplyKind::from_encoded_reply(counter_offer.as_str())
.expect("classify counter-offer"),
OfferReplyKind::CounterOffer
);
let output =
format_answer_offer_output(counter_offer.clone()).expect("format counter-offer output");
assert_eq!(output.result, counter_offer);
assert_eq!(output.display_text(), counter_offer);
let notice = output
.stderr_notice()
.expect("stderr notice for counter-offer");
assert!(
notice.contains("Counter-offer"),
"unexpected notice: {notice}"
);
assert!(
notice.contains("answered: false"),
"unexpected notice: {notice}"
);
assert!(
notice.contains("rings connect answer"),
"unexpected notice: {notice}"
);
assert!(
notice.contains("rings connect accept"),
"unexpected notice: {notice}"
);
}
#[test]
fn accept_answer_refuses_counter_offer_with_clear_instruction() {
let answer = encoded_answer_fixture();
assert!(ensure_accept_answer_is_not_counter_offer(answer.as_str()).is_ok());
let counter_offer = encoded_counter_offer_fixture();
let err = ensure_accept_answer_is_not_counter_offer(counter_offer.as_str())
.expect_err("counter-offer must be refused by connect accept");
let msg = err.to_string();
assert!(msg.contains("counter-offer"), "unexpected error: {msg}");
assert!(
msg.contains("rings connect answer"),
"unexpected error: {msg}"
);
assert!(
msg.contains("rings connect accept"),
"unexpected error: {msg}"
);
}
}