anya_core/bitcoin/
node.rs1use crate::bitcoin::BitcoinConfig;
8use crate::{AnyaError, AnyaResult};
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use std::sync::Arc;
12use tokio::sync::RwLock;
13
14#[derive(Debug, Clone)]
16pub struct BitcoinNode {
17 config: BitcoinConfig,
19 status: Arc<RwLock<NodeStatus>>,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct NodeStatus {
26 pub connected: bool,
28 pub last_connection: Option<DateTime<Utc>>,
30 pub block_height: Option<u64>,
32 pub network: String,
34 pub version: Option<String>,
36 pub peer_count: Option<u32>,
38}
39
40impl BitcoinNode {
41 pub fn new(config: BitcoinConfig) -> AnyaResult<Self> {
43 let status = NodeStatus {
44 connected: false,
45 last_connection: None,
46 block_height: None,
47 network: config.network.to_string(),
48 version: None,
49 peer_count: None,
50 };
51
52 Ok(Self {
53 config,
54 status: Arc::new(RwLock::new(status)),
55 })
56 }
57
58 pub async fn start(&self) -> AnyaResult<()> {
60 let mut status = self.status.write().await;
61
62 status.connected = true;
64 status.last_connection = Some(Utc::now());
65 status.network = self.config.network.to_string();
66 status.version = Some("23.0.0".to_string());
67 status.peer_count = Some(8);
68 status.block_height = Some(800000); Ok(())
71 }
72
73 pub async fn stop(&self) -> AnyaResult<()> {
75 let mut status = self.status.write().await;
76 status.connected = false;
77 status.peer_count = Some(0);
78 Ok(())
79 }
80
81 pub async fn get_status(&self) -> NodeStatus {
83 self.status.read().await.clone()
84 }
85
86 pub async fn is_connected(&self) -> bool {
88 self.status.read().await.connected
89 }
90
91 pub async fn get_block_height(&self) -> AnyaResult<u64> {
93 let status = self.status.read().await;
94 status
95 .block_height
96 .ok_or_else(|| AnyaError::Bitcoin("Block height not available".to_string()))
97 }
98
99 pub fn get_network(&self) -> String {
101 self.config.network.to_string()
102 }
103
104 pub fn get_config(&self) -> &BitcoinConfig {
106 &self.config
107 }
108}
109
110impl Default for BitcoinNode {
111 fn default() -> Self {
112 let config = BitcoinConfig::default();
113 Self::new(config).expect("Failed to create default BitcoinNode")
114 }
115}