use crate::error::{NetError, Result};
use crate::node::{Message, Node};
use crate::profile::Profile;
use libp2p::{Multiaddr, PeerId};
use weirdnet_keys::{Key32, Sealed};
use zeroize::Zeroizing;
pub trait Envelope: Message {
fn sealed(exchange: String, sealed: Sealed) -> Self;
}
pub trait Reply: Message {
fn sealed(sealed: Sealed) -> Self;
fn into_sealed(self) -> std::result::Result<Sealed, Self>;
}
pub enum Answered<R> {
Opened(Zeroizing<Vec<u8>>),
Other(R),
}
pub struct Exchange<'a> {
pub id: &'a str,
pub key: &'a Key32,
pub peer: PeerId,
}
pub fn call<Q: Envelope, R: Reply>(p: &Profile, node: &Node<Q, R>, x: &Exchange, addrs: &[Multiaddr], plain: &[u8]) -> Result<Answered<R>> {
let me = node.peer_id();
let sealed = p.seal_msg(x.key, x.id, &me, &x.peer, plain)?;
Ok(match node.request(x.peer, addrs, Q::sealed(x.id.to_string(), sealed))?.into_sealed() {
Ok(s) => Answered::Opened(p.open_msg(x.key, x.id, &x.peer, &me, &s)?),
Err(other) => Answered::Other(other),
})
}
pub trait Exchanges {
type Exchange;
type Error: From<NetError>;
fn exchange(&self, id: &str) -> std::result::Result<Option<Self::Exchange>, Self::Error>;
fn active(x: &Self::Exchange) -> bool;
fn peer(x: &Self::Exchange) -> Option<&str>;
fn key(&self, x: &Self::Exchange) -> std::result::Result<Option<Key32>, Self::Error>;
}
pub fn serve<S: Exchanges>(
p: &Profile,
store: &mut S,
local: &PeerId,
from: &PeerId,
exchange: &str,
sealed: &Sealed,
answer: impl FnOnce(&mut S, &S::Exchange, &[u8]) -> std::result::Result<Vec<u8>, S::Error>,
) -> std::result::Result<Sealed, S::Error> {
let x = store.exchange(exchange)?.ok_or_else(|| NetError::invalid("exchange", "unknown exchange"))?;
if !S::active(&x) {
return Err(NetError::invalid("exchange", "this exchange is not active (revoked or never completed)").into());
}
if S::peer(&x) != Some(&from.to_string()) {
return Err(NetError::invalid("exchange", "this exchange belongs to another node").into());
}
let id = exchange.to_string();
let key = store.key(&x)?.ok_or_else(|| NetError::invalid("exchange", "no key"))?;
let plain = p.open_msg(&key, &id, from, local, sealed)?;
let out = answer(store, &x, &plain)?;
Ok(p.seal_msg(&key, &id, local, from, &out)?)
}