use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use weirdnet_keys::Key32;
use weirdnet_net::node::{Handler, Message, Node, NodeConfig};
use weirdnet_net::{Keypair, PeerId, now_ms};
use crate::offer::has_circuit;
use crate::reach::{self, LinkNode};
use crate::session::{Host, HostStatus, Sender};
use crate::wire::{LinkReply, LinkRequest, Received, Transfer};
use crate::{Error, LINK_PROFILE, Result, decode_link, offer_addrs};
const LISTEN_WAIT: Duration = Duration::from_secs(5);
const RELAY_WAIT: Duration = Duration::from_secs(5);
pub(crate) fn listen_addrs<Q: Message, R: Message>(node: &Node<Q, R>, want_relay: bool) -> Option<Vec<String>> {
let start = Instant::now();
let mut direct_at: Option<Instant> = None;
loop {
let addrs = offer_addrs(&node.reachable_addrs());
if !addrs.is_empty() {
let since = *direct_at.get_or_insert_with(Instant::now);
if !want_relay || has_circuit(&addrs) || since.elapsed() > RELAY_WAIT {
return Some(addrs);
}
} else if start.elapsed() > LISTEN_WAIT {
node.halt();
return None;
}
std::thread::sleep(Duration::from_millis(20));
}
}
struct HostHandler(Arc<OnceLock<Arc<Host>>>);
impl Handler<LinkRequest, LinkReply> for HostHandler {
fn request(&self, from: &PeerId, req: LinkRequest) -> LinkReply {
match self.0.get() {
Some(host) => host.handle(from, req, now_ms()),
None => LinkReply::refused("not ready"),
}
}
}
pub struct HostNode {
node: LinkNode<LinkRequest, LinkReply>,
host: Arc<Host>,
}
impl HostNode {
pub fn start(scheme: &str, node_key: Keypair, cfg: NodeConfig, hint: &str) -> Result<Self> {
let slot = Arc::new(OnceLock::new());
let node = reach::start(&LINK_PROFILE, node_key.clone(), cfg, Arc::new(HostHandler(slot.clone())))?;
let addrs =
listen_addrs(&node.node, !node.relays.is_empty()).ok_or_else(|| Error::Net("network: could not listen for the other device".into()))?;
let host = Arc::new(Host::new(scheme, &node_key, addrs, hint, now_ms())?);
let _ = slot.set(host.clone());
Ok(HostNode { node, host })
}
pub fn link(&self) -> &str {
self.host.link()
}
pub fn expires_ms(&self) -> i64 {
self.host.expires_ms()
}
pub fn status(&self) -> HostStatus {
self.host.status(now_ms())
}
pub fn confirm(&self) {
self.host.confirm();
}
pub fn take(&self) -> Result<Transfer> {
self.host.take()
}
pub fn take_any(&self) -> Result<Received> {
self.host.take_any()
}
pub fn cancel(&self) {
self.host.cancel();
}
pub fn peer_id(&self) -> PeerId {
self.node.node.peer_id()
}
pub fn net_status(&self) -> weirdnet_net::node::Status {
self.node.node.status()
}
}
impl Drop for HostNode {
fn drop(&mut self) {
self.host.cancel();
self.node.node.halt();
}
}
pub struct Pairing {
node: LinkNode<LinkRequest, LinkReply>,
sender: Sender,
sent: bool,
}
struct NoRequests;
impl Handler<LinkRequest, LinkReply> for NoRequests {
fn request(&self, _from: &PeerId, _req: LinkRequest) -> LinkReply {
LinkReply::refused("this device is not offering a link")
}
}
impl Pairing {
pub fn start(scheme: &str, link: &str, cfg: NodeConfig) -> Result<Self> {
let offer = decode_link(scheme, link)?;
let (sender, hello) = Sender::start(offer, now_ms())?;
let node = reach::start(&LINK_PROFILE, Keypair::generate_ed25519(), cfg, Arc::new(NoRequests))?;
let pairing = Pairing { node, sender, sent: false };
pairing.ask(hello)?;
Ok(pairing)
}
fn ask(&self, req: LinkRequest) -> Result<()> {
let offer = self.sender.offer();
match self.node.node.request(offer.peer(), &offer.dial_addrs(), req)? {
LinkReply::Ok => Ok(()),
LinkReply::Refused { reason } => Err(Error::Refused(reason)),
}
}
pub fn sas(&self) -> &str {
self.sender.sas()
}
pub fn device(&self) -> &str {
&self.sender.offer().offer.hint
}
pub fn peer(&self) -> PeerId {
self.sender.offer().peer()
}
pub fn net_status(&self) -> weirdnet_net::node::Status {
self.node.node.status()
}
pub fn send(&mut self, seed: &Key32, profile_name: &str, settings: &str) -> Result<()> {
self.send_with(seed, profile_name, settings, &[]).map(|_| ())
}
pub fn send_with(&mut self, seed: &Key32, profile_name: &str, settings: &str, sync: &[String]) -> Result<weirdnet_net::user::NodeCert> {
if self.sent {
return Err(Error::Invalid("already sent"));
}
let t = crate::session::make_transfer_with(seed, profile_name, settings, sync, self.sender.offer(), now_ms())?;
let cert = t.node_cert.clone();
self.ask(self.sender.transfer(&t)?)?;
self.sent = true;
Ok(cert)
}
pub fn send_credential(
&mut self,
user: &Keypair,
profile_name: &str,
settings: &str,
sync: &[String],
bundle: &[u8],
) -> Result<weirdnet_net::user::NodeCert> {
if self.sent {
return Err(Error::Invalid("already sent"));
}
let c = crate::session::make_credential(user, profile_name, settings, sync, bundle, self.sender.offer(), now_ms())?;
let cert = c.node_cert.clone();
self.ask(self.sender.credential(&c)?)?;
self.sent = true;
Ok(cert)
}
pub fn cancel(&self) -> Result<()> {
self.ask(self.sender.cancel())
}
}
impl Drop for Pairing {
fn drop(&mut self) {
self.node.node.halt();
}
}
#[cfg(test)]
mod tests {
use super::*;
const SCHEME: &str = "weirdnet-morph://";
fn memory() -> NodeConfig {
NodeConfig { listen: vec!["/memory/0".parse().unwrap()], memory: true, ..Default::default() }
}
fn dial_only() -> NodeConfig {
NodeConfig { memory: true, ..Default::default() }
}
#[test]
fn an_identity_moves_over_the_network_after_both_confirm() {
let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "Morph on desk").unwrap();
assert_eq!(new_device.status(), HostStatus::Waiting);
let mut phone = Pairing::start(SCHEME, new_device.link(), dial_only()).unwrap();
assert_eq!(phone.device(), "Morph on desk");
assert_eq!(phone.peer(), new_device.peer_id());
let HostStatus::Paired { sas } = new_device.status() else { panic!("not paired") };
assert_eq!(sas, phone.sas());
let seed = Key32::random().unwrap();
new_device.confirm();
phone.send(&seed, "Work", "{}").unwrap();
assert!(phone.send(&seed, "Work", "{}").is_err(), "single send");
let t = new_device.take().unwrap();
assert_eq!(t.seed, seed.0.to_vec());
assert_eq!(t.node_cert.peer_id, new_device.peer_id().to_string());
assert_eq!(new_device.status(), HostStatus::Done);
}
#[test]
fn a_service_link_moves_over_the_network_without_a_seed() {
let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "model node").unwrap();
let mut phone = Pairing::start(SCHEME, new_device.link(), dial_only()).unwrap();
let user = Keypair::generate_ed25519();
new_device.confirm();
let big = vec![7u8; crate::MAX_BUNDLE];
let cert = phone.send_credential(&user, "Work", "{}", &[], &big).unwrap();
assert!(phone.send_credential(&user, "Work", "{}", &[], &big).is_err(), "single send");
let Received::Service(c) = new_device.take_any().unwrap() else { panic!("expected a service link") };
assert_eq!(c.node_cert, cert);
assert_eq!(c.node_cert.peer_id, new_device.peer_id().to_string());
assert_eq!(c.bundle, big);
}
#[test]
#[ignore = "needs the public relay"]
fn a_link_works_through_the_public_relay_alone() {
let relays: Vec<weirdnet_net::Multiaddr> = crate::KNOWN_RELAYS.iter().map(|a| a.parse().unwrap()).collect();
let cfg = NodeConfig { relays: relays.clone(), ..Default::default() };
let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), cfg.clone(), "Morph behind NAT").unwrap();
let offer = decode_link(SCHEME, new_device.link()).unwrap();
assert!(offer.offer.addrs.iter().all(|a| a.contains("/p2p-circuit")), "{:?}", offer.offer.addrs);
let mut phone = Pairing::start(SCHEME, new_device.link(), cfg).unwrap();
let HostStatus::Paired { sas } = new_device.status() else { panic!("not paired") };
assert_eq!(sas, phone.sas());
new_device.confirm();
phone.send(&Key32::random().unwrap(), "Work", "{}").unwrap();
assert!(new_device.take().is_ok());
}
#[test]
fn a_cancel_from_the_phone_ends_the_offer() {
let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "desk").unwrap();
let phone = Pairing::start(SCHEME, new_device.link(), dial_only()).unwrap();
phone.cancel().unwrap();
assert_eq!(new_device.status(), HostStatus::Cancelled);
assert!(matches!(Pairing::start(SCHEME, new_device.link(), dial_only()), Err(Error::Refused(_))));
}
}