1use std::collections::HashMap;
2
3use bincode::{Decode, Encode};
4
5use karyon_core::util::encode;
6use karyon_net::{Addr, Port};
7
8use crate::{protocol::ProtocolID, routing_table::Entry, version::VersionInt, PeerID, Result};
9
10#[derive(Decode, Encode, Debug, Clone)]
16pub struct NetMsg {
17 pub header: NetMsgHeader,
18 pub payload: Vec<u8>,
19}
20
21impl NetMsg {
22 pub fn new<T: Encode>(command: NetMsgCmd, t: T) -> Result<Self> {
23 Ok(Self {
24 header: NetMsgHeader { command },
25 payload: encode(&t)?,
26 })
27 }
28}
29
30#[derive(Decode, Encode, Debug, Clone)]
32pub struct NetMsgHeader {
33 pub command: NetMsgCmd,
34}
35
36#[derive(Decode, Encode, Debug, Clone)]
38#[repr(u8)]
39pub enum NetMsgCmd {
40 Version,
41 Verack,
42 Protocol,
43 Shutdown,
44
45 Ping,
47 Pong,
48 FindPeer,
49 Peer,
50 Peers,
51}
52
53#[derive(Decode, Encode, Debug, Clone)]
54pub enum RefreshMsg {
55 Ping([u8; 32]),
56 Pong([u8; 32]),
57}
58
59#[derive(Decode, Encode, Debug, Clone)]
61pub struct ProtocolMsg {
62 pub protocol_id: ProtocolID,
63 pub payload: Vec<u8>,
64}
65
66#[derive(Decode, Encode, Debug, Clone)]
68pub struct VerMsg {
69 pub peer_id: PeerID,
70 pub version: VersionInt,
71 pub protocols: HashMap<ProtocolID, VersionInt>,
72}
73
74#[derive(Decode, Encode, Debug, Clone)]
78pub struct VerAckMsg {
79 pub peer_id: PeerID,
80 pub ack: bool,
81}
82
83#[derive(Decode, Encode, Debug, Clone)]
85pub struct ShutdownMsg(pub u8);
86
87#[derive(Decode, Encode, Debug, Clone)]
89pub struct PingMsg {
90 pub nonce: [u8; 32],
91 pub version: VersionInt,
92}
93
94#[derive(Decode, Encode, Debug)]
96pub struct PongMsg(pub [u8; 32]);
97
98#[derive(Decode, Encode, Debug)]
100pub struct FindPeerMsg(pub PeerID);
101
102#[derive(Decode, Encode, Debug, Clone, PartialEq, Eq)]
104pub struct PeerMsg {
105 pub peer_id: PeerID,
106 pub addr: Addr,
107 pub port: Port,
108 pub discovery_port: Port,
109}
110
111#[derive(Decode, Encode, Debug)]
113pub struct PeersMsg {
114 pub peers: Vec<PeerMsg>,
115}
116
117impl From<Entry> for PeerMsg {
118 fn from(entry: Entry) -> PeerMsg {
119 PeerMsg {
120 peer_id: PeerID(entry.key),
121 addr: entry.addr,
122 port: entry.port,
123 discovery_port: entry.discovery_port,
124 }
125 }
126}
127
128impl From<PeerMsg> for Entry {
129 fn from(peer: PeerMsg) -> Entry {
130 Entry {
131 key: peer.peer_id.0,
132 addr: peer.addr,
133 port: peer.port,
134 discovery_port: peer.discovery_port,
135 }
136 }
137}