use std::collections::HashMap;
use bincode::{Decode, Encode};
use karyon_core::util::encode;
use karyon_net::{Addr, Port};
use crate::{protocol::ProtocolID, routing_table::Entry, version::VersionInt, PeerID, Result};
#[derive(Decode, Encode, Debug, Clone)]
pub struct NetMsg {
pub header: NetMsgHeader,
pub payload: Vec<u8>,
}
impl NetMsg {
pub fn new<T: Encode>(command: NetMsgCmd, t: T) -> Result<Self> {
Ok(Self {
header: NetMsgHeader { command },
payload: encode(&t)?,
})
}
}
#[derive(Decode, Encode, Debug, Clone)]
pub struct NetMsgHeader {
pub command: NetMsgCmd,
}
#[derive(Decode, Encode, Debug, Clone)]
#[repr(u8)]
pub enum NetMsgCmd {
Version,
Verack,
Protocol,
Shutdown,
Ping,
Pong,
FindPeer,
Peer,
Peers,
}
#[derive(Decode, Encode, Debug, Clone)]
pub enum RefreshMsg {
Ping([u8; 32]),
Pong([u8; 32]),
}
#[derive(Decode, Encode, Debug, Clone)]
pub struct ProtocolMsg {
pub protocol_id: ProtocolID,
pub payload: Vec<u8>,
}
#[derive(Decode, Encode, Debug, Clone)]
pub struct VerMsg {
pub peer_id: PeerID,
pub version: VersionInt,
pub protocols: HashMap<ProtocolID, VersionInt>,
}
#[derive(Decode, Encode, Debug, Clone)]
pub struct VerAckMsg {
pub peer_id: PeerID,
pub ack: bool,
}
#[derive(Decode, Encode, Debug, Clone)]
pub struct ShutdownMsg(pub u8);
#[derive(Decode, Encode, Debug, Clone)]
pub struct PingMsg {
pub nonce: [u8; 32],
pub version: VersionInt,
}
#[derive(Decode, Encode, Debug)]
pub struct PongMsg(pub [u8; 32]);
#[derive(Decode, Encode, Debug)]
pub struct FindPeerMsg(pub PeerID);
#[derive(Decode, Encode, Debug, Clone, PartialEq, Eq)]
pub struct PeerMsg {
pub peer_id: PeerID,
pub addr: Addr,
pub port: Port,
pub discovery_port: Port,
}
#[derive(Decode, Encode, Debug)]
pub struct PeersMsg {
pub peers: Vec<PeerMsg>,
}
impl From<Entry> for PeerMsg {
fn from(entry: Entry) -> PeerMsg {
PeerMsg {
peer_id: PeerID(entry.key),
addr: entry.addr,
port: entry.port,
discovery_port: entry.discovery_port,
}
}
}
impl From<PeerMsg> for Entry {
fn from(peer: PeerMsg) -> Entry {
Entry {
key: peer.peer_id.0,
addr: peer.addr,
port: peer.port,
discovery_port: peer.discovery_port,
}
}
}