structure
This commit is contained in:
85
client-network/src/lib.rs
Normal file
85
client-network/src/lib.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
mod data;
|
||||
|
||||
/// Messages sent to the Network thread by the GUI.
|
||||
pub enum NetworkCommand {
|
||||
ConnectPeer(String), // e.g., IP:PORT
|
||||
RequestFileTree(String), // e.g., peer_id
|
||||
RequestDirectoryContent(String, String),
|
||||
RequestChunk(String, String),
|
||||
// ...
|
||||
}
|
||||
|
||||
/// Messages sent to the GUI by the Network thread.
|
||||
pub enum NetworkEvent {
|
||||
PeerConnected(String),
|
||||
PeerListUpdated(Vec<String>),
|
||||
FileTreeReceived(String, Vec<MerkleNode>), // peer_id, content
|
||||
DataReceived(String, MerkleNode),
|
||||
FileTreeRootReceived(String, String),
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
|
||||
|
||||
use crossbeam_channel::{Receiver, Sender};
|
||||
pub use crate::data::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub fn calculate_chunk_id(data: &[u8]) -> String {
|
||||
// 1. Create a new Sha256 hasher instance
|
||||
let mut hasher = Sha256::new();
|
||||
|
||||
// 2. Write the input data into the hasher
|
||||
hasher.update(data);
|
||||
|
||||
// 3. Finalize the hash computation and get the resulting bytes
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
|
||||
pub fn start_p2p_executor(
|
||||
cmd_rx: Receiver<NetworkCommand>,
|
||||
event_tx: Sender<NetworkEvent>,
|
||||
) -> tokio::task::JoinHandle<()> {
|
||||
|
||||
// Use tokio to spawn the asynchronous networking logic
|
||||
tokio::task::spawn(async move {
|
||||
|
||||
// P2P/Networking Setup goes here
|
||||
|
||||
println!("Network executor started.");
|
||||
|
||||
// Main network loop
|
||||
loop {
|
||||
// Check for commands from the GUI
|
||||
if let Ok(cmd) = cmd_rx.try_recv() {
|
||||
match cmd {
|
||||
NetworkCommand::ConnectPeer(addr) => {
|
||||
println!("Attempting to connect to: {}", addr);
|
||||
// Network logic to connect...
|
||||
// If successful, send an event back:
|
||||
// event_tx.send(NetworkEvent::PeerConnected(addr)).unwrap();
|
||||
},
|
||||
NetworkCommand::RequestFileTree(_) => todo!(),
|
||||
// ... handle other commands
|
||||
NetworkCommand::RequestDirectoryContent(_, _) => todo!(),
|
||||
NetworkCommand::RequestChunk(_, _) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user