This commit is contained in:
Tiago Batista Cardoso
2026-01-25 16:01:11 +01:00
parent 600f617c85
commit 3c17b5fa1f
6 changed files with 22 additions and 69 deletions

View File

@@ -22,7 +22,6 @@ enum ServerStatus {
pub struct P2PClientApp { pub struct P2PClientApp {
remaining: std::time::Duration, // temps restant remaining: std::time::Duration, // temps restant
last_update: std::time::Instant, // pour calculer delta last_update: std::time::Instant, // pour calculer delta
timer_started: bool,
network_cmd_tx: Sender<NetworkCommand>, network_cmd_tx: Sender<NetworkCommand>,
network_event_rx: Receiver<NetworkEvent>, network_event_rx: Receiver<NetworkEvent>,
@@ -65,7 +64,6 @@ impl P2PClientApp {
Self { Self {
remaining: std::time::Duration::from_secs(0), remaining: std::time::Duration::from_secs(0),
timer_started: false,
last_update: std::time::Instant::now(), last_update: std::time::Instant::now(),
network_cmd_tx: cmd_tx, network_cmd_tx: cmd_tx,
network_event_rx: event_rx, network_event_rx: event_rx,
@@ -106,10 +104,9 @@ impl P2PClientApp {
impl eframe::App for P2PClientApp { impl eframe::App for P2PClientApp {
fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) { fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
if matches!(self.server_status, ServerStatus::Connected) && !self.timer_started { if matches!(self.server_status, ServerStatus::Connected) {
self.remaining = std::time::Duration::from_secs(30 * 60); self.remaining = std::time::Duration::from_secs(30 * 60);
self.last_update = std::time::Instant::now(); self.last_update = std::time::Instant::now();
self.timer_started = true;
} }
let now = std::time::Instant::now(); let now = std::time::Instant::now();
@@ -437,18 +434,27 @@ impl eframe::App for P2PClientApp {
if self.show_network_window { if self.show_network_window {
match self.server_status { match self.server_status {
ServerStatus::Connected | ServerStatus::ConnectedHandshake => { ServerStatus::Connected | ServerStatus::ConnectedHandshake => {
egui::Window::new("Network")
.resizable(false)
.collapsible(false)
.title_bar(false)
.show(ctx, |ui| {
let desired = egui::vec2(300.0, 0.0); // width 300, auto-height if 0 let desired = egui::vec2(300.0, 0.0); // width 300, auto-height if 0
ui.set_min_size(desired); ui.set_min_size(desired);
ui.vertical(|ui| { ui.vertical(|ui| {
if ui.button("Disconnect").clicked() { if ui.button("Disconnect").clicked() {
println!("Disconnecting..."); println!("Disconnecting...");
let _ = self.network_cmd_tx.send(NetworkCommand::Disconnect()); let _ = self
.network_cmd_tx
.send(NetworkCommand::Disconnect());
self.server_status = ServerStatus::NotConnected; self.server_status = ServerStatus::NotConnected;
self.remaining = std::time::Duration::from_secs(0); self.remaining = std::time::Duration::from_secs(0);
self.timer_started = false;
self.show_network_window = false; self.show_network_window = false;
self.loaded_fs.clear();
self.active_peer = None;
} }
}); });
});
} }
ServerStatus::NotConnected => { ServerStatus::NotConnected => {
egui::Window::new("Network") egui::Window::new("Network")

View File

@@ -62,18 +62,12 @@ impl ChunkNode {
pub fn new_random() -> Self { pub fn new_random() -> Self {
let mut rng = rand::rng(); let mut rng = rand::rng();
// Determine a random length between 1 and MAX_CHUNK_DATA_SIZE (inclusive).
// Using +1 ensures the range is up to 1024.
let random_len = rng.random_range(1..=MAX_CHUNK_DATA_SIZE); let random_len = rng.random_range(1..=MAX_CHUNK_DATA_SIZE);
// Initialize a vector with the random length
let mut data = vec![0u8; random_len]; let mut data = vec![0u8; random_len];
// Fill the vector with random bytes
rng.fill(&mut data[..]); rng.fill(&mut data[..]);
// Since we generated the length based on MAX_CHUNK_DATA_SIZE,
// this is guaranteed to be valid and doesn't need to return a Result.
ChunkNode { data } ChunkNode { data }
} }
} }
@@ -188,17 +182,6 @@ fn hash(data: &[u8]) -> NodeHash {
println!("root hash: {:?}", root_hash); println!("root hash: {:?}", root_hash);
let res: NodeHash = root_hash.try_into().expect("incorrect size"); let res: NodeHash = root_hash.try_into().expect("incorrect size");
res res
/*let mut hasher = DefaultHasher::new();
data.hash(&mut hasher);
let hash_u64 = hasher.finish();
let mut hash_array = [0u8; FILENAME_HASH_SIZE];
// Simple way to spread a 64-bit hash across 32 bytes for a unique-ish ID
for i in 0..8 {
hash_array[i] = (hash_u64 >> (i * 8)) as u8;
}
hash_array // The rest remains 0, satisfying the 32-byte requirement
*/
} }
fn generate_random_filename() -> [u8; FILENAME_HASH_SIZE] { fn generate_random_filename() -> [u8; FILENAME_HASH_SIZE] {

View File

@@ -13,7 +13,6 @@ pub fn parse_received_datum(
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 value = &recevied_datum[32..datum_length];
let value_slice = value.to_vec(); let value_slice = value.to_vec();
// println!("valueslice: {:?}, {}", value_slice, value_slice.len());
println!( println!(
"((value_slice.len() - 1) / 32) {} ", "((value_slice.len() - 1) / 32) {} ",

View File

@@ -218,17 +218,12 @@ 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)
} }
@@ -237,15 +232,11 @@ 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
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) => { NetworkCommand::InitDownload(hash, ip, name) => {
@@ -384,9 +375,6 @@ pub fn start_p2p_executor(
NetworkCommand::ConnectPeer((username, _)) => { NetworkCommand::ConnectPeer((username, _)) => {
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");
@@ -549,18 +537,7 @@ pub fn start_p2p_executor(
}; };
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"); println!("[Network] FetchPeerList() called");
@@ -716,12 +693,6 @@ pub fn start_p2p_executor(
} }
} }
// 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
sleep(std::time::Duration::from_millis(50)).await; sleep(std::time::Duration::from_millis(50)).await;
} }
}) })
@@ -762,7 +733,6 @@ async fn quick_ping(addr: &SocketAddr, timeout_ms: u64, sd: &P2PSharedData) -> b
/// ///
/// 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( pub async fn get_socket_address(
username: String, username: String,
ip: String, ip: String,

View File

@@ -266,10 +266,6 @@ 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];
println!("received_address:{:?}", received_message);
//let addressv4 = IpAddr::V4(Ipv4Addr::from_octets(
// received_address[0..4].try_into().expect("incorrect size"),
//));
let bytes: [u8; 4] = received_address[0..4].try_into().expect("incorrect size"); let bytes: [u8; 4] = received_address[0..4].try_into().expect("incorrect size");
let addr_v4 = Ipv4Addr::from(bytes); let addr_v4 = Ipv4Addr::from(bytes);
let addressv4 = IpAddr::V4(addr_v4); let addressv4 = IpAddr::V4(addr_v4);

View File

@@ -50,7 +50,6 @@ pub fn parse_addresses(input: &String) -> Vec<SocketAddr> {
/// ///
/// registers the IP addresses by sending a Hello request to the server. /// registers the IP addresses by sending a Hello request to the server.
/// ///
pub async fn perform_handshake( pub async fn perform_handshake(
sd: &P2PSharedData, sd: &P2PSharedData,
username: String, username: String,