use std::{path::PathBuf, time::Duration};
use bitcoin::Network;
use super::{client::Client, node::Node};
use crate::chain::ChainState;
use crate::network::ConnectionType;
use crate::{BlockType, Config, FilterType};
use crate::{Socks5Proxy, TrustedPeer};
const MIN_PEERS: u8 = 1;
const MAX_PEERS: u8 = 15;
#[derive(Debug)]
pub struct Builder {
config: Config,
network: Network,
}
impl Builder {
pub fn new(network: Network) -> Self {
Self {
config: Config::default(),
network,
}
}
pub fn network(&self) -> Network {
self.network
}
pub fn whitelist_only(mut self) -> Self {
self.config.whitelist_only = true;
self
}
pub fn add_peers(mut self, whitelist: impl IntoIterator<Item = TrustedPeer>) -> Self {
self.config.white_list.extend(whitelist);
self
}
pub fn add_peer(mut self, trusted_peer: impl Into<TrustedPeer>) -> Self {
self.config.white_list.push(trusted_peer.into());
self
}
pub fn data_dir(mut self, path: impl Into<PathBuf>) -> Self {
self.config.data_path = Some(path.into());
self
}
pub fn required_peers(mut self, num_peers: u8) -> Self {
self.config.required_peers = num_peers.clamp(MIN_PEERS, MAX_PEERS);
self
}
pub fn chain_state(mut self, state: ChainState) -> Self {
self.config.chain_state = Some(state);
self
}
pub fn handshake_timeout(mut self, handshake_timeout: impl Into<Duration>) -> Self {
self.config.peer_timeout_config.handshake_timeout = handshake_timeout.into();
self
}
pub fn response_timeout(mut self, response_timeout: impl Into<Duration>) -> Self {
self.config.peer_timeout_config.response_timeout = response_timeout.into();
self
}
pub fn maximum_connection_time(mut self, max_connection_time: impl Into<Duration>) -> Self {
self.config.peer_timeout_config.max_connection_time = max_connection_time.into();
self
}
pub fn socks5_proxy(mut self, proxy: impl Into<Socks5Proxy>) -> Self {
let ip_addr = proxy.into();
let connection = ConnectionType::Socks5Proxy(ip_addr);
self.config.connection_type = connection;
self
}
pub fn filter_type(mut self, filter_type: FilterType) -> Self {
self.config.filter_type = filter_type;
self
}
pub fn fetch_witness_data(mut self) -> Self {
self.config.block_type = BlockType::Witness;
self
}
pub fn build(mut self) -> (Node, Client) {
Node::new(self.network, core::mem::take(&mut self.config))
}
}