mod behaviour;
mod handler;
pub use behaviour::{BlueprintProtocolBehaviour, BlueprintProtocolEvent};
use blueprint_crypto::KeyType;
use libp2p::PeerId;
use crate::discovery::peers::VerificationIdentifierKey;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound = "K: KeyType")]
pub enum InstanceMessageRequest<K: KeyType> {
Handshake {
verification_id_key: VerificationIdentifierKey<K>,
signature: K::Signature,
msg: HandshakeMessage,
},
Protocol {
protocol: String,
payload: Vec<u8>,
metadata: Option<Vec<u8>>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound = "K: KeyType")]
pub enum InstanceMessageResponse<K: KeyType> {
Handshake {
verification_id_key: VerificationIdentifierKey<K>,
signature: K::Signature,
msg: HandshakeMessage,
},
Success {
protocol: String,
data: Option<Vec<u8>>,
},
Error {
code: u16,
message: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HandshakeMessage {
pub sender: PeerId,
pub timestamp: u128,
}
impl HandshakeMessage {
pub const MAX_AGE: u128 = 30_000;
#[must_use]
pub fn new(sender: PeerId) -> Self {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("time went backwards")
.as_millis();
Self { sender, timestamp }
}
#[must_use]
pub fn is_expired(&self, max_age: u128) -> bool {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("time went backwards")
.as_millis();
now.saturating_sub(self.timestamp) > max_age
}
#[must_use]
pub fn to_bytes(&self, other_peer_id: &PeerId) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend(&self.sender.to_bytes());
bytes.extend(other_peer_id.to_bytes());
bytes.extend(&self.timestamp.to_be_bytes());
bytes
}
}