1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use crate::websocket::{
    get_client, get_client_tls, perform_handshake, Client, ClientSSLConfig, NodeType,
};
use std::collections::HashMap;
use std::io::{Error, ErrorKind};
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::task::JoinHandle;

pub struct FullnodeClient {
    pub client: Arc<Mutex<Client>>,
    handle: JoinHandle<()>,
}
impl FullnodeClient {
    pub async fn new(
        host: &str,
        port: u16,
        network_id: &str,
        additional_headers: &Option<HashMap<String, String>>,
        run: Arc<AtomicBool>,
    ) -> Result<Self, Error> {
        let (client, mut stream) = get_client(host, port, additional_headers).await?;
        let handle = tokio::spawn(async move { stream.run(run).await });
        let client = Arc::new(Mutex::new(client));
        perform_handshake(client.clone(), network_id, port, NodeType::FullNode).await?;
        Ok(FullnodeClient { client, handle })
    }
    pub async fn new_ssl(
        host: &str,
        port: u16,
        ssl_info: ClientSSLConfig<'_>,
        network_id: &str,
        additional_headers: &Option<HashMap<String, String>>,
        run: Arc<AtomicBool>,
    ) -> Result<Self, Error> {
        let (client, mut stream) = get_client_tls(host, port, ssl_info, additional_headers).await?;
        let handle = tokio::spawn(async move { stream.run(run).await });
        let client = Arc::new(Mutex::new(client));
        perform_handshake(client.clone(), network_id, port, NodeType::FullNode).await?;
        Ok(FullnodeClient { client, handle })
    }

    pub async fn join(self) -> Result<(), Error> {
        self.handle.await.map_err(|e| {
            Error::new(
                ErrorKind::Other,
                format!("Failed to join fullnode: {:?}", e),
            )
        })?;
        self.client.lock().await.shutdown().await
    }
}