wip handling root request
This commit is contained in:
@@ -49,11 +49,11 @@ pub struct P2PClientApp {
|
||||
|
||||
impl P2PClientApp {
|
||||
pub fn new(cmd_tx: Sender<NetworkCommand>, event_rx: Receiver<NetworkEvent>) -> Self {
|
||||
let (root_hash, tree_content) = MerkleNode::generate_base_tree();
|
||||
//let (root_hash, tree_content) = MerkleNode::generate_base_tree();
|
||||
|
||||
let mut loaded_fs = HashMap::new();
|
||||
let tree = MerkleTree::new(tree_content, root_hash);
|
||||
loaded_fs.insert("bob".to_string(), tree);
|
||||
//let tree = MerkleTree::new(tree_content, root_hash);
|
||||
//loaded_fs.insert("bob".to_string(), tree);
|
||||
|
||||
Self {
|
||||
remaining: std::time::Duration::from_secs(0),
|
||||
@@ -124,22 +124,23 @@ impl eframe::App for P2PClientApp {
|
||||
todo!();
|
||||
|
||||
//self.loaded_tree_nodes.insert(_peer_id, tree);
|
||||
self.status_message = "🔄 File tree updated successfully.".to_string();
|
||||
//self.status_message = "🔄 File tree updated successfully.".to_string();
|
||||
}
|
||||
NetworkEvent::FileTreeRootReceived(peer_id, root_hash) => {
|
||||
todo!();
|
||||
// todo!();
|
||||
|
||||
self.status_message = format!(
|
||||
"🔄 Received Merkle Root from {}: {}",
|
||||
peer_id,
|
||||
&root_hash[..8]
|
||||
);
|
||||
|
||||
// self.status_message = format!("🔄 Received Merkle Root from {}: {}", peer_id, &root_hash[..8]);
|
||||
//
|
||||
//
|
||||
//self.active_peer_id = Some(peer_id.clone());
|
||||
//
|
||||
//
|
||||
// // Request the content of the root directory immediately
|
||||
// let _ = self.network_cmd_tx.send(NetworkCommand::RequestDirectoryContent(
|
||||
// peer_id,
|
||||
// root_hash,
|
||||
// ));
|
||||
|
||||
// Request the content of the root directory immediately
|
||||
/*let _ = self
|
||||
.network_cmd_tx
|
||||
.send(NetworkCommand::RequestDirectoryContent(peer_id, root_hash));*/
|
||||
}
|
||||
NetworkEvent::Connected(ip) => {
|
||||
self.server_status = ServerStatus::Connected;
|
||||
@@ -360,11 +361,11 @@ impl eframe::App for P2PClientApp {
|
||||
.loaded_fs
|
||||
.contains_key(self.active_peer.as_ref().unwrap())
|
||||
{
|
||||
todo!();
|
||||
// let _ = self.network_cmd_tx.send(NetworkCommand::RequestDirectoryContent(
|
||||
// peer.clone(),
|
||||
// peer.clone(),
|
||||
// ));
|
||||
//todo!();
|
||||
let _ = self.network_cmd_tx.send(NetworkCommand::Discover(
|
||||
peer.clone(),
|
||||
"root".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
selectable.context_menu(|ui| {
|
||||
@@ -508,7 +509,13 @@ impl P2PClientApp {
|
||||
entry.content_hash,
|
||||
tree,
|
||||
depth + 1,
|
||||
Some(entry.filename),
|
||||
Some(
|
||||
entry
|
||||
.filename
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.expect("incorrect size"),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -529,7 +536,7 @@ impl P2PClientApp {
|
||||
.enabled(true)
|
||||
.show(ui, |ui| {
|
||||
for child in &node.children_hashes {
|
||||
self.draw_file_node(ui, child.clone(), tree, depth + 1, None);
|
||||
self.draw_file_node(ui, child.content_hash, tree, depth + 1, None);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ impl MerkleTree {
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_random_file_node(
|
||||
/*fn generate_random_file_node(
|
||||
storage: &mut HashMap<NodeHash, MerkleNode>,
|
||||
) -> Result<NodeHash, String> {
|
||||
let mut rng = rng();
|
||||
@@ -110,9 +110,9 @@ fn generate_random_file_node(
|
||||
storage.insert(hash, node);
|
||||
Ok(hash)
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
fn generate_random_directory_node(
|
||||
/*fn generate_random_directory_node(
|
||||
depth: u32,
|
||||
max_depth: u32,
|
||||
storage: &mut HashMap<NodeHash, MerkleNode>,
|
||||
@@ -172,7 +172,7 @@ fn generate_random_directory_node(
|
||||
storage.insert(hash, node);
|
||||
Ok(hash)
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChunkNode {
|
||||
@@ -310,14 +310,14 @@ impl MerkleNode {
|
||||
}
|
||||
MerkleNode::BigDirectory(node) => {
|
||||
for hash in &node.children_hashes {
|
||||
bytes.extend_from_slice(hash);
|
||||
bytes.extend_from_slice(&hash.content_hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
pub fn generate_random_tree(
|
||||
/*pub fn generate_random_tree(
|
||||
max_depth: u32,
|
||||
) -> Result<(NodeHash, HashMap<NodeHash, MerkleNode>), String> {
|
||||
let mut storage = HashMap::new();
|
||||
@@ -326,9 +326,9 @@ impl MerkleNode {
|
||||
let root_hash = generate_random_directory_node(0, max_depth, &mut storage)?;
|
||||
|
||||
Ok((root_hash, storage))
|
||||
}
|
||||
}*/
|
||||
|
||||
pub fn generate_base_tree() -> (NodeHash, HashMap<NodeHash, MerkleNode>) {
|
||||
/*pub fn generate_base_tree() -> (NodeHash, HashMap<NodeHash, MerkleNode>) {
|
||||
let mut res = HashMap::new();
|
||||
|
||||
let node1 = MerkleNode::Chunk(ChunkNode::new_random());
|
||||
@@ -378,5 +378,5 @@ impl MerkleNode {
|
||||
res.insert(root_hash, root);
|
||||
|
||||
(root_hash, res)
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
@@ -12,8 +12,10 @@ use crate::{
|
||||
cryptographic_signature::CryptographicSignature,
|
||||
message_handling::EventType,
|
||||
messages_channels::{MultipleSenders, start_receving_thread},
|
||||
messages_structure::construct_message,
|
||||
peers_refresh::HandshakeHistory,
|
||||
registration::{
|
||||
get_socket_address, parse_addresses, register_ip_addresses, register_with_the_server,
|
||||
get_socket_address, parse_addresses, perform_handshake, register_with_the_server,
|
||||
},
|
||||
server_communication::{generate_id, get_peer_list},
|
||||
};
|
||||
@@ -33,6 +35,7 @@ pub struct P2PSharedData {
|
||||
shared_messageslist: Arc<Mutex<HashMap<i32, EventType>>>,
|
||||
shared_senders: Arc<MultipleSenders>,
|
||||
server_name: Arc<Mutex<String>>,
|
||||
handshake_peers: Arc<HandshakeHistory>,
|
||||
}
|
||||
|
||||
impl P2PSharedData {
|
||||
@@ -51,12 +54,14 @@ impl P2PSharedData {
|
||||
let senders = MultipleSenders::new(1, &shared_socket, cmd_tx);
|
||||
let shared_senders = Arc::new(senders);
|
||||
let server_name = Arc::new(Mutex::new("".to_string()));
|
||||
let handhsake_peers = Arc::new(HandshakeHistory::new());
|
||||
Ok(P2PSharedData {
|
||||
shared_socket: shared_socket,
|
||||
shared_cryptopair: shared_cryptopair,
|
||||
shared_messageslist: shared_messageslist,
|
||||
shared_senders: shared_senders,
|
||||
server_name: server_name,
|
||||
handshake_peers: handhsake_peers,
|
||||
})
|
||||
}
|
||||
pub fn socket(&self) -> Arc<UdpSocket> {
|
||||
@@ -87,6 +92,9 @@ impl P2PSharedData {
|
||||
pub fn cryptopair_ref(&self) -> &CryptographicSignature {
|
||||
&*self.shared_cryptopair
|
||||
}
|
||||
pub fn handshake_ref(&self) -> &HandshakeHistory {
|
||||
&*self.handshake_peers
|
||||
}
|
||||
|
||||
pub fn messages_list_ref(&self) -> &Mutex<HashMap<i32, EventType>> {
|
||||
&*self.shared_messageslist
|
||||
@@ -115,6 +123,8 @@ pub enum NetworkCommand {
|
||||
RequestChunk(String, String),
|
||||
Disconnect(),
|
||||
ResetServerPeer(),
|
||||
Discover(String, String),
|
||||
GetChildren(String, String),
|
||||
// ...
|
||||
}
|
||||
|
||||
@@ -173,61 +183,11 @@ pub fn start_p2p_executor(
|
||||
match cmd {
|
||||
NetworkCommand::ServerHandshake(username, ip) => {
|
||||
if let Some(sd) = shared_data.as_ref() {
|
||||
println!("username:{}, ip:{}", username, ip);
|
||||
let server_addr_query = get_socket_address(username.clone(), ip);
|
||||
|
||||
match server_addr_query.await {
|
||||
Ok(sockaddr_bytes) => {
|
||||
match String::from_utf8(sockaddr_bytes.to_vec()) {
|
||||
Ok(s) => {
|
||||
let addresses = parse_addresses(&s);
|
||||
if let Some(first) = addresses.first() {
|
||||
sd.set_servername(username);
|
||||
// first: &SocketAddr
|
||||
start_receving_thread(
|
||||
sd,
|
||||
*first, // copie le SocketAddr (implémente Copy pour SocketAddr)
|
||||
event_tx.clone(), //
|
||||
);
|
||||
register_ip_addresses(
|
||||
sd.cryptopair_ref(),
|
||||
first.to_string(),
|
||||
sd.senders_ref(),
|
||||
sd.messages_list_ref(),
|
||||
generate_id(),
|
||||
);
|
||||
|
||||
//let res = event_tx
|
||||
// .send(NetworkEvent::());
|
||||
} else {
|
||||
//let res = event_tx.send(NetworkEvent::Error());
|
||||
let err_msg = format!(
|
||||
"no valid socket addresses found in: {}",
|
||||
s
|
||||
)
|
||||
.to_string();
|
||||
let res =
|
||||
event_tx.send(NetworkEvent::Error(err_msg));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
//let res = event_tx.send(NetworkEvent::Error());
|
||||
let err_msg = format!(
|
||||
"invalid UTF-8 in socket address bytes: {}",
|
||||
e
|
||||
)
|
||||
.to_string();
|
||||
let res = event_tx.send(NetworkEvent::Error(err_msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let err_msg =
|
||||
format!("failed to retreive socket address: {}", e)
|
||||
.to_string();
|
||||
let res = event_tx.send(NetworkEvent::Error(err_msg));
|
||||
}
|
||||
}
|
||||
perform_handshake(&sd, username, ip, event_tx.clone());
|
||||
}
|
||||
}
|
||||
NetworkCommand::ConnectPeer(addr) => {
|
||||
@@ -240,6 +200,12 @@ pub fn start_p2p_executor(
|
||||
NetworkCommand::RequestFileTree(_) => {
|
||||
println!("[Network] RequestFileTree() called");
|
||||
}
|
||||
NetworkCommand::Discover(username, hash) => {
|
||||
// envoie un handshake au peer, puis un root request
|
||||
}
|
||||
NetworkCommand::GetChildren(username, hash) => {
|
||||
// envoie un datum request au peer
|
||||
}
|
||||
NetworkCommand::RequestDirectoryContent(_, _) => {
|
||||
println!("[Network] RequestDirectoryContent() called");
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ use crate::{
|
||||
},
|
||||
messages_channels::MultipleSenders,
|
||||
messages_structure::construct_message,
|
||||
peers_refresh::HandshakeHistory,
|
||||
registration,
|
||||
server_communication::generate_id,
|
||||
};
|
||||
use std::{collections::HashMap, net::SocketAddr};
|
||||
use std::{
|
||||
@@ -14,9 +16,7 @@ use std::{
|
||||
};
|
||||
|
||||
pub enum EventType {
|
||||
ServerHelloReply,
|
||||
PeerHelloReply,
|
||||
PeerHello,
|
||||
SendRootRequest,
|
||||
}
|
||||
|
||||
const ID: usize = 4;
|
||||
@@ -42,11 +42,12 @@ pub fn handle_recevied_message(
|
||||
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
|
||||
recevied_message: &Vec<u8>,
|
||||
crypto_pair: &CryptographicSignature,
|
||||
socket_addr: &SocketAddr,
|
||||
//socket_addr: &SocketAddr,
|
||||
senders: &MultipleSenders,
|
||||
server_name: &String,
|
||||
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
|
||||
ip: SocketAddr,
|
||||
handshake_history: HandshakeHistory,
|
||||
) {
|
||||
if recevied_message.len() < 4 {
|
||||
return;
|
||||
@@ -70,13 +71,27 @@ pub fn handle_recevied_message(
|
||||
}
|
||||
}
|
||||
|
||||
let resp = parse_message(recevied_message.to_vec(), id, crypto_pair, cmd_tx, ip);
|
||||
let resp = parse_message(
|
||||
recevied_message.to_vec(),
|
||||
id,
|
||||
crypto_pair,
|
||||
cmd_tx,
|
||||
ip,
|
||||
messages_list,
|
||||
handshake_history,
|
||||
);
|
||||
|
||||
match resp {
|
||||
None => {}
|
||||
Some(resp_msg) => {
|
||||
println!("msg_sent:{:?}", resp_msg);
|
||||
senders.send_via(0, resp_msg, ip.to_string(), is_resp_to_server_handshake);
|
||||
senders.send_via(
|
||||
0,
|
||||
resp_msg,
|
||||
ip.to_string(),
|
||||
is_resp_to_server_handshake,
|
||||
messages_list,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +167,8 @@ pub fn parse_message(
|
||||
crypto_pair: &CryptographicSignature,
|
||||
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
|
||||
ip: SocketAddr,
|
||||
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
|
||||
handhsake_history: HandshakeHistory,
|
||||
) -> Option<Vec<u8>> {
|
||||
let cmd_tx_clone = cmd_tx.clone();
|
||||
|
||||
@@ -166,7 +183,6 @@ pub fn parse_message(
|
||||
.expect("Taille incorrecte");
|
||||
|
||||
let msg_length = u16::from_be_bytes(length_bytes) as usize;
|
||||
|
||||
// verify signature
|
||||
match msgtype {
|
||||
HELLO | HELLOREPLY | ROOTREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => {
|
||||
@@ -176,10 +192,13 @@ pub fn parse_message(
|
||||
let received_username = String::from_utf8(received_name.to_vec());
|
||||
match received_username {
|
||||
Ok(username) => {
|
||||
let peer_pubkey = tokio::runtime::Runtime::new()
|
||||
let peer_pubkey = match handhsake_history.get_peer_info_username(username) {
|
||||
Some(peerinfo) => peerinfo.pubkey,
|
||||
_ => tokio::runtime::Runtime::new()
|
||||
.unwrap()
|
||||
.block_on(get_peer_key(&username))
|
||||
.expect("failed to retrieve public key");
|
||||
.expect("failed to retrieve public key"),
|
||||
};
|
||||
let signature: [u8; SIGNATURE] = received_message
|
||||
[LENGTH + msg_length..LENGTH + msg_length + SIGNATURE]
|
||||
.try_into()
|
||||
@@ -248,7 +267,30 @@ pub fn parse_message(
|
||||
//
|
||||
//
|
||||
// ajoute a la liste des peers handshake
|
||||
HELLOREPLY => {}
|
||||
HELLOREPLY => {
|
||||
// ajoute a la liste des peers handshake
|
||||
handhsake_history.add_new_handshake(hash, username, ip);
|
||||
// verifie s'il faut renvoyer un root request
|
||||
let guard = messages_list.lock().expect("Échec du verrouillage");
|
||||
let res = guard.get(&id);
|
||||
match res {
|
||||
Some(ev) => {
|
||||
match ev {
|
||||
EventType::SendRootRequest => {
|
||||
// envoyer la root request
|
||||
let rootrequest = construct_message(
|
||||
ROOTREQUEST,
|
||||
Vec::new(),
|
||||
generate_id(),
|
||||
crypto_pair,
|
||||
);
|
||||
return rootrequest;
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
//
|
||||
// ROOTREQUEST
|
||||
//
|
||||
@@ -256,7 +298,20 @@ pub fn parse_message(
|
||||
//
|
||||
// ROOTREPLY
|
||||
//
|
||||
// envoie un datum request
|
||||
ROOTREPLY => {
|
||||
// recuperer le pseudo du peers ayant repondu
|
||||
|
||||
// envoyer le hash a la gui
|
||||
let received_hash = String::from_utf8(received_message[LENGTH..(32 + LENGTH)].to_vec());
|
||||
match received_hash {
|
||||
Ok(hash) => {
|
||||
cmd_tx_clone.send(NetworkEvent::FileTreeRootReceived());
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
// DATUMREQUEST
|
||||
//
|
||||
@@ -328,6 +383,6 @@ pub fn parse_message(
|
||||
//
|
||||
// envoie OK à S puis envoie un ping à S
|
||||
_ => return None,
|
||||
}
|
||||
};
|
||||
constructed_message
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ use crate::P2PSharedData;
|
||||
use crate::cryptographic_signature::CryptographicSignature;
|
||||
use crate::message_handling::EventType;
|
||||
use crate::message_handling::handle_recevied_message;
|
||||
use crate::peers_refresh::HandshakeHistory;
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::UdpSocket;
|
||||
@@ -21,9 +22,9 @@ pub struct MultipleSenders {
|
||||
}
|
||||
|
||||
pub struct Message {
|
||||
payload: Vec<u8>,
|
||||
address: String,
|
||||
is_resp_to_server_handshake: bool,
|
||||
pub payload: Vec<u8>,
|
||||
pub address: String,
|
||||
pub is_resp_to_server_handshake: bool,
|
||||
}
|
||||
|
||||
struct RetryMessage {
|
||||
@@ -205,18 +206,22 @@ impl MultipleSenders {
|
||||
data: Vec<u8>,
|
||||
remote_addr: String,
|
||||
is_resp_to_server_handshake: bool,
|
||||
messages_list: &Mutex<HashMap<i32, EventType>>,
|
||||
) {
|
||||
println!(
|
||||
"is_resp_to_server_handshake {}",
|
||||
is_resp_to_server_handshake
|
||||
);
|
||||
if let Some(sender) = self.senders.get(channel_idx) {
|
||||
let _ = sender.send(Message {
|
||||
payload: data,
|
||||
let msg_to_send = Message {
|
||||
payload: data.clone(),
|
||||
address: remote_addr,
|
||||
is_resp_to_server_handshake,
|
||||
});
|
||||
}
|
||||
};
|
||||
if let Some(sender) = self.senders.get(channel_idx) {
|
||||
let _ = sender.send(msg_to_send);
|
||||
let mut guard = messages_list.lock().expect("Échec du verrouillage");
|
||||
let id = i32::from_be_bytes(data[..4].try_into().unwrap());
|
||||
guard.insert(id, EventType::SendRootRequest);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +260,6 @@ impl MultipleSenders {
|
||||
|
||||
pub fn start_receving_thread(
|
||||
shared_data: &P2PSharedData,
|
||||
socket_addr: SocketAddr,
|
||||
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
|
||||
) {
|
||||
let sock_clone = shared_data.socket();
|
||||
@@ -263,6 +267,7 @@ pub fn start_receving_thread(
|
||||
let senders_clone = shared_data.senders();
|
||||
let messages_clone = shared_data.messages_list();
|
||||
let servername_clone = shared_data.servername();
|
||||
let handshake_history = HandshakeHistory::new();
|
||||
thread::spawn(move || {
|
||||
let mut buf = [0u8; 1024];
|
||||
loop {
|
||||
@@ -275,11 +280,11 @@ pub fn start_receving_thread(
|
||||
&messages_clone,
|
||||
&received_data,
|
||||
&cryptopair_clone,
|
||||
&socket_addr,
|
||||
&senders_clone,
|
||||
&servername_clone,
|
||||
cmd_tx.clone(),
|
||||
src,
|
||||
handshake_history,
|
||||
);
|
||||
}
|
||||
Err(e) => eprintln!("Erreur de réception: {}", e),
|
||||
@@ -287,3 +292,4 @@ pub fn start_receving_thread(
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ const OK: u8 = 128;
|
||||
const ERROR: u8 = 129;
|
||||
const HELLO: u8 = 1;
|
||||
const HELLOREPLY: u8 = 130;
|
||||
const ROOTREQUEST: u8 = 2;
|
||||
pub const ROOTREQUEST: u8 = 2;
|
||||
const ROOTREPLY: u8 = 131;
|
||||
const DATUMREQUEST: u8 = 3;
|
||||
const NODATUM: u8 = 133;
|
||||
@@ -46,11 +46,11 @@ pub fn construct_message(
|
||||
let signature = sign_message(crypto_pair, &message);
|
||||
return Some(signature);
|
||||
}
|
||||
PING | OK => {
|
||||
PING | OK | ROOTREQUEST => {
|
||||
message.extend_from_slice(&0u16.to_be_bytes());
|
||||
return Some(message);
|
||||
}
|
||||
ERROR | ROOTREQUEST | DATUMREQUEST => {
|
||||
ERROR | DATUMREQUEST => {
|
||||
message.extend_from_slice(&payload.len().to_be_bytes());
|
||||
message.extend_from_slice(&payload);
|
||||
return Some(message);
|
||||
|
||||
@@ -11,54 +11,113 @@ use std::{
|
||||
time::{self, Duration, SystemTime},
|
||||
};
|
||||
|
||||
use crate::NetworkEvent;
|
||||
use crate::{
|
||||
P2PSharedData, construct_message, generate_id, messages_structure,
|
||||
registration::perform_handshake,
|
||||
};
|
||||
use crossbeam_channel::{Receiver, Sender};
|
||||
use p256::ecdsa::VerifyingKey;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PeerInfo {
|
||||
username: String,
|
||||
ip: SocketAddr,
|
||||
pub pubkey: VerifyingKey,
|
||||
pub ip: SocketAddr,
|
||||
}
|
||||
|
||||
pub struct HandshakeHistory {
|
||||
time_k_ip_v: HashMap<u64, u64>,
|
||||
ip_k_peerinfo_v: HashMap<u64, PeerInfo>,
|
||||
//time_k_ip_v: HashMap<u64, u64>,
|
||||
username_k_peerinfo_v: HashMap<String, PeerInfo>,
|
||||
ip_k_peerinfo_v: HashMap<String, PeerInfo>,
|
||||
}
|
||||
|
||||
impl HandshakeHistory {
|
||||
pub fn new() -> HandshakeHistory {
|
||||
HandshakeHistory {
|
||||
time_k_ip_v: HashMap::new(),
|
||||
//time_k_ip_v: HashMap::new(),
|
||||
//ip_k_peerinfo_v: HashMap::new(),
|
||||
username_k_peerinfo_v: HashMap::new(),
|
||||
ip_k_peerinfo_v: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_handshake(&mut self) {
|
||||
/*pub fn update_handshake(&self) {
|
||||
let hashmap_shared = Arc::new(self.username_k_peerinfo_v);
|
||||
thread::spawn(move || {
|
||||
let mut times_to_check = VecDeque::new();
|
||||
let current_time: u64 = SystemTime::now()
|
||||
.duration_since(time::UNIX_EPOCH)
|
||||
.expect("system time before UNIX EPOCH")
|
||||
.add(Duration::from_secs(10))
|
||||
.as_secs();
|
||||
// adds 10 seconds in the queue every 10 seconds
|
||||
let selfhashmap = hashmap_shared.clone();
|
||||
loop {
|
||||
let mut child = Command::new("sleep").arg("9").spawn().unwrap();
|
||||
let _result = child.wait().unwrap();
|
||||
for n in 0..9 {
|
||||
// push 9 successive seconds
|
||||
times_to_check.push_back(current_time + n);
|
||||
// gestion d'erreur si verrou mort
|
||||
for peer in selfhashmap.keys() {
|
||||
let peer_ip = selfhashmap.get(peer);
|
||||
// send ping
|
||||
}
|
||||
let mut child = Command::new("sleep").arg("10").spawn().unwrap();
|
||||
let _result = child.wait().unwrap();
|
||||
}
|
||||
});
|
||||
}*/
|
||||
|
||||
pub fn get_peer_info_username(&self, username: String) -> Option<&PeerInfo> {
|
||||
self.username_k_peerinfo_v.get(&username).clone()
|
||||
}
|
||||
|
||||
pub fn get_peer_info_ip(&self, ip: String) -> Option<&PeerInfo> {
|
||||
self.ip_k_peerinfo_v.get(&ip).clone()
|
||||
}
|
||||
|
||||
pub fn update_handshake(&self) {
|
||||
// clone the map so we own it (cheap if PeerInfo is Clone)
|
||||
let map_clone: Arc<HashMap<String, PeerInfo>> =
|
||||
Arc::new(self.username_k_peerinfo_v.clone());
|
||||
//let map_ip_clone: Arc<HashMap<String, PeerInfo>> = Arc::new(self.ip_k_peerinfo_v.clone());
|
||||
let map_for_thread = Arc::clone(&map_clone);
|
||||
thread::spawn(move || {
|
||||
loop {
|
||||
// Arc<HashMap<..>> derefs to &HashMap so these reads work
|
||||
for (peer, peerinfo) in map_for_thread.iter() {
|
||||
// send ping to peerinfo
|
||||
}
|
||||
thread::sleep(Duration::from_secs(10));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn add_new_handshake(&mut self, hash: u64, username: String, ip: SocketAddr) {
|
||||
let current_time: u64 = SystemTime::now()
|
||||
.duration_since(time::UNIX_EPOCH)
|
||||
.expect("system time before UNIX EPOCH")
|
||||
.as_secs();
|
||||
println!("time:{}", current_time);
|
||||
/*self.time_k_hash_v.insert(current_time, hash);
|
||||
self.hash_k_peerinfo_v
|
||||
.insert(hash, PeerInfo { username, ip });*/
|
||||
pub fn add_new_handshake(&mut self, hash: VerifyingKey, username: String, ip: SocketAddr) {
|
||||
let peerinfo = PeerInfo {
|
||||
username: username.clone(),
|
||||
pubkey: hash,
|
||||
ip,
|
||||
};
|
||||
self.username_k_peerinfo_v
|
||||
.insert(username, peerinfo.clone());
|
||||
self.ip_k_peerinfo_v
|
||||
.insert(ip.to_string(), peerinfo.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn perform_discover(
|
||||
username: String,
|
||||
hash: String,
|
||||
sd: &P2PSharedData,
|
||||
server_ip: String,
|
||||
event_tx: Sender<NetworkEvent>,
|
||||
) {
|
||||
// first, sends handshake
|
||||
if hash == "root" {
|
||||
perform_handshake(sd, username, server_ip, event_tx);
|
||||
if let Some(data) = construct_message(
|
||||
messages_structure::ROOTREQUEST,
|
||||
Vec::new(),
|
||||
generate_id(),
|
||||
sd.cryptopair_ref(),
|
||||
) {
|
||||
if let Some(peerinfo) = sd.handshake_ref() {
|
||||
sd.senders_ref()
|
||||
.send_via(0, data, peerinfo.ip.to_string(), false);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// envoyer un datum request
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,10 +127,7 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
///
|
||||
/// creates a cryptographic signature
|
||||
///
|
||||
#[test]
|
||||
/*#[test]
|
||||
fn creating_cryptographic_signature() {
|
||||
let mut hh = HandshakeHistory::new();
|
||||
hh.add_new_handshake(
|
||||
@@ -79,5 +135,5 @@ mod tests {
|
||||
"putain".to_string(),
|
||||
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1),
|
||||
);
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
use bytes::Bytes;
|
||||
use getrandom::Error;
|
||||
|
||||
use crate::NetworkEvent;
|
||||
use crate::P2PSharedData;
|
||||
use crate::cryptographic_signature::{CryptographicSignature, formatPubKey, sign_message};
|
||||
use crate::message_handling::EventType;
|
||||
use crate::messages_channels::{Message, MultipleSenders};
|
||||
use crate::messages_structure::construct_message;
|
||||
use crate::server_communication::generate_id;
|
||||
use crossbeam_channel::{Receiver, Sender};
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::UdpSocket;
|
||||
@@ -66,23 +70,66 @@ pub fn parse_addresses(input: &String) -> Vec<SocketAddr> {
|
||||
///
|
||||
/// registers the IP addresses by sending a Hello request to the server.
|
||||
///
|
||||
pub fn register_ip_addresses(
|
||||
crypto_pair: &CryptographicSignature,
|
||||
server_uri: String,
|
||||
senders: &MultipleSenders,
|
||||
messages_list: &Mutex<HashMap<i32, EventType>>,
|
||||
id: i32,
|
||||
pub async fn perform_handshake(
|
||||
sd: &P2PSharedData,
|
||||
username: String,
|
||||
ip: String,
|
||||
event_tx: Sender<NetworkEvent>,
|
||||
) {
|
||||
let crypto_pair = sd.cryptopair_ref();
|
||||
let senders = sd.senders_ref();
|
||||
let messages_list = sd.messages_list_ref();
|
||||
let id = generate_id();
|
||||
let server_addr_query = get_socket_address(username.clone(), ip.clone());
|
||||
|
||||
match server_addr_query.await {
|
||||
Ok(sockaddr_bytes) => {
|
||||
match String::from_utf8(sockaddr_bytes.to_vec()) {
|
||||
Ok(s) => {
|
||||
let addresses = parse_addresses(&s);
|
||||
if let Some(first) = addresses.first() {
|
||||
sd.set_servername(username);
|
||||
// first: &SocketAddr
|
||||
let mut payload = Vec::new();
|
||||
payload.extend_from_slice(&0u32.to_be_bytes());
|
||||
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes());
|
||||
let hello_handshake = construct_message(1, payload, id, crypto_pair);
|
||||
match hello_handshake {
|
||||
Some(handshake_message) => {
|
||||
senders.send_via(0, handshake_message, server_uri, false);
|
||||
senders.send_via(
|
||||
0,
|
||||
handshake_message,
|
||||
first.to_string(),
|
||||
false,
|
||||
messages_list,
|
||||
);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
//let res = event_tx
|
||||
// .send(NetworkEvent::());
|
||||
} else {
|
||||
//let res = event_tx.send(NetworkEvent::Error());
|
||||
let err_msg =
|
||||
format!("no valid socket addresses found in: {}", s).to_string();
|
||||
let res = event_tx.send(NetworkEvent::Error(err_msg));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
//let res = event_tx.send(NetworkEvent::Error());
|
||||
let err_msg =
|
||||
format!("invalid UTF-8 in socket address bytes: {}", e).to_string();
|
||||
let res = event_tx.send(NetworkEvent::Error(err_msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let err_msg = format!("failed to retreive socket address: {}", e).to_string();
|
||||
let res = event_tx.send(NetworkEvent::Error(err_msg));
|
||||
}
|
||||
}
|
||||
|
||||
/*let mut list = messages_list.lock().expect("Failed to lock messages_list");
|
||||
match list.get(&id) {
|
||||
Some(_) => {
|
||||
|
||||
Reference in New Issue
Block a user