blueprint_networking/blueprint_protocol/
mod.rs1mod behaviour;
2mod handler;
3
4pub use behaviour::{BlueprintProtocolBehaviour, BlueprintProtocolEvent};
5use blueprint_crypto::KeyType;
6use libp2p::PeerId;
7
8use crate::discovery::peers::VerificationIdentifierKey;
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
13#[serde(bound = "K: KeyType")]
14pub enum InstanceMessageRequest<K: KeyType> {
15 Handshake {
17 verification_id_key: VerificationIdentifierKey<K>,
19 signature: K::Signature,
21 msg: HandshakeMessage,
23 },
24 Protocol {
26 protocol: String,
28 payload: Vec<u8>,
30 metadata: Option<Vec<u8>>,
32 },
33}
34
35#[derive(Debug, Clone, Serialize, Deserialize)]
37#[serde(bound = "K: KeyType")]
38pub enum InstanceMessageResponse<K: KeyType> {
39 Handshake {
41 verification_id_key: VerificationIdentifierKey<K>,
43 signature: K::Signature,
45 msg: HandshakeMessage,
47 },
48 Success {
50 protocol: String,
52 data: Option<Vec<u8>>,
54 },
55 Error {
57 code: u16,
59 message: String,
61 },
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct HandshakeMessage {
66 pub sender: PeerId,
68 pub timestamp: u128,
70}
71
72impl HandshakeMessage {
73 pub const MAX_AGE: u128 = 30_000;
75
76 #[must_use]
81 pub fn new(sender: PeerId) -> Self {
82 let timestamp = std::time::SystemTime::now()
83 .duration_since(std::time::UNIX_EPOCH)
84 .expect("time went backwards")
85 .as_millis();
86 Self { sender, timestamp }
87 }
88
89 #[must_use]
100 pub fn is_expired(&self, max_age: u128) -> bool {
101 let now = std::time::SystemTime::now()
102 .duration_since(std::time::UNIX_EPOCH)
103 .expect("time went backwards")
104 .as_millis();
105 now.saturating_sub(self.timestamp) > max_age
106 }
107
108 #[must_use]
110 pub fn to_bytes(&self, other_peer_id: &PeerId) -> Vec<u8> {
111 let mut bytes = Vec::new();
112 bytes.extend(&self.sender.to_bytes());
113 bytes.extend(other_peer_id.to_bytes());
114 bytes.extend(&self.timestamp.to_be_bytes());
115 bytes
116 }
117}