Skip to main content

ethos_bitcoind/node/
node_manager.rs

1//! Node module for Bitcoin Core RPC testing
2//!
3//! This module provides utilities for managing Bitcoin Core nodes in test environments.
4
5use std::process::Stdio;
6use std::sync::Arc;
7use std::time::{Duration, Instant};
8
9use async_trait::async_trait;
10use tempfile::TempDir;
11use tokio::io::AsyncBufReadExt;
12use tokio::process::{Child, Command};
13use tokio::sync::{Mutex, RwLock};
14use tracing::{debug, error, info};
15
16use crate::test_config::TestConfig;
17use crate::transport::core::TransportExt;
18use crate::transport::{DefaultTransport, TransportError};
19
20/// Represents the current state of a node
21#[derive(Debug, Default, Clone)]
22pub struct NodeState {
23    /// Whether the node is currently running
24    pub is_running: bool,
25}
26
27/// Configuration for port selection behavior
28#[derive(Debug, Clone)]
29pub enum PortSelection {
30    /// Use the specified port number
31    Fixed(u16),
32    /// Let the OS assign an available port
33    Dynamic,
34    /// Use port 0 (not recommended, may cause daemon to fail)
35    Zero,
36}
37
38/// Trait defining the interface for a node manager
39#[async_trait]
40pub trait NodeManager: Send + Sync + std::any::Any + std::fmt::Debug {
41    async fn start(&self) -> Result<(), TransportError>;
42    async fn stop(&mut self) -> Result<(), TransportError>;
43    async fn get_state(&self) -> Result<NodeState, TransportError>;
44    /// Return the RPC port this manager was configured with
45    fn rpc_port(&self) -> u16;
46    /// Return the RPC username this manager was configured with
47    fn rpc_username(&self) -> &str;
48    /// Return the RPC password this manager was configured with
49    fn rpc_password(&self) -> &str;
50    /// Create a transport for communicating with the node
51    async fn create_transport(
52        &self,
53    ) -> Result<std::sync::Arc<crate::transport::DefaultTransport>, TransportError>;
54}
55
56/// Implementation of the node manager
57#[derive(Debug)]
58pub struct BitcoinNodeManager {
59    /// Shared state of the node
60    state: Arc<RwLock<NodeState>>,
61    /// Child process handle for the daemon
62    child: Arc<Mutex<Option<Child>>>,
63    /// RPC port for communication with the node
64    pub rpc_port: u16,
65    /// Test configuration for the node
66    config: TestConfig,
67    /// Temporary directory for node data (cleaned up on drop)
68    _datadir: Option<TempDir>,
69}
70
71impl BitcoinNodeManager {
72    /// Create a new node manager with default configuration
73    pub fn new() -> Result<Self, TransportError> { Self::new_with_config(&TestConfig::default()) }
74
75    /// Create a new node manager with custom configuration
76    pub fn new_with_config(config: &TestConfig) -> Result<Self, TransportError> {
77        let datadir = TempDir::new()?;
78
79        // Handle automatic port selection
80        let rpc_port = if config.rpc_port == 0 {
81            // Get a random free port by binding to 127.0.0.1:0
82            // The listener is dropped at the end of the block, freeing the port
83            {
84                let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
85                listener.local_addr()?.port()
86            }
87        } else {
88            config.rpc_port
89        };
90
91        Ok(Self {
92            state: Arc::new(RwLock::new(NodeState::default())),
93            child: Arc::new(Mutex::new(None)),
94            rpc_port,
95            config: config.clone(),
96            _datadir: Some(datadir),
97        })
98    }
99
100    /// Get the RPC port for this node manager
101    pub fn rpc_port(&self) -> u16 { self.rpc_port }
102
103    /// Gets the test configuration used by this node manager
104    pub fn config(&self) -> &TestConfig { &self.config }
105
106    /// Get the RPC username from the configuration
107    pub fn rpc_username(&self) -> &str { &self.config.rpc_username }
108
109    /// Get the RPC password from the configuration
110    pub fn rpc_password(&self) -> &str { &self.config.rpc_password }
111}
112
113#[async_trait]
114impl NodeManager for BitcoinNodeManager {
115    async fn start(&self) -> Result<(), TransportError> {
116        let mut state = self.state.write().await;
117        if state.is_running {
118            return Ok(());
119        }
120
121        let datadir = self._datadir.as_ref().unwrap().path();
122        let mut cmd = Command::new("bitcoind");
123
124        let chain = format!("-chain={}", self.config.as_chain_str());
125        let data_dir = format!("-datadir={}", datadir.display());
126        let rpc_port = format!("-rpcport={}", self.rpc_port);
127        let rpc_bind = format!("-rpcbind=127.0.0.1:{}", self.rpc_port);
128        let rpc_user = format!("-rpcuser={}", self.config.rpc_username);
129        let rpc_password = format!("-rpcpassword={}", self.config.rpc_password);
130
131        let mut args = vec![
132            &chain,
133            "-listen=0",
134            &data_dir,
135            &rpc_port,
136            &rpc_bind,
137            "-rpcallowip=127.0.0.1",
138            "-fallbackfee=0.0002",
139            "-server=1",
140            "-prune=1",
141            &rpc_user,
142            &rpc_password,
143        ];
144
145        for arg in &self.config.extra_args {
146            args.push(arg);
147        }
148
149        cmd.args(&args);
150
151        // Capture both stdout and stderr for better error reporting
152        cmd.stderr(Stdio::piped());
153        cmd.stdout(Stdio::piped());
154
155        let mut child = cmd.spawn()?;
156
157        // Read stderr in a separate task
158        let stderr = child.stderr.take().unwrap();
159        let stderr_reader = tokio::io::BufReader::new(stderr);
160        tokio::spawn(async move {
161            let mut lines = stderr_reader.lines();
162            while let Ok(Some(line)) = lines.next_line().await {
163                error!("bitcoind stderr: {}", line);
164            }
165        });
166
167        // Read stdout in a separate task
168        let stdout = child.stdout.take().unwrap();
169        let stdout_reader = tokio::io::BufReader::new(stdout);
170        tokio::spawn(async move {
171            let mut lines = stdout_reader.lines();
172            while let Ok(Some(line)) = lines.next_line().await {
173                info!("bitcoind stdout: {}", line);
174            }
175        });
176
177        // Store the child process
178        let mut child_guard = self.child.lock().await;
179        *child_guard = Some(child);
180
181        info!("Waiting for bitcoind node to initialize...");
182        tokio::time::sleep(Duration::from_millis(150)).await;
183
184        // Create transport for RPC health check
185        let transport = DefaultTransport::new(
186            format!("http://127.0.0.1:{}/", self.rpc_port),
187            Some((self.config.rpc_username.clone(), self.config.rpc_password.clone())),
188        );
189
190        // Wait for node to be ready
191        let deadline = Instant::now() + Duration::from_secs(10);
192        let mut attempts = 0;
193        while Instant::now() < deadline {
194            if let Some(child) = child_guard.as_mut() {
195                if let Ok(Some(status)) = child.try_wait() {
196                    let error = format!("bitcoind node exited early with status: {}", status);
197                    error!("{}", error);
198                    return Err(TransportError::Rpc(error));
199                }
200            }
201
202            // Try to connect to RPC
203            match transport.call::<serde_json::Value>("getnetworkinfo", &[]).await {
204                Ok(_) => {
205                    state.is_running = true;
206                    info!("bitcoind node started successfully on port {}", self.rpc_port);
207                    return Ok(());
208                }
209                Err(e) => {
210                    debug!("Failed to connect to RPC (attempt {}): {}", attempts, e);
211                }
212            }
213
214            attempts += 1;
215            tokio::time::sleep(Duration::from_millis(200)).await;
216        }
217
218        let error = format!(
219            "Timed out waiting for bitcoind node to start on port {} after {} attempts",
220            self.rpc_port, attempts
221        );
222        error!("{}", error);
223        return Err(TransportError::Rpc(error));
224    }
225
226    async fn stop(&mut self) -> Result<(), TransportError> {
227        let mut state = self.state.write().await;
228        if !state.is_running {
229            return Ok(());
230        }
231
232        let mut child = self.child.lock().await;
233        if let Some(mut child_process) = child.take() {
234            info!("Stopping bitcoind node...");
235            let _ = child_process.kill().await;
236        }
237
238        state.is_running = false;
239        info!("bitcoind node stopped");
240        Ok(())
241    }
242
243    async fn get_state(&self) -> Result<NodeState, TransportError> {
244        Ok(self.state.read().await.clone())
245    }
246
247    fn rpc_port(&self) -> u16 { self.rpc_port }
248
249    fn rpc_username(&self) -> &str { &self.config.rpc_username }
250
251    fn rpc_password(&self) -> &str { &self.config.rpc_password }
252
253    async fn create_transport(
254        &self,
255    ) -> Result<std::sync::Arc<crate::transport::DefaultTransport>, TransportError> {
256        use std::sync::Arc;
257
258        use crate::transport::DefaultTransport;
259
260        // Create HTTP transport for Bitcoin Core
261        let rpc_url = format!("http://127.0.0.1:{}", self.rpc_port());
262        let auth = Some((self.rpc_username().to_string(), self.rpc_password().to_string()));
263        let transport = Arc::new(DefaultTransport::new(rpc_url, auth));
264
265        // Wait for node to be ready for RPC with Bitcoin Core specific initialization logic
266        // Bitcoin Core initialization states that require waiting:
267        // -28: RPC in warmup
268        // -4:  RPC in warmup (alternative code)
269        let init_states = ["\"code\":-28", "\"code\":-4"];
270
271        let max_retries = 30;
272        let mut retries = 0;
273
274        loop {
275            match transport.call::<serde_json::Value>("getnetworkinfo", &[]).await {
276                Ok(_) => break,
277                Err(TransportError::Rpc(e)) => {
278                    // Check if the error matches any known initialization state
279                    let is_init_state = init_states.iter().any(|state| e.contains(state));
280                    if is_init_state && retries < max_retries {
281                        tracing::debug!(
282                            "Waiting for initialization: {} (attempt {}/{})",
283                            e,
284                            retries + 1,
285                            max_retries
286                        );
287                        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
288                        retries += 1;
289                        continue;
290                    }
291                    return Err(TransportError::Rpc(e));
292                }
293                Err(e) => return Err(e),
294            }
295        }
296
297        if retries > 0 {
298            tracing::debug!("Node initialization completed after {} attempts", retries);
299        }
300
301        Ok(transport)
302    }
303}