use std::fmt;
use std::net;
use borsh::{BorshDeserialize, BorshSerialize};
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct PeerData {
agent: String,
location: Location,
identity: Identity,
}
impl PeerData {
pub fn new_loc(location: Location) -> Self {
Self {
location,
..Self::default()
}
}
pub fn agent(&self) -> &str {
&self.agent
}
pub fn set_agent(&mut self, agent: String) {
self.agent = agent;
}
pub fn location(&self) -> &Location {
&self.location
}
pub fn set_location(&mut self, loc: Location) {
self.location = loc;
}
pub fn identity(&self) -> &Identity {
&self.identity
}
pub fn set_identity(&mut self, ident: Identity) {
self.identity = ident;
}
}
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub enum Location {
#[default]
Unspecified,
Ip(net::SocketAddr),
Url(String),
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unspecified => f.write_str("unspecified"),
Self::Ip(sock_addr) => sock_addr.fmt(f),
Self::Url(url) => f.write_str(url),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub enum Identity {
#[default]
Unidentified,
EcksKey(EcksKeyId),
TlsDomain(String),
CustomKey(CustomKeyId),
CustomUsername(String),
}
impl Identity {
pub fn is_authed(&self) -> bool {
!matches!(self, Identity::Unidentified)
}
}
impl fmt::Display for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unidentified => f.write_str("unidentified"),
Self::EcksKey(k) => k.fmt(f),
Self::TlsDomain(domain) => f.write_str(domain),
Self::CustomKey(k) => k.fmt(f),
Self::CustomUsername(name) => {
f.write_str("name:")?;
f.write_str(name)
}
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, BorshDeserialize, BorshSerialize)]
pub struct EcksKeyId([u8; 32]);
impl From<[u8; 32]> for EcksKeyId {
fn from(value: [u8; 32]) -> Self {
Self(value)
}
}
impl Into<[u8; 32]> for EcksKeyId {
fn into(self) -> [u8; 32] {
self.0
}
}
impl fmt::Display for EcksKeyId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut buf = [0; 64];
hex::encode_to_slice(self.0, &mut buf).expect("peer: encode key ID");
f.write_str("ek:")?;
f.write_str(unsafe { std::str::from_utf8_unchecked(&buf) })
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, BorshDeserialize, BorshSerialize)]
pub struct CustomKeyId([u8; 32]);
impl From<[u8; 32]> for CustomKeyId {
fn from(value: [u8; 32]) -> Self {
Self(value)
}
}
impl Into<[u8; 32]> for CustomKeyId {
fn into(self) -> [u8; 32] {
self.0
}
}
impl fmt::Display for CustomKeyId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut buf = [0; 64];
hex::encode_to_slice(self.0, &mut buf).expect("peer: encode key ID");
f.write_str("ck:")?;
f.write_str(unsafe { std::str::from_utf8_unchecked(&buf) })
}
}