code tidy

This commit is contained in:
Tiago Batista Cardoso
2026-01-25 14:22:20 +01:00
parent 55a0eb21bb
commit 15bfbcd0d4
12 changed files with 124 additions and 537 deletions

View File

@@ -102,14 +102,6 @@ impl P2PClientApp {
pub fn clear_success(&mut self) {
self.success_message = None;
}
fn set_current_total_chunks(&mut self, len: Option<usize>) {
self.current_total_chunks = len
}
fn set_current_received_chunks(&mut self, arg: usize) {
self.current_received_chunks = arg
}
}
impl eframe::App for P2PClientApp {
@@ -195,8 +187,8 @@ impl eframe::App for P2PClientApp {
None => {}
}
}
NetworkEvent::FileTreeRootReceived(peer_id, root_hash) => {
if let Ok(chunknode) = ChunkNode::new(Vec::new()) {
NetworkEvent::FileTreeRootReceived(_, root_hash) => {
if let Ok(_) = ChunkNode::new(Vec::new()) {
let data_map: HashMap<NodeHash, MerkleNode> = HashMap::new();
//data_map.insert(root_hash, MerkleNode::Chunk(chunknode));
println!("len root: {}", data_map.len());
@@ -279,6 +271,13 @@ impl eframe::App for P2PClientApp {
}
_ => {}
}
if let Some(total) = self.current_total_chunks {
// recompute received (safer than incrementing)
let received = total.saturating_sub(self.remaining_chunks.len());
self.current_received_chunks = received;
}
println!("remaining chunks size: {}", self.remaining_chunks.len());
match create_dir("./Download/") {
Ok(_) => println!("Directory created successfully!"),
@@ -312,17 +311,9 @@ impl eframe::App for P2PClientApp {
}
println!("bigfile téléchargé {}", self.root_downloading_file);
if let Some(total) = self.current_total_chunks {
// recompute received (safer than incrementing)
let received = total.saturating_sub(self.remaining_chunks.len());
self.current_received_chunks = received;
}
if self.remaining_chunks.is_empty() {
self.current_total_chunks = None;
self.current_received_chunks = 0;
println!("bigfile téléchargé");
}
self.current_total_chunks = None;
self.current_received_chunks = 0;
println!("bigfile téléchargé");
}
}
NetworkEvent::Success(msg, peer_username) => {
@@ -440,7 +431,7 @@ impl eframe::App for P2PClientApp {
});
if ui.button("Network").clicked() {
self.show_network_window = true;
self.show_network_window = !self.show_network_window;
}
if self.show_network_window {
@@ -462,6 +453,8 @@ impl eframe::App for P2PClientApp {
ServerStatus::NotConnected => {
egui::Window::new("Network")
.resizable(false)
.collapsible(false)
.title_bar(false)
.show(ctx, |ui| {
ui.horizontal(|ui| {
ui.label("Server IP:");
@@ -654,7 +647,7 @@ impl eframe::App for P2PClientApp {
_ => {}
}
if ui.button("Send Ping").clicked() {
let res = self.network_cmd_tx.send(NetworkCommand::Ping(
let _ = self.network_cmd_tx.send(NetworkCommand::Ping(
peer.0.to_string(),
self.connected_address.clone(),
));
@@ -848,7 +841,7 @@ impl P2PClientApp {
}
});
}
MerkleNode::Big(node) => {
MerkleNode::Big(_) => {
if ui
.selectable_label(false, format!("📄 (B) {}", name))
.on_hover_text("Click to request file chunks...")

View File

@@ -1,11 +1,6 @@
use std::io::Read;
use bytes::Bytes;
use p256::EncodedPoint;
use p256::ecdsa::{
Signature, SigningKey, VerifyingKey,
signature::{Signer, Verifier},
};
use p256::ecdsa::{Signature, SigningKey, VerifyingKey, signature::Verifier};
use rand_core::OsRng;
use sha2::{Digest, Sha256};
@@ -37,15 +32,6 @@ impl CryptographicSignature {
}
}
///
/// returns a string representing the pub_key as a String
///
pub fn formatPubKey(crypto_pair: CryptographicSignature) -> String {
let encoded_point = crypto_pair.pub_key.to_encoded_point(false);
let pubkey_bytes = encoded_point.as_bytes();
hex::encode(pubkey_bytes)
}
pub async fn get_peer_key(username: &String) -> Result<VerifyingKey, reqwest::Error> {
let client = reqwest::Client::new();
let uri = format!("https://jch.irif.fr:8443/peers/{}/key", username);
@@ -126,34 +112,7 @@ pub fn sign_message(crypto_pair: &CryptographicSignature, message: &Vec<u8>) ->
signed_message
}
Err(e) => {
panic!("error");
panic!("error : {}", e);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/*
///
/// creates a cryptographic signature
///
#[test]
fn creating_cryptographic_signature() {
let username = String::from("gamixtreize");
let crypto_pair = CryptographicSignature::new(username);
let formatted_pubkey = formatPubKey(crypto_pair);
println!("pubkey : {}", formatted_pubkey);
}*/
/*#[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

@@ -1,14 +1,9 @@
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;
use std::io::Write;
// --- Constants ---
pub const MAX_CHUNK_DATA_SIZE: usize = 1024;
@@ -345,9 +340,9 @@ pub fn generate_base_tree() -> MerkleTree {
let oscar_content = "oscar is the opponent".to_string().into_bytes();
let mut children_nodes = Vec::new();
for i in 0..10 {
for _ in 0..10 {
let mut i_nodes = Vec::new();
for j in 0..10 {
for _ in 0..10 {
let node1 = MerkleNode::Chunk(ChunkNode::new(bob_content.clone()).unwrap());
let hash = hash(&node1.serialize());
i_nodes.push(hash);
@@ -368,14 +363,14 @@ pub fn generate_base_tree() -> MerkleTree {
let node2 = MerkleNode::Chunk(ChunkNode::new(alice_content).unwrap());
let hash2 = hash(&node2.serialize());
//res.insert(hash1, node1);
//res.insert(hash2, node2);
res.insert(hash1, node1);
res.insert(hash2, node2);
res.insert(hashbig, bignode);
let node3 = MerkleNode::Chunk(ChunkNode::new(oscar_content).unwrap());
let hash3 = hash(&node3.serialize());
//res.insert(hash3, node3);
res.insert(hash3, node3);
let dir1 = MerkleNode::Directory(DirectoryNode {
entries: [DirectoryEntry {
@@ -386,7 +381,7 @@ pub fn generate_base_tree() -> MerkleTree {
});
let hash_dir1 = hash(&dir1.serialize());
//res.insert(hash_dir1, dir1);
res.insert(hash_dir1, dir1);
let root = MerkleNode::Directory(DirectoryNode {
entries: [
@@ -394,14 +389,14 @@ pub fn generate_base_tree() -> MerkleTree {
filename: generate_random_filename(),
content_hash: hashbig,
},
/*DirectoryEntry {
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash2,
},
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash_dir1,
},*/
},
]
.to_vec(),
});
@@ -486,42 +481,3 @@ pub fn big_or_chunk_to_file(tree: &MerkleTree, node: &MerkleNode, file: &mut Fil
}
}
}
#[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

@@ -1,200 +0,0 @@
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

@@ -1,4 +1,4 @@
use crate::{BigDirectoryNode, DirectoryEntry, DirectoryNode, MerkleNode, MerkleTree, NodeHash};
use crate::{BigDirectoryNode, DirectoryEntry, DirectoryNode, MerkleNode, NodeHash};
use sha2::{Digest, Sha256};
const CHUNK: u8 = 0;
@@ -40,7 +40,7 @@ pub fn parse_received_datum(
)),
DIRECTORY => {
let mut dir_entries = Vec::new();
let mut offset = 1 as usize;
let mut offset: usize;
for i in 0..((value_slice.len() - 1) / 64) as u8 {
offset = (1 + 64 * i as usize) as usize;
println!("offset:{}, i:{}", offset, i);
@@ -68,7 +68,7 @@ pub fn parse_received_datum(
}
BIG => {
let mut bigdir_entries: Vec<NodeHash> = Vec::new();
let mut offset = 1 as usize;
let mut offset: 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);
@@ -88,7 +88,7 @@ pub fn parse_received_datum(
}
BIGDIRECTORY => {
let mut bigdir_entries: Vec<NodeHash> = Vec::new();
let mut offset = 1 as usize;
let mut offset: 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);

View File

@@ -1,6 +1,5 @@
mod cryptographic_signature;
mod data;
mod datum_generation;
mod datum_parsing;
mod fetchsocketaddresserror;
mod message_handling;
@@ -21,18 +20,16 @@ use crate::{
message_handling::EventType,
messages_channels::{MultipleSenders, start_receving_thread, start_retry_thread},
messages_structure::{
DATUM, DATUMREQUEST, NATTRAVERSALREQUEST, NATTRAVERSALREQUEST2, NODATUM, PING, ROOTREQUEST,
construct_message,
DATUM, DATUMREQUEST, NATTRAVERSALREQUEST, 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::collections::HashSet;
use std::{
io::Error,
net::{IpAddr, Ipv4Addr, UdpSocket},
net::{IpAddr, UdpSocket},
time::Duration,
};
use std::{
@@ -274,12 +271,8 @@ pub fn start_p2p_executor(
None => {}
Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().send_dispatch(
resp_msg,
addr.clone(),
false,
sd.messages_list(),
);
sd.senders_ref()
.send_dispatch(resp_msg, addr.clone(), false);
}
}
}
@@ -296,12 +289,8 @@ pub fn start_p2p_executor(
None => {}
Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().send_dispatch(
resp_msg,
addr.clone(),
false,
sd.messages_list(),
);
sd.senders_ref()
.send_dispatch(resp_msg, addr.clone(), false);
}
}
}
@@ -319,12 +308,8 @@ pub fn start_p2p_executor(
None => {}
Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().send_dispatch(
resp_msg,
addr.clone(),
false,
sd.messages_list(),
);
sd.senders_ref()
.send_dispatch(resp_msg, addr.clone(), false);
}
}
}
@@ -396,7 +381,7 @@ pub fn start_p2p_executor(
println!("no shared data");
}
}
NetworkCommand::ConnectPeer((username, connected)) => {
NetworkCommand::ConnectPeer((username, _)) => {
println!("[Network] ConnectPeer() called");
println!("[Network] Attempting to connect to: {}", username);
// Network logic to connect...
@@ -406,7 +391,7 @@ pub fn start_p2p_executor(
NetworkCommand::RequestFileTree(_) => {
println!("[Network] RequestFileTree() called");
}
NetworkCommand::Discover(username, hash, ip) => {
NetworkCommand::Discover(username, _, ip) => {
// envoie un handshake au peer, puis un root request
if let Some(sd) = shared_data.as_ref() {
let res = sd
@@ -439,7 +424,6 @@ pub fn start_p2p_executor(
resp_msg,
peerinfo.ip.to_string(),
false,
sd.messages_list(),
);
}
}
@@ -503,12 +487,7 @@ pub fn start_p2p_executor(
false,
);
sd.senders_ref().send_dispatch(
resp_msg,
ip.clone(),
false,
sd.messages_list(),
);
sd.senders_ref().send_dispatch(resp_msg, ip.clone(), false);
}
}
}
@@ -529,9 +508,18 @@ 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, name.to_owned()));
let res = event_tx.send(NetworkEvent::Disconnected());
match event_tx.send(NetworkEvent::Error(err_msg, name.to_owned())) {
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
match event_tx.send(NetworkEvent::Disconnected()) {
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
None
}
};
@@ -540,11 +528,25 @@ 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, name.to_owned()));
let res = event_tx.send(NetworkEvent::Disconnected());
match event_tx.send(NetworkEvent::Error(err_msg, name.to_owned())) {
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
match event_tx.send(NetworkEvent::Disconnected()) {
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
} else {
let res = event_tx.send(NetworkEvent::Connected(ip));
match event_tx.send(NetworkEvent::Connected(ip)) {
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
println!("username created: {}", sd.cryptopair().username);
}
//println!("ip: {}", ip);
@@ -563,10 +565,15 @@ pub fn start_p2p_executor(
NetworkCommand::FetchPeerList(ip) => {
println!("[Network] FetchPeerList() called");
if ip == "" {
let res = event_tx.send(NetworkEvent::Error(
match event_tx.send(NetworkEvent::Error(
"Not registered to any server".to_string(),
"".to_owned(),
));
)) {
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
} else {
println!("cc");
match get_peer_list(ip).await {
@@ -691,7 +698,6 @@ pub fn start_p2p_executor(
),
server_addr.to_string(),
false,
sd.messages_list(),
);
}
Err(err_msg) => {
@@ -730,22 +736,6 @@ fn socket_addr_to_vec(addr: SocketAddr) -> Vec<u8> {
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);
@@ -753,7 +743,7 @@ async fn quick_ping(addr: &SocketAddr, timeout_ms: u64, sd: &P2PSharedData) -> b
if let Some(ping) = pingreq {
sd.add_message(id, EventType::Ping);
sd.senders_ref()
.send_dispatch(ping, addr.to_string(), false, sd.messages_list());
.send_dispatch(ping, addr.to_string(), false);
}
sleep(Duration::from_millis(timeout_ms)).await;
@@ -848,7 +838,6 @@ pub async fn get_socket_address(
natreq.expect("couldnt construct message nattraversalrequest2"),
sd.serveraddress().to_string(),
false,
sd.messages_list(),
);
sleep(Duration::from_millis(5000)).await;

View File

@@ -10,7 +10,6 @@ use crate::{
};
use std::{
collections::HashMap,
default,
net::{Ipv4Addr, SocketAddr},
};
use std::{
@@ -61,7 +60,6 @@ const ID: usize = 4;
const TYPE: usize = 5;
const LENGTH: usize = 7;
const EXTENSIONS: usize = 4;
const SIGNATURE: usize = 64;
pub const PING: u8 = 0;
const OK: u8 = 128;
@@ -101,7 +99,6 @@ pub fn handle_recevied_message(
let length_bytes: [u8; 2] = recevied_message[TYPE..LENGTH]
.try_into()
.expect("Taille incorrecte");
let msg_length = u16::from_be_bytes(length_bytes) as usize;
let ilength = u16::from_be_bytes(length_bytes);
let received_name = &recevied_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize];
let name = String::from_utf8(received_name.to_vec()).expect("wrong name");
@@ -126,12 +123,7 @@ pub fn handle_recevied_message(
None => {}
Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg);
senders.send_dispatch(
resp_msg,
ip.to_string(),
is_resp_to_server_handshake,
messages_list.clone(),
);
senders.send_dispatch(resp_msg, ip.to_string(), is_resp_to_server_handshake);
}
}
}
@@ -149,10 +141,6 @@ pub fn parse_message(
) -> Option<Vec<u8>> {
let cmd_tx_clone = cmd_tx.clone();
let id_bytes: [u8; 4] = received_message[0..ID]
.try_into()
.expect("Taille incorrecte");
let msgtype = received_message[ID];
messages_received
@@ -269,7 +257,6 @@ pub fn parse_message(
natreq2.expect("couldnt construct message nattraversalrequest2"),
address,
false,
messages_list.clone(),
);
}
@@ -300,14 +287,12 @@ pub fn parse_message(
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;
}
@@ -408,11 +393,15 @@ pub fn parse_message(
[LENGTH..(32 + LENGTH)]
.try_into()
.expect("incorrect size");
let res =
cmd_tx_clone.send(NetworkEvent::FileTreeRootReceived(
peerinfo.username.clone(),
received_hash,
));
match cmd_tx_clone.send(NetworkEvent::FileTreeRootReceived(
peerinfo.username.clone(),
received_hash,
)) {
Ok(_) => {}
Err(e) => {
println!("Network Event Error : {}", e.to_string());
}
};
println!("file tree sent");
// envoyer un datum
let mut payload = Vec::new();

View File

@@ -1,26 +1,20 @@
use crossbeam_channel::Receiver;
use tokio::sync::oneshot;
use tokio::time::sleep;
use crate::P2PSharedData;
use crate::message_handling::EventType;
use crate::message_handling::handle_recevied_message;
use crate::peers_refresh::HandshakeHistory;
use crate::threads_handling::Worker;
use std::clone;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::net::SocketAddr;
use std::collections::HashMap;
use std::net::UdpSocket;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{self, Sender};
use std::thread;
use std::collections::VecDeque;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use std::time::{Duration, Instant};
use crate::NetworkEvent;
@@ -38,10 +32,8 @@ struct RetryMessage {
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 {
@@ -68,7 +60,12 @@ impl MultipleSenders {
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());
match cmd_tx_clone.send(NetworkEvent::ConnectedHandshake()) {
Ok(_) => {}
Err(e) => {
println!("Network Event Error : {}", e.to_string());
}
};
}
let message_id: [u8; 4] =
msg.payload[0..4].try_into().expect("size error");
@@ -96,18 +93,13 @@ impl MultipleSenders {
}
});
threads.push(Worker::spawn(
thread,
crate::threads_handling::WorkerType::MSGSENDER,
));
threads.push(Worker::spawn(thread));
}
MultipleSenders {
sender: tx1,
receiver: rx1,
response_channel: cmd_tx.clone(),
retry_queue: Arc::new(Mutex::new(VecDeque::new())),
completed_messages: HashSet::new(),
}
}
@@ -116,7 +108,6 @@ impl MultipleSenders {
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(),
@@ -192,9 +183,15 @@ pub fn start_retry_thread(
);
println!("{}", str);
if front.msg.is_resp_to_server_handshake {
let res = senders
match senders
.response_channel
.send(NetworkEvent::ServerHandshakeFailed(str));
.send(NetworkEvent::ServerHandshakeFailed(str))
{
Ok(_) => {}
Err(e) => {
println!("Network Event Error : {}", e.to_string());
}
};
}
} else {
let str = format!(
@@ -207,7 +204,6 @@ pub fn start_retry_thread(
front.msg.payload.clone(),
front.msg.address.clone(),
front.msg.is_resp_to_server_handshake,
messages_list.clone(),
);
let base: u64 = 2;
@@ -232,10 +228,7 @@ pub fn start_retry_thread(
}
}
});
threads.push(Worker::spawn(
thread,
crate::threads_handling::WorkerType::MSGRETRY,
));
threads.push(Worker::spawn(thread));
}
pub fn start_receving_thread(
@@ -273,8 +266,5 @@ pub fn start_receving_thread(
}
}
});
shared_data.threads.push(Worker::spawn(
thread,
crate::threads_handling::WorkerType::MSGRECEPTION,
));
shared_data.threads.push(Worker::spawn(thread));
}

View File

@@ -1,3 +1,4 @@
#![allow(unused)]
use crate::cryptographic_signature::{CryptographicSignature, sign_message};
const ID: usize = 4;
@@ -163,7 +164,7 @@ impl HandshakeMessage {
}
}
pub fn helloReply(id: u32, length: u16, username: String) -> HandshakeMessage {
pub fn hello_reply(id: u32, length: u16, username: String) -> HandshakeMessage {
let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec();
HandshakeMessage {
id: id,
@@ -219,28 +220,3 @@ impl HandshakeMessage {
}
}
}
#[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

@@ -4,24 +4,18 @@
pub use crate::message_handling::*;
use std::{
collections::{HashMap, VecDeque},
net::{AddrParseError, Ipv4Addr, SocketAddr},
ops::Add,
process::Command,
collections::HashMap,
net::SocketAddr,
sync::{Arc, Mutex},
thread::{self, JoinHandle},
time::{self, Duration, SystemTime},
thread::{self},
time::Duration,
};
use crate::{construct_message, generate_id};
use crate::{
NetworkEvent, cryptographic_signature::CryptographicSignature,
messages_channels::MultipleSenders, threads_handling::Worker,
cryptographic_signature::CryptographicSignature, messages_channels::MultipleSenders,
threads_handling::Worker,
};
use crate::{
P2PSharedData, construct_message, generate_id, messages_structure,
registration::perform_handshake,
};
use crossbeam_channel::{Receiver, Sender};
use p256::ecdsa::VerifyingKey;
#[derive(Debug, Clone)]
@@ -117,7 +111,7 @@ pub fn update_handshake(
let handle = thread::spawn(move || {
loop {
let guard = map_for_thread.lock().unwrap();
for (peer, peerinfo) in guard.iter() {
for (_, peerinfo) in guard.iter() {
let id = generate_id();
let mut map = messages_list.lock().unwrap();
map.insert(id, EventType::Ping);
@@ -128,34 +122,12 @@ pub fn update_handshake(
peerinfo.ip.to_string(),
false,
);
senders.send_dispatch(
ping,
peerinfo.ip.to_string(),
false,
messages_list.clone(),
);
senders.send_dispatch(ping, peerinfo.ip.to_string(), false);
}
}
drop(guard);
thread::sleep(Duration::from_secs(60));
}
});
Worker::spawn(handle, crate::threads_handling::WorkerType::PING)
}
#[cfg(test)]
mod tests {
use std::net::{IpAddr, Ipv4Addr};
use super::*;
/*#[test]
fn creating_cryptographic_signature() {
let mut hh = HandshakeHistory::new();
hh.add_new_handshake(
20,
"putain".to_string(),
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1),
);
}*/
Worker::spawn(handle)
}

View File

@@ -1,7 +1,6 @@
use crate::NetworkEvent;
use crate::P2PSharedData;
use crate::cryptographic_signature::CryptographicSignature;
use crate::get_server_address;
use crate::get_socket_address;
use crate::message_handling::EventType;
use crate::messages_structure::construct_message;
@@ -106,37 +105,10 @@ pub async fn perform_handshake(
match hello_handshake {
Some(handshake_message) => {
senders.send_dispatch(
handshake_message,
address,
is_server_handshake.0,
sd.messages_list(),
);
senders.send_dispatch(handshake_message, address, is_server_handshake.0);
}
None => {}
}
//let server_addr_query = get_socket_address(username.clone(), ip.clone(), Some(sd)).await;
//match server_addr_query {
// Ok(sockaddr_bytes) => {}
// Err(err_msg) => {}
//}
/*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);
}
}
println!("message sent: {}", &id);*/
// 3. Perform the insertion
/*let mut buf = [0u8; 1024];
socket.recv_from(&mut buf).expect("receive failed");
let hello_handshake_received = UDPMessage::parse(buf.to_vec());
hello_handshake_received.display();*/
//TODO
return true;
}

View File

@@ -4,25 +4,16 @@ use std::sync::{
};
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 {
pub fn spawn(thread: JoinHandle<()>) -> Self {
Worker {
stop: Arc::new(AtomicBool::new(false)),
thread: Some(thread),
workertype,
}
}