freenet_test_network/
peer.rs

1use crate::{process::PeerProcess, remote::PeerLocation, Result};
2use std::path::{Path, PathBuf};
3
4/// Represents a single peer in the test network
5pub struct TestPeer {
6    pub(crate) id: String,
7    pub(crate) is_gateway: bool,
8    pub(crate) ws_port: u16,
9    pub(crate) network_port: u16,
10    pub(crate) network_address: String,
11    pub(crate) data_dir: PathBuf,
12    pub(crate) process: Box<dyn PeerProcess + Send>,
13    pub(crate) public_key_path: Option<PathBuf>,
14    pub(crate) location: PeerLocation,
15}
16
17impl TestPeer {
18    /// Get the WebSocket URL for connecting to this peer
19    pub fn ws_url(&self) -> String {
20        format!("ws://127.0.0.1:{}/v1/contract/command", self.ws_port)
21    }
22
23    /// Get the peer's identifier
24    pub fn id(&self) -> &str {
25        &self.id
26    }
27
28    /// Check if this is a gateway peer
29    pub fn is_gateway(&self) -> bool {
30        self.is_gateway
31    }
32
33    /// Get the peer's network address
34    pub fn network_address(&self) -> &str {
35        &self.network_address
36    }
37
38    /// Get the root data directory for this peer
39    pub fn data_dir_path(&self) -> &Path {
40        &self.data_dir
41    }
42
43    /// Get the path to this peer's log file
44    pub fn log_path(&self) -> PathBuf {
45        self.process.log_path()
46    }
47
48    /// Check if the peer process is still running
49    pub fn is_running(&self) -> bool {
50        self.process.is_running()
51    }
52
53    /// Kill the peer process
54    pub fn kill(&mut self) -> Result<()> {
55        self.process.kill()
56    }
57
58    /// Get the peer's location (local or remote)
59    pub fn location(&self) -> &PeerLocation {
60        &self.location
61    }
62}
63
64/// Get a free port by binding to port 0 and letting the OS assign one
65pub(crate) fn get_free_port() -> Result<u16> {
66    use std::net::TcpListener;
67    let listener = TcpListener::bind("127.0.0.1:0")?;
68    Ok(listener.local_addr()?.port())
69}