26 Commits

Author SHA1 Message Date
TIBERGHIEN corentin
aec686b502 fix out of boudns 2026-01-24 23:59:15 +01:00
Tiago Batista Cardoso
95c2dfe83c pretty 2026-01-24 23:04:01 +01:00
Tiago Batista Cardoso
7a1155c0bd carre 2026-01-24 22:32:01 +01:00
Tiago Batista Cardoso
a3648c2116 working 2026-01-24 20:09:36 +01:00
Tiago Batista Cardoso
f8e3e46672 decent progress 2026-01-24 19:54:00 +01:00
Tiago Batista Cardoso
9ba752641b tried 2026-01-24 19:54:00 +01:00
Tiago Batista Cardoso
5899a275a2 give up 2026-01-24 19:54:00 +01:00
Tiago Batista Cardoso
da29d67472 wip 2026-01-24 19:54:00 +01:00
Tiago Batista Cardoso
b465608797 splash 2026-01-24 19:54:00 +01:00
Tiago Batista Cardoso
732daf0578 work 2026-01-24 19:53:30 +01:00
Tiago Batista Cardoso
65447912bf temp 2026-01-24 19:52:32 +01:00
TIBERGHIEN corentin
c928d98b56 wip big download 2026-01-24 16:50:56 +01:00
TIBERGHIEN corentin
31b26e96b0 file system and file donload 2026-01-23 01:11:02 +01:00
TIBERGHIEN corentin
26fa7a833f datum parsing 2026-01-22 03:19:43 +01:00
TIBERGHIEN corentin
fb2c3310af ping deadlock 2026-01-21 23:19:29 +01:00
Tiago Batista Cardoso
bdb800a986 fixed deprecated function use 2026-01-21 17:03:07 +01:00
TIBERGHIEN corentin
8b2ab4861b zzzz 2026-01-21 02:45:48 +01:00
TIBERGHIEN corentin
dacedd1ceb exp backoff and theads handling 2026-01-20 01:10:09 +01:00
08518892f2 Merge pull request 'nat_transversal' (#3) from nat_transversal into master
Reviewed-on: #3
2026-01-16 10:20:01 +00:00
TIBERGHIEN corentin
14fa256f9c wip nattraversal 2026-01-16 11:19:20 +01:00
Tiago Batista Cardoso
29c67e340c update 2026-01-16 11:18:45 +01:00
Tiago Batista Cardoso
be7430fdc6 peer address in nat traversal 2026-01-16 11:18:44 +01:00
Tiago Batista Cardoso
60145f279a implementation 2026-01-16 11:15:56 +01:00
Tiago Batista Cardoso
003d55bd75 thing 2026-01-16 10:55:56 +01:00
b61e1b1036 Merge pull request 'tmp' (#2) from tmp into master
Reviewed-on: #2
2026-01-16 09:54:46 +00:00
0c601a76b8 Merge pull request 'tmp' (#1) from tmp into master
Reviewed-on: #1
2026-01-11 20:58:30 +00:00
17 changed files with 2486 additions and 1063 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
/target
target/

View File

@@ -1,13 +1,17 @@
use client_network::{
ChunkNode, MerkleNode, MerkleTree, NetworkCommand, NetworkEvent, NodeHash, filename_to_string,
node_hash_to_hex_string,
ChunkNode, MerkleNode, MerkleTree, NetworkCommand, NetworkEvent, NodeHash,
big_or_chunk_to_file, filename_to_string, generate_base_tree, node_hash_to_hex_string,
node_to_file, remove_null_bytes,
};
use crossbeam_channel::{Receiver, Sender};
use egui::{
Align, Align2, Button, CentralPanel, CollapsingHeader, Context, Id, LayerId, Layout, Order,
Popup, ScrollArea, SidePanel, TextStyle, TopBottomPanel, Ui, ViewportCommand,
Align, CentralPanel, CollapsingHeader, Color32, Context, CornerRadius, Frame, Layout, Response,
ScrollArea, SidePanel, Stroke, TopBottomPanel, Ui, ViewportCommand,
};
use std::{collections::HashMap, fmt::format};
use std::collections::HashSet;
use std::{collections::HashMap, fmt::format, io::Seek};
use std::fs::{File, OpenOptions, create_dir};
enum ServerStatus {
Loading,
@@ -27,13 +31,15 @@ pub struct P2PClientApp {
// GUI State
status_message: String,
known_peers: Vec<String>,
known_peers: Vec<(String, bool)>,
loading_peers: Vec<String>,
connect_address_input: String,
connected_address: String,
connect_name_input: String,
// Key: Parent Directory Hash (String), Value: List of children FileNode
loaded_fs: HashMap<String, MerkleTree>,
shared_tree: MerkleTree,
// Current peer tree displayed
active_peer: Option<String>,
@@ -42,9 +48,13 @@ pub struct P2PClientApp {
show_network_popup: bool, // gérer selon besoin
error_message: Option<String>, // Some(message) -> afficher, None -> rien
//
error_message: Option<(String, String)>, // Some(message) -> afficher, None -> rien
success_message: Option<(String, String)>, // Some(message) -> afficher, None -> rien
active_server: String,
current_downloading_file_map: MerkleTree,
remaining_chunks: HashSet<[u8; 32]>,
root_downloading_file: String,
}
impl P2PClientApp {
@@ -52,6 +62,7 @@ impl P2PClientApp {
//let (root_hash, tree_content) = MerkleNode::generate_base_tree();
let mut loaded_fs = HashMap::new();
let mut current_downloading_file_map = MerkleTree::new(HashMap::new(), [0; 32]);
//let tree = MerkleTree::new(tree_content, root_hash);
//loaded_fs.insert("bob".to_string(), tree);
@@ -62,7 +73,8 @@ impl P2PClientApp {
network_cmd_tx: cmd_tx,
network_event_rx: event_rx,
status_message: "Client Initialized. Awaiting network status...".to_string(),
known_peers: vec!["bob".to_string()],
known_peers: Vec::new(),
loading_peers: Vec::new(),
connect_address_input: "https://jch.irif.fr:8443".to_string(),
connected_address: "".to_string(),
loaded_fs,
@@ -70,16 +82,27 @@ impl P2PClientApp {
server_status: ServerStatus::NotConnected,
show_network_popup: false,
error_message: None,
success_message: None,
connect_name_input: "bob".to_string(),
active_server: "".to_string(),
shared_tree: generate_base_tree(),
current_downloading_file_map: current_downloading_file_map,
root_downloading_file: "".to_string(),
remaining_chunks: HashSet::new(),
}
}
pub fn show_error(&mut self, msg: impl Into<String>) {
self.error_message = Some(msg.into());
pub fn show_error(&mut self, msg: impl Into<String>, peer_username: impl Into<String>) {
self.error_message = Some((msg.into(), peer_username.into()));
}
pub fn show_success(&mut self, msg: impl Into<String>, peer_username: impl Into<String>) {
self.success_message = Some((msg.into(), peer_username.into()));
}
pub fn clear_error(&mut self) {
self.error_message = None;
}
pub fn clear_success(&mut self) {
self.success_message = None;
}
}
// --- eframe::App Trait Implementation ---
@@ -111,8 +134,32 @@ impl eframe::App for P2PClientApp {
todo!();
self.status_message = format!("✅ Peer connected: {}", addr);
if !self.known_peers.contains(&addr) {
self.known_peers.push(addr);
if !self.known_peers.contains(&(addr, true)) {
self.known_peers.push((addr, true));
}
}
NetworkEvent::RootRequest(addr) => {
let root = self.shared_tree.root;
let _ = self
.network_cmd_tx
.send(NetworkCommand::SendRootReply(root.to_vec(), addr));
}
NetworkEvent::DatumRequest(node_hash, addr) => {
let hash: NodeHash = node_hash.try_into().expect("incorrect size");
let asked_datum = self.shared_tree.data.get(&hash);
match asked_datum {
Some(datum_found) => {
let _ = self.network_cmd_tx.send(NetworkCommand::SendDatum(
datum_found.clone(),
node_hash,
addr,
));
}
None => {
let _ = self
.network_cmd_tx
.send(NetworkCommand::SendNoDatum(node_hash.to_vec(), addr));
}
}
}
NetworkEvent::PeerListUpdated(peers) => {
@@ -120,11 +167,41 @@ impl eframe::App for P2PClientApp {
self.known_peers = peers;
}
NetworkEvent::FileTreeReceived(_peer_id, _) => {
todo!();
//self.loaded_tree_nodes.insert(_peer_id, tree);
//self.status_message = "🔄 File tree updated successfully.".to_string();
NetworkEvent::FileTreeReceived(node_hash, merklenode, ip) => {
match &self.active_peer {
Some(active_peer) => {
if let Some(maptree) = self.loaded_fs.get_mut(active_peer) {
maptree.data.insert(node_hash, merklenode.clone());
match merklenode {
MerkleNode::Directory(d) => {
for entry in d.entries {
let _ = self.network_cmd_tx.send(
NetworkCommand::GetChildren(
entry.content_hash,
ip.clone(),
false,
),
);
}
}
MerkleNode::BigDirectory(bigd) => {
for entry in bigd.children_hashes {
let _ = self.network_cmd_tx.send(
NetworkCommand::GetChildren(
entry,
ip.clone(),
false,
),
);
}
}
_ => {}
}
}
}
None => {}
}
}
NetworkEvent::FileTreeRootReceived(peer_id, root_hash) => {
// todo!();
@@ -136,8 +213,10 @@ impl eframe::App for P2PClientApp {
);*/
if let Ok(chunknode) = ChunkNode::new(Vec::new()) {
let mut data_map: HashMap<NodeHash, MerkleNode> = HashMap::new();
data_map.insert(root_hash, MerkleNode::Chunk(chunknode));
let data_map: HashMap<NodeHash, MerkleNode> = HashMap::new();
//data_map.insert(root_hash, MerkleNode::Chunk(chunknode));
println!("len root: {}", data_map.len());
println!("node hash: {:?}", root_hash.to_vec());
let tree = MerkleTree {
data: data_map,
root: root_hash,
@@ -175,16 +254,88 @@ impl eframe::App for P2PClientApp {
self.known_peers.clear();
self.server_status = ServerStatus::NotConnected;
}
NetworkEvent::Error(err) => {
self.show_error(err);
NetworkEvent::Error(err, peer_username) => {
self.loading_peers.retain(|s| s != peer_username.as_str());
self.show_error(err, peer_username);
}
NetworkEvent::InitDownload(hash, ip, name) => {
if let Some(addr) = &self.active_peer {
if let Some(roottree) = self.loaded_fs.get(addr) {
if let Some(root) = roottree.data.get(&hash) {
self.root_downloading_file = name;
let _ = self
.current_downloading_file_map
.data
.insert(hash, root.clone());
let _ = self
.network_cmd_tx
.send(NetworkCommand::GetChildren(hash, ip, true));
}
}
}
}
NetworkEvent::DataReceived(hash, merkle_node, ip) => {
let _ = self
.current_downloading_file_map
.data
.insert(hash, merkle_node.clone());
println!("merkle:{}", merkle_node.get_type_byte());
match merkle_node {
MerkleNode::Big(bigfile) => {
for entry in bigfile.children_hashes {
println!("entry: {:?}", entry);
let _ = self.network_cmd_tx.send(NetworkCommand::GetChildren(
entry,
ip.clone(),
true,
));
self.remaining_chunks.insert(entry);
}
self.remaining_chunks.remove(&hash);
}
MerkleNode::Chunk(chunk) => {
self.remaining_chunks.remove(&hash);
}
_ => {}
}
if self.remaining_chunks.is_empty() {
/*let file = OpenOptions::new()
.append(true)
.create(true)
.open(self.root_downloading_file.clone());
if let Some(current) = self
.current_downloading_file_map
.data
.get(&self.current_downloading_file_map.root)
{
match file {
Ok(mut fileok) => {
big_or_chunk_to_file(
&self.current_downloading_file_map,
current,
&mut fileok,
);
}
Err(e) => {
eprintln!("error creaation file: {}", e);
}
}
}*/
println!("bigfile téléchargé");
}
}
NetworkEvent::Success(msg, peer_username) => {
self.loading_peers.retain(|s| s != peer_username.as_str());
self.show_success(msg, peer_username);
}
NetworkEvent::DataReceived(_, merkle_node) => todo!(),
NetworkEvent::HandshakeFailed() => {}
NetworkEvent::ServerHandshakeFailed(err) => {
self.active_server = "".to_string();
self.server_status = ServerStatus::NotConnected;
let err_msg = format!("Failed to connect to the server: {}", err);
self.show_error(err_msg);
self.show_error(err_msg, "");
let res = self.network_cmd_tx.send(NetworkCommand::ResetServerPeer());
}
}
@@ -245,64 +396,7 @@ impl eframe::App for P2PClientApp {
}
_ => {}
}
/* ui.horizontal(|ui| {
ui.label("Server peer name:");
ui.text_edit_singleline(&mut self.connect_server_name_input);
if ui.button("Connect").clicked() {
let addr = self.connect_address_input.clone();
let serv_name = self.connect_server_name_input.clone();
let _ = self
.network_cmd_tx
.send(NetworkCommand::ConnectToServer(addr, serv_name));
self.server_status = ServerStatus::Loading;
ui.close();
}
});*/
});
// état
/*if ui.button("Network").clicked() {
self.show_network_popup = true;
}*/
/*if self.show_network_popup {
egui::Window::new("Network")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.horizontal_wrapped(|ui| {
ui.with_layout(
egui::Layout::right_to_left(egui::Align::TOP),
|ui| {
if ui.button("✕").clicked() {
self.show_network_popup = false;
}
},
);
});
ui.horizontal(|ui| {
ui.label("Server IP:");
ui.text_edit_singleline(&mut self.connect_address_input);
});
ui.horizontal(|ui| {
ui.label("Server peer name:");
ui.text_edit_singleline(&mut self.connect_server_name_input);
if ui.button("Connect").clicked() {
// envoyer commande...
let addr = self.connect_address_input.clone();
let serv_name = self.connect_server_name_input.clone();
let _ = self
.network_cmd_tx
.send(NetworkCommand::ConnectToServer(addr, serv_name));
self.server_status = ServerStatus::Loading;
self.show_network_popup = false;
}
});
});
}*/
});
});
@@ -350,6 +444,11 @@ impl eframe::App for P2PClientApp {
error.to_string()
);
}
if let Some(active_peer) = &self.active_peer {
if let Some(tree) = self.loaded_fs.get(active_peer) {
println!("{}", tree.data.len());
}
}
}
});
@@ -361,56 +460,204 @@ impl eframe::App for P2PClientApp {
} else {
for peer in &self.known_peers {
let is_active =
self.active_peer.as_ref().map_or(false, |id| id == peer); // if peer.id == self.active_peer_id
self.active_peer.as_ref().map_or(false, |id| id == &peer.0); // if peer.id == self.active_peer_id
let selectable;
if &self.active_server == peer {
selectable =
ui.selectable_label(is_active, format!("{} 📡 🌀", peer))
} else {
selectable = ui.selectable_label(is_active, format!("{}", peer));
}
if selectable.clicked() {
// switch to displaying this peer's tree
self.active_peer = Some(peer.clone());
// Request root content if not loaded
if !self
.loaded_fs
.contains_key(self.active_peer.as_ref().unwrap())
{
//todo!();
let _ = self.network_cmd_tx.send(NetworkCommand::Discover(
peer.clone(),
"root".to_string(),
self.connected_address.clone(),
));
let selectable: Response;
// if &self.active_server == &peer.0 {
// // Create a frame with green background and render the selectable inside it.
// // Adjust rounding, padding and stroke as desired.
// let frame = Frame {
// fill: Color32::DARK_BLUE,
// stroke: Stroke::default(),
// corner_radius: CornerRadius::from(0.5),
// ..Default::default()
// };
// let internal = frame.show(ui, |ui| {
// // horizontal row: label on the left, spinner on the right
// ui.horizontal(|ui| {
// // let selectable label take remaining space
// ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
// ui.add_space(0.0); // ensure layout established
// return ui.selectable_label(
// is_active,
// format!("{}", peer.0),
// );
// })
// .inner // return Response from the inner closure if your egui version does so
// })
// });
// selectable = internal.inner.inner;
// } else {
// selectable = ui.selectable_label(is_active, format!("{}", peer.0));
// }
// place spinner to the right of the label
ui.horizontal(|ui| {
// Use same width for the label widget as the selectable we already created:
// Recreate selectable inline so both label and spinner share the same row.
let resp = if &self.active_server == &peer.0 {
// draw with frame inline
let frame = Frame {
fill: Color32::DARK_BLUE,
stroke: Stroke::default(),
corner_radius: CornerRadius::from(0.5),
..Default::default()
};
frame
.show(ui, |ui| {
ui.selectable_label(is_active, format!("{}", peer.0))
})
.inner
} else {
ui.selectable_label(is_active, format!("{}", peer.0))
};
ui.add_space(4.0); // small gap
if self.loading_peers.contains(&peer.0) {
// push spinner to right by expanding a spacer before it
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.spinner();
});
}
}
selectable.context_menu(|ui| {
// ... action
match self.server_status {
ServerStatus::Connected => {
if ui
.button("Utiliser le peer en tant que serveur")
.clicked()
{
self.active_server = peer.to_string();
let res = self.network_cmd_tx.send(
NetworkCommand::ServerHandshake(
peer.to_string(),
self.connected_address.clone(),
),
);
// use resp (click handling etc.)
if resp.clicked() {
// switch to displaying this peer's tree
self.active_peer = Some(peer.0.clone());
// Request root content if not loaded
if !self
.loaded_fs
.contains_key(self.active_peer.as_ref().unwrap())
{
//todo!();
let _ = self.network_cmd_tx.send(NetworkCommand::Discover(
peer.0.clone(),
"root".to_string(),
self.connected_address.clone(),
));
}
}
resp.context_menu(|ui| {
// ... action
match self.server_status {
ServerStatus::Connected => {
if ui
.button("Utiliser le peer en tant que serveur")
.clicked()
{
self.active_server = peer.0.to_string();
let res = self.network_cmd_tx.send(
NetworkCommand::ServerHandshake(
peer.0.to_string(),
self.connected_address.clone(),
),
);
}
}
_ => {}
}
if ui.button("Send Ping").clicked() {
let res = self.network_cmd_tx.send(NetworkCommand::Ping(
peer.0.to_string(),
self.connected_address.clone(),
));
self.loading_peers.push(peer.0.to_owned());
}
if ui.button("Send Nat Traversal Request").clicked() {
match self.network_cmd_tx.send(
NetworkCommand::NatTraversal(
peer.0.to_string(),
self.connected_address.clone(),
),
) {
Ok(_) => {
print!(
"[+] successfully sent nat traversal request"
)
}
Err(_) => {
print!("[-] failed to send nat traversal request")
}
}
}
_ => {}
}
if ui.button("Infos").clicked() {
// action 3
ui.close();
}
// ... autres boutons
if ui.button("Infos").clicked() {
// action 3
ui.close();
}
// ... autres boutons
});
});
// if self.loading_peers.contains(&peer.0) {
// ui.spinner();
// }
//if selectable.clicked() {
// switch to displaying this peer's tree
//self.active_peer = Some(peer.0.clone());
//// Request root content if not loaded
//if !self
// .loaded_fs
// .contains_key(self.active_peer.as_ref().unwrap())
//{
// //todo!();
// let _ = self.network_cmd_tx.send(NetworkCommand::Discover(
// peer.0.clone(),
// "root".to_string(),
// self.connected_address.clone(),
// ));
//}
//}
//selectable.context_menu(|ui| {
// // ... action
// match self.server_status {
// ServerStatus::Connected => {
// if ui
// .button("Utiliser le peer en tant que serveur")
// .clicked()
// {
// self.active_server = peer.0.to_string();
// let res = self.network_cmd_tx.send(
// NetworkCommand::ServerHandshake(
// peer.0.to_string(),
// self.connected_address.clone(),
// ),
// );
// }
// }
// _ => {}
// }
// if ui.button("Send Ping").clicked() {
// let res = self.network_cmd_tx.send(NetworkCommand::Ping(
// peer.0.to_string(),
// self.connected_address.clone(),
// ));
// self.loading_peers.push(peer.0.to_owned());
// }
// if ui.button("Send Nat Traversal Request").clicked() {
// match self.network_cmd_tx.send(NetworkCommand::NatTraversal(
// peer.0.to_string(),
// self.connected_address.clone(),
// )) {
// Ok(_) => {
// print!("[+] successfully sent nat traversal request")
// }
// Err(_) => {
// print!("[-] failed to send nat traversal request")
// }
// }
// }
// if ui.button("Infos").clicked() {
// // action 3
// ui.close();
// }
// // ... autres boutons
//});
}
}
});
@@ -452,13 +699,29 @@ impl eframe::App for P2PClientApp {
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
ui.label(&msg);
ui.label(&msg.1);
ui.label(&msg.0);
if ui.button("OK").clicked() {
self.clear_error();
}
});
ctx.request_repaint();
}
if let Some(msg) = &self.success_message {
let msg = msg.clone();
egui::Window::new("Success")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
ui.label(&msg.1);
ui.label(&msg.0);
if ui.button("OK").clicked() {
self.clear_success();
}
});
ctx.request_repaint();
}
ctx.request_repaint_after(std::time::Duration::from_millis(10));
}
@@ -497,11 +760,12 @@ impl P2PClientApp {
if let Some(current) = tree.data.get(&to_draw) {
let name = {
if filename.is_some() {
filename_to_string(filename.unwrap())
String::from_utf8(filename.unwrap().to_vec()).expect("err")
} else {
node_hash_to_hex_string(&to_draw)
}
};
match current {
MerkleNode::Chunk(node) => {
if ui
@@ -509,11 +773,30 @@ impl P2PClientApp {
.on_hover_text("Click to request file chunks...")
.clicked()
{
todo!();
match create_dir("./Download/") {
Ok(_) => println!("Directory created successfully!"),
Err(e) => println!("Failed to create directory: {}", e),
}
let new_name = format!("./Download/{}", name);
let sani = remove_null_bytes(&new_name);
println!("sani:{}", sani);
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(sani)
.unwrap();
big_or_chunk_to_file(tree, &MerkleNode::Chunk(node.clone()), &mut file);
// if let Some(peer_id) = active_peer_id.clone() {
// let _ = self.network_cmd_tx.send(NetworkCommand::RequestChunk(peer_id, entry_hash.clone()));
// // self.status_message = format!("Requested file chunks for: {}...", &entry_hash[..8]);
// }
// todo!();
}
}
MerkleNode::Directory(node) => {
@@ -527,19 +810,32 @@ impl P2PClientApp {
entry.content_hash,
tree,
depth + 1,
Some(
entry
.filename
.as_slice()
.try_into()
.expect("incorrect size"),
),
Some(entry.filename.try_into().expect("incorrect size")),
);
}
});
}
MerkleNode::Big(node) => {
CollapsingHeader::new(format!("📄 (B) {}", name))
if ui
.selectable_label(false, format!("📄 (B) {}", name))
.on_hover_text("Click to request file chunks...")
.clicked()
{
if let Some(name) = filename {
if let Ok(nameb) = String::from_utf8(name.to_vec()) {
if let Some(addr) = &self.active_peer {
let _ = self.network_cmd_tx.send(NetworkCommand::InitDownload(
to_draw,
addr.clone(),
nameb,
));
}
}
}
}
}
MerkleNode::BigDirectory(node) => {
CollapsingHeader::new(format!("📁 (BD) {}", name))
.default_open(false)
.enabled(true)
.show(ui, |ui| {
@@ -548,16 +844,6 @@ impl P2PClientApp {
}
});
}
MerkleNode::BigDirectory(node) => {
CollapsingHeader::new(format!("📁 (BD) {}", name))
.default_open(false)
.enabled(true)
.show(ui, |ui| {
for child in &node.children_hashes {
self.draw_file_node(ui, child.content_hash, tree, depth + 1, None);
}
});
}
}
}
}

View File

@@ -134,7 +134,7 @@ pub fn sign_message(crypto_pair: &CryptographicSignature, message: &Vec<u8>) ->
#[cfg(test)]
mod tests {
use super::*;
/*
///
/// creates a cryptographic signature
///
@@ -144,7 +144,7 @@ mod tests {
let crypto_pair = CryptographicSignature::new(username);
let formatted_pubkey = formatPubKey(crypto_pair);
println!("pubkey : {}", formatted_pubkey);
}
}*/
/*#[test]
fn signing_message() {

View File

@@ -1,17 +1,199 @@
use rand::{Rng, rng};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::fs::{File, OpenOptions, create_dir};
use std::io::{self, Write};
use std::env;
use crate::data;
// --- Constants ---
const MAX_CHUNK_DATA_SIZE: usize = 1024;
const MAX_DIRECTORY_ENTRIES: usize = 16;
const MAX_BIG_CHILDREN: usize = 32;
const MIN_BIG_CHILDREN: usize = 2;
const FILENAME_HASH_SIZE: usize = 32;
const DIRECTORY_ENTRY_SIZE: usize = FILENAME_HASH_SIZE * 2; // 64 bytes
pub const MAX_CHUNK_DATA_SIZE: usize = 1024;
pub const MAX_DIRECTORY_ENTRIES: usize = 16;
pub const MAX_BIG_CHILDREN: usize = 32;
pub const MIN_BIG_CHILDREN: usize = 2;
pub const FILENAME_HASH_SIZE: usize = 32;
pub const DIRECTORY_ENTRY_SIZE: usize = FILENAME_HASH_SIZE * 2; // 64 bytes
pub type NodeHash = [u8; FILENAME_HASH_SIZE];
pub fn node_hash_to_hex_string(hash: &NodeHash) -> String {
hash.iter().map(|b| format!("{:02x}", b)).collect()
}
#[repr(u8)]
#[derive(Debug, Clone)]
pub enum MerkleNode {
// up to 1024 bytes of raw data.
Chunk(ChunkNode) = 0,
// 0 to 16 directory entries.
Directory(DirectoryNode) = 1,
// list of 2 to 32 hashes pointing to Chunk or Big nodes.
Big(BigNode) = 2,
// list of 2 to 32 hashes pointing to Directory or BigDirectory nodes.
BigDirectory(BigDirectoryNode) = 3,
}
#[derive(Debug, Clone)]
pub struct MerkleTree {
pub data: HashMap<NodeHash, MerkleNode>,
pub root: NodeHash,
}
impl MerkleTree {
pub fn new(data: HashMap<NodeHash, MerkleNode>, root: NodeHash) -> MerkleTree {
MerkleTree { data, root }
}
pub fn clear_data(&mut self) {
self.data.clear();
}
}
#[derive(Debug, Clone)]
pub struct ChunkNode {
pub data: Vec<u8>,
}
impl ChunkNode {
pub fn new(data: Vec<u8>) -> Result<Self, String> {
if data.len() > MAX_CHUNK_DATA_SIZE {
return Err(format!("Chunk data exceeds {} bytes", data.len()));
}
Ok(ChunkNode { data })
}
pub fn new_random() -> Self {
let mut rng = rand::rng();
// Determine a random length between 1 and MAX_CHUNK_DATA_SIZE (inclusive).
// Using +1 ensures the range is up to 1024.
let random_len = rng.random_range(1..=MAX_CHUNK_DATA_SIZE);
// Initialize a vector with the random length
let mut data = vec![0u8; random_len];
// Fill the vector with random bytes
rng.fill(&mut data[..]);
// Since we generated the length based on MAX_CHUNK_DATA_SIZE,
// this is guaranteed to be valid and doesn't need to return a Result.
ChunkNode { data }
}
}
// Helper struct
#[derive(Debug, Clone)]
pub struct DirectoryEntry {
pub filename: [u8; FILENAME_HASH_SIZE],
pub content_hash: NodeHash,
}
pub fn filename_to_string(filename: [u8; FILENAME_HASH_SIZE]) -> String {
let end_index = filename
.iter()
.position(|&b| b == 0)
.unwrap_or(FILENAME_HASH_SIZE);
String::from_utf8_lossy(&filename[..end_index]).to_string()
}
#[derive(Debug, Clone)]
pub struct DirectoryNode {
pub entries: Vec<DirectoryEntry>,
}
impl DirectoryNode {
pub fn new(entries: Vec<DirectoryEntry>) -> Result<Self, String> {
if entries.len() > MAX_DIRECTORY_ENTRIES {
return Err(format!("Directory exceeds {} bytes", entries.len()));
}
Ok(DirectoryNode { entries })
}
}
#[derive(Debug, Clone)]
pub struct BigNode {
pub children_hashes: Vec<NodeHash>,
}
impl BigNode {
pub fn new(children_hashes: Vec<NodeHash>) -> Result<Self, String> {
let n = children_hashes.len();
if n < MIN_BIG_CHILDREN || n > MAX_BIG_CHILDREN {
return Err(format!(
"Big node must have between {} and {} children, found {}",
MIN_BIG_CHILDREN, MAX_BIG_CHILDREN, n
));
}
Ok(BigNode { children_hashes })
}
}
#[derive(Debug, Clone)]
pub struct BigDirectoryNode {
pub children_hashes: Vec<NodeHash>,
// pub children_hashes: Vec<DirectoryEntry>,
}
impl BigDirectoryNode {
pub fn new(children_hashes: Vec<NodeHash>) -> Result<Self, String> {
let n = children_hashes.len();
if n < MIN_BIG_CHILDREN || n > MAX_BIG_CHILDREN {
return Err(format!(
"BigDirectory node must have between {} and {} children, found {}",
MIN_BIG_CHILDREN, MAX_BIG_CHILDREN, n
));
}
Ok(BigDirectoryNode { children_hashes })
}
}
impl MerkleNode {
pub fn get_type_byte(&self) -> u8 {
match self {
MerkleNode::Chunk(_) => 0,
MerkleNode::Directory(_) => 1,
MerkleNode::Big(_) => 2,
MerkleNode::BigDirectory(_) => 3,
}
}
pub fn serialize(&self) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.push(self.get_type_byte());
match self {
MerkleNode::Chunk(node) => {
bytes.extend_from_slice(&node.data);
}
MerkleNode::Directory(node) => {
for entry in &node.entries {
bytes.extend_from_slice(&entry.filename);
bytes.extend_from_slice(&entry.content_hash);
}
}
MerkleNode::Big(node) => {
for hash in &node.children_hashes {
bytes.extend_from_slice(hash);
}
}
MerkleNode::BigDirectory(node) => {
for hash in &node.children_hashes {
bytes.extend_from_slice(hash);
}
}
}
bytes
}
}
fn hash(data: &[u8]) -> NodeHash {
let mut hasher = DefaultHasher::new();
let root_hash = Sha256::digest(&data);
println!("root hash: {:?}", root_hash);
let res: NodeHash = root_hash.try_into().expect("incorrect size");
res
/*let mut hasher = DefaultHasher::new();
data.hash(&mut hasher);
let hash_u64 = hasher.finish();
@@ -21,6 +203,7 @@ fn hash(data: &[u8]) -> NodeHash {
hash_array[i] = (hash_u64 >> (i * 8)) as u8;
}
hash_array // The rest remains 0, satisfying the 32-byte requirement
*/
}
fn generate_random_filename() -> [u8; FILENAME_HASH_SIZE] {
@@ -49,38 +232,7 @@ fn generate_random_filename() -> [u8; FILENAME_HASH_SIZE] {
filename_bytes
}
pub type NodeHash = [u8; FILENAME_HASH_SIZE];
pub fn node_hash_to_hex_string(hash: &NodeHash) -> String {
hash.iter().map(|b| format!("{:02x}", b)).collect()
}
#[repr(u8)]
#[derive(Debug, Clone)]
pub enum MerkleNode {
// up to 1024 bytes of raw data.
Chunk(ChunkNode) = 0,
// 0 to 16 directory entries.
Directory(DirectoryNode) = 1,
// list of 2 to 32 hashes pointing to Chunk or Big nodes.
Big(BigNode) = 3,
// list of 2 to 32 hashes pointing to Directory or BigDirectory nodes.
BigDirectory(BigDirectoryNode) = 4,
}
#[derive(Debug, Clone)]
pub struct MerkleTree {
pub data: HashMap<NodeHash, MerkleNode>,
pub root: NodeHash,
}
impl MerkleTree {
pub fn new(data: HashMap<NodeHash, MerkleNode>, root: NodeHash) -> MerkleTree {
MerkleTree { data, root }
}
}
/*fn generate_random_file_node(
fn generate_random_file_node(
storage: &mut HashMap<NodeHash, MerkleNode>,
) -> Result<NodeHash, String> {
let mut rng = rng();
@@ -110,9 +262,9 @@ impl MerkleTree {
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,211 +324,199 @@ impl MerkleTree {
storage.insert(hash, node);
Ok(hash)
}
}*/
#[derive(Debug, Clone)]
pub struct ChunkNode {
pub data: Vec<u8>,
}
impl ChunkNode {
pub fn new(data: Vec<u8>) -> Result<Self, String> {
if data.len() > MAX_CHUNK_DATA_SIZE {
return Err(format!("Chunk data exceeds {} bytes", data.len()));
pub fn generate_random_tree(
max_depth: u32,
) -> Result<(NodeHash, HashMap<NodeHash, MerkleNode>), String> {
let mut storage = HashMap::new();
// Start tree generation from the root directory at depth 0
let root_hash = generate_random_directory_node(0, max_depth, &mut storage)?;
Ok((root_hash, storage))
}
pub fn generate_base_tree() -> MerkleTree {
let mut res = HashMap::new();
let bob_content = "where is bob".to_string().into_bytes();
let alice_content = "alice".to_string().into_bytes();
let oscar_content = "oscar is the opponent".to_string().into_bytes();
let mut children_nodes = Vec::new();
for i in 0..10 {
let mut i_nodes = Vec::new();
for j in 0..10 {
let node1 = MerkleNode::Chunk(ChunkNode::new(bob_content.clone()).unwrap());
let hash = hash(&node1.serialize());
i_nodes.push(hash);
res.insert(hash, node1);
}
Ok(ChunkNode { data })
let bignode = MerkleNode::Big(BigNode::new(i_nodes).unwrap());
let hashbig = hash(&bignode.serialize());
children_nodes.push(hashbig);
res.insert(hashbig, bignode);
}
pub fn new_random() -> Self {
let mut rng = rand::rng();
let bignode = MerkleNode::Big(BigNode::new(children_nodes).unwrap());
let hashbig = hash(&bignode.serialize());
// Determine a random length between 1 and MAX_CHUNK_DATA_SIZE (inclusive).
// Using +1 ensures the range is up to 1024.
let random_len = rng.random_range(1..=MAX_CHUNK_DATA_SIZE);
let node1 = MerkleNode::Chunk(ChunkNode::new(bob_content).unwrap());
let hash1 = hash(&node1.serialize());
// Initialize a vector with the random length
let mut data = vec![0u8; random_len];
let node2 = MerkleNode::Chunk(ChunkNode::new(alice_content).unwrap());
let hash2 = hash(&node2.serialize());
// Fill the vector with random bytes
rng.fill(&mut data[..]);
//res.insert(hash1, node1);
//res.insert(hash2, node2);
res.insert(hashbig, bignode);
// Since we generated the length based on MAX_CHUNK_DATA_SIZE,
// this is guaranteed to be valid and doesn't need to return a Result.
ChunkNode { data }
}
}
let node3 = MerkleNode::Chunk(ChunkNode::new(oscar_content).unwrap());
let hash3 = hash(&node3.serialize());
// Helper struct
#[derive(Debug, Clone)]
pub struct DirectoryEntry {
pub filename: Vec<u8>,
pub content_hash: NodeHash,
}
//res.insert(hash3, node3);
pub fn filename_to_string(filename: [u8; FILENAME_HASH_SIZE]) -> String {
let end_index = filename
.iter()
.position(|&b| b == 0)
.unwrap_or(FILENAME_HASH_SIZE);
String::from_utf8_lossy(&filename[..end_index]).to_string()
}
let dir1 = MerkleNode::Directory(DirectoryNode {
entries: [DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash3,
}]
.to_vec(),
});
let hash_dir1 = hash(&dir1.serialize());
#[derive(Debug, Clone)]
pub struct DirectoryNode {
pub entries: Vec<DirectoryEntry>,
}
//res.insert(hash_dir1, dir1);
impl DirectoryNode {
pub fn new(entries: Vec<DirectoryEntry>) -> Result<Self, String> {
if entries.len() > MAX_DIRECTORY_ENTRIES {
return Err(format!("Directory exceeds {} bytes", entries.len()));
}
Ok(DirectoryNode { entries })
}
}
#[derive(Debug, Clone)]
pub struct BigNode {
pub children_hashes: Vec<NodeHash>,
}
impl BigNode {
/*pub fn new(children_hashes: Vec<NodeHash>) -> Result<Self, String> {
let n = children_hashes.len();
if n < MIN_BIG_CHILDREN || n > MAX_BIG_CHILDREN {
return Err(format!(
"Big node must have between {} and {} children, found {}",
MIN_BIG_CHILDREN, MAX_BIG_CHILDREN, n
));
}
Ok(BigNode { children_hashes })
}*/
}
#[derive(Debug, Clone)]
pub struct BigDirectoryNode {
//pub children_hashes: Vec<NodeHash>,
pub children_hashes: Vec<DirectoryEntry>,
}
impl BigDirectoryNode {
/*pub fn new(children_hashes: Vec<NodeHash>) -> Result<Self, String> {
let n = children_hashes.len();
if n < MIN_BIG_CHILDREN || n > MAX_BIG_CHILDREN {
return Err(format!(
"BigDirectory node must have between {} and {} children, found {}",
MIN_BIG_CHILDREN, MAX_BIG_CHILDREN, n
));
}
Ok(BigDirectoryNode { children_hashes })
}*/
pub fn new(entries: Vec<DirectoryEntry>) -> Result<Self, String> {
if entries.len() > MAX_DIRECTORY_ENTRIES {
return Err(format!("Directory exceeds {} bytes", entries.len()));
}
Ok(BigDirectoryNode {
children_hashes: entries,
})
}
}
impl MerkleNode {
pub fn get_type_byte(&self) -> u8 {
match self {
MerkleNode::Chunk(_) => 0,
MerkleNode::Directory(_) => 1,
MerkleNode::Big(_) => 3,
MerkleNode::BigDirectory(_) => 4,
}
}
pub fn serialize(&self) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.push(self.get_type_byte());
match self {
MerkleNode::Chunk(node) => {
bytes.extend_from_slice(&node.data);
}
MerkleNode::Directory(node) => {
for entry in &node.entries {
bytes.extend_from_slice(&entry.filename);
bytes.extend_from_slice(&entry.content_hash);
}
}
MerkleNode::Big(node) => {
for hash in &node.children_hashes {
bytes.extend_from_slice(hash);
}
}
MerkleNode::BigDirectory(node) => {
for hash in &node.children_hashes {
bytes.extend_from_slice(&hash.content_hash);
}
}
}
bytes
}
/*pub fn generate_random_tree(
max_depth: u32,
) -> Result<(NodeHash, HashMap<NodeHash, MerkleNode>), String> {
let mut storage = HashMap::new();
// Start tree generation from the root directory at depth 0
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>) {
let mut res = HashMap::new();
let node1 = MerkleNode::Chunk(ChunkNode::new_random());
let hash1 = hash(&node1.serialize());
let node2 = MerkleNode::Chunk(ChunkNode::new_random());
let hash2 = hash(&node2.serialize());
res.insert(hash1, node1);
res.insert(hash2, node2);
let node3 = MerkleNode::Chunk(ChunkNode::new_random());
let hash3 = hash(&node3.serialize());
res.insert(hash3, node3);
let dir1 = MerkleNode::Directory(DirectoryNode {
entries: [DirectoryEntry {
let root = MerkleNode::Directory(DirectoryNode {
entries: [
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash3,
}]
.to_vec(),
});
let hash_dir1 = hash(&dir1.serialize());
content_hash: hashbig,
},
/*DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash2,
},
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash_dir1,
},*/
]
.to_vec(),
});
res.insert(hash_dir1, dir1);
let root_hash = Sha256::digest(&root.serialize());
println!("root hash: {:?}", root_hash);
res.insert(root_hash.try_into().expect("incorrect size"), root);
let root = MerkleNode::Directory(DirectoryNode {
entries: [
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash1,
},
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash2,
},
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash_dir1,
},
]
.to_vec(),
});
MerkleTree::new(res, root_hash.try_into().expect("incorrect size"))
}
let root_hash = hash(&root.serialize());
res.insert(root_hash, root);
pub fn node_to_file(tree: &MerkleTree, node: &MerkleNode, path: String, i: u8) {
match node.clone() {
MerkleNode::Directory(dir) => {
if i != 0 {
let new_path = format!("{}/fold_{}", path.clone(), i);
match create_dir(new_path.clone()) {
Ok(_) => println!("Directory created successfully!"),
Err(e) => println!("Failed to create directory: {}", e),
}
}
for entry in dir.entries {
// creer un fichier pour chaque entry
if let Ok(filename_str) = String::from_utf8(entry.filename.to_vec()) {
let new_name = format!("{}{}", path.clone(), remove_null_bytes(&filename_str));
(root_hash, res)
println!("new_name: {}", new_name);
let file = OpenOptions::new()
.append(true)
.create(true)
.open(new_name.clone());
match file {
Ok(mut fileok) => {
if let Some(current) = tree.data.get(&entry.content_hash) {
big_or_chunk_to_file(&tree, &current, &mut fileok);
}
}
Err(e) => {
eprintln!("error creaation file: {}", e);
}
}
}
}
}
MerkleNode::BigDirectory(bigdir) => {
for entry in bigdir.children_hashes.iter() {
if let Some(current) = tree.data.get(entry) {
node_to_file(tree, current, path.clone(), i + 1);
}
}
}
_ => {
eprintln!("invalid type of dir");
}
}
}
pub fn remove_null_bytes(input: &str) -> String {
input.chars().filter(|&c| c != '\0').collect()
}
pub fn big_or_chunk_to_file(tree: &MerkleTree, node: &MerkleNode, file: &mut File) {
match node {
MerkleNode::Big(big) => {
for entry in big.children_hashes.iter() {
if let Some(current) = tree.data.get(entry) {
big_or_chunk_to_file(tree, current, file);
}
}
}
MerkleNode::Chunk(chunk) => {
println!("wrote data");
let _ = file.write_all(&chunk.data);
}
_ => {
println!("invalid type of file");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
///
/// creates a cryptographic signature
///
#[test]
fn test_saving_tree() {
if let Ok(current_dir) = env::current_dir() {
println!("Current working directory: {:?}", current_dir);
}
println!("--------- tree test starts ------------");
match create_dir("../Download/") {
Ok(_) => println!("Directory created successfully!"),
Err(e) => println!("Failed to create directory: {}", e),
}
let tree = generate_base_tree();
println!("--------- test tree created ------------");
if let Some(root_node) = tree.data.get(&tree.root) {
node_to_file(&tree, root_node, "../Download/".to_string(), 0);
}
}
/*#[test]
fn signing_message() {
let username = String::from("gamixtreize");
let crypto_pair = CryptographicSignature::new(username.clone());
let handshake = HandshakeMessage::hello(0, 12, username);
let ser = handshake.serialize();
let signed_message = sign_message(&crypto_pair, &ser);
println!("unsigned_message: {:?}", ser);
println!("signed_message: {:?}", signed_message);
}*/
}

View File

@@ -0,0 +1,200 @@
use crate::data::*;
use rand::{Rng, rng};
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
fn hash(data: &[u8]) -> NodeHash {
let mut hasher = DefaultHasher::new();
data.hash(&mut hasher);
let hash_u64 = hasher.finish();
let mut hash_array = [0u8; FILENAME_HASH_SIZE];
// Simple way to spread a 64-bit hash across 32 bytes for a unique-ish ID
for i in 0..8 {
hash_array[i] = (hash_u64 >> (i * 8)) as u8;
}
hash_array // The rest remains 0, satisfying the 32-byte requirement
}
fn generate_random_filename() -> [u8; FILENAME_HASH_SIZE] {
let mut rng = rand::rng();
let mut filename_bytes = [0; FILENAME_HASH_SIZE];
// Generate a random length for the base name
let name_len = rng.random_range(5..21);
// Generate random alphanumeric characters
for i in 0..name_len {
let char_code = rng.random_range(97..123); // 'a' through 'z'
if i < FILENAME_HASH_SIZE {
filename_bytes[i] = char_code as u8;
}
}
// Append a common extension
let ext = if rng.random_bool(0.5) { ".txt" } else { ".dat" };
let ext_bytes = ext.as_bytes();
let start_index = name_len.min(FILENAME_HASH_SIZE - ext_bytes.len());
if start_index < FILENAME_HASH_SIZE {
filename_bytes[start_index..(start_index + ext_bytes.len())].copy_from_slice(ext_bytes);
}
filename_bytes
}
fn generate_random_file_node(
storage: &mut HashMap<NodeHash, MerkleNode>,
) -> Result<NodeHash, String> {
let mut rng = rng();
let is_big = rng.random_bool(0.2); // 20% chance of being a big file
if !is_big {
// Generate a simple Chunk Node
let node = MerkleNode::Chunk(ChunkNode::new_random());
let hash = hash(&node.serialize());
storage.insert(hash, node);
Ok(hash)
} else {
// Generate a Big Node (a file composed of chunks)
let num_children = rng.random_range(MIN_BIG_CHILDREN..=MAX_BIG_CHILDREN.min(8)); // Limit complexity
let mut children_hashes = Vec::with_capacity(num_children);
for _ in 0..num_children {
// Children must be Chunk or Big; for simplicity, we only generate Chunk children here.
let chunk_node = MerkleNode::Chunk(ChunkNode::new_random());
let chunk_hash = hash(&chunk_node.serialize());
storage.insert(chunk_hash, chunk_node);
children_hashes.push(chunk_hash);
}
let node = MerkleNode::Big(BigNode::new(children_hashes)?);
let hash = hash(&node.serialize());
storage.insert(hash, node);
Ok(hash)
}
}
fn generate_random_directory_node(
depth: u32,
max_depth: u32,
storage: &mut HashMap<NodeHash, MerkleNode>,
) -> Result<NodeHash, String> {
let mut rng = rng();
let current_depth = depth + 1;
let is_big_dir = rng.random_bool(0.3) && current_depth < max_depth;
if !is_big_dir || current_depth >= max_depth {
// Generate a simple Directory Node (leaf level directory)
let num_entries = rng.random_range(1..=MAX_DIRECTORY_ENTRIES.min(5)); // Limit directory size for testing
let mut entries = Vec::with_capacity(num_entries);
for _ in 0..num_entries {
if rng.random_bool(0.7) {
// 70% chance of creating a file (Chunk/Big)
let file_hash = generate_random_file_node(storage)?;
let entry = DirectoryEntry {
filename: generate_random_filename(),
content_hash: file_hash,
};
entries.push(entry);
} else if current_depth < max_depth {
// 30% chance of creating a subdirectory
let dir_hash = generate_random_directory_node(current_depth, max_depth, storage)?;
// Create a basic directory entry name
let mut filename_bytes = [0; 32];
let subdir_name = format!("dir_{}", current_depth);
filename_bytes[..subdir_name.len()].copy_from_slice(subdir_name.as_bytes());
let entry = DirectoryEntry {
filename: filename_bytes,
content_hash: dir_hash,
};
entries.push(entry);
}
}
let node = MerkleNode::Directory(DirectoryNode::new(entries)?);
let hash = hash(&node.serialize());
storage.insert(hash, node);
Ok(hash)
} else {
// Generate a BigDirectory Node (internal directory structure)
let num_children = rng.random_range(MIN_BIG_CHILDREN..=MAX_BIG_CHILDREN.min(4)); // Limit children count
let mut children = Vec::with_capacity(num_children);
for _ in 0..num_children {
// Children must be Directory or BigDirectory
let child_hash = generate_random_directory_node(current_depth, max_depth, storage)?;
children.push(child_hash);
}
let node = MerkleNode::BigDirectory(BigDirectoryNode::new(children)?);
let hash = hash(&node.serialize());
storage.insert(hash, node);
Ok(hash)
}
}
pub fn generate_random_tree(
max_depth: u32,
) -> Result<(NodeHash, HashMap<NodeHash, MerkleNode>), String> {
let mut storage = HashMap::new();
// Start tree generation from the root directory at depth 0
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>) {
let mut res = HashMap::new();
let node1 = MerkleNode::Chunk(ChunkNode::new_random());
let hash1 = hash(&node1.serialize());
let node2 = MerkleNode::Chunk(ChunkNode::new_random());
let hash2 = hash(&node2.serialize());
res.insert(hash1, node1);
res.insert(hash2, node2);
let node3 = MerkleNode::Chunk(ChunkNode::new_random());
let hash3 = hash(&node3.serialize());
res.insert(hash3, node3);
let dir1 = MerkleNode::Directory(DirectoryNode {
entries: [DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash3,
}]
.to_vec(),
});
let hash_dir1 = hash(&dir1.serialize());
res.insert(hash_dir1, dir1);
let root = MerkleNode::Directory(DirectoryNode {
entries: [
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash1,
},
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash2,
},
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash_dir1,
},
]
.to_vec(),
});
let root_hash = hash(&root.serialize());
res.insert(root_hash, root);
(root_hash, res)
}

View File

@@ -6,91 +6,89 @@ const DIRECTORY: u8 = 1;
const BIG: u8 = 2;
const BIGDIRECTORY: u8 = 3;
fn parse_received_datum(recevied_datum: Vec<u8>, datum_length: usize, mut tree: MerkleTree) {
if datum_length > recevied_datum.len() {
return;
}
if datum_length < 32 + 64 {
return;
}
pub fn parse_received_datum(
recevied_datum: Vec<u8>,
datum_length: usize,
) -> Option<([u8; 32], MerkleNode)> {
let hash_name: [u8; 32] = recevied_datum[..32].try_into().expect("error");
let sigstart = datum_length - 64;
let value = &recevied_datum[32..sigstart];
let value = &recevied_datum[32..recevied_datum.len()];
let value_slice = value.to_vec();
let signature: [u8; 32] = recevied_datum[sigstart..datum_length]
.try_into()
.expect("Taille incorrecte");
println!("valueslice: {:?}, {}", value_slice, value_slice.len());
let datum_type = value_slice[0];
match datum_type {
CHUNK => {
tree.data.insert(
hash_name,
MerkleNode::Chunk(crate::ChunkNode { data: value_slice }),
);
}
CHUNK => Some((
hash_name,
MerkleNode::Chunk(crate::ChunkNode { data: value_slice }),
)),
DIRECTORY => {
let nb_entries = value_slice[1];
let mut dir_entries = Vec::new();
let mut offset = 1 as usize;
for i in 0..nb_entries {
offset = (offset as u8 + 64 * i) as usize;
let name = &recevied_datum[offset..offset + 32];
for i in 0..((value_slice.len() - 1) / 64) as u8 {
offset = (1 + 64 * i as usize) as usize;
println!("offset:{}, i:{}", offset, i);
let name = &value_slice[offset..offset + 32];
let mut hash = [0u8; 32];
hash.copy_from_slice(&recevied_datum[offset + 32..offset + 64]);
hash.copy_from_slice(&value_slice[offset + 32..offset + 64]);
let dp_name = String::from_utf8(name.to_vec()).expect("err");
println!("name:{}", dp_name);
// envoyer un datum request
dir_entries.push(DirectoryEntry {
filename: name.to_vec(),
filename: name.try_into().expect("incorrect size"),
content_hash: hash,
});
}
let current = DirectoryNode::new(dir_entries);
match current {
Ok(current_node) => {
tree.data
.insert(hash_name, MerkleNode::Directory(current_node));
}
Ok(current_node) => Some((hash_name, MerkleNode::Directory(current_node))),
Err(e) => {
println!("{}", e);
None
}
}
}
BIG => {
let chlidren: Vec<NodeHash> = Vec::new();
tree.data.insert(
hash_name,
MerkleNode::Big(crate::BigNode {
children_hashes: chlidren,
}),
);
}
BIGDIRECTORY => {
let nb_entries = value_slice[1];
let mut dir_entries = Vec::new();
let mut bigdir_entries: Vec<NodeHash> = Vec::new();
let mut offset = 1 as usize;
for i in 0..nb_entries {
offset = (offset as u8 + 64 * i) as usize;
let name = &recevied_datum[offset..offset + 32];
let mut hash = [0u8; 32];
hash.copy_from_slice(&recevied_datum[offset + 32..offset + 64]);
for i in 0..((value_slice.len() - 1) / 32) as u8 {
offset = (1 + 32 * i as usize) as usize;
println!("offset:{}, i:{}", offset, i);
let hash = &value_slice[offset..offset + 32];
// envoyer un datum request
dir_entries.push(DirectoryEntry {
filename: name.to_vec(),
content_hash: hash,
});
bigdir_entries.push(hash.try_into().expect("incorrect size"));
}
let current = BigDirectoryNode::new(dir_entries);
println!("its a BIG bro");
Some((
hash_name,
MerkleNode::Big(crate::BigNode {
children_hashes: bigdir_entries,
}),
))
}
BIGDIRECTORY => {
let mut bigdir_entries: Vec<NodeHash> = Vec::new();
let mut offset = 1 as usize;
for i in 0..((value_slice.len() - 1) / 32) as u8 {
offset = (1 + 32 * i as usize) as usize;
println!("offset:{}, i:{}", offset, i);
let hash = &value_slice[offset..offset + 32];
// envoyer un datum request
bigdir_entries.push(hash.try_into().expect("incorrect size"));
}
let current = BigDirectoryNode::new(bigdir_entries);
match current {
Ok(current_node) => {
tree.data
.insert(hash_name, MerkleNode::BigDirectory(current_node));
}
Ok(current_node) => Some((hash_name, MerkleNode::BigDirectory(current_node))),
Err(e) => {
println!("{}", e);
None
}
}
}
_ => {}
_ => None,
}
}

View File

@@ -0,0 +1,26 @@
use std::fmt;
#[derive(Debug)]
pub enum FetchSocketAddressError {
NoIPV4Address,
NoRegisteredAddresses,
NoResponseFromUser,
ClientError(String),
}
impl fmt::Display for FetchSocketAddressError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FetchSocketAddressError::NoIPV4Address => write!(f, "No IPv4 Address registered."),
FetchSocketAddressError::NoRegisteredAddresses => {
write!(f, "No Registered Addresses found.")
}
FetchSocketAddressError::NoResponseFromUser => {
write!(f, "No Response from user after contact.")
}
FetchSocketAddressError::ClientError(error) => {
write!(f, "Client error : {}", error)
}
}
}
}

View File

@@ -1,67 +1,94 @@
mod cryptographic_signature;
mod data;
mod datum_generation;
mod datum_parsing;
mod fetchsocketaddresserror;
mod message_handling;
mod messages_channels;
mod messages_structure;
mod peers_refresh;
mod registration;
mod server_communication;
mod threads_handling;
mod timestamp;
use crate::fetchsocketaddresserror::FetchSocketAddressError;
use crate::messages_structure::ROOTREPLY;
use crate::peers_refresh::*;
use crate::timestamp::Timestamp;
use crate::{
cryptographic_signature::CryptographicSignature,
message_handling::EventType,
messages_channels::{MultipleSenders, start_receving_thread},
messages_structure::{ROOTREQUEST, construct_message},
peers_refresh::HandshakeHistory,
registration::{
get_socket_address, parse_addresses, perform_handshake, register_with_the_server,
messages_channels::{MultipleSenders, start_receving_thread, start_retry_thread},
messages_structure::{
DATUM, DATUMREQUEST, NATTRAVERSALREQUEST, NATTRAVERSALREQUEST2, NODATUM, PING, ROOTREQUEST,
construct_message,
},
peers_refresh::HandshakeHistory,
registration::{parse_addresses, perform_handshake, register_with_the_server},
server_communication::{generate_id, get_peer_list},
threads_handling::Worker,
};
use std::{
fmt,
sync::{Arc, Mutex},
};
use std::collections::HashSet;
use std::{
io::Error,
net::{SocketAddr, UdpSocket},
str::FromStr,
net::{IpAddr, Ipv4Addr, UdpSocket},
time::Duration,
};
use std::{
net::SocketAddr,
sync::{Arc, Mutex},
};
pub struct P2PSharedData {
shared_socket: Arc<UdpSocket>,
shared_cryptopair: Arc<CryptographicSignature>,
shared_messageslist: Arc<Mutex<HashMap<i32, EventType>>>,
shared_messagesreceived: Arc<Mutex<HashMap<String, (EventType, Timestamp)>>>,
shared_senders: Arc<MultipleSenders>,
server_name: Arc<Mutex<String>>,
server_address: Arc<Mutex<String>>,
handshake_peers: Arc<HandshakeHistory>,
threads: Vec<Worker>,
}
use bytes::Bytes;
use reqwest::Client;
use tokio::time::sleep;
impl P2PSharedData {
pub fn new(
username: String,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
) -> Result<P2PSharedData, Error> {
let messages_list = HashMap::<i32, EventType>::new();
let messagesrecv_list = HashMap::<String, (EventType, Timestamp)>::new();
let username = String::from(username);
let crypto_pair = CryptographicSignature::new(username);
let socket = UdpSocket::bind("0.0.0.0:0")?;
let shared_socket = Arc::new(socket);
let shared_cryptopair = Arc::new(crypto_pair);
let shared_messageslist = Arc::new(Mutex::new(messages_list));
let shared_messagesreceived = Arc::new(Mutex::new(messagesrecv_list));
let senders = MultipleSenders::new(1, &shared_socket, cmd_tx);
let mut threads = Vec::new();
let senders = MultipleSenders::new(1, &shared_socket, cmd_tx, &mut threads);
let shared_senders = Arc::new(senders);
let server_name = Arc::new(Mutex::new("".to_string()));
let server_address = 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_messagesreceived: shared_messagesreceived,
shared_senders: shared_senders,
server_name: server_name,
server_address: server_address,
handshake_peers: handhsake_peers,
threads,
})
}
pub fn socket(&self) -> Arc<UdpSocket> {
@@ -74,32 +101,52 @@ impl P2PSharedData {
pub fn messages_list(&self) -> Arc<Mutex<HashMap<i32, EventType>>> {
self.shared_messageslist.clone()
}
pub fn messages_received(&self) -> Arc<Mutex<HashMap<String, (EventType, Timestamp)>>> {
self.shared_messagesreceived.clone()
}
pub fn servername(&self) -> String {
let guard = self.server_name.lock().unwrap();
let guard = {
let maybe_sn = self.server_name.lock().unwrap();
maybe_sn.clone()
};
guard.to_string()
}
pub fn serveraddress(&self) -> String {
let guard = {
let maybe_sn = self.server_address.lock().unwrap();
maybe_sn.clone()
};
guard.to_string()
}
pub fn set_servername(&self, new: String) {
let mut guard = self.server_name.lock().unwrap();
*guard = new
}
pub fn set_serveraddress(&self, new: String) {
let mut guard = self.server_address.lock().unwrap();
*guard = new
}
pub fn senders(&self) -> Arc<MultipleSenders> {
self.shared_senders.clone()
}
pub fn socket_ref(&self) -> &UdpSocket {
&*self.shared_socket
}
pub fn handshakes(&self) -> Arc<HandshakeHistory> {
self.handshake_peers.clone()
}
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
}
pub fn messages_received_ref(&self) -> &Mutex<HashMap<String, (EventType, Timestamp)>> {
&*self.shared_messagesreceived
}
pub fn senders_ref(&self) -> &MultipleSenders {
&*self.shared_senders
}
@@ -108,6 +155,15 @@ impl P2PSharedData {
let mut map = self.shared_messageslist.lock().unwrap();
map.insert(id, evt);
}
pub fn threads(&mut self) -> &mut Vec<Worker> {
&mut self.threads
}
pub fn close_threads(&mut self) {
for w in self.threads.drain(..) {
w.stop();
}
}
}
/// Messages sent to the Network thread by the GUI.
@@ -116,15 +172,20 @@ pub enum NetworkCommand {
ServerHandshake(String, String), // ServerName
FetchPeerList(String), // ServerIP
RegisterAsPeer(String),
Ping(),
ConnectPeer(String), // IP:PORT
RequestFileTree(String), // peer_id
Ping(String, String),
NatTraversal(String, String),
ConnectPeer((String, bool)), // IP:PORT
RequestFileTree(String), // peer_id
RequestDirectoryContent(String, String),
RequestChunk(String, String),
Disconnect(),
ResetServerPeer(),
Discover(String, String, String),
GetChildren(String, String),
GetChildren([u8; 32], String, bool),
SendDatum(MerkleNode, [u8; 32], String),
SendNoDatum(Vec<u8>, String),
SendRootReply(Vec<u8>, String),
InitDownload([u8; 32], String, String),
// ...
}
@@ -133,14 +194,18 @@ pub enum NetworkEvent {
Connected(String),
ConnectedHandshake(),
Disconnected(),
Error(String),
Error(String, String),
Success(String, String),
PeerConnected(String),
PeerListUpdated(Vec<String>),
FileTreeReceived(String, Vec<MerkleNode>), // peer_id, content
DataReceived(String, MerkleNode),
PeerListUpdated(Vec<(String, bool)>),
FileTreeReceived([u8; 32], MerkleNode, String), // peer_id, content
DataReceived([u8; 32], MerkleNode, String),
FileTreeRootReceived(String, NodeHash),
HandshakeFailed(),
ServerHandshakeFailed(String),
DatumRequest([u8; 32], String),
RootRequest(String),
InitDownload([u8; 32], String, String),
// ...
}
@@ -173,8 +238,6 @@ pub fn start_p2p_executor(
// Use tokio to spawn the asynchronous networking logic
tokio::task::spawn(async move {
// P2P/Networking Setup goes here
let handshake_history = Arc::new(Mutex::new(HandshakeHistory::new()));
let handshake_clone = handshake_history.clone();
println!("Network executor started.");
@@ -183,19 +246,110 @@ pub fn start_p2p_executor(
// Check for commands from the GUI
if let Ok(cmd) = cmd_rx.try_recv() {
match cmd {
NetworkCommand::InitDownload(hash, ip, name) => {
if let Some(sd) = shared_data.as_ref() {
if let Some(res) = sd.handshake_peers.get_peer_info_username(ip) {
let _ = event_tx.send(NetworkEvent::InitDownload(
hash,
res.ip.to_string(),
name.to_string(),
));
}
}
}
NetworkCommand::SendRootReply(node_hash, addr) => {
if let Some(sd) = shared_data.as_mut() {
let mut payload = Vec::new();
payload.extend_from_slice(&node_hash);
let new_id = generate_id();
let message =
construct_message(ROOTREPLY, payload, new_id, sd.cryptopair_ref());
match message {
None => {}
Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().send_dispatch(
resp_msg,
addr.clone(),
false,
sd.messages_list(),
);
}
}
}
}
NetworkCommand::SendNoDatum(node_hash, addr) => {
if let Some(sd) = shared_data.as_mut() {
let mut payload = Vec::new();
payload.extend_from_slice(&node_hash);
let new_id = generate_id();
let message =
construct_message(NODATUM, payload, new_id, sd.cryptopair_ref());
match message {
None => {}
Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().send_dispatch(
resp_msg,
addr.clone(),
false,
sd.messages_list(),
);
}
}
}
}
NetworkCommand::SendDatum(merklennode, node_hash, addr) => {
if let Some(sd) = shared_data.as_mut() {
let mut payload = Vec::new();
payload.extend_from_slice(&node_hash);
payload.extend_from_slice(&merklennode.serialize());
let new_id = generate_id();
let message =
construct_message(DATUM, payload, new_id, sd.cryptopair_ref());
match message {
None => {}
Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().send_dispatch(
resp_msg,
addr.clone(),
false,
sd.messages_list(),
);
}
}
}
}
NetworkCommand::ServerHandshake(username, ip) => {
println!("server handshake called");
if let Some(sd) = shared_data.as_ref() {
start_receving_thread(sd, event_tx.clone(), &handshake_clone);
if let Some(sd) = shared_data.as_mut() {
start_receving_thread(sd, event_tx.clone(), sd.handshakes());
start_retry_thread(
sd.senders(),
4,
sd.messages_list(),
sd.threads().as_mut(),
);
update_handshake(
sd.senders(),
sd.cryptopair(),
sd.messages_list(),
sd.handshake_peers.get_username_peerinfo_map(),
);
let res =
perform_handshake(&sd, username, ip, event_tx.clone(), true).await;
} else {
println!("no shared data");
}
}
NetworkCommand::ConnectPeer(addr) => {
NetworkCommand::ConnectPeer((username, connected)) => {
println!("[Network] ConnectPeer() called");
println!("[Network] Attempting to connect to: {}", addr);
println!("[Network] Attempting to connect to: {}", username);
// Network logic to connect...
// If successful, send an event back:
// event_tx.send(NetworkEvent::PeerConnected(addr)).unwrap();
@@ -206,30 +360,35 @@ pub fn start_p2p_executor(
NetworkCommand::Discover(username, hash, ip) => {
// envoie un handshake au peer, puis un root request
if let Some(sd) = shared_data.as_ref() {
let res = {
let m = handshake_clone.lock().unwrap();
m.get_peer_info_username(username.clone()).cloned()
};
let res = sd.handshake_peers.get_peer_info_username(username.clone());
match res {
Some(peerinfo) => {
let id = generate_id();
// envoyer un root request
let rootrequest = construct_message(
ROOTREQUEST,
Vec::new(),
generate_id(),
id,
sd.cryptopair_ref(),
);
println!("matching");
match rootrequest {
None => {}
Some(resp_msg) => {
sd.add_message(id, EventType::RootRequest);
println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().send_via(
0,
sd.senders_ref().add_message_to_retry_queue(
resp_msg.clone(),
peerinfo.ip.to_string(),
false,
);
sd.senders_ref().send_dispatch(
resp_msg,
peerinfo.ip.to_string(),
false,
sd.messages_list_ref(),
sd.messages_list(),
);
}
}
@@ -250,8 +409,41 @@ pub fn start_p2p_executor(
println!("no shared data");
}
}
NetworkCommand::GetChildren(username, hash) => {
// envoie un datum request au peer
NetworkCommand::GetChildren(hash, ip, is_file) => {
if let Some(sd) = shared_data.as_ref() {
let mut payload = Vec::new();
payload.extend_from_slice(&hash);
let new_id = generate_id();
let datumreqest = construct_message(
DATUMREQUEST,
payload,
new_id,
sd.cryptopair_ref(),
);
match datumreqest {
None => {}
Some(resp_msg) => {
if is_file {
sd.add_message(new_id, EventType::DatumRequestBig);
} else {
sd.add_message(new_id, EventType::DatumRequest);
}
println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().add_message_to_retry_queue(
resp_msg.clone(),
ip.clone(),
false,
);
sd.senders_ref().send_dispatch(
resp_msg,
ip.clone(),
false,
sd.messages_list(),
);
}
}
}
}
NetworkCommand::RequestDirectoryContent(_, _) => {
println!("[Network] RequestDirectoryContent() called");
@@ -269,7 +461,8 @@ pub fn start_p2p_executor(
Err(e) => {
let mut err_msg = String::from("failed to initialize socket: ");
err_msg += &e.to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg));
let res =
event_tx.send(NetworkEvent::Error(err_msg, name.to_owned()));
let res = event_tx.send(NetworkEvent::Disconnected());
None
}
@@ -279,7 +472,8 @@ pub fn start_p2p_executor(
if let Err(e) = register_with_the_server(&sd.cryptopair(), &ip).await {
let mut err_msg = String::from("request failed: ");
err_msg += &e.to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg));
let res =
event_tx.send(NetworkEvent::Error(err_msg, name.to_owned()));
let res = event_tx.send(NetworkEvent::Disconnected());
} else {
let res = event_tx.send(NetworkEvent::Connected(ip));
@@ -299,20 +493,22 @@ pub fn start_p2p_executor(
}*/
}
NetworkCommand::FetchPeerList(ip) => {
println!("[Network] FetchPeerList() called");
if ip == "" {
let res = event_tx.send(NetworkEvent::Error(
"Not registered to any server".to_string(),
"".to_owned(),
));
} else {
println!("cc");
match get_peer_list(ip).await {
Ok(body) => match String::from_utf8(body.to_vec()) {
Ok(peers_list) => {
let mut peers: Vec<String> = Vec::new();
let mut peers: Vec<(String, bool)> = Vec::new();
let mut current = String::new();
for i in peers_list.chars() {
if i == '\n' {
peers.push(current.clone());
peers.push((current.clone(), false));
current.clear();
} else {
current.push(i);
@@ -328,19 +524,70 @@ pub fn start_p2p_executor(
Err(e) => println!("error"),
}
}
println!("[Network] FetchPeerList() called");
}
NetworkCommand::RegisterAsPeer(_) => {
println!("[Network] RegisterAsPeer() called");
}
NetworkCommand::Ping() => {
println!("[Network] Ping() called");
NetworkCommand::Ping(str, ip) => {
println!("[Network] Ping({}) called", str);
if let Some(sd) = shared_data.as_ref() {
let id = generate_id();
sd.add_message(id, EventType::Ping);
let pingrequest =
construct_message(PING, Vec::new(), id, sd.cryptopair_ref());
let peer_address =
get_socket_address(str.to_owned(), ip, shared_data.as_ref()).await;
match peer_address {
Ok(addr) => {
//if let Some(ping) = pingrequest {
// sd.senders_ref().add_message_to_retry_queue(
// ping.clone(),
// addr.to_string(),
// false,
// );
// sd.senders_ref().send_dispatch(
// ping,
// addr.to_string(),
// false,
// sd.messages_list(),
// );
//}
match event_tx.send(NetworkEvent::Success(
format!(
"Successfully sent ping message to {}.",
addr.to_string(),
),
str.to_owned(),
)) {
Ok(_) => {}
Err(e) => {
eprintln!("NetworkEvent error : {}", e);
}
};
}
Err(err_msg) => {
match event_tx
.send(NetworkEvent::Error(err_msg.to_string(), str))
{
Ok(_) => {}
Err(e) => {
eprintln!("NetworkEvent error : {}", e);
}
}
}
}
}
}
NetworkCommand::Disconnect() => {
if let Some(sd) = shared_data.as_ref() {
println!("Disconnecting: {}", &sd.cryptopair().username);
shared_data = None;
let res = event_tx.send(NetworkEvent::Disconnected());
match event_tx.send(NetworkEvent::Disconnected()) {
Ok(_) => {}
Err(e) => {
eprintln!("NetworkEvent error : {}", e);
}
}
} else {
println!("no p2p data");
}
@@ -352,6 +599,54 @@ pub fn start_p2p_executor(
println!("no p2p data");
}
}
NetworkCommand::NatTraversal(username, ip) => {
if let Some(sd) = shared_data.as_ref() {
println!("username:{}, ip:{}", username, ip);
// user server to send nattraversal request
let server_addr = sd.serveraddress();
let peer_addr_query = get_socket_address(
username.clone(),
ip.clone(),
shared_data.as_ref(),
);
match peer_addr_query.await {
Ok(peer_addr) => {
let payload = socket_addr_to_vec(peer_addr);
print!("{:?}", payload.clone());
let id = generate_id();
let natreq = construct_message(
NATTRAVERSALREQUEST,
payload.clone(),
id.clone(),
&sd.cryptopair(),
);
sd.add_message(id, EventType::NatTraversal);
sd.senders_ref().send_dispatch(
natreq.expect(
"couldnt construct message nattraversalrequest2",
),
server_addr.to_string(),
false,
sd.messages_list(),
);
}
Err(err_msg) => {
match event_tx
.send(NetworkEvent::Error(err_msg.to_string(), username))
{
Ok(_) => {}
Err(e) => {
eprintln!("NetworkEvent error : {}", e);
}
}
}
}
}
}
}
}
@@ -361,7 +656,181 @@ pub fn start_p2p_executor(
// event_tx.send(NetworkEvent::PeerConnected("NewPeerID".to_string())).unwrap();
// Avoid spinning too fast
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
sleep(std::time::Duration::from_millis(50)).await;
}
})
}
fn socket_addr_to_vec(addr: SocketAddr) -> Vec<u8> {
let mut v = match addr.ip() {
IpAddr::V4(v4) => v4.octets().to_vec(),
IpAddr::V6(v6) => v6.octets().to_vec(),
};
v.extend(&addr.port().to_be_bytes());
v
}
fn parse_pack(s: &str) -> Option<[u8; 6]> {
// split into "ip" and "port"
let mut parts = s.rsplitn(2, ':');
let port_str = parts.next()?;
let ip_str = parts.next()?; // if missing, invalid
let ip: Ipv4Addr = ip_str.parse().ok()?;
let port: u16 = port_str.parse().ok()?;
let octets = ip.octets();
let port_be = port.to_be_bytes();
Some([
octets[0], octets[1], octets[2], octets[3], port_be[0], port_be[1],
])
}
async fn quick_ping(addr: &SocketAddr, timeout_ms: u64, sd: &P2PSharedData) -> bool {
let id = generate_id();
let pingreq = construct_message(PING, Vec::new(), id, &sd.shared_cryptopair);
if let Some(ping) = pingreq {
sd.add_message(id, EventType::Ping);
sd.senders_ref()
.send_dispatch(ping, addr.to_string(), false, sd.messages_list());
}
sleep(Duration::from_millis(timeout_ms)).await;
let msg_list = sd.messages_list_ref().lock().expect("yooo");
let res = !msg_list.contains_key(&id);
for (id, evt) in msg_list.iter() {
println!("id : {}, evt : {}", id, evt.to_string());
}
println!("message list doesnt contain key? {}", res);
res
}
///
/// sends a get request to the server to get the socket address of the given peer
///
pub async fn get_socket_address(
username: String,
ip: String,
shared_data: Option<&P2PSharedData>,
) -> Result<SocketAddr, FetchSocketAddressError> {
let sd = shared_data.expect("No shared data");
let client = match Client::builder().timeout(Duration::from_secs(5)).build() {
Ok(c) => c,
Err(e) => {
return Err(FetchSocketAddressError::ClientError(e.to_string()));
}
};
let uri = format!("{}/peers/{}/addresses", ip, username);
let res = match client.get(&uri).send().await {
Ok(r) => r,
Err(e) => return Err(FetchSocketAddressError::ClientError(e.to_string())),
};
if res.status().is_success() {
println!("Successfully retrieved the addresses. {}", res.status());
} else {
eprintln!(
"Failed to get the peers addresses from the server. Status: {}",
res.status()
);
}
let body = match res.bytes().await {
Ok(b) => b,
Err(e) => {
return Err(FetchSocketAddressError::ClientError(e.to_string()));
}
};
let s = match String::from_utf8(body.to_vec()) {
Ok(st) => st,
Err(e) => {
return Err(FetchSocketAddressError::ClientError(e.to_string()));
}
};
let addresses = parse_addresses(&s); // assumes parse_addresses: &str -> Vec<SocketAddr>
if addresses.is_empty() {
return Err(FetchSocketAddressError::NoRegisteredAddresses);
} else if !addresses.iter().any(|a| matches!(a, SocketAddr::V4(_))) {
return Err(FetchSocketAddressError::NoIPV4Address);
}
for addr in addresses {
println!("trying address : {}", addr);
if quick_ping(&addr, 5000, sd).await {
return Ok(addr);
}
let payload = socket_addr_to_vec(addr);
let id = generate_id();
let natreq = construct_message(NATTRAVERSALREQUEST, payload.clone(), id, &sd.cryptopair());
sd.add_message(id, EventType::NatTraversal);
sd.senders_ref().send_dispatch(
natreq.expect("couldnt construct message nattraversalrequest2"),
sd.serveraddress().to_string(),
false,
sd.messages_list(),
);
sleep(Duration::from_millis(5000)).await;
let maybe_entry = {
let guard = sd.messages_received_ref().lock().unwrap();
guard.clone()
}; // guard dropped
for (id, (evt, time)) in maybe_entry.iter() {
println!("{} : {} at {}", id, evt.to_string(), time.to_string());
if id.eq(&addr.to_string()) && Timestamp::now().diff(time) < 10 {
println!("received message from address, returning said address..");
return Ok(addr);
}
}
if quick_ping(&addr, 15000, sd).await {
return Ok(addr);
}
}
Err(FetchSocketAddressError::NoResponseFromUser)
}
pub async fn get_server_address(username: String, ip: String) -> Option<SocketAddr> {
let client = Client::builder()
.timeout(Duration::from_secs(5))
.build()
.expect("cannot create client");
let uri = format!("{}/peers/{}/addresses", ip, username);
let res = client.get(uri).send().await.expect("couldnt get response");
if res.status().is_success() {
println!("Successfully retreived the addresses. {}", res.status());
} else {
eprintln!(
"Failed to get the peers addresses from the server. Status: {}",
res.status()
);
}
let body: Bytes = res.bytes().await.expect("couldnt get bytes");
match String::from_utf8(body.to_vec()) {
Ok(s) => {
let addresses = parse_addresses(&s);
if let Some(first) = addresses.first() {
Some(first.clone())
} else {
None
}
}
Err(_) => None,
}
}

View File

@@ -1,22 +1,60 @@
use crate::{
NetworkEvent, NodeHash,
cryptographic_signature::{
CryptographicSignature, get_peer_key, sign_message, verify_signature,
},
cryptographic_signature::{CryptographicSignature, get_peer_key, verify_signature},
datum_parsing::parse_received_datum,
messages_channels::MultipleSenders,
messages_structure::construct_message,
peers_refresh::HandshakeHistory,
registration,
server_communication::generate_id,
timestamp::Timestamp,
};
use std::{
collections::HashMap,
default,
net::{Ipv4Addr, SocketAddr},
};
use std::{collections::HashMap, net::SocketAddr};
use std::{
net::IpAddr,
sync::{Arc, Mutex},
};
// Types of messages that await for a response
#[derive(Debug, Clone)]
pub enum EventType {
SendRootRequest,
HelloThenRootRequest,
Hello,
RootRequest,
Ping,
NatTraversal,
DatumRequest,
DatumRequestBig,
Unknown,
}
impl EventType {
pub fn to_string(&self) -> String {
match self {
EventType::HelloThenRootRequest => "HelloThenRootRequest".to_owned(),
EventType::Hello => "Hello".to_owned(),
EventType::RootRequest => "RootRequest".to_owned(),
EventType::Ping => "Ping".to_owned(),
EventType::NatTraversal => "NatTraversal".to_owned(),
EventType::DatumRequest => "DatumRequest".to_owned(),
EventType::Unknown => "Unknown".to_owned(),
EventType::DatumRequestBig => "DatumRequestBig".to_owned(),
}
}
pub fn from_msgtype(msgtype: u8) -> EventType {
match msgtype {
PING => EventType::Ping,
HELLO => EventType::Hello,
ROOTREQUEST => EventType::RootRequest,
NATTRAVERSALREQUEST => EventType::NatTraversal,
DATUMREQUEST => EventType::DatumRequest,
_ => EventType::Unknown,
}
}
}
const ID: usize = 4;
@@ -25,7 +63,7 @@ const LENGTH: usize = 7;
const EXTENSIONS: usize = 4;
const SIGNATURE: usize = 64;
const PING: u8 = 0;
pub const PING: u8 = 0;
const OK: u8 = 128;
const ERROR: u8 = 129;
const HELLO: u8 = 1;
@@ -40,6 +78,7 @@ const NATTRAVERSALREQUEST2: u8 = 5;
pub fn handle_recevied_message(
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
messages_received: &Arc<Mutex<HashMap<String, (EventType, Timestamp)>>>,
recevied_message: &Vec<u8>,
crypto_pair: &CryptographicSignature,
//socket_addr: &SocketAddr,
@@ -47,7 +86,7 @@ pub fn handle_recevied_message(
server_name: &String,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
ip: SocketAddr,
handhsake_history: &Arc<Mutex<HandshakeHistory>>,
handhsake_history: Arc<HandshakeHistory>,
) {
if recevied_message.len() < 4 {
return;
@@ -78,87 +117,23 @@ pub fn handle_recevied_message(
cmd_tx,
ip,
messages_list,
messages_received,
handhsake_history,
senders,
);
match resp {
None => {}
Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg);
senders.send_via(
0,
senders.send_dispatch(
resp_msg,
ip.to_string(),
is_resp_to_server_handshake,
messages_list,
messages_list.clone(),
);
}
}
// Lock the mutex to access the HashMap
/*let list = messages_list.lock().unwrap();
let eventtype = list.get(&id); // Clone the enum so we can release the lock if needed
match eventtype {
Some(EventType::ServerHelloReply) => {
/*registration::register_ip_addresses(
crypto_pair,
socket_addr.to_string(),
senders,
&messages_list, // Pass the mutable reference inside the lock
546,
);*/
}
Some(_) => print!("Not implemented"),
None => {
let message_type = recevied_message[4];
// Handle handshake
if message_type == 1 {
let mut resp_to_serv = false;
println!("verify the signature");
let parsed_received_message = HandshakeMessage::parse(recevied_message.to_vec());
let received_name = String::from_utf8(parsed_received_message.name).expect("error");
let peer_pubkey = tokio::runtime::Runtime::new()
.unwrap()
.block_on(get_peer_key(&received_name))
.expect("failed to retrieve public key");
if received_name == server_name.to_string() {
resp_to_serv = true;
}
if !verify_signature(peer_pubkey, recevied_message) {
println!(
"incorrect signature from given peer: {}, ignoring message {}",
&received_name, id
);
} else {
// verify if this is a server handshake request
let username_size = crypto_pair.username.len();
let hello_handshake = HandshakeMessage::helloReply(
id as u32,
username_size as u16 + 4,
crypto_pair.username.clone(),
);
//HandshakeMessage::display(&hello_handshake);
let hello_handshake_serialized = hello_handshake.serialize();
let message_signed = sign_message(crypto_pair, &hello_handshake_serialized);
senders.send_via(0, message_signed, socket_addr.to_string(), resp_to_serv);
let mut list = messages_list.lock().expect("Failed to lock messages_list");
match list.get(&id) {
Some(_) => {
list.remove(&id);
}
None => {
list.insert(id, EventType::ServerHelloReply);
}
}
}
}
print!("Message not found for ID: {}", id)
}
}*/
}
pub fn parse_message(
@@ -168,9 +143,10 @@ pub fn parse_message(
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
ip: SocketAddr,
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
handhsake_history_mutex: &Arc<Mutex<HandshakeHistory>>,
messages_received: &Arc<Mutex<HashMap<String, (EventType, Timestamp)>>>,
handhsake_history: Arc<HandshakeHistory>,
senders: &MultipleSenders,
) -> Option<Vec<u8>> {
let mut handhsake_history = handhsake_history_mutex.lock().unwrap();
let cmd_tx_clone = cmd_tx.clone();
let id_bytes: [u8; 4] = received_message[0..ID]
@@ -179,6 +155,14 @@ pub fn parse_message(
let msgtype = received_message[ID];
messages_received
.lock()
.expect("couldnt lock received map")
.insert(
ip.to_string(),
(EventType::from_msgtype(msgtype), Timestamp::now()),
);
let length_bytes: [u8; 2] = received_message[TYPE..LENGTH]
.try_into()
.expect("Taille incorrecte");
@@ -186,8 +170,9 @@ pub fn parse_message(
let msg_length = u16::from_be_bytes(length_bytes) as usize;
// verify signature
match msgtype {
HELLO | HELLOREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => {
HELLO | HELLOREPLY => {
let ilength = u16::from_be_bytes(length_bytes);
println!("hello");
println!("name received length: {}", ilength);
let received_name = &received_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize];
let received_username = String::from_utf8(received_name.to_vec());
@@ -205,12 +190,10 @@ pub fn parse_message(
HELLOREPLY => {
handhsake_history.add_new_handshake(peer_pubkey, "".to_string(), ip);
}
_ => {}
_ => {
println!("no handshake added");
}
}
let signature: [u8; SIGNATURE] = received_message
[LENGTH + msg_length..LENGTH + msg_length + SIGNATURE]
.try_into()
.expect("Taille incorrecte");
if !verify_signature(peer_pubkey, &received_message) {
println!(
"incorrect signature from given peer: {}, ignoring message of type {} with id {}",
@@ -225,7 +208,7 @@ pub fn parse_message(
}
}
}
ROOTREPLY => {
ROOTREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => {
let ilength = u16::from_be_bytes(length_bytes);
println!("name received length: {}", ilength);
if let Some(peerinfo) = handhsake_history.get_peer_info_ip(ip.to_string()) {
@@ -247,39 +230,115 @@ pub fn parse_message(
// Message handling
let mut constructed_message: Option<Vec<u8>> = None;
match msgtype {
// PING
//
// envoie un OK
PING => {
constructed_message = construct_message(OK, Vec::new(), id, crypto_pair);
}
//
// OK
//
// rien ?
// si NATTRAVERSALREQUEST alors
//
// ERROR
//
// affiche un msg d'erreur
ERROR => {
if let Ok(err_received) =
String::from_utf8(received_message[LENGTH..(msg_length + LENGTH)].to_vec())
{
let err_msg = format!("Error received from peer {} : {}", ip, err_received);
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg));
} else {
let err_msg = format!("Error received from peer {} : N/A", ip,);
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg));
OK => {
let mut guard = messages_list.lock().unwrap();
let res = guard.get(&id);
match res {
Some(ev) => {
println!("{:?}", ev);
let _ = &guard.remove_entry(&id);
println!("message {} retiré de la liste", id);
}
None => {
println!("ping non trouvé");
}
}
}
// HELLO
//
// envoie une hello reply
//
NATTRAVERSALREQUEST => {
// send ok & send nattraversalrequest2 to peer
constructed_message = construct_message(OK, Vec::new(), id, crypto_pair);
let ilength = u16::from_be_bytes(length_bytes);
let received_address =
&received_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize];
let address = String::from_utf8(received_address.to_vec()).expect("wrong name");
let natreq2 = construct_message(
NATTRAVERSALREQUEST2,
ip.to_string().into_bytes(),
id,
crypto_pair,
);
senders.send_dispatch(
natreq2.expect("couldnt construct message nattraversalrequest2"),
address,
false,
messages_list.clone(),
);
}
NATTRAVERSALREQUEST2 => {
// send ok & send ping to peer
constructed_message = construct_message(OK, Vec::new(), id, crypto_pair);
let ilength = u16::from_be_bytes(length_bytes);
let received_address = &received_message[LENGTH..LENGTH + ilength as usize];
println!("received_address:{:?}", received_message);
//let addressv4 = IpAddr::V4(Ipv4Addr::from_octets(
// received_address[0..4].try_into().expect("incorrect size"),
//));
let bytes: [u8; 4] = received_address[0..4].try_into().expect("incorrect size");
let addr_v4 = Ipv4Addr::from(bytes);
let addressv4 = IpAddr::V4(addr_v4);
let address = SocketAddr::new(
addressv4,
u16::from_be_bytes(received_address[4..6].try_into().expect("incorrect size")),
);
println!("ip: {}", address);
let pingreq = construct_message(PING, Vec::new(), id, crypto_pair);
senders.send_dispatch(
constructed_message.expect("couldnt construct message ping request"),
ip.to_string(),
false,
messages_list.clone(),
);
senders.send_dispatch(
pingreq.expect("couldnt construct message ping request"),
address.to_string(),
false,
messages_list.clone(),
);
constructed_message = None;
}
ERROR => {
if let Ok(err_received) =
String::from_utf8(received_message[LENGTH..(msg_length + LENGTH + 4)].to_vec())
{
let err_msg = format!("Error received from peer {} : {}", ip, err_received);
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg, "".to_owned()));
} else {
let err_msg = format!("Error received from peer {} : N/A", ip,);
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg, "".to_owned()));
}
}
HELLO => {
let mut payload = Vec::new();
let received_length = u16::from_be_bytes(
received_message[TYPE..LENGTH]
.try_into()
.expect("incorrect size"),
);
let received_username =
&received_message[LENGTH + EXTENSIONS..LENGTH + received_length as usize];
handhsake_history.update_peer_info(
ip.to_string(),
String::from_utf8(received_username.to_vec()).expect("invalid conversion"),
);
payload.extend_from_slice(&0u32.to_be_bytes());
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes());
@@ -287,10 +346,7 @@ pub fn parse_message(
return helloreply;
}
// HELLOREPLY
//
//
// ajoute a la liste des peers handshake
HELLOREPLY => {
// ajoute l'username a la liste des peers handshake
let received_length = u16::from_be_bytes(
@@ -305,123 +361,157 @@ pub fn parse_message(
String::from_utf8(received_username.to_vec()).expect("invalid conversion"),
);
// verifie s'il faut renvoyer un root request
let guard = messages_list.lock().expect("Échec du verrouillage");
let mut guard = messages_list.lock().expect("Échec du verrouillage");
let res = guard.get(&id);
match res {
Some(ev) => {
match ev {
EventType::SendRootRequest => {
EventType::HelloThenRootRequest => {
// envoyer la root request
let _ = &guard.remove_entry(&id);
println!("message {} retiré de la liste", id);
let rootrequest = construct_message(
ROOTREQUEST,
Vec::new(),
generate_id(),
crypto_pair,
);
//&guard.insert(, v)
return rootrequest;
}
EventType::Hello => {
let _ = &guard.remove_entry(&id);
println!("message {} retiré de la liste", id);
}
_ => {}
}
}
None => {}
}
}
//
// ROOTREQUEST
//
// envoie un root reply
//
// ROOTREPLY
//
ROOTREPLY => {
// recuperer le pseudo du peers ayant repondu
let peers_exist = handhsake_history.get_peer_info_ip(ip.to_string());
match peers_exist {
Some(peerinfo) => {
// envoyer le hash a la gui
let received_hash: NodeHash = received_message[LENGTH..(32 + LENGTH)]
.try_into()
.expect("incorrect size");
let res = cmd_tx_clone.send(NetworkEvent::FileTreeRootReceived(
peerinfo.username.clone(),
received_hash,
));
println!("file tree sent")
let mut guard = messages_list.lock().expect("Échec du verrouillage");
let res = guard.get(&id);
match res {
Some(ev) => {
match ev {
EventType::RootRequest => {
// envoyer la root request
let _ = &guard.remove_entry(&id);
println!("message {} retiré de la liste", id);
// envoyer le hash a la gui
let received_hash: NodeHash = received_message
[LENGTH..(32 + LENGTH)]
.try_into()
.expect("incorrect size");
let res =
cmd_tx_clone.send(NetworkEvent::FileTreeRootReceived(
peerinfo.username.clone(),
received_hash,
));
println!("file tree sent");
// envoyer un datum
let mut payload = Vec::new();
payload.extend_from_slice(&received_hash);
let new_id = generate_id();
let datumreqest = construct_message(
DATUMREQUEST,
payload,
new_id,
crypto_pair,
);
constructed_message = datumreqest;
guard.insert(new_id, EventType::DatumRequest);
}
_ => {}
}
}
None => {}
}
}
None => {
eprintln!("no peers found");
}
}
}
//
// DATUMREQUEST
//
// envoie le datum
//
// NODATUM
//
// affiche un msg d'erreur
//
// DATUM
//
// parcourt le directory recu ou le big directory et renvoie une DATUMREQUEST pour chaque
// directory ou big directory lu
//
// NATTRAVERSALREQUEST
//
// repond OK et envoie un NATTRAVERSALREQUEST2 au pair B
//
// NATTRAVERSALREQUEST2
//
// envoie OK à S puis envoie un ping à S
// PING
//
// envoie un OK
//
// OK
//
// si NATTRAVERSALREQUEST alors
//
// ERROR
//
// affiche un msg d'erreur
//
// HELLO
//
// envoie une hello reply
//
// HELLOREPLY
//
// envoie un root request
//
// ROOTREQUEST
//
// envoie un root reply
//
// ROOTREPLY
//
// envoie un datum request
//
// DATUMREQUEST
//
// envoie le datum
//
// NODATUM
//
// affiche un msg d'erreur
//
// DATUM
//
// parcourt le directory recu ou le big directory et renvoie une DATUMREQUEST pour chaque
// directory ou big directory lu
//
// NATTRAVERSALREQUEST
//
// repond OK et envoie un NATTRAVERSALREQUEST2 au pair B
//
// NATTRAVERSALREQUEST2
//
// envoie OK à S puis envoie un ping à S
DATUM => {
let mut guard = messages_list.lock().expect("Échec du verrouillage");
let res = guard.get(&id);
match res {
Some(ev) => match ev {
EventType::DatumRequest => {
let _ = &guard.remove_entry(&id);
println!("message {} retiré de la liste", id);
let received_length = u16::from_be_bytes(
received_message[TYPE..LENGTH]
.try_into()
.expect("incorrect size"),
);
let received_datum = &received_message[LENGTH..];
let parsed_node =
parse_received_datum(received_datum.to_vec(), received_length as usize);
match parsed_node {
Some(tuple) => {
let _ = cmd_tx.send(NetworkEvent::FileTreeReceived(
tuple.0,
tuple.1,
ip.to_string(),
));
}
None => {}
}
}
EventType::DatumRequestBig => {
let _ = &guard.remove_entry(&id);
println!("message {} retiré de la liste", id);
let received_length = u16::from_be_bytes(
received_message[TYPE..LENGTH]
.try_into()
.expect("incorrect size"),
);
println!("received length:{}", received_length);
let received_datum = &received_message[LENGTH..];
let parsed_node =
parse_received_datum(received_datum.to_vec(), received_length as usize);
match parsed_node {
Some(tuple) => {
let _ = cmd_tx.send(NetworkEvent::DataReceived(
tuple.0,
tuple.1,
ip.to_string(),
));
println!("datareceived event sent");
}
None => {}
}
}
_ => {}
},
None => {}
}
}
ROOTREQUEST => {
println!("root request received");
let _ = cmd_tx.send(NetworkEvent::RootRequest(ip.to_string()));
}
DATUMREQUEST => {
let received_length = u16::from_be_bytes(
received_message[TYPE..LENGTH]
.try_into()
.expect("incorrect size"),
);
let received_hash = &received_message[LENGTH..LENGTH + received_length as usize];
let _ = cmd_tx.send(NetworkEvent::DatumRequest(
received_hash.try_into().expect("incorrect size"),
ip.to_string(),
));
}
_ => return None,
};
constructed_message

View File

@@ -1,9 +1,15 @@
use crossbeam_channel::Receiver;
use tokio::sync::oneshot;
use tokio::time::sleep;
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 crate::threads_handling::Worker;
use std::clone;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::net::SocketAddr;
use std::net::UdpSocket;
use std::sync::{Arc, Mutex};
@@ -12,15 +18,12 @@ use std::sync::mpsc::{self, Sender};
use std::thread;
use std::collections::VecDeque;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use std::time::{Duration, Instant};
use crate::NetworkEvent;
pub struct MultipleSenders {
senders: Vec<Sender<Message>>,
response_channel: crossbeam_channel::Sender<NetworkEvent>,
}
pub struct Message {
pub payload: Vec<u8>,
pub address: String,
@@ -30,175 +33,77 @@ pub struct Message {
struct RetryMessage {
msg: Message,
attempts: u8,
next_try: Instant,
next_try: u64,
}
pub struct MultipleSenders {
sender: crossbeam_channel::Sender<Message>,
receiver: crossbeam_channel::Receiver<Message>,
response_channel: crossbeam_channel::Sender<NetworkEvent>,
retry_queue: Arc<Mutex<VecDeque<RetryMessage>>>,
completed_messages: HashSet<i32>,
}
impl MultipleSenders {
/*pub fn new(num_channels: usize, socket: &Arc<UdpSocket>) -> Self {
let mut senders = Vec::new();
// Wrap the socket in an Arc so it can be shared across threads
for i in 0..num_channels {
let (tx, rx) = mpsc::channel::<Message>();
// Clone the Arc (this just bumps the reference count, it doesn't copy the socket)
let sock_clone = Arc::clone(&socket);
senders.push(tx);
thread::spawn(move || {
println!("Canal d'envoi {} prêt", i);
for msg in rx {
// Use the cloned Arc inside the thread
if let Err(e) = sock_clone.send_to(&msg.payload, &msg.address) {
eprintln!(
"Erreur d'envoi sur canal {}: {}, address: {}",
i, e, &msg.address
);
} else {
let message_id: [u8; 4] = msg.payload[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id);
let message_type = msg.payload[4];
println!(
"Message {0} de type {1} envoyé à {2} par le canal {3}",
id, message_type, msg.address, i
);
}
}
});
}
MultipleSenders { senders }
}*/
pub fn new(
num_channels: usize,
socket: &Arc<UdpSocket>,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
threads: &mut Vec<Worker>,
) -> Self {
let mut senders = Vec::new();
let (tx1, rx1) = crossbeam_channel::unbounded();
for i in 0..num_channels {
let (tx, rx) = mpsc::channel::<Message>();
let sock_clone = Arc::clone(&socket);
let cmd_tx_clone = cmd_tx.clone();
let rx: Receiver<Message> = rx1.clone();
senders.push(tx);
thread::spawn(move || {
let thread = thread::spawn(move || {
println!("Canal d'envoi {} prêt", i);
let mut queue: VecDeque<RetryMessage> = VecDeque::new();
let max_attempts = 5;
loop {
// Priorité aux messages en attente prêts à être réessayés
if let Some(front) = queue.front() {
if front.next_try <= Instant::now() {
// On prend le message de la queue
let mut item = queue.pop_front().unwrap();
match sock_clone.send_to(&item.msg.payload, &item.msg.address) {
Ok(_) => {
if (&item).msg.is_resp_to_server_handshake {
let res =
cmd_tx_clone.send(NetworkEvent::ConnectedHandshake());
}
let message_id: [u8; 4] =
item.msg.payload[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id);
let message_type = item.msg.payload[4];
println!(
"Message {0} de type {1} envoyé à {2} par le canal {3} (retry {4})",
id, message_type, item.msg.address, i, item.attempts
);
}
Err(e) => {
item.attempts += 1;
if item.attempts >= max_attempts {
let str = format!(
"Abandon du message après {} tentatives sur canal {}: {}, address: {}",
item.attempts, i, e, item.msg.address
);
if (&item).msg.is_resp_to_server_handshake {
let res = cmd_tx_clone
.send(NetworkEvent::ServerHandshakeFailed(str));
}
} else {
// Backoff exponentiel simple
let backoff = Duration::from_millis(
2000u64.saturating_pow(item.attempts as u32),
);
item.next_try = Instant::now() + backoff;
eprintln!(
"Erreur d'envoi sur canal {}: {}, reprogrammation dans {:?}, tentative {}",
i, e, backoff, item.attempts
);
queue.push_front(item); // remettre en tête pour réessayer plus tôt
}
}
}
continue;
}
}
// Si aucun retry prêt, on bloque sur rx avec timeout court, pour pouvoir traiter les timers
match rx.recv_timeout(Duration::from_millis(200)) {
Ok(msg) => {
// On tente d'envoyer immédiatement
match sock_clone.send_to(&msg.payload, &msg.address) {
Ok(_) => {
if msg.is_resp_to_server_handshake {
let res =
cmd_tx_clone.send(NetworkEvent::ConnectedHandshake());
}
let message_id: [u8; 4] =
msg.payload[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id);
let message_type = msg.payload[4];
println!(
"Message {0} de type {1} envoyé à {2} par le canal {3}",
id, message_type, msg.address, i
);
}
Err(e) => {
eprintln!(
"Erreur d'envoi initial sur canal {}: {}, address: {} -- mise en queue pour retry",
i, e, &msg.address
);
let retry = RetryMessage {
msg,
attempts: 1,
next_try: Instant::now() + Duration::from_millis(100),
};
queue.push_back(retry);
}
let msg = rx.recv().unwrap();
match sock_clone.send_to(&msg.payload, &msg.address) {
Ok(_) => {
if msg.is_resp_to_server_handshake {
let res = cmd_tx_clone.send(NetworkEvent::ConnectedHandshake());
}
}
Err(mpsc::RecvTimeoutError::Timeout) => {
// Permet de vérifier la queue à nouveau
continue;
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
// Le sender a été fermé ; vider la queue et sortir
eprintln!(
"Sender fermé pour le canal {}, fermeture du thread d'envoi",
i
let message_id: [u8; 4] =
msg.payload[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id);
let message_type = msg.payload[4];
println!(
"Message {0} de type {1} envoyé à {2} par le canal {3}",
id, message_type, msg.address, i
);
}
Err(e) => {
eprintln!(
"Erreur d'envoi initial sur canal {}: {}, address: {}",
i, e, &msg.address
);
break;
}
}
}
});
threads.push(Worker::spawn(
thread,
crate::threads_handling::WorkerType::MSGSENDER,
));
}
MultipleSenders {
senders,
sender: tx1,
receiver: rx1,
response_channel: cmd_tx.clone(),
retry_queue: Arc::new(Mutex::new(VecDeque::new())),
completed_messages: HashSet::new(),
}
}
/*
/// Envoie un message via un canal spécifique (round-robin ou index précis)
pub fn send_via(
&self,
@@ -226,55 +131,147 @@ impl MultipleSenders {
let id = i32::from_be_bytes(message_id);
guard.insert(id, EventType::SendRootRequest);
}
}*/
pub fn send_dispatch(
&self,
data: Vec<u8>,
remote_addr: String,
is_resp_to_server_handshake: bool,
messages_list: Arc<Mutex<HashMap<i32, EventType>>>,
) {
let msg_to_send = Message {
payload: data.clone(),
address: remote_addr,
is_resp_to_server_handshake,
};
let _ = self.sender.send(msg_to_send);
println!("message sent");
}
/*pub fn start_receving_thread(
socket: &Arc<UdpSocket>,
messages_list: &Arc<HashMap<i32, EventType>>,
crypto_pair: &Arc<CryptographicSignature>,
socket_addr: SocketAddr,
senders: &Arc<MultipleSenders>,
pub fn add_message_to_retry_queue(
&self,
data: Vec<u8>,
remote_addr: String,
is_resp_to_server_handshake: bool,
) {
let sock_clone = Arc::clone(socket);
let cryptopair_clone = Arc::clone(crypto_pair);
let senders_clone = Arc::clone(senders);
let msg_to_send = Message {
payload: data.clone(),
address: remote_addr,
is_resp_to_server_handshake,
};
let base: u64 = 2;
let attempts = 1;
let backoff = base.saturating_pow(attempts); // 2^1 == 2 seconds
let newretry = RetryMessage {
next_try: SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("clock")
.as_secs()
+ backoff,
msg: msg_to_send,
attempts: attempts as u8,
};
let messages_clone = Arc::clone(messages_list);
thread::spawn(move || {
let mut buf = [0u8; 1024];
let mut guard = self.retry_queue.lock().unwrap();
guard.push_back(newretry);
}
}
loop {
match sock_clone.recv_from(&mut buf) {
Ok((amt, src)) => {
handle_recevied_message(
&messages_clone,
&buf.to_vec(),
&cryptopair_clone,
&socket_addr,
&senders_clone,
);
println!("Reçu {} octets de {}: {:?}", amt, src, &buf[..amt]);
pub fn start_retry_thread(
senders: Arc<MultipleSenders>,
max_attempts: u8,
messages_list: Arc<Mutex<HashMap<i32, EventType>>>,
threads: &mut Vec<Worker>,
) {
let thread = thread::spawn(move || {
loop {
thread::sleep(Duration::from_millis(100));
let mut q = senders.retry_queue.lock().unwrap();
//println!("size of retry thread: {}", q.len());
if let Some(front) = q.pop_front() {
// on verifie si le message a recu une reponse
let message_id: [u8; 4] = front.msg.payload[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id);
let message_type = front.msg.payload[4];
let guard = messages_list.lock().unwrap();
if guard.contains_key(&id) {
drop(guard);
// si le message est n'a pas encore a etre traité, on le
// remet en queue de liste
if front.next_try
<= SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("clock")
.as_secs()
{
let attempt = front.attempts + 1;
if attempt >= max_attempts {
let str = format!(
"Abandon du message {} de type {} après {} tentatives, address: {}",
id, message_type, front.attempts, front.msg.address
);
println!("{}", str);
if front.msg.is_resp_to_server_handshake {
let res = senders
.response_channel
.send(NetworkEvent::ServerHandshakeFailed(str));
}
} else {
let str = format!(
"Reemission du message {} de type {}, {} tentatives, address: {}",
id, message_type, front.attempts, front.msg.address
);
println!("{}", str);
senders.send_dispatch(
front.msg.payload.clone(),
front.msg.address.clone(),
front.msg.is_resp_to_server_handshake,
messages_list.clone(),
);
let base: u64 = 2;
let backoff = base.saturating_pow(attempt as u32); // 2^1 == 2 seconds
let newretry = RetryMessage {
next_try: SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("clock")
.as_secs()
+ backoff,
msg: front.msg,
attempts: attempt,
};
q.push_back(newretry); // remettre en tête pour réessayer plus tôt
}
} else {
q.push_back(front); // remettre en tête pour réessayer plus tôt
}
Err(e) => eprintln!("Erreur de réception: {}", e),
}
}
});
}*/
}
});
threads.push(Worker::spawn(
thread,
crate::threads_handling::WorkerType::MSGRETRY,
));
}
pub fn start_receving_thread(
shared_data: &P2PSharedData,
shared_data: &mut P2PSharedData,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
handshake_history: &Arc<Mutex<HandshakeHistory>>,
handshake_history: Arc<HandshakeHistory>,
) {
let sock_clone = shared_data.socket();
let cryptopair_clone = shared_data.cryptopair();
let senders_clone = shared_data.senders();
let messages_clone = shared_data.messages_list();
let messages_received_clone = shared_data.messages_received();
let servername_clone = shared_data.servername();
let handshake_clone = handshake_history.clone();
thread::spawn(move || {
let thread = thread::spawn(move || {
let mut buf = [0u8; 1024];
loop {
match sock_clone.recv_from(&mut buf) {
@@ -284,17 +281,22 @@ pub fn start_receving_thread(
println!("Reçu {} octets de {}: {:?}", amt, src, received_data);
handle_recevied_message(
&messages_clone,
&messages_received_clone,
&received_data,
&cryptopair_clone,
&senders_clone,
&servername_clone,
cmd_tx.clone(),
src,
&handshake_clone,
handshake_history.clone(),
);
}
Err(e) => eprintln!("Erreur de réception: {}", e),
}
}
});
shared_data.threads.push(Worker::spawn(
thread,
crate::threads_handling::WorkerType::MSGRECEPTION,
));
}

View File

@@ -1,7 +1,4 @@
use crate::{
cryptographic_signature::{CryptographicSignature, sign_message},
server_communication::generate_id,
};
use crate::cryptographic_signature::{CryptographicSignature, sign_message};
const ID: usize = 4;
const TYPE: usize = 5;
@@ -9,18 +6,18 @@ const LENGTH: usize = 7;
const EXTENSIONS: usize = 4;
const SIGNATURE: usize = 64;
const PING: u8 = 0;
const OK: u8 = 128;
const ERROR: u8 = 129;
const HELLO: u8 = 1;
const HELLOREPLY: u8 = 130;
pub const ROOTREQUEST: u8 = 2;
const ROOTREPLY: u8 = 131;
const DATUMREQUEST: u8 = 3;
const NODATUM: u8 = 133;
const DATUM: u8 = 132;
const NATTRAVERSALREQUEST: u8 = 4;
const NATTRAVERSALREQUEST2: u8 = 5;
pub(crate) const PING: u8 = 0;
pub(crate) const OK: u8 = 128;
pub(crate) const ERROR: u8 = 129;
pub(crate) const HELLO: u8 = 1;
pub(crate) const HELLOREPLY: u8 = 130;
pub(crate) const ROOTREQUEST: u8 = 2;
pub(crate) const ROOTREPLY: u8 = 131;
pub(crate) const DATUMREQUEST: u8 = 3;
pub(crate) const NODATUM: u8 = 133;
pub(crate) const DATUM: u8 = 132;
pub(crate) const NATTRAVERSALREQUEST: u8 = 4;
pub(crate) const NATTRAVERSALREQUEST2: u8 = 5;
pub fn construct_message(
msgtype: u8,
@@ -51,19 +48,199 @@ pub fn construct_message(
return Some(message);
}
ERROR | DATUMREQUEST => {
message.extend_from_slice(&payload.len().to_be_bytes());
let a = payload.len() as u16;
println!("payload size:{}", a);
message.extend_from_slice(&a.to_be_bytes());
message.extend_from_slice(&payload);
return Some(message);
}
ROOTREPLY | NODATUM | DATUM | NATTRAVERSALREQUEST => {
message.extend_from_slice(&payload.len().to_be_bytes());
println!("payload:{:?}", &payload);
let a = payload.len() as u16;
println!("payload size:{}", a);
message.extend_from_slice(&a.to_be_bytes());
message.extend_from_slice(&payload);
println!("payload:{:?}", &message);
let signature = sign_message(crypto_pair, &message);
message.extend_from_slice(&signature);
return Some(message);
println!("message_to_send_len:{}", &message.len());
return Some(signature);
}
_ => {}
}
None
}
pub struct UDPMessage {
id: u32,
msg_type: u8,
length: u16,
body: Vec<u8>,
signature: Vec<u8>,
}
pub struct HandshakeMessage {
pub id: u32,
msg_type: u8,
length: u16,
extensions: u32,
pub name: Vec<u8>,
pub signature: Vec<u8>,
}
pub struct NatTraversal {}
impl UDPMessage {
pub fn ping(id: u32) -> UDPMessage {
UDPMessage {
id: id,
msg_type: 0,
length: 0,
body: vec![0; 985],
signature: vec![0; 32],
}
}
pub fn error(id: u32) -> UDPMessage {
UDPMessage {
id: id,
msg_type: 129,
length: 0,
body: vec![0; 985],
signature: vec![0; 32],
}
}
pub fn parse(received_message: Vec<u8>) -> UDPMessage {
let id_bytes: [u8; 4] = received_message[0..4]
.try_into()
.expect("Taille incorrecte");
let length_bytes: [u8; 2] = received_message[5..7]
.try_into()
.expect("Taille incorrecte");
let msg_length = u16::from_be_bytes(length_bytes);
let name_bytes = &received_message[7..msg_length as usize + 8];
let signature_bytes =
&received_message[msg_length as usize + 8..msg_length as usize + 9 + 32];
UDPMessage {
id: u32::from_be_bytes(id_bytes),
msg_type: received_message[4],
length: u16::from_be_bytes(length_bytes),
body: name_bytes.to_vec(),
signature: signature_bytes.to_vec(),
}
}
pub fn display(&self) {
println!("ID: {:?}", self.id);
println!("Message Type: {}", self.msg_type);
println!("Length: {:?}", self.length);
let good_length = usize::min(self.length as usize, 985);
println!("name: {:?}", &self.body[..good_length]);
println!("Signature: {:?}", self.signature);
}
}
impl HandshakeMessage {
pub fn display(&self) {
println!("ID: {:?}", self.id);
println!("Message Type: {}", self.msg_type);
println!("Length: {:?}", self.length);
println!("extensions: {:?}", self.extensions);
println!("name: {:?}", &self.name[..(self.length - 4) as usize]);
println!("Signature: {:?}", self.signature);
}
pub fn hello(id: u32, length: u16, username: String) -> HandshakeMessage {
let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec();
HandshakeMessage {
id: id,
msg_type: 1,
length: length,
extensions: 0,
name: name_vec,
signature: vec![0; 64],
}
}
pub fn helloReply(id: u32, length: u16, username: String) -> HandshakeMessage {
let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec();
HandshakeMessage {
id: id,
msg_type: 130,
length: length,
extensions: 0,
name: name_vec,
signature: vec![0; 64],
}
}
pub fn serialize(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + 1 + 2 + 4 + self.name.len() + self.signature.len());
// id: u32 little-endian
out.extend_from_slice(&self.id.to_be_bytes());
// msg_type: u8
out.push(self.msg_type);
out.extend_from_slice(&self.length.to_be_bytes());
out.extend_from_slice(&self.extensions.to_be_bytes());
out.extend_from_slice(&self.name);
out.extend_from_slice(&self.signature);
out
}
pub fn parse(received_message: Vec<u8>) -> HandshakeMessage {
let id_bytes: [u8; 4] = received_message[0..4]
.try_into()
.expect("Taille incorrecte");
let length_bytes: [u8; 2] = received_message[5..7]
.try_into()
.expect("Taille incorrecte");
let msg_length = u16::from_be_bytes(length_bytes);
let extensions_bytes: [u8; 4] = received_message[7..11]
.try_into()
.expect("Taille incorrecte");
let name_bytes = &received_message[11..(11 + msg_length - 4) as usize];
let signature_bytes =
&received_message[(11 + msg_length - 4) as usize..(11 + msg_length - 4 + 64) as usize];
HandshakeMessage {
id: u32::from_be_bytes(id_bytes),
msg_type: received_message[4],
length: u16::from_be_bytes(length_bytes),
extensions: u32::from_be_bytes(extensions_bytes),
name: name_bytes.to_vec(),
signature: signature_bytes.to_vec(),
}
}
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
/*
/// creates an handshake message
#[tokio::test]
async fn creating_handshake_msg() {
let username = String::from("charlie_kirk");
let handshake = HandshakeMessage::hello(0, 12, username);
handshake.display();
}
/// parses an handshake message
#[tokio::test]
async fn parse_handshakemessage() {
let username = String::from("charlie_kirk");
let handshake = HandshakeMessage::hello(0, 12, username);
let ser = handshake.serialize();
let parsed = HandshakeMessage::parse(ser);
handshake.display();
parsed.display();
}*/
}

View File

@@ -1,17 +1,22 @@
// this class consists of a thread that will re send pings every time the first element
// of the stack is at the correct unix time
pub use crate::message_handling::*;
use std::{
collections::{HashMap, VecDeque},
net::{AddrParseError, Ipv4Addr, SocketAddr},
ops::Add,
process::Command,
sync::{Arc, Mutex},
thread,
thread::{self, JoinHandle},
time::{self, Duration, SystemTime},
};
use crate::NetworkEvent;
use crate::{
NetworkEvent, cryptographic_signature::CryptographicSignature,
messages_channels::MultipleSenders, threads_handling::Worker,
};
use crate::{
P2PSharedData, construct_message, generate_id, messages_structure,
registration::perform_handshake,
@@ -26,63 +31,35 @@ pub struct PeerInfo {
pub ip: SocketAddr,
}
#[derive(Debug, Clone)]
pub struct HandshakeHistory {
//time_k_ip_v: HashMap<u64, u64>,
username_k_peerinfo_v: HashMap<String, PeerInfo>,
ip_k_peerinfo_v: HashMap<String, PeerInfo>,
pub username_k_peerinfo_v: Arc<Mutex<HashMap<String, PeerInfo>>>,
ip_k_peerinfo_v: Arc<Mutex<HashMap<String, PeerInfo>>>,
}
impl HandshakeHistory {
pub fn new() -> HandshakeHistory {
HandshakeHistory {
//time_k_ip_v: HashMap::new(),
//ip_k_peerinfo_v: HashMap::new(),
username_k_peerinfo_v: HashMap::new(),
ip_k_peerinfo_v: HashMap::new(),
username_k_peerinfo_v: Arc::new(Mutex::new(HashMap::new())),
ip_k_peerinfo_v: Arc::new(Mutex::new(HashMap::new())),
}
}
/*pub fn update_handshake(&self) {
let hashmap_shared = Arc::new(self.username_k_peerinfo_v);
thread::spawn(move || {
let selfhashmap = hashmap_shared.clone();
loop {
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_username(&self, username: String) -> Option<&PeerInfo> {
self.username_k_peerinfo_v.get(&username).clone()
let guard = self.username_k_peerinfo_v.lock().unwrap();
guard.get(&username).cloned()
}
pub fn get_peer_info_ip(&self, ip: String) -> Option<&PeerInfo> {
self.ip_k_peerinfo_v.get(&ip).clone()
pub fn get_peer_info_ip(&self, ip: String) -> Option<PeerInfo> {
let guard = self.ip_k_peerinfo_v.lock().unwrap();
guard.get(&ip).cloned()
}
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 update_peer_info(&mut self, ip: String, username: String) {
pub fn update_peer_info(&self, ip: String, username: String) {
let peerinfo = self.get_peer_info_ip(ip.clone());
match peerinfo {
Some(peer_info) => match ip.parse::<SocketAddr>() {
@@ -92,8 +69,18 @@ impl HandshakeHistory {
pubkey: peer_info.pubkey,
ip: addr,
};
self.ip_k_peerinfo_v.insert(ip, new_peer_info.clone());
self.username_k_peerinfo_v.insert(username, new_peer_info);
let mut guardb = self.ip_k_peerinfo_v.lock().unwrap();
guardb.insert(ip.to_string(), new_peer_info.clone());
let mut guard = self.username_k_peerinfo_v.lock().unwrap();
guard.insert(username.to_string(), new_peer_info);
println!(
"handshake added: {}, {}, {}",
username.to_string(),
ip.to_string(),
guard.len(),
);
}
Err(e) => eprintln!("parse error: {}", e),
},
@@ -103,43 +90,57 @@ impl HandshakeHistory {
}
}
pub fn add_new_handshake(&mut self, hash: VerifyingKey, username: String, ip: SocketAddr) {
pub fn get_username_peerinfo_map(&self) -> Arc<Mutex<HashMap<String, PeerInfo>>> {
self.username_k_peerinfo_v.clone()
}
pub fn add_new_handshake(&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());
let mut guard = self.username_k_peerinfo_v.lock().unwrap();
guard.insert(username, peerinfo.clone());
let mut guardb = self.ip_k_peerinfo_v.lock().unwrap();
guardb.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, false);
/*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);
pub fn update_handshake(
senders: Arc<MultipleSenders>,
crypto_pair: Arc<CryptographicSignature>,
messages_list: Arc<Mutex<HashMap<i32, EventType>>>,
username_k_peerinfo_v: Arc<Mutex<HashMap<String, PeerInfo>>>,
) -> Worker {
let map_for_thread = username_k_peerinfo_v.clone();
let handle = thread::spawn(move || {
loop {
let guard = map_for_thread.lock().unwrap();
for (peer, peerinfo) in guard.iter() {
let id = generate_id();
let mut map = messages_list.lock().unwrap();
map.insert(id, EventType::Ping);
let pingrequest = construct_message(PING, Vec::new(), id, &crypto_pair);
if let Some(ping) = pingrequest {
senders.add_message_to_retry_queue(
ping.clone(),
peerinfo.ip.to_string(),
false,
);
senders.send_dispatch(
ping,
peerinfo.ip.to_string(),
false,
messages_list.clone(),
);
}
}
}*/
} else {
// envoyer un datum request
}
drop(guard);
thread::sleep(Duration::from_secs(60));
}
});
Worker::spawn(handle, crate::threads_handling::WorkerType::PING)
}
#[cfg(test)]

View File

@@ -1,19 +1,14 @@
use bytes::Bytes;
use getrandom::Error;
use crate::NetworkEvent;
use crate::P2PSharedData;
use crate::cryptographic_signature::{CryptographicSignature, formatPubKey, sign_message};
use crate::cryptographic_signature::CryptographicSignature;
use crate::get_server_address;
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 crossbeam_channel::Sender;
use std::net::SocketAddr;
use std::net::UdpSocket;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::sync::Arc;
///
/// sends the cryptographic signature to the server using a PUT request over the HTTP API.
@@ -29,28 +24,13 @@ pub async fn register_with_the_server(
let pubkey_bytes_minus = pubkey_bytes[1..].to_vec();
let res = client.put(uri).body(pubkey_bytes_minus).send().await?;
let res = res.error_for_status()?;
println!("register ip adresses");
Ok(())
}
///
/// sends a get request to the server to get the socket address of the given peer
///
pub async fn get_socket_address(username: String, ip: String) -> Result<Bytes, reqwest::Error> {
let client = reqwest::Client::new();
let uri = format!("{}/peers/{}/addresses", ip, username);
let res = client.get(uri).send().await?;
if res.status().is_success() {
println!("Successfully retreived the addresses.");
} else {
eprintln!(
"Failed to get the peers addresses from the server. Status: {}",
res.status()
);
match res.error_for_status() {
Ok(_) => {
println!("register ip adresses");
Ok(())
}
Err(e) => Err(e),
}
let body: Bytes = res.bytes().await?;
Ok(body)
}
pub fn parse_addresses(input: &String) -> Vec<SocketAddr> {
@@ -80,54 +60,39 @@ pub async fn perform_handshake(
println!("username: {}, ip: {}", username.clone(), ip.clone());
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,
first.to_string(),
is_server_handshake,
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));
let id = generate_id();
let server_addr_query = get_server_address(username.clone(), ip.clone());
match server_addr_query.await {
Some(sockaddr_bytes) => {
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);
if is_server_handshake {
sd.add_message(id, EventType::Hello);
sd.set_serveraddress(sockaddr_bytes.to_string());
} else {
sd.add_message(id, EventType::HelloThenRootRequest);
}
match hello_handshake {
Some(handshake_message) => {
senders.send_dispatch(
handshake_message,
sockaddr_bytes.to_string(),
is_server_handshake,
sd.messages_list(),
);
}
None => {}
}
}
Err(e) => {
let err_msg = format!("failed to retreive socket address: {}", e).to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg));
None => {
let err_msg = format!("failed to retreive socket address:").to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg, "".to_owned()));
}
}
@@ -151,8 +116,6 @@ pub async fn perform_handshake(
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
/*///
/// does the procedure to register with the server

View File

@@ -0,0 +1,35 @@
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use std::thread::JoinHandle;
pub enum WorkerType {
MSGRECEPTION,
MSGSENDER,
PING,
MSGRETRY,
}
pub struct Worker {
thread: Option<JoinHandle<()>>,
stop: Arc<AtomicBool>,
workertype: WorkerType,
}
impl Worker {
pub fn spawn(thread: JoinHandle<()>, workertype: WorkerType) -> Self {
Worker {
stop: Arc::new(AtomicBool::new(false)),
thread: Some(thread),
workertype,
}
}
pub fn stop(mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(h) = self.thread.take() {
let _ = h.join();
}
}
}

View File

@@ -0,0 +1,46 @@
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timestamp {
secs: u64, // seconds since UNIX epoch
}
unsafe impl Send for Timestamp {}
impl Timestamp {
// Create a Timestamp from current system time
pub fn now() -> Self {
let dur = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system time before UNIX_EPOCH");
Self {
secs: dur.as_secs(),
}
}
// Create from explicit fields (optional helper)
pub fn from_secs(secs: u64) -> Self {
Self { secs }
}
// Return underlying seconds
pub fn as_secs(&self) -> u64 {
self.secs
}
// Return elapsed seconds between `self` and `other`.
// Panics if `other` is in the future relative to `self`.
// If you call `Timestamp::now().diff(past)`, it returns seconds since `past`.
pub fn diff(&self, earlier: &Timestamp) -> u64 {
assert!(earlier.secs <= self.secs, "given time is in the future");
self.secs - earlier.secs
}
pub fn to_string(&self) -> String {
let secs_of_day = self.secs % 86_400;
let hh = secs_of_day / 3600;
let mm = (secs_of_day % 3600) / 60;
let ss = secs_of_day % 60;
format!("{:02}:{:02}:{:02}", hh, mm, ss)
}
}

Binary file not shown.

47
todo.md
View File

@@ -1,38 +1,19 @@
# Todo :
# Todo
## peer discovery
## fonctionnalités :
- proposer des fichiers
- telechargement des fichiers
- receivers threads
- ask for nat traversal
## handshake
- 5min timeout after handshake
- matain connection every 4 min
## data transfer
- request structure
- root/root reply structure
- datum/nodatum and datum structures
- nattraversal 1 and 2 structures
- setting in gui to act as a relay
- chunk, directory, big, bigdirectory structures
## fonctionnalités application :
rechercher les fichiers d'un pair
telechargement des fichiers
choisir un dossier à partager
choisir le nombre de canaux
handshake server DOING
se deconnecter du réseau DOING
## autre :
## autre
socket ipv6
# FAIT
# FAIT :
rechercher les fichiers d'un pair OK
- choisir un pseudo OK
- get rsquest to the uri /peers/ OK
- generation of the cryptographic key OK
@@ -45,4 +26,12 @@ socket ipv6
- generer une clé publique OK
- verifier signature OK
- 2 channels -> un pour envoyer et un pour recevoir OK
- get rsquest to the uri /peers/ OK
- request structure
- root/root reply structure
- datum/nodatum and datum structures
- nattraversal 1 and 2 structures
- chunk, directory, big, bigdirectory structures
- ajouter hello et nat a l'exp backoff OK
- peers n'ayant pas d'adresse OK
- verifier le refresh des peers OK