1 Commits

Author SHA1 Message Date
Tiago Batista Cardoso
6b3cbbe557 some modifications 2026-01-16 12:33:21 +01:00
19 changed files with 1511 additions and 2225 deletions

1
.gitignore vendored
View File

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

BIN
README.md

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -32,7 +32,7 @@ async fn main() -> eframe::Result<()> {
eframe::run_native( eframe::run_native(
"p2p-merkle client", "p2p-merkle client",
options, options,
Box::new(|_| { Box::new(|cc| {
let app = P2PClientApp::new(network_cmd_tx, network_event_rx); let app = P2PClientApp::new(network_cmd_tx, network_event_rx);
Ok(Box::new(app)) Ok(Box::new(app))
}), }),

View File

@@ -1,7 +1,13 @@
use std::io::Read;
use bytes::Bytes; use bytes::Bytes;
use p256::EncodedPoint; use p256::EncodedPoint;
use p256::ecdsa::{Signature, SigningKey, VerifyingKey, signature::Verifier}; use p256::ecdsa::{
Signature, SigningKey, VerifyingKey,
signature::{Signer, Verifier},
};
use rand_core::OsRng; use rand_core::OsRng;
use reqwest::Error;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
/// ///
@@ -32,23 +38,37 @@ 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> { pub async fn get_peer_key(username: &String) -> Result<VerifyingKey, reqwest::Error> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let uri = format!("https://jch.irif.fr:8443/peers/{}/key", username); let uri = format!("https://jch.irif.fr:8443/peers/{}/key", username);
let res = client.get(uri).send().await?; let res = client.get(uri).send().await?;
if res.status().is_success() {
println!("Successfully retreived the peers key."); match res.error_for_status_ref() {
} else { Ok(_) => {
eprintln!( println!("Successfully retreived the peers key.");
"Failed to get the peers key from the server. Status: {}", let body: Bytes = res.bytes().await?;
res.status() let slice: &[u8] = body.as_ref();
); let body_bytes: &[u8; 64] = slice.try_into().expect("size error");
let received_key = convert_verifyingkey(body_bytes);
Ok(received_key)
}
Err(e) => {
eprintln!(
"Failed to get the peers key from the server. Status: {}",
res.status()
);
Err(e)
}
} }
let body: Bytes = res.bytes().await?;
let slice: &[u8] = body.as_ref();
let body_bytes: &[u8; 64] = slice.try_into().expect("size error");
let received_key = convert_verifyingkey(body_bytes);
Ok(received_key)
} }
fn convert_verifyingkey(raw_xy: &[u8; 64]) -> VerifyingKey { fn convert_verifyingkey(raw_xy: &[u8; 64]) -> VerifyingKey {
@@ -112,7 +132,34 @@ pub fn sign_message(crypto_pair: &CryptographicSignature, message: &Vec<u8>) ->
signed_message signed_message
} }
Err(e) => { Err(e) => {
panic!("error : {}", e); panic!("error");
} }
} }
} }
#[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,187 +1,26 @@
use rand::{Rng, rng}; use rand::{Rng, rng};
use sha2::{Digest, Sha256};
use std::collections::HashMap; use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::fs::{File, OpenOptions, create_dir};
use std::io::Write;
// --- Constants --- // --- Constants ---
pub const MAX_CHUNK_DATA_SIZE: usize = 1024; const MAX_CHUNK_DATA_SIZE: usize = 1024;
pub const MAX_DIRECTORY_ENTRIES: usize = 16; const MAX_DIRECTORY_ENTRIES: usize = 16;
pub const MAX_BIG_CHILDREN: usize = 32; const MAX_BIG_CHILDREN: usize = 32;
pub const MIN_BIG_CHILDREN: usize = 2; const MIN_BIG_CHILDREN: usize = 2;
pub const FILENAME_HASH_SIZE: usize = 32; const FILENAME_HASH_SIZE: usize = 32;
pub const DIRECTORY_ENTRY_SIZE: usize = FILENAME_HASH_SIZE * 2; // 64 bytes 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();
let random_len = rng.random_range(1..=MAX_CHUNK_DATA_SIZE);
let mut data = vec![0u8; random_len];
rng.fill(&mut data[..]);
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 { fn hash(data: &[u8]) -> NodeHash {
let root_hash = Sha256::digest(&data); let mut hasher = DefaultHasher::new();
println!("root hash: {:?}", root_hash); data.hash(&mut hasher);
let res: NodeHash = root_hash.try_into().expect("incorrect size"); let hash_u64 = hasher.finish();
res
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] { fn generate_random_filename() -> [u8; FILENAME_HASH_SIZE] {
@@ -210,7 +49,38 @@ fn generate_random_filename() -> [u8; FILENAME_HASH_SIZE] {
filename_bytes filename_bytes
} }
fn generate_random_file_node( 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(
storage: &mut HashMap<NodeHash, MerkleNode>, storage: &mut HashMap<NodeHash, MerkleNode>,
) -> Result<NodeHash, String> { ) -> Result<NodeHash, String> {
let mut rng = rng(); let mut rng = rng();
@@ -240,9 +110,9 @@ fn generate_random_file_node(
storage.insert(hash, node); storage.insert(hash, node);
Ok(hash) Ok(hash)
} }
} }*/
fn generate_random_directory_node( /*fn generate_random_directory_node(
depth: u32, depth: u32,
max_depth: u32, max_depth: u32,
storage: &mut HashMap<NodeHash, MerkleNode>, storage: &mut HashMap<NodeHash, MerkleNode>,
@@ -302,165 +172,211 @@ fn generate_random_directory_node(
storage.insert(hash, node); storage.insert(hash, node);
Ok(hash) Ok(hash)
} }
}*/
#[derive(Debug, Clone)]
pub struct ChunkNode {
pub data: Vec<u8>,
} }
impl ChunkNode {
pub fn generate_random_tree( pub fn new(data: Vec<u8>) -> Result<Self, String> {
max_depth: u32, if data.len() > MAX_CHUNK_DATA_SIZE {
) -> Result<(NodeHash, HashMap<NodeHash, MerkleNode>), String> { return Err(format!("Chunk data exceeds {} bytes", data.len()));
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 _ in 0..10 {
let mut i_nodes = Vec::new();
for _ 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);
} }
let bignode = MerkleNode::Big(BigNode::new(i_nodes).unwrap()); Ok(ChunkNode { data })
let hashbig = hash(&bignode.serialize());
children_nodes.push(hashbig);
res.insert(hashbig, bignode);
} }
let bignode = MerkleNode::Big(BigNode::new(children_nodes).unwrap()); pub fn new_random() -> Self {
let hashbig = hash(&bignode.serialize()); let mut rng = rand::rng();
let node1 = MerkleNode::Chunk(ChunkNode::new(bob_content).unwrap()); // Determine a random length between 1 and MAX_CHUNK_DATA_SIZE (inclusive).
let hash1 = hash(&node1.serialize()); // Using +1 ensures the range is up to 1024.
let random_len = rng.random_range(1..=MAX_CHUNK_DATA_SIZE);
let node2 = MerkleNode::Chunk(ChunkNode::new(alice_content).unwrap()); // Initialize a vector with the random length
let hash2 = hash(&node2.serialize()); let mut data = vec![0u8; random_len];
res.insert(hash1, node1); // Fill the vector with random bytes
res.insert(hash2, node2); rng.fill(&mut data[..]);
res.insert(hashbig, bignode);
let node3 = MerkleNode::Chunk(ChunkNode::new(oscar_content).unwrap()); // Since we generated the length based on MAX_CHUNK_DATA_SIZE,
let hash3 = hash(&node3.serialize()); // this is guaranteed to be valid and doesn't need to return a Result.
ChunkNode { data }
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: hashbig,
},
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash2,
},
DirectoryEntry {
filename: generate_random_filename(),
content_hash: hash_dir1,
},
]
.to_vec(),
});
let root_hash = Sha256::digest(&root.serialize());
println!("root hash: {:?}", root_hash);
res.insert(root_hash.try_into().expect("incorrect size"), root);
MerkleTree::new(res, root_hash.try_into().expect("incorrect size"))
}
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));
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 { // Helper struct
input.chars().filter(|&c| c != '\0').collect() #[derive(Debug, Clone)]
pub struct DirectoryEntry {
pub filename: Vec<u8>,
pub content_hash: NodeHash,
} }
pub fn big_or_chunk_to_file(tree: &MerkleTree, node: &MerkleNode, file: &mut File) { pub fn filename_to_string(filename: [u8; FILENAME_HASH_SIZE]) -> String {
match node { let end_index = filename
MerkleNode::Big(big) => { .iter()
for entry in big.children_hashes.iter() { .position(|&b| b == 0)
if let Some(current) = tree.data.get(entry) { .unwrap_or(FILENAME_HASH_SIZE);
big_or_chunk_to_file(tree, current, file); 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 })
}*/
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);
} }
} }
} }
MerkleNode::Chunk(chunk) => { bytes
if !chunk.data.is_empty() {
let mut data = chunk.data.clone();
data.remove(0);
let _ = file.write(&data);
} else {
println!("chunk.data is empty, nothing to write");
}
}
_ => {
println!("invalid type of file");
}
} }
/*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, NodeHash}; use crate::{BigDirectoryNode, DirectoryEntry, DirectoryNode, MerkleNode, MerkleTree, NodeHash};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
const CHUNK: u8 = 0; const CHUNK: u8 = 0;
@@ -6,107 +6,91 @@ const DIRECTORY: u8 = 1;
const BIG: u8 = 2; const BIG: u8 = 2;
const BIGDIRECTORY: u8 = 3; const BIGDIRECTORY: u8 = 3;
pub fn parse_received_datum( fn parse_received_datum(recevied_datum: Vec<u8>, datum_length: usize, mut tree: MerkleTree) {
recevied_datum: Vec<u8>, if datum_length > recevied_datum.len() {
datum_length: usize, return;
) -> Option<([u8; 32], MerkleNode)> { }
if datum_length < 32 + 64 {
return;
}
let hash_name: [u8; 32] = recevied_datum[..32].try_into().expect("error"); let hash_name: [u8; 32] = recevied_datum[..32].try_into().expect("error");
let value = &recevied_datum[32..datum_length]; let sigstart = datum_length - 64;
let value = &recevied_datum[32..sigstart];
let value_slice = value.to_vec(); let value_slice = value.to_vec();
let signature: [u8; 32] = recevied_datum[sigstart..datum_length]
println!( .try_into()
"((value_slice.len() - 1) / 32) {} ", .expect("Taille incorrecte");
((value_slice.len() - 1) / 32) let datum_type = value_slice[0];
); match datum_type {
// Créer une instance de Sha256 CHUNK => {
let mut hasher = Sha256::new(); tree.data.insert(
// Alimenter le hasher avec les données
hasher.update(value_slice.clone());
// Obtention du résultat
let result = hasher.finalize();
if result.to_vec() != hash_name.to_vec() {
println!("{:?},{:?}", result.to_vec(), hash_name.to_vec());
None
} else {
println!("hashes equals!");
let datum_type = value_slice[0];
match datum_type {
CHUNK => Some((
hash_name, hash_name,
MerkleNode::Chunk(crate::ChunkNode { data: value_slice }), MerkleNode::Chunk(crate::ChunkNode { data: value_slice }),
)), );
DIRECTORY => {
let mut dir_entries = Vec::new();
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);
let name = &value_slice[offset..offset + 32];
let mut hash = [0u8; 32];
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.try_into().expect("incorrect size"),
content_hash: hash,
});
}
let current = DirectoryNode::new(dir_entries);
match current {
Ok(current_node) => Some((hash_name, MerkleNode::Directory(current_node))),
Err(e) => {
println!("{}", e);
None
}
}
}
BIG => {
let mut bigdir_entries: Vec<NodeHash> = Vec::new();
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);
let hash = &value_slice[offset..offset + 32];
// envoyer un datum request
bigdir_entries.push(hash.try_into().expect("incorrect size"));
}
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: 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) => Some((hash_name, MerkleNode::BigDirectory(current_node))),
Err(e) => {
println!("{}", e);
None
}
}
}
_ => None,
} }
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];
let mut hash = [0u8; 32];
hash.copy_from_slice(&recevied_datum[offset + 32..offset + 64]);
// envoyer un datum request
dir_entries.push(DirectoryEntry {
filename: name.to_vec(),
content_hash: hash,
});
}
let current = DirectoryNode::new(dir_entries);
match current {
Ok(current_node) => {
tree.data
.insert(hash_name, MerkleNode::Directory(current_node));
}
Err(e) => {
println!("{}", e);
}
}
}
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 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]);
// envoyer un datum request
dir_entries.push(DirectoryEntry {
filename: name.to_vec(),
content_hash: hash,
});
}
let current = BigDirectoryNode::new(dir_entries);
match current {
Ok(current_node) => {
tree.data
.insert(hash_name, MerkleNode::BigDirectory(current_node));
}
Err(e) => {
println!("{}", e);
}
}
}
_ => {}
} }
} }

View File

@@ -1,26 +0,0 @@
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,36 +1,27 @@
mod cryptographic_signature; mod cryptographic_signature;
mod data; mod data;
mod datum_parsing; mod datum_parsing;
mod fetchsocketaddresserror;
mod message_handling; mod message_handling;
mod messages_channels; mod messages_channels;
mod messages_structure; mod messages_structure;
mod peers_refresh; mod peers_refresh;
mod registration; mod registration;
mod server_communication; 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::{ use crate::{
cryptographic_signature::CryptographicSignature, cryptographic_signature::CryptographicSignature,
message_handling::EventType, message_handling::EventType,
messages_channels::{MultipleSenders, start_receving_thread, start_retry_thread}, messages_channels::{MultipleSenders, start_receving_thread},
messages_structure::{ messages_structure::{
DATUM, DATUMREQUEST, NATTRAVERSALREQUEST, NODATUM, PING, ROOTREQUEST, construct_message, NATTRAVERSALREQUEST, NATTRAVERSALREQUEST2, ROOTREQUEST, construct_message,
}, },
peers_refresh::HandshakeHistory, peers_refresh::HandshakeHistory,
registration::{parse_addresses, perform_handshake, register_with_the_server}, registration::{parse_addresses, perform_handshake, register_with_the_server},
server_communication::{generate_id, get_peer_list}, server_communication::{generate_id, get_peer_list},
threads_handling::Worker,
}; };
use std::{ use std::{
io::Error, io::Error,
net::{IpAddr, UdpSocket}, net::{IpAddr, Ipv4Addr, UdpSocket},
time::Duration,
}; };
use std::{ use std::{
net::SocketAddr, net::SocketAddr,
@@ -41,17 +32,13 @@ pub struct P2PSharedData {
shared_socket: Arc<UdpSocket>, shared_socket: Arc<UdpSocket>,
shared_cryptopair: Arc<CryptographicSignature>, shared_cryptopair: Arc<CryptographicSignature>,
shared_messageslist: Arc<Mutex<HashMap<i32, EventType>>>, shared_messageslist: Arc<Mutex<HashMap<i32, EventType>>>,
shared_messagesreceived: Arc<Mutex<HashMap<String, (EventType, Timestamp)>>>,
shared_senders: Arc<MultipleSenders>, shared_senders: Arc<MultipleSenders>,
server_name: Arc<Mutex<String>>, server_name: Arc<Mutex<String>>,
server_address: Arc<Mutex<String>>,
handshake_peers: Arc<HandshakeHistory>, handshake_peers: Arc<HandshakeHistory>,
threads: Vec<Worker>,
} }
use bytes::Bytes; use bytes::Bytes;
use reqwest::Client; use p256::pkcs8::der::pem::Base64Encoder;
use tokio::time::sleep;
impl P2PSharedData { impl P2PSharedData {
pub fn new( pub fn new(
@@ -59,39 +46,24 @@ impl P2PSharedData {
cmd_tx: crossbeam_channel::Sender<NetworkEvent>, cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
) -> Result<P2PSharedData, Error> { ) -> Result<P2PSharedData, Error> {
let messages_list = HashMap::<i32, EventType>::new(); let messages_list = HashMap::<i32, EventType>::new();
let messagesrecv_list = HashMap::<String, (EventType, Timestamp)>::new();
let username = String::from(username); let username = String::from(username);
let crypto_pair = CryptographicSignature::new(username); let crypto_pair = CryptographicSignature::new(username);
let socket = UdpSocket::bind("0.0.0.0:0")?; let socket = UdpSocket::bind("0.0.0.0:0")?;
let shared_socket = Arc::new(socket); let shared_socket = Arc::new(socket);
let shared_cryptopair = Arc::new(crypto_pair); let shared_cryptopair = Arc::new(crypto_pair);
let shared_messageslist = Arc::new(Mutex::new(messages_list)); let shared_messageslist = Arc::new(Mutex::new(messages_list));
let shared_messagesreceived = Arc::new(Mutex::new(messagesrecv_list));
let mut threads = Vec::new(); let senders = MultipleSenders::new(1, &shared_socket, cmd_tx);
let senders = MultipleSenders::new(
5,
&shared_socket,
cmd_tx,
&mut threads,
shared_messageslist.clone(),
);
let shared_senders = Arc::new(senders); let shared_senders = Arc::new(senders);
let server_name = Arc::new(Mutex::new("".to_string())); 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()); let handhsake_peers = Arc::new(HandshakeHistory::new());
Ok(P2PSharedData { Ok(P2PSharedData {
shared_socket: shared_socket, shared_socket: shared_socket,
shared_cryptopair: shared_cryptopair, shared_cryptopair: shared_cryptopair,
shared_messageslist: shared_messageslist, shared_messageslist: shared_messageslist,
shared_messagesreceived: shared_messagesreceived,
shared_senders: shared_senders, shared_senders: shared_senders,
server_name: server_name, server_name: server_name,
server_address: server_address,
handshake_peers: handhsake_peers, handshake_peers: handhsake_peers,
threads,
}) })
} }
pub fn socket(&self) -> Arc<UdpSocket> { pub fn socket(&self) -> Arc<UdpSocket> {
@@ -104,52 +76,32 @@ impl P2PSharedData {
pub fn messages_list(&self) -> Arc<Mutex<HashMap<i32, EventType>>> { pub fn messages_list(&self) -> Arc<Mutex<HashMap<i32, EventType>>> {
self.shared_messageslist.clone() self.shared_messageslist.clone()
} }
pub fn messages_received(&self) -> Arc<Mutex<HashMap<String, (EventType, Timestamp)>>> {
self.shared_messagesreceived.clone()
}
pub fn servername(&self) -> String { pub fn servername(&self) -> String {
let guard = { let guard = self.server_name.lock().unwrap();
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() guard.to_string()
} }
pub fn set_servername(&self, new: String) { pub fn set_servername(&self, new: String) {
let mut guard = self.server_name.lock().unwrap(); let mut guard = self.server_name.lock().unwrap();
*guard = new *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> { pub fn senders(&self) -> Arc<MultipleSenders> {
self.shared_senders.clone() self.shared_senders.clone()
} }
pub fn socket_ref(&self) -> &UdpSocket { pub fn socket_ref(&self) -> &UdpSocket {
&*self.shared_socket &*self.shared_socket
} }
pub fn handshakes(&self) -> Arc<HandshakeHistory> {
self.handshake_peers.clone()
}
pub fn cryptopair_ref(&self) -> &CryptographicSignature { pub fn cryptopair_ref(&self) -> &CryptographicSignature {
&*self.shared_cryptopair &*self.shared_cryptopair
} }
pub fn handshake_ref(&self) -> &HandshakeHistory {
&*self.handshake_peers
}
pub fn messages_list_ref(&self) -> &Mutex<HashMap<i32, EventType>> { pub fn messages_list_ref(&self) -> &Mutex<HashMap<i32, EventType>> {
&*self.shared_messageslist &*self.shared_messageslist
} }
pub fn messages_received_ref(&self) -> &Mutex<HashMap<String, (EventType, Timestamp)>> {
&*self.shared_messagesreceived
}
pub fn senders_ref(&self) -> &MultipleSenders { pub fn senders_ref(&self) -> &MultipleSenders {
&*self.shared_senders &*self.shared_senders
} }
@@ -158,15 +110,6 @@ impl P2PSharedData {
let mut map = self.shared_messageslist.lock().unwrap(); let mut map = self.shared_messageslist.lock().unwrap();
map.insert(id, evt); 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. /// Messages sent to the Network thread by the GUI.
@@ -175,7 +118,7 @@ pub enum NetworkCommand {
ServerHandshake(String, String), // ServerName ServerHandshake(String, String), // ServerName
FetchPeerList(String), // ServerIP FetchPeerList(String), // ServerIP
RegisterAsPeer(String), RegisterAsPeer(String),
Ping(String, String), Ping(String),
NatTraversal(String, String), NatTraversal(String, String),
ConnectPeer((String, bool)), // IP:PORT ConnectPeer((String, bool)), // IP:PORT
RequestFileTree(String), // peer_id RequestFileTree(String), // peer_id
@@ -184,11 +127,7 @@ pub enum NetworkCommand {
Disconnect(), Disconnect(),
ResetServerPeer(), ResetServerPeer(),
Discover(String, String, String), Discover(String, String, String),
GetChildren([u8; 32], String, bool), GetChildren(String, String),
SendDatum(MerkleNode, [u8; 32], String),
SendNoDatum(Vec<u8>, String),
SendRootReply(Vec<u8>, String),
InitDownload([u8; 32], String, String),
// ... // ...
} }
@@ -197,17 +136,14 @@ pub enum NetworkEvent {
Connected(String), Connected(String),
ConnectedHandshake(), ConnectedHandshake(),
Disconnected(), Disconnected(),
Error(String, String), Error(String),
Success(String, String), PeerConnected(String),
PeerListUpdated(Vec<(String, bool)>), PeerListUpdated(Vec<(String, bool)>),
FileTreeReceived([u8; 32], MerkleNode, String), // peer_id, content FileTreeReceived(String, Vec<MerkleNode>), // peer_id, content
DataReceived([u8; 32], MerkleNode, String), DataReceived(String, MerkleNode),
FileTreeRootReceived(String, NodeHash), FileTreeRootReceived(String, NodeHash),
HandshakeFailed(), HandshakeFailed(),
ServerHandshakeFailed(String), ServerHandshakeFailed(String),
DatumRequest([u8; 32], String),
RootRequest(String),
InitDownload([u8; 32], String, String),
// ... // ...
} }
@@ -218,12 +154,17 @@ use crossbeam_channel::{Receiver, Sender};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
pub fn calculate_chunk_id(data: &[u8]) -> String { pub fn calculate_chunk_id(data: &[u8]) -> String {
// 1. Create a new Sha256 hasher instance
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
// 2. Write the input data into the hasher
hasher.update(data); hasher.update(data);
// 3. Finalize the hash computation and get the resulting bytes
let hash_bytes = hasher.finalize(); let hash_bytes = hasher.finalize();
// 4. Convert the hash bytes (array of u8) into a hexadecimal string
// This is the common, human-readable format for cryptographic IDs.
hex::encode(hash_bytes) hex::encode(hash_bytes)
} }
@@ -232,253 +173,88 @@ pub fn start_p2p_executor(
event_tx: Sender<NetworkEvent>, event_tx: Sender<NetworkEvent>,
mut shared_data: Option<P2PSharedData>, mut shared_data: Option<P2PSharedData>,
) -> tokio::task::JoinHandle<()> { ) -> tokio::task::JoinHandle<()> {
// Use tokio to spawn the asynchronous networking logic
tokio::task::spawn(async move { 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."); println!("Network executor started.");
// Main network loop // Main network loop
loop { loop {
// Check for commands from the GUI
if let Ok(cmd) = cmd_rx.try_recv() { if let Ok(cmd) = cmd_rx.try_recv() {
match cmd { 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);
}
}
}
}
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);
}
}
}
}
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);
}
}
}
}
NetworkCommand::ServerHandshake(username, ip) => { NetworkCommand::ServerHandshake(username, ip) => {
println!("server handshake called"); println!("server handshake called");
if let Some(sd) = shared_data.as_mut() { if let Some(sd) = shared_data.as_ref() {
start_receving_thread(sd, event_tx.clone(), sd.handshakes()); start_receving_thread(sd, event_tx.clone(), &handshake_clone);
start_retry_thread( let res =
sd.senders(), perform_handshake(&sd, username, ip, event_tx.clone(), true).await;
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 server_address = {
match get_server_address(username.to_owned(), ip.to_owned()).await {
Some(addr) => addr.to_string(),
None => {
match event_tx.send(NetworkEvent::Error(
"Couldn't fetch server socket address.".to_owned(),
username.to_owned(),
)) {
Ok(_) => {}
Err(e) => {
println!("Network Event Error : {}", e.to_string());
}
}
"".to_owned()
}
}
};
if server_address.to_owned().eq(&"".to_owned()) {
continue;
}
sd.set_servername(username.to_owned());
sd.set_serveraddress(server_address.to_string());
println!("SET SERVERADDRESS");
match perform_handshake(
&sd,
username.to_owned(),
ip,
event_tx.clone(),
(true, server_address.to_string()),
)
.await
{
true => {
match event_tx.send(NetworkEvent::Success(
"Handshake established ✔️".to_string(),
username.to_owned(),
)) {
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
}
false => {}
};
} else { } else {
println!("no shared data"); println!("no shared data");
} }
} }
NetworkCommand::ConnectPeer((username, _)) => { NetworkCommand::ConnectPeer((username, connected)) => {
println!("[Network] ConnectPeer() called"); println!("[Network] ConnectPeer() called");
println!("[Network] Attempting to connect to: {}", username); println!("[Network] Attempting to connect to: {}", username);
// Network logic to connect...
// If successful, send an event back:
// event_tx.send(NetworkEvent::PeerConnected(addr)).unwrap();
} }
NetworkCommand::RequestFileTree(_) => { NetworkCommand::RequestFileTree(_) => {
println!("[Network] RequestFileTree() called"); println!("[Network] RequestFileTree() called");
} }
NetworkCommand::Discover(username, _, ip) => { NetworkCommand::Discover(username, hash, ip) => {
// envoie un handshake au peer, puis un root request // envoie un handshake au peer, puis un root request
if let Some(sd) = shared_data.as_ref() { if let Some(sd) = shared_data.as_ref() {
let res = sd let res = {
.handshake_peers let m = handshake_clone.lock().unwrap();
.get_peer_info_username(username.to_owned()); m.get_peer_info_username(username.clone()).cloned()
};
match res { match res {
Some(peerinfo) => { Some(peerinfo) => {
let id = generate_id();
// envoyer un root request // envoyer un root request
let rootrequest = construct_message( let rootrequest = construct_message(
ROOTREQUEST, ROOTREQUEST,
Vec::new(), Vec::new(),
id, generate_id(),
sd.cryptopair_ref(), sd.cryptopair_ref(),
); );
println!("matching");
match rootrequest { match rootrequest {
None => {} None => {}
Some(resp_msg) => { Some(resp_msg) => {
sd.add_message(id, EventType::RootRequest);
println!("msg_sent:{:?}", resp_msg); println!("msg_sent:{:?}", resp_msg);
sd.senders_ref().add_message_to_retry_queue( sd.senders_ref().send_via(
resp_msg.clone(), 0,
peerinfo.ip.to_string(),
false,
);
sd.senders_ref().send_dispatch(
resp_msg, resp_msg,
peerinfo.ip.to_string(), peerinfo.ip.to_string(),
false, false,
sd.messages_list_ref(),
); );
} }
} }
} }
None => { None => {
// envoyer un handshake // envoyer un handshake
match perform_handshake( let res = perform_handshake(
&sd, &sd,
username.to_owned(), username,
ip, ip,
event_tx.clone(), event_tx.clone(),
(false, "".to_string()), false,
) )
.await .await;
{
true => {
match event_tx.send(NetworkEvent::Success(
"Handshake established ✔️".to_string(),
username.to_owned(),
)) {
Ok(_) => {}
Err(err) => {
println!(
"Network Event Error : {}",
err.to_string()
);
}
};
}
false => {}
}
} }
} }
} else { } else {
println!("no shared data"); println!("no shared data");
} }
} }
NetworkCommand::GetChildren(hash, ip, is_file) => { NetworkCommand::GetChildren(username, hash) => {
if let Some(sd) = shared_data.as_ref() { // envoie un datum request au peer
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);
}
}
}
} }
NetworkCommand::RequestDirectoryContent(_, _) => { NetworkCommand::RequestDirectoryContent(_, _) => {
println!("[Network] RequestDirectoryContent() called"); println!("[Network] RequestDirectoryContent() called");
@@ -496,18 +272,8 @@ pub fn start_p2p_executor(
Err(e) => { Err(e) => {
let mut err_msg = String::from("failed to initialize socket: "); let mut err_msg = String::from("failed to initialize socket: ");
err_msg += &e.to_string(); err_msg += &e.to_string();
match event_tx.send(NetworkEvent::Error(err_msg, name.to_owned())) { let res = event_tx.send(NetworkEvent::Error(err_msg));
Ok(_) => {} let res = event_tx.send(NetworkEvent::Disconnected());
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 None
} }
}; };
@@ -516,41 +282,30 @@ pub fn start_p2p_executor(
if let Err(e) = register_with_the_server(&sd.cryptopair(), &ip).await { if let Err(e) = register_with_the_server(&sd.cryptopair(), &ip).await {
let mut err_msg = String::from("request failed: "); let mut err_msg = String::from("request failed: ");
err_msg += &e.to_string(); err_msg += &e.to_string();
match event_tx.send(NetworkEvent::Error(err_msg, name.to_owned())) { let res = event_tx.send(NetworkEvent::Error(err_msg));
Ok(_) => {} let res = event_tx.send(NetworkEvent::Disconnected());
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 { } else {
match event_tx.send(NetworkEvent::Connected(ip)) { let res = event_tx.send(NetworkEvent::Connected(ip));
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
println!("username created: {}", sd.cryptopair().username); println!("username created: {}", sd.cryptopair().username);
} }
//println!("ip: {}", ip);
} }
//tokio::time::sleep(std::time::Duration::from_millis(5000)).await;
/*let res = event_tx.send(NetworkEvent::Connected());
if let Some(error) = res.err() {
println!(
"[Network] Couldn't send crossbeam message to GUI: {}",
error.to_string()
);
}*/
} }
NetworkCommand::FetchPeerList(ip) => { NetworkCommand::FetchPeerList(ip) => {
println!("[Network] FetchPeerList() called");
if ip == "" { if ip == "" {
match event_tx.send(NetworkEvent::Error( let res = event_tx.send(NetworkEvent::Error(
"Not registered to any server".to_string(), "Not registered to any server".to_string(),
"".to_owned(), ));
)) {
Ok(_) => {}
Err(err) => {
println!("Network Event Error : {}", err.to_string());
}
};
} else { } else {
println!("cc"); println!("cc");
match get_peer_list(ip).await { match get_peer_list(ip).await {
@@ -566,72 +321,29 @@ pub fn start_p2p_executor(
current.push(i); current.push(i);
} }
} }
match event_tx.send(NetworkEvent::PeerListUpdated(peers)) { let res =
Ok(_) => {} event_tx.send(NetworkEvent::PeerListUpdated(peers));
Err(err) => {
println!(
"Network Event Error : {}",
err.to_string()
);
}
};
} }
Err(e) => { Err(e) => {
eprintln!("invalid UTF-8 in socket address bytes: {}", e); eprintln!("invalid UTF-8 in socket address bytes: {}", e);
} }
}, },
Err(e) => println!("error : {}", e), Err(e) => println!("error"),
} }
} }
println!("[Network] FetchPeerList() called");
} }
NetworkCommand::RegisterAsPeer(_) => { NetworkCommand::RegisterAsPeer(_) => {
println!("[Network] RegisterAsPeer() called"); println!("[Network] RegisterAsPeer() called");
} }
NetworkCommand::Ping(str, ip) => { NetworkCommand::Ping(String) => {
println!("[Network] Ping({}) called", str); println!("[Network] Ping() called");
if let Some(sd) = shared_data.as_ref() {
let id = generate_id();
sd.add_message(id, EventType::Ping);
let peer_address =
get_socket_address(str.to_owned(), ip, shared_data.as_ref()).await;
match peer_address {
Ok(addr) => {
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() => { NetworkCommand::Disconnect() => {
if let Some(sd) = shared_data.as_ref() { if let Some(sd) = shared_data.as_ref() {
println!("Disconnecting: {}", &sd.cryptopair().username); println!("Disconnecting: {}", &sd.cryptopair().username);
shared_data = None; shared_data = None;
match event_tx.send(NetworkEvent::Disconnected()) { let res = event_tx.send(NetworkEvent::Disconnected());
Ok(_) => {}
Err(e) => {
eprintln!("NetworkEvent error : {}", e);
}
}
} else { } else {
println!("no p2p data"); println!("no p2p data");
} }
@@ -647,45 +359,44 @@ pub fn start_p2p_executor(
if let Some(sd) = shared_data.as_ref() { if let Some(sd) = shared_data.as_ref() {
println!("username:{}, ip:{}", username, ip); println!("username:{}, ip:{}", username, ip);
// user server to send nattraversal request // user server to send nattraversal request
let server_addr = sd.serveraddress(); let server_addr_query =
let peer_addr_query = get_socket_address( get_socket_address(sd.servername().clone(), ip.clone());
username.clone(), let peer_addr_query = get_socket_address(username.clone(), ip.clone());
ip.clone(),
shared_data.as_ref(),
);
match peer_addr_query.await { match server_addr_query.await {
Ok(peer_addr) => { Some(server_addr) => match peer_addr_query.await {
let payload = socket_addr_to_vec(peer_addr); Some(peer_addr) => {
let payload = socket_addr_to_vec(server_addr);
print!("{:?}", payload.clone()); print!("{:?}", payload.clone());
let id = generate_id(); let natreq = construct_message(
let natreq = construct_message( NATTRAVERSALREQUEST,
NATTRAVERSALREQUEST, server_addr.to_string().into_bytes(),
payload.clone(), generate_id(),
id.clone(), &sd.cryptopair(),
&sd.cryptopair(), );
);
sd.add_message(id, EventType::NatTraversal); sd.senders_ref().send_via(
sd.senders_ref().send_dispatch( 0,
natreq.expect( natreq.expect(
"couldnt construct message nattraversalrequest2", "couldnt construct message nattraversalrequest2",
), ),
server_addr.to_string(), server_addr.to_string(),
false, false,
); sd.messages_list_ref(),
} );
Err(err_msg) => {
match event_tx
.send(NetworkEvent::Error(err_msg.to_string(), username))
{
Ok(_) => {}
Err(e) => {
eprintln!("NetworkEvent error : {}", e);
}
} }
None => {
let err_msg = format!("failed to retreive socket address")
.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));
} }
} }
} }
@@ -693,7 +404,13 @@ pub fn start_p2p_executor(
} }
} }
sleep(std::time::Duration::from_millis(50)).await; // 2. Poll network for new events (e.g., an incoming connection)
// ...
// When a new peer is found:
// event_tx.send(NetworkEvent::PeerConnected("NewPeerID".to_string())).unwrap();
// Avoid spinning too fast
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
} }
}) })
} }
@@ -707,141 +424,32 @@ fn socket_addr_to_vec(addr: SocketAddr) -> Vec<u8> {
v v
} }
async fn quick_ping(addr: &SocketAddr, timeout_ms: u64, sd: &P2PSharedData) -> bool { fn parse_pack(s: &str) -> Option<[u8; 6]> {
let id = generate_id(); // split into "ip" and "port"
let pingreq = construct_message(PING, Vec::new(), id, &sd.shared_cryptopair); let mut parts = s.rsplitn(2, ':');
let port_str = parts.next()?;
let ip_str = parts.next()?; // if missing, invalid
if let Some(ping) = pingreq { let ip: Ipv4Addr = ip_str.parse().ok()?;
sd.add_message(id, EventType::Ping); let port: u16 = port_str.parse().ok()?;
sd.senders_ref()
.send_dispatch(ping, addr.to_string(), false);
}
sleep(Duration::from_millis(timeout_ms)).await; let octets = ip.octets();
let port_be = port.to_be_bytes();
let msg_list = sd.messages_list_ref().lock().expect("yooo"); Some([
let res = !msg_list.contains_key(&id); octets[0], octets[1], octets[2], octets[3], port_be[0], port_be[1],
])
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 /// 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() { pub async fn get_socket_address(username: String, ip: String) -> Option<SocketAddr> {
Ok(c) => c, let client = reqwest::Client::new();
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: Vec<SocketAddr> = {
let temp = parse_addresses(&s);
temp.iter()
.filter_map(|a| match a {
SocketAddr::V4(_) => Some(*a),
SocketAddr::V6(_) => None,
})
.collect()
};
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, 1000, 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,
);
sleep(Duration::from_millis(1000)).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, 5000, 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 uri = format!("{}/peers/{}/addresses", ip, username);
let res = client.get(uri).send().await.expect("couldnt get response"); let res = client.get(uri).send().await.expect("couldnt get response");
if res.status().is_success() { if res.status().is_success() {
println!("Successfully retreived the addresses. {}", res.status()); println!("Successfully retreived the addresses.");
} else { } else {
eprintln!( eprintln!(
"Failed to get the peers addresses from the server. Status: {}", "Failed to get the peers addresses from the server. Status: {}",
@@ -853,12 +461,31 @@ pub async fn get_server_address(username: String, ip: String) -> Option<SocketAd
match String::from_utf8(body.to_vec()) { match String::from_utf8(body.to_vec()) {
Ok(s) => { Ok(s) => {
let addresses = parse_addresses(&s); let addresses = parse_addresses(&s);
if let Some(first) = addresses.first() { addresses.iter().copied().find(|a| a.is_ipv4())
Some(first.clone())
} else {
None
}
} }
Err(_) => None, Err(_) => None,
} }
} }
pub async fn get_possible_socket_address(username: String, ip: String) -> Vec<SocketAddr> {
let client = reqwest::Client::new();
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.");
} 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);
addresses.iter().copied().filter(|a| a.is_ipv4()).collect()
}
Err(_) => Vec::new(),
}
}

View File

@@ -1,67 +1,31 @@
use crate::{ use crate::{
NetworkEvent, NodeHash, NetworkEvent, NodeHash,
cryptographic_signature::{CryptographicSignature, get_peer_key, verify_signature}, cryptographic_signature::{
datum_parsing::parse_received_datum, CryptographicSignature, get_peer_key, sign_message, verify_signature,
},
messages_channels::MultipleSenders, messages_channels::MultipleSenders,
messages_structure::construct_message, messages_structure::construct_message,
peers_refresh::HandshakeHistory, peers_refresh::HandshakeHistory,
registration,
server_communication::generate_id, server_communication::generate_id,
timestamp::Timestamp,
};
use std::{
collections::HashMap,
net::{Ipv4Addr, SocketAddr},
}; };
use std::{collections::HashMap, net::SocketAddr};
use std::{ use std::{
net::IpAddr, net::IpAddr,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
// Types of messages that await for a response
#[derive(Debug, Clone)]
pub enum EventType { pub enum EventType {
HelloThenRootRequest, SendRootRequest,
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; const ID: usize = 4;
const TYPE: usize = 5; const TYPE: usize = 5;
const LENGTH: usize = 7; const LENGTH: usize = 7;
const EXTENSIONS: usize = 4; const EXTENSIONS: usize = 4;
const SIGNATURE: usize = 64;
pub const PING: u8 = 0; const PING: u8 = 0;
const OK: u8 = 128; const OK: u8 = 128;
const ERROR: u8 = 129; const ERROR: u8 = 129;
const HELLO: u8 = 1; const HELLO: u8 = 1;
@@ -76,7 +40,6 @@ const NATTRAVERSALREQUEST2: u8 = 5;
pub fn handle_recevied_message( pub fn handle_recevied_message(
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>, messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
messages_received: &Arc<Mutex<HashMap<String, (EventType, Timestamp)>>>,
recevied_message: &Vec<u8>, recevied_message: &Vec<u8>,
crypto_pair: &CryptographicSignature, crypto_pair: &CryptographicSignature,
//socket_addr: &SocketAddr, //socket_addr: &SocketAddr,
@@ -84,7 +47,7 @@ pub fn handle_recevied_message(
server_name: &String, server_name: &String,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>, cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
ip: SocketAddr, ip: SocketAddr,
handhsake_history: Arc<HandshakeHistory>, handhsake_history: &Arc<Mutex<HandshakeHistory>>,
) { ) {
if recevied_message.len() < 4 { if recevied_message.len() < 4 {
return; return;
@@ -99,6 +62,7 @@ pub fn handle_recevied_message(
let length_bytes: [u8; 2] = recevied_message[TYPE..LENGTH] let length_bytes: [u8; 2] = recevied_message[TYPE..LENGTH]
.try_into() .try_into()
.expect("Taille incorrecte"); .expect("Taille incorrecte");
let msg_length = u16::from_be_bytes(length_bytes) as usize;
let ilength = u16::from_be_bytes(length_bytes); let ilength = u16::from_be_bytes(length_bytes);
let received_name = &recevied_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize]; let received_name = &recevied_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize];
let name = String::from_utf8(received_name.to_vec()).expect("wrong name"); let name = String::from_utf8(received_name.to_vec()).expect("wrong name");
@@ -114,7 +78,6 @@ pub fn handle_recevied_message(
cmd_tx, cmd_tx,
ip, ip,
messages_list, messages_list,
messages_received,
handhsake_history, handhsake_history,
senders, senders,
); );
@@ -123,9 +86,80 @@ pub fn handle_recevied_message(
None => {} None => {}
Some(resp_msg) => { Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg); println!("msg_sent:{:?}", resp_msg);
senders.send_dispatch(resp_msg, ip.to_string(), is_resp_to_server_handshake); senders.send_via(
0,
resp_msg,
ip.to_string(),
is_resp_to_server_handshake,
messages_list,
);
} }
} }
// 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( pub fn parse_message(
@@ -135,21 +169,17 @@ pub fn parse_message(
cmd_tx: crossbeam_channel::Sender<NetworkEvent>, cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
ip: SocketAddr, ip: SocketAddr,
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>, messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
messages_received: &Arc<Mutex<HashMap<String, (EventType, Timestamp)>>>, handhsake_history_mutex: &Arc<Mutex<HandshakeHistory>>,
handhsake_history: Arc<HandshakeHistory>,
senders: &MultipleSenders, senders: &MultipleSenders,
) -> Option<Vec<u8>> { ) -> Option<Vec<u8>> {
let mut handhsake_history = handhsake_history_mutex.lock().unwrap();
let cmd_tx_clone = cmd_tx.clone(); let cmd_tx_clone = cmd_tx.clone();
let msgtype = received_message[ID]; let id_bytes: [u8; 4] = received_message[0..ID]
.try_into()
.expect("Taille incorrecte");
messages_received let msgtype = received_message[ID];
.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] let length_bytes: [u8; 2] = received_message[TYPE..LENGTH]
.try_into() .try_into()
@@ -158,9 +188,8 @@ pub fn parse_message(
let msg_length = u16::from_be_bytes(length_bytes) as usize; let msg_length = u16::from_be_bytes(length_bytes) as usize;
// verify signature // verify signature
match msgtype { match msgtype {
HELLO | HELLOREPLY => { HELLO | HELLOREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => {
let ilength = u16::from_be_bytes(length_bytes); let ilength = u16::from_be_bytes(length_bytes);
println!("hello");
println!("name received length: {}", ilength); println!("name received length: {}", ilength);
let received_name = &received_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize]; let received_name = &received_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize];
let received_username = String::from_utf8(received_name.to_vec()); let received_username = String::from_utf8(received_name.to_vec());
@@ -178,10 +207,12 @@ pub fn parse_message(
HELLOREPLY => { HELLOREPLY => {
handhsake_history.add_new_handshake(peer_pubkey, "".to_string(), ip); 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) { if !verify_signature(peer_pubkey, &received_message) {
println!( println!(
"incorrect signature from given peer: {}, ignoring message of type {} with id {}", "incorrect signature from given peer: {}, ignoring message of type {} with id {}",
@@ -196,7 +227,7 @@ pub fn parse_message(
} }
} }
} }
ROOTREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => { ROOTREPLY => {
let ilength = u16::from_be_bytes(length_bytes); let ilength = u16::from_be_bytes(length_bytes);
println!("name received length: {}", ilength); println!("name received length: {}", ilength);
if let Some(peerinfo) = handhsake_history.get_peer_info_ip(ip.to_string()) { if let Some(peerinfo) = handhsake_history.get_peer_info_ip(ip.to_string()) {
@@ -218,25 +249,17 @@ pub fn parse_message(
// Message handling // Message handling
let mut constructed_message: Option<Vec<u8>> = None; let mut constructed_message: Option<Vec<u8>> = None;
match msgtype { match msgtype {
// PING
//
// envoie un OK
PING => { PING => {
constructed_message = construct_message(OK, Vec::new(), id, crypto_pair); constructed_message = construct_message(OK, Vec::new(), id, crypto_pair);
} }
//
OK => { // OK
let mut guard = messages_list.lock().unwrap(); //
let res = guard.get(&id); // rien ?
match res { // si NATTRAVERSALREQUEST alors
Some(ev) => {
println!("{:?}", ev);
let _ = &guard.remove_entry(&id);
println!("message {} retiré de la liste", id);
}
None => {
println!("ping non trouvé");
}
}
}
NATTRAVERSALREQUEST => { NATTRAVERSALREQUEST => {
// send ok & send nattraversalrequest2 to peer // send ok & send nattraversalrequest2 to peer
constructed_message = construct_message(OK, Vec::new(), id, crypto_pair); constructed_message = construct_message(OK, Vec::new(), id, crypto_pair);
@@ -253,10 +276,12 @@ pub fn parse_message(
crypto_pair, crypto_pair,
); );
senders.send_dispatch( senders.send_via(
0,
natreq2.expect("couldnt construct message nattraversalrequest2"), natreq2.expect("couldnt construct message nattraversalrequest2"),
address, address,
false, false,
&messages_list,
); );
} }
@@ -266,60 +291,40 @@ pub fn parse_message(
let ilength = u16::from_be_bytes(length_bytes); let ilength = u16::from_be_bytes(length_bytes);
let received_address = &received_message[LENGTH..LENGTH + ilength as usize]; let received_address = &received_message[LENGTH..LENGTH + ilength as usize];
let bytes: [u8; 4] = received_address[0..4].try_into().expect("incorrect size"); let address = String::from_utf8(received_address.to_vec()).expect("wrong name");
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); let pingreq = construct_message(PING, Vec::new(), id, crypto_pair);
senders.send_dispatch( senders.send_via(
constructed_message.expect("couldnt construct message ping request"), 0,
ip.to_string(),
false,
);
senders.send_dispatch(
pingreq.expect("couldnt construct message ping request"), pingreq.expect("couldnt construct message ping request"),
address.to_string(), address,
false, false,
&messages_list,
); );
constructed_message = None;
} }
//
// ERROR
//
// affiche un msg d'erreur
ERROR => { ERROR => {
if let Ok(err_received) = if let Ok(err_received) =
String::from_utf8(received_message[LENGTH..(msg_length + LENGTH)].to_vec()) String::from_utf8(received_message[LENGTH..(msg_length + LENGTH)].to_vec())
{ {
let err_msg = format!("Error received from peer {} : {}", ip, err_received); let err_msg = format!("Error received from peer {} : {}", ip, err_received);
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg, "".to_owned())); let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg));
} else { } else {
let err_msg = format!("Error received from peer {} : N/A", ip,); let err_msg = format!("Error received from peer {} : N/A", ip,);
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg, "".to_owned())); let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg));
} }
} }
// HELLO
//
// envoie une hello reply
//
HELLO => { HELLO => {
let mut payload = Vec::new(); 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(&0u32.to_be_bytes());
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes()); payload.extend_from_slice(&crypto_pair.username.clone().as_bytes());
@@ -327,7 +332,10 @@ pub fn parse_message(
return helloreply; return helloreply;
} }
// HELLOREPLY
//
//
// ajoute a la liste des peers handshake
HELLOREPLY => { HELLOREPLY => {
// ajoute l'username a la liste des peers handshake // ajoute l'username a la liste des peers handshake
let received_length = u16::from_be_bytes( let received_length = u16::from_be_bytes(
@@ -342,163 +350,123 @@ pub fn parse_message(
String::from_utf8(received_username.to_vec()).expect("invalid conversion"), String::from_utf8(received_username.to_vec()).expect("invalid conversion"),
); );
// verifie s'il faut renvoyer un root request // verifie s'il faut renvoyer un root request
let mut guard = messages_list.lock().expect("Échec du verrouillage"); let guard = messages_list.lock().expect("Échec du verrouillage");
let res = guard.get(&id); let res = guard.get(&id);
match res { match res {
Some(ev) => { Some(ev) => {
match ev { match ev {
EventType::HelloThenRootRequest => { EventType::SendRootRequest => {
// envoyer la root request // envoyer la root request
let _ = &guard.remove_entry(&id); let rootrequest = construct_message(
println!("message {} retiré de la liste", id); ROOTREQUEST,
let new_id = generate_id(); Vec::new(),
let rootrequest = generate_id(),
construct_message(ROOTREQUEST, Vec::new(), new_id, crypto_pair); crypto_pair,
let _ = &guard.insert(new_id, EventType::RootRequest); );
println!("root requesst sent");
return rootrequest; return rootrequest;
} }
EventType::Hello => {
let _ = &guard.remove_entry(&id);
println!("message {} retiré de la liste", id);
}
_ => {}
} }
} }
None => {} None => {}
} }
} }
//
// ROOTREQUEST
//
// envoie un root reply
//
// ROOTREPLY
//
ROOTREPLY => { ROOTREPLY => {
// recuperer le pseudo du peers ayant repondu // recuperer le pseudo du peers ayant repondu
println!("root reply received");
let peers_exist = handhsake_history.get_peer_info_ip(ip.to_string()); let peers_exist = handhsake_history.get_peer_info_ip(ip.to_string());
match peers_exist { match peers_exist {
Some(peerinfo) => { Some(peerinfo) => {
let mut guard = messages_list.lock().expect("Échec du verrouillage"); // envoyer le hash a la gui
let res = guard.get(&id); let received_hash: NodeHash = received_message[LENGTH..(32 + LENGTH)]
match res { .try_into()
Some(ev) => { .expect("incorrect size");
match ev { let res = cmd_tx_clone.send(NetworkEvent::FileTreeRootReceived(
EventType::RootRequest => { peerinfo.username.clone(),
// envoyer la root request received_hash,
let _ = &guard.remove_entry(&id); ));
println!("message {} retiré de la liste", id); println!("file tree sent")
// envoyer le hash a la gui
let received_hash: NodeHash = received_message
[LENGTH..(32 + LENGTH)]
.try_into()
.expect("incorrect size");
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();
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);
}
_ => {
println!("event not prensent");
}
}
}
None => {}
}
} }
None => { None => {
eprintln!("no peers found"); eprintln!("no peers found");
} }
} }
} }
DATUM => { //
let mut guard = messages_list.lock().expect("Échec du verrouillage"); // DATUMREQUEST
let res = guard.get(&id); //
match res { // envoie le datum
Some(ev) => match ev { //
EventType::DatumRequest => { // NODATUM
let _ = &guard.remove_entry(&id); //
println!("message {} retiré de la liste", id); // affiche un msg d'erreur
let received_length = u16::from_be_bytes( //
received_message[TYPE..LENGTH] // DATUM
.try_into() //
.expect("incorrect size"), // parcourt le directory recu ou le big directory et renvoie une DATUMREQUEST pour chaque
); // directory ou big directory lu
let received_datum = &received_message[LENGTH..]; //
let parsed_node = // NATTRAVERSALREQUEST
parse_received_datum(received_datum.to_vec(), received_length as usize); //
match parsed_node { // repond OK et envoie un NATTRAVERSALREQUEST2 au pair B
Some(tuple) => { //
let _ = cmd_tx.send(NetworkEvent::FileTreeReceived( // NATTRAVERSALREQUEST2
tuple.0, //
tuple.1, // envoie OK à S puis envoie un ping à S
ip.to_string(),
)); // PING
} //
None => {} // envoie un OK
} //
} // OK
EventType::DatumRequestBig => { //
println!("message {} retiré de la liste", id); // si NATTRAVERSALREQUEST alors
let received_length = u16::from_be_bytes( //
received_message[TYPE..LENGTH] // ERROR
.try_into() //
.expect("incorrect size"), // affiche un msg d'erreur
); //
println!("received length:{}", received_length); // HELLO
let received_datum = &received_message[LENGTH..]; //
let parsed_node = // envoie une hello reply
parse_received_datum(received_datum.to_vec(), received_length as usize); //
match parsed_node { // HELLOREPLY
Some(tuple) => { //
let _ = &guard.remove_entry(&id); // envoie un root request
let _ = cmd_tx.send(NetworkEvent::DataReceived( //
tuple.0, // ROOTREQUEST
tuple.1, //
ip.to_string(), // envoie un root reply
)); //
println!("datareceived event sent"); // ROOTREPLY
} //
None => { // envoie un datum request
println!("message corrompu, nouvelle tentative"); //
} // DATUMREQUEST
} //
} // envoie le datum
_ => {} //
}, // NODATUM
None => {} //
} // affiche un msg d'erreur
} //
ROOTREQUEST => { // DATUM
println!("root request received"); //
let _ = cmd_tx.send(NetworkEvent::RootRequest(ip.to_string())); // parcourt le directory recu ou le big directory et renvoie une DATUMREQUEST pour chaque
} // directory ou big directory lu
DATUMREQUEST => { //
let received_length = u16::from_be_bytes( // NATTRAVERSALREQUEST
received_message[TYPE..LENGTH] //
.try_into() // repond OK et envoie un NATTRAVERSALREQUEST2 au pair B
.expect("incorrect size"), //
); // NATTRAVERSALREQUEST2
let received_hash = &received_message[LENGTH..LENGTH + received_length as usize]; //
let _ = cmd_tx.send(NetworkEvent::DatumRequest( // envoie OK à S puis envoie un ping à S
received_hash.try_into().expect("incorrect size"),
ip.to_string(),
));
}
_ => return None, _ => return None,
}; };
constructed_message constructed_message

View File

@@ -1,23 +1,26 @@
use crossbeam_channel::Receiver;
use crate::P2PSharedData; use crate::P2PSharedData;
use crate::cryptographic_signature::CryptographicSignature;
use crate::message_handling::EventType; use crate::message_handling::EventType;
use crate::message_handling::handle_recevied_message; use crate::message_handling::handle_recevied_message;
use crate::peers_refresh::HandshakeHistory; use crate::peers_refresh::HandshakeHistory;
use crate::threads_handling::Worker;
use std::collections::HashMap; use std::collections::HashMap;
use std::net::SocketAddr;
use std::net::UdpSocket; use std::net::UdpSocket;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::sync::mpsc::{self, Sender};
use std::thread; use std::thread;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::time::Duration; use std::time::{Duration, Instant};
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use crate::NetworkEvent; use crate::NetworkEvent;
pub struct MultipleSenders {
senders: Vec<Sender<Message>>,
response_channel: crossbeam_channel::Sender<NetworkEvent>,
}
pub struct Message { pub struct Message {
pub payload: Vec<u8>, pub payload: Vec<u8>,
pub address: String, pub address: String,
@@ -27,244 +30,271 @@ pub struct Message {
struct RetryMessage { struct RetryMessage {
msg: Message, msg: Message,
attempts: u8, attempts: u8,
next_try: u64, next_try: Instant,
}
pub struct MultipleSenders {
sender: crossbeam_channel::Sender<Message>,
response_channel: crossbeam_channel::Sender<NetworkEvent>,
retry_queue: Arc<Mutex<VecDeque<RetryMessage>>>,
} }
impl MultipleSenders { 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( pub fn new(
num_channels: usize, num_channels: usize,
socket: &Arc<UdpSocket>, socket: &Arc<UdpSocket>,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>, cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
threads: &mut Vec<Worker>,
messages_list: Arc<Mutex<HashMap<i32, EventType>>>,
) -> Self { ) -> Self {
let (tx1, rx1) = crossbeam_channel::unbounded(); let mut senders = Vec::new();
for i in 0..num_channels { for i in 0..num_channels {
let (tx, rx) = mpsc::channel::<Message>();
let sock_clone = Arc::clone(&socket); let sock_clone = Arc::clone(&socket);
let cmd_tx_clone = cmd_tx.clone(); let cmd_tx_clone = cmd_tx.clone();
let rx: Receiver<Message> = rx1.clone();
let msg_list_clone = messages_list.clone();
let thread = thread::spawn(move || { senders.push(tx);
thread::spawn(move || {
println!("Canal d'envoi {} prêt", i); println!("Canal d'envoi {} prêt", i);
loop { let mut queue: VecDeque<RetryMessage> = VecDeque::new();
let msg = rx.recv().unwrap(); let max_attempts = 5;
match sock_clone.send_to(&msg.payload, &msg.address) {
Ok(_) => {
if msg.is_resp_to_server_handshake {
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");
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
);
let mut guard = msg_list_clone.lock().unwrap();
let message_id: [u8; 4] =
msg.payload[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id); loop {
guard.remove_entry(&id); // Priorité aux messages en attente prêts à être réessayés
drop(guard); 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);
}
}
}
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
);
break;
} }
} }
} }
}); });
threads.push(Worker::spawn(thread));
} }
MultipleSenders { MultipleSenders {
sender: tx1, senders,
response_channel: cmd_tx.clone(), response_channel: cmd_tx.clone(),
retry_queue: Arc::new(Mutex::new(VecDeque::new())),
} }
} }
pub fn send_dispatch( /// Envoie un message via un canal spécifique (round-robin ou index précis)
pub fn send_via(
&self, &self,
channel_idx: usize,
data: Vec<u8>, data: Vec<u8>,
remote_addr: String, remote_addr: String,
is_resp_to_server_handshake: bool, is_resp_to_server_handshake: bool,
messages_list: &Mutex<HashMap<i32, EventType>>,
) { ) {
println!(
"is_resp_to_server_handshake {}",
is_resp_to_server_handshake
);
let msg_to_send = Message { let msg_to_send = Message {
payload: data.clone(), payload: data.clone(),
address: remote_addr, address: remote_addr,
is_resp_to_server_handshake, is_resp_to_server_handshake,
}; };
let _ = self.sender.send(msg_to_send); if let Some(sender) = self.senders.get(channel_idx) {
println!("message sent"); let _ = sender.send(msg_to_send);
}
if !is_resp_to_server_handshake {
let mut guard = messages_list.lock().unwrap();
let message_id: [u8; 4] = data[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id);
guard.insert(id, EventType::SendRootRequest);
}
} }
pub fn add_message_to_retry_queue( /*pub fn start_receving_thread(
&self, socket: &Arc<UdpSocket>,
data: Vec<u8>, messages_list: &Arc<HashMap<i32, EventType>>,
remote_addr: String, crypto_pair: &Arc<CryptographicSignature>,
is_resp_to_server_handshake: bool, socket_addr: SocketAddr,
senders: &Arc<MultipleSenders>,
) { ) {
let msg_to_send = Message { let sock_clone = Arc::clone(socket);
payload: data.clone(), let cryptopair_clone = Arc::clone(crypto_pair);
address: remote_addr, let senders_clone = Arc::clone(senders);
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 mut guard = self.retry_queue.lock().unwrap(); let messages_clone = Arc::clone(messages_list);
guard.push_back(newretry); thread::spawn(move || {
} let mut buf = [0u8; 1024];
}
pub fn start_retry_thread( loop {
senders: Arc<MultipleSenders>, match sock_clone.recv_from(&mut buf) {
max_attempts: u8, Ok((amt, src)) => {
messages_list: Arc<Mutex<HashMap<i32, EventType>>>, handle_recevied_message(
threads: &mut Vec<Worker>, &messages_clone,
) { &buf.to_vec(),
let thread = thread::spawn(move || { &cryptopair_clone,
loop { &socket_addr,
thread::sleep(Duration::from_millis(100)); &senders_clone,
let mut q = senders.retry_queue.lock().unwrap(); );
//println!("size of retry thread: {}", q.len()); println!("Reçu {} octets de {}: {:?}", amt, src, &buf[..amt]);
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);
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 {
match senders
.response_channel
.send(NetworkEvent::ServerHandshakeFailed(str))
{
Ok(_) => {}
Err(e) => {
println!("Network Event Error : {}", e.to_string());
}
};
}
} 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,
);
let base: u64 = 2;
let backoff = base.saturating_pow(attempt as u32); // 2^1 == 2 seconds
//let backoff = 1;
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);
}
} else {
q.push_back(front);
} }
Err(e) => eprintln!("Erreur de réception: {}", e),
} }
} }
} });
}); }*/
threads.push(Worker::spawn(thread));
} }
pub fn start_receving_thread( pub fn start_receving_thread(
shared_data: &mut P2PSharedData, shared_data: &P2PSharedData,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>, cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
handshake_history: Arc<HandshakeHistory>, handshake_history: &Arc<Mutex<HandshakeHistory>>,
) { ) {
let sock_clone = shared_data.socket(); let sock_clone = shared_data.socket();
let cryptopair_clone = shared_data.cryptopair(); let cryptopair_clone = shared_data.cryptopair();
let senders_clone = shared_data.senders(); let senders_clone = shared_data.senders();
let messages_clone = shared_data.messages_list(); let messages_clone = shared_data.messages_list();
let messages_received_clone = shared_data.messages_received();
let servername_clone = shared_data.servername(); let servername_clone = shared_data.servername();
let thread = thread::spawn(move || {
let mut buf = [0u8; 1500]; let handshake_clone = handshake_history.clone();
thread::spawn(move || {
let mut buf = [0u8; 1024];
loop { loop {
match sock_clone.recv_from(&mut buf) { match sock_clone.recv_from(&mut buf) {
Ok((amt, src)) => { Ok((amt, src)) => {
let received_data = buf[..amt].to_vec(); let received_data = buf[..amt].to_vec();
println!("Reçu {} octets de {}", amt, src); println!("Reçu {} octets de {}: {:?}", amt, src, received_data);
handle_recevied_message( handle_recevied_message(
&messages_clone, &messages_clone,
&messages_received_clone,
&received_data, &received_data,
&cryptopair_clone, &cryptopair_clone,
&senders_clone, &senders_clone,
&servername_clone, &servername_clone,
cmd_tx.clone(), cmd_tx.clone(),
src, src,
handshake_history.clone(), &handshake_clone,
); );
} }
Err(e) => eprintln!("Erreur de réception: {}", e), Err(e) => eprintln!("Erreur de réception: {}", e),
} }
} }
}); });
shared_data.threads.push(Worker::spawn(thread));
} }

View File

@@ -1,4 +1,3 @@
#![allow(unused)]
use crate::cryptographic_signature::{CryptographicSignature, sign_message}; use crate::cryptographic_signature::{CryptographicSignature, sign_message};
const ID: usize = 4; const ID: usize = 4;
@@ -49,23 +48,18 @@ pub fn construct_message(
return Some(message); return Some(message);
} }
ERROR | DATUMREQUEST => { ERROR | DATUMREQUEST => {
let a = payload.len() as u16; message.extend_from_slice(&payload.len().to_be_bytes());
println!("payload size:{}", a);
message.extend_from_slice(&a.to_be_bytes());
message.extend_from_slice(&payload); message.extend_from_slice(&payload);
return Some(message); return Some(message);
} }
ROOTREPLY | NODATUM | DATUM | NATTRAVERSALREQUEST => { ROOTREPLY | NODATUM | DATUM | NATTRAVERSALREQUEST => {
println!("payload:{:?}", &payload); println!("payload:{:?}", &payload);
let a = payload.len() as u16; message.extend_from_slice(&(payload.len() as u16).to_be_bytes());
println!("payload size:{}", a);
message.extend_from_slice(&a.to_be_bytes());
message.extend_from_slice(&payload); message.extend_from_slice(&payload);
println!("payload:{:?}", &message); println!("payload:{:?}", &message);
let signature = sign_message(crypto_pair, &message); let signature = sign_message(crypto_pair, &message);
message.extend_from_slice(&signature); message.extend_from_slice(&signature);
println!("message_to_send_len:{}", &message.len()); return Some(message);
return Some(signature);
} }
_ => {} _ => {}
@@ -164,7 +158,7 @@ impl HandshakeMessage {
} }
} }
pub fn hello_reply(id: u32, length: u16, username: String) -> HandshakeMessage { pub fn helloReply(id: u32, length: u16, username: String) -> HandshakeMessage {
let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec(); let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec();
HandshakeMessage { HandshakeMessage {
id: id, id: id,
@@ -220,3 +214,28 @@ 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

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

View File

@@ -1,14 +1,19 @@
use bytes::Bytes;
use crate::NetworkEvent; use crate::NetworkEvent;
use crate::P2PSharedData; use crate::P2PSharedData;
use crate::cryptographic_signature::CryptographicSignature; use crate::cryptographic_signature::{CryptographicSignature, formatPubKey, sign_message};
use crate::get_socket_address; use crate::get_socket_address;
use crate::message_handling::EventType; use crate::message_handling::EventType;
use crate::messages_channels::MultipleSenders;
use crate::messages_structure::construct_message; use crate::messages_structure::construct_message;
use crate::server_communication::generate_id; use crate::server_communication::generate_id;
use crossbeam_channel::Sender; use crossbeam_channel::{Receiver, Sender};
use std::collections::HashMap;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::net::UdpSocket;
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::{Arc, Mutex};
/// ///
/// sends the cryptographic signature to the server using a PUT request over the HTTP API. /// sends the cryptographic signature to the server using a PUT request over the HTTP API.
@@ -24,13 +29,8 @@ pub async fn register_with_the_server(
let pubkey_bytes_minus = pubkey_bytes[1..].to_vec(); let pubkey_bytes_minus = pubkey_bytes[1..].to_vec();
let res = client.put(uri).body(pubkey_bytes_minus).send().await?; let res = client.put(uri).body(pubkey_bytes_minus).send().await?;
let res = res.error_for_status()?; let res = res.error_for_status()?;
match res.error_for_status() { println!("register ip adresses");
Ok(_) => { Ok(())
println!("register ip adresses");
Ok(())
}
Err(e) => Err(e),
}
} }
pub fn parse_addresses(input: &String) -> Vec<SocketAddr> { pub fn parse_addresses(input: &String) -> Vec<SocketAddr> {
@@ -55,59 +55,90 @@ pub async fn perform_handshake(
username: String, username: String,
ip: String, ip: String,
event_tx: Sender<NetworkEvent>, event_tx: Sender<NetworkEvent>,
is_server_handshake: (bool, String), is_server_handshake: bool,
) -> bool { ) {
println!("username: {}, ip: {}", username.clone(), ip.clone()); println!("username: {}, ip: {}", username.clone(), ip.clone());
let crypto_pair = sd.cryptopair_ref(); let crypto_pair = sd.cryptopair_ref();
let senders = sd.senders_ref(); let senders = sd.senders_ref();
let messages_list = sd.messages_list_ref();
let id = generate_id(); let id = generate_id();
let server_addr_query = get_socket_address(username.clone(), ip.clone());
let address = { match server_addr_query.await {
if is_server_handshake.0 { Some(sockaddr_bytes) => {
is_server_handshake.1 sd.set_servername(username);
} else { // first: &SocketAddr
let server_addr_query = let mut payload = Vec::new();
get_socket_address(username.clone(), ip.clone(), Some(sd)).await; payload.extend_from_slice(&0u32.to_be_bytes());
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes());
match server_addr_query { let hello_handshake = construct_message(1, payload, id, crypto_pair);
Ok(sockaddr_bytes) => sockaddr_bytes.to_string(), match hello_handshake {
Err(err_msg) => { Some(handshake_message) => {
match event_tx.send(NetworkEvent::Error( senders.send_via(
err_msg.to_string(), 0,
username.to_owned(), handshake_message,
)) { sockaddr_bytes.to_string(),
Ok(_) => {} is_server_handshake,
Err(err) => { messages_list,
println!("Network Event Error : {}", err.to_string()); );
}
}
"".to_string()
} }
None => {}
} }
} }
}; None => {
let err_msg = format!("failed to retreive socket address:").to_string();
if address.eq(&"".to_string()) { let res = event_tx.send(NetworkEvent::Error(err_msg));
return false;
}
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.0 {
sd.add_message(id, EventType::Hello);
} else {
sd.add_message(id, EventType::HelloThenRootRequest);
}
match hello_handshake {
Some(handshake_message) => {
senders.send_dispatch(handshake_message, address, is_server_handshake.0);
} }
None => {}
} }
return true; /*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
}
#[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
///
#[tokio::test]
async fn registering_with_server() {
let username = String::from("gameixtreize");
let server_uri = String::from("https://jch.irif.fr:8443");
let crypto_pair = CryptographicSignature::new(username);
if let Err(e) = register_with_the_server(crypto_pair, server_uri).await {
eprintln!("Error during registration: {}", e);
}
}*/
/*///
/// retreives the socket address of a given peer
///
#[tokio::test]
async fn retreive_socket_addr() {
let username = String::from("ipjkndqfshjldfsjlbsdfjhhj");
match get_socket_address(username).await {
Ok(body) => {
println!("{:?}", body);
}
Err(e) => {
eprintln!("Erreur HTTP: {}", e);
}
}
}*/
} }

View File

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

View File

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

View File

@@ -1 +0,0 @@
https://docs.google.com/document/d/1emhrAfjJyJTWpBYx4IJGcCz0_iLVjDRAAdq2EZFchKo/edit?usp=sharing

66
todo.md
View File

@@ -1,11 +1,57 @@
# Todo # Todo
## peer discovery
## fonctionnalités : ## handshake
- proposer des fichiers
- telechargement des fichiers # Todo
- receivers threads
- ask for nat traversal ## peer discovery
- get rsquest to the uri /peers/
## registration with the server
- generation of the cryptographic key OK
- put request to the uri (check if the peer is already connected) OK
- udp handshakes OK
- get request to the uri /peers/key to get the public key of a peer OK
- get request to the uri /peers/key/addresses OK
## handshake
- handshake structure OK
- 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
## nat traversal
- make hello and helloreply messages set the first extension bit to announce that peer is available for nat traversal
- implement actual nat traversal requests
- implement nat traversal :
- if hello/helloreply doesnt work with a peer, find a peer that supports nat traversal (server in priority) then begin protocol
fonctionnalités :
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
@@ -13,7 +59,6 @@ socket ipv6
# FAIT # FAIT
rechercher les fichiers d'un pair OK
- choisir un pseudo OK - choisir un pseudo OK
- get rsquest to the uri /peers/ OK - get rsquest to the uri /peers/ OK
- generation of the cryptographic key OK - generation of the cryptographic key OK
@@ -26,12 +71,3 @@ rechercher les fichiers d'un pair OK
- generer une clé publique OK - generer une clé publique OK
- verifier signature OK - verifier signature OK
- 2 channels -> un pour envoyer et un pour recevoir 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