Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: load bitcoin network from rpc #224

Merged
merged 1 commit into from
Feb 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 17 additions & 30 deletions bitcoin/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,9 @@
#![cfg(feature = "cli")]

use crate::{BitcoinCore, Error};
use crate::{BitcoinCore, BitcoinCoreBuilder, Error};
use bitcoincore_rpc::{bitcoin::Network, Auth};
use clap::Clap;
use std::{str::FromStr, time::Duration};

#[derive(Debug, Copy, Clone)]
pub struct BitcoinNetwork(pub Network);

impl FromStr for BitcoinNetwork {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
match s {
"mainnet" => Ok(BitcoinNetwork(Network::Bitcoin)),
"testnet" => Ok(BitcoinNetwork(Network::Testnet)),
"regtest" => Ok(BitcoinNetwork(Network::Regtest)),
_ => Err(Error::InvalidBitcoinNetwork),
}
}
}
use std::time::Duration;

#[derive(Clap, Debug, Clone)]
pub struct BitcoinOpts {
Expand All @@ -35,10 +20,6 @@ pub struct BitcoinOpts {
#[clap(long, default_value = "60000")]
pub bitcoin_connection_timeout_ms: u64,

/// Bitcoin network type for address encoding.
#[clap(long, default_value = "regtest")]
pub network: BitcoinNetwork,

/// Url of the electrs server - used for theft reporting. If unset, a default
/// fallback is used depending on the network argument.
#[clap(long)]
Expand All @@ -50,14 +31,20 @@ impl BitcoinOpts {
Auth::UserPass(self.bitcoin_rpc_user.clone(), self.bitcoin_rpc_pass.clone())
}

pub fn new_client(&self, wallet_name: Option<String>) -> Result<BitcoinCore, Error> {
BitcoinCore::new(
self.bitcoin_rpc_url.clone(),
self.new_auth(),
wallet_name,
self.network.0,
Duration::from_millis(self.bitcoin_connection_timeout_ms),
self.electrs_url.clone(),
)
fn new_client_builder(&self, wallet_name: Option<String>) -> BitcoinCoreBuilder {
BitcoinCoreBuilder::new(self.bitcoin_rpc_url.clone())
.set_auth(self.new_auth())
.set_wallet_name(wallet_name)
.set_electrs_url(self.electrs_url.clone())
}

pub async fn new_client(&self, wallet_name: Option<String>) -> Result<BitcoinCore, Error> {
self.new_client_builder(wallet_name)
.build_and_connect(Duration::from_millis(self.bitcoin_connection_timeout_ms))
.await
}

pub fn new_client_with_network(&self, wallet_name: Option<String>, network: Network) -> Result<BitcoinCore, Error> {
self.new_client_builder(wallet_name).build_with_network(network)
}
}
178 changes: 113 additions & 65 deletions bitcoin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub use bitcoincore_rpc::{
Address, Amount, Block, BlockHeader, Network, OutPoint, PrivateKey, PubkeyHash, PublicKey, Script, ScriptHash,
Transaction, TxIn, TxMerkleNode, TxOut, Txid, WPubkeyHash, WScriptHash,
},
bitcoincore_rpc_json::{CreateRawTransactionInput, GetTransactionResult, WalletTxInfo},
bitcoincore_rpc_json::{CreateRawTransactionInput, GetBlockchainInfoResult, GetTransactionResult, WalletTxInfo},
json::{self, AddressType, GetBlockResult},
jsonrpc::{error::RpcError, Error as JsonRpcError},
Auth, Client, Error as BitcoinError, RpcApi,
Expand Down Expand Up @@ -183,35 +183,125 @@ impl LockedTransaction {
}
}

fn parse_bitcoin_network(src: &str) -> Result<Network, Error> {
match src {
"main" => Ok(Network::Bitcoin),
"test" => Ok(Network::Testnet),
"regtest" => Ok(Network::Regtest),
_ => Err(Error::InvalidBitcoinNetwork),
}
}

/// Connect to a bitcoin-core full node or timeout.
async fn connect(rpc: &Client, connection_timeout: Duration) -> Result<Network, Error> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to make this a private function in BitcoinCoreBuilder? Just to help with organization

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO no because it doesn't require any of the shared fields.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is possible to put functions in impls that do not take a self argument. But I don't feel super strongly enough about it, so approving..

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yah but it's a private function anyway so I don't think it'll add much to the code organization.

info!("Connecting to bitcoin-core...");
timeout(connection_timeout, async move {
loop {
match rpc.get_blockchain_info() {
Err(BitcoinError::JsonRpc(JsonRpcError::Hyper(HyperError::Io(err))))
if err.kind() == IoErrorKind::ConnectionRefused =>
{
trace!("could not connect to bitcoin-core");
sleep(RETRY_DURATION).await;
continue;
}
Err(BitcoinError::JsonRpc(JsonRpcError::Rpc(err)))
if BitcoinRpcError::from(err.clone()) == BitcoinRpcError::RpcInWarmup =>
{
// may be loading block index or verifying wallet
trace!("bitcoin-core still in warm up");
sleep(RETRY_DURATION).await;
continue;
}
Err(BitcoinError::JsonRpc(JsonRpcError::Json(err))) if err.classify() == SerdeJsonCategory::Syntax => {
// invalid response, can happen if server is in shutdown
trace!("bitcoin-core gave an invalid response: {}", err);
sleep(RETRY_DURATION).await;
continue;
}
Ok(GetBlockchainInfoResult { chain, .. }) => {
info!("Connected to {}", chain);
return parse_bitcoin_network(&chain);
}
Err(err) => return Err(err.into()),
}
}
})
.await?
}

struct BitcoinCoreBuilder {
url: String,
auth: Auth,
wallet_name: Option<String>,
electrs_url: Option<String>,
}

impl BitcoinCoreBuilder {
pub(crate) fn new(url: String) -> Self {
Self {
url,
auth: Auth::None,
wallet_name: None,
electrs_url: None,
}
}

pub(crate) fn set_auth(mut self, auth: Auth) -> Self {
self.auth = auth;
self
}

pub(crate) fn set_wallet_name(mut self, wallet_name: Option<String>) -> Self {
self.wallet_name = wallet_name;
self
}

pub(crate) fn set_electrs_url(mut self, electrs_url: Option<String>) -> Self {
self.electrs_url = electrs_url;
self
}

fn new_client(&self) -> Result<Client, Error> {
let url = match self.wallet_name {
Some(ref x) => format!("{}/wallet/{}", self.url, x),
None => self.url.clone(),
};
Ok(Client::new(url, self.auth.clone())?)
}

pub fn build_with_network(self, network: Network) -> Result<BitcoinCore, Error> {
Ok(BitcoinCore::new(
self.new_client()?,
self.wallet_name,
network,
self.electrs_url,
))
}

pub async fn build_and_connect(self, connection_timeout: Duration) -> Result<BitcoinCore, Error> {
let client = self.new_client()?;
let network = connect(&client, connection_timeout).await?;
Ok(BitcoinCore::new(client, self.wallet_name, network, self.electrs_url))
}
}

#[derive(Clone)]
pub struct BitcoinCore {
rpc: Arc<Client>,
wallet_name: Option<String>,
network: Network,
transaction_creation_lock: Arc<Mutex<()>>,
connection_timeout: Duration,
electrs_config: ElectrsConfiguration,
}

impl BitcoinCore {
pub fn new(
url: String,
auth: Auth,
wallet_name: Option<String>,
network: Network,
connection_timeout: Duration,
electrs_url: Option<String>,
) -> Result<Self, Error> {
let url = match wallet_name {
Some(ref x) => format!("{}/wallet/{}", url, x),
None => url,
};
Ok(Self {
rpc: Arc::new(Client::new(url, auth)?),
fn new(client: Client, wallet_name: Option<String>, network: Network, electrs_url: Option<String>) -> Self {
BitcoinCore {
rpc: Arc::new(client),
wallet_name,
network,
transaction_creation_lock: Arc::new(Mutex::new(())),
connection_timeout,
electrs_config: ElectrsConfiguration {
base_path: electrs_url.unwrap_or_else(|| {
match network {
Expand All @@ -223,47 +313,11 @@ impl BitcoinCore {
}),
..Default::default()
},
})
}
}

/// Connect to a bitcoin-core full node or timeout.
pub async fn connect(&self) -> Result<(), Error> {
info!("Connecting to bitcoin-core...");
timeout(self.connection_timeout, async move {
loop {
match self.rpc.get_blockchain_info() {
Err(BitcoinError::JsonRpc(JsonRpcError::Hyper(HyperError::Io(err))))
if err.kind() == IoErrorKind::ConnectionRefused =>
{
trace!("could not connect to bitcoin-core");
sleep(RETRY_DURATION).await;
continue;
}
Err(BitcoinError::JsonRpc(JsonRpcError::Rpc(err)))
if BitcoinRpcError::from(err.clone()) == BitcoinRpcError::RpcInWarmup =>
{
// may be loading block index or verifying wallet
trace!("bitcoin-core still in warm up");
sleep(RETRY_DURATION).await;
continue;
}
Err(BitcoinError::JsonRpc(JsonRpcError::Json(err)))
if err.classify() == SerdeJsonCategory::Syntax =>
{
// invalid response, can happen if server is in shutdown
trace!("bitcoin-core gave an invalid response: {}", err);
sleep(RETRY_DURATION).await;
continue;
}
Ok(_) => {
info!("Connected!");
return Ok(());
}
Err(err) => return Err(err.into()),
}
}
})
.await?
pub fn network(&self) -> Network {
self.network
}

/// Wait indefinitely for the node to sync.
Expand Down Expand Up @@ -884,15 +938,9 @@ mod tests {

#[tokio::test(flavor = "multi_thread")]
async fn test_find_duplicate_payments_succeeds() {
let bitcoin_core = BitcoinCore::new(
"".to_string(),
Auth::None,
None,
Network::Testnet,
Duration::from_secs(5),
None,
)
.unwrap();
let bitcoin_core = BitcoinCoreBuilder::new("".to_string())
.build_with_network(Network::Testnet)
.unwrap();

let raw_tx = Vec::from_hex("020000000001011f876af6685f6e872b18d288a614adfd21d0246f52e3ca086cdb15d125837a270100000000fdffffff020000000000000000226a208b26f7cf49e1ad4d9f81d237933da8810644a85ac25b3c22a6a2324e1ba02efcba0e0000000000001600148cb0d2c0597a4b496370f94c2e1424d6d1e3432d02473044022023159d039a42095066036b25f08bf77dbf8a8813bf3d842aa998f7437e0da5d002202a102568194e3bba597a31f432c8d3beb5fca9129366f115831b4abba356aa4001210223a4dbc56f6d53a2014dfb106e754323da8e9c095cf9d68f627169f7c059d07a08e71f00").unwrap();
let transaction: Transaction = deserialize(&raw_tx).unwrap();
Expand Down
17 changes: 7 additions & 10 deletions bitcoin/tests/integration_test.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
#![cfg(feature = "uses-bitcoind")]

use bitcoin::{
Auth, BitcoinCore, BitcoinCoreApi, Error, Network, PartialAddress, Payload, PrivateKey, PUBLIC_KEY_SIZE,
Auth, BitcoinCore, BitcoinCoreApi, BitcoinCoreBuilder, Error, Network, PartialAddress, Payload, PrivateKey,
PUBLIC_KEY_SIZE,
};
use regex::Regex;
use std::env::var;

fn new_bitcoin_core(wallet: Option<String>) -> Result<BitcoinCore, Error> {
Ok(BitcoinCore::new(
var("BITCOIN_RPC_URL").expect("BITCOIN_RPC_URL not set"),
Auth::UserPass(
BitcoinCoreBuilder::new(var("BITCOIN_RPC_URL").expect("BITCOIN_RPC_URL not set"))
.set_auth(Auth::UserPass(
var("BITCOIN_RPC_USER").expect("BITCOIN_RPC_USER not set"),
var("BITCOIN_RPC_PASS").expect("BITCOIN_RPC_PASS not set"),
),
wallet,
Network::Regtest,
Default::default(),
None,
)?)
))
.set_wallet_name(wallet)
.build_with_network(Network::Regtest)
}

#[tokio::test]
Expand Down
6 changes: 3 additions & 3 deletions service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ impl<Config: Clone + Send + 'static, S: Service<Config>> ConnectionManager<Confi
let config = self.config.clone();
let (shutdown_tx, _) = tokio::sync::broadcast::channel(16);

let bitcoin_core = self.bitcoin_config.new_client(None)?;
bitcoin_core.connect().await?;
let bitcoin_core = self.bitcoin_config.new_client(None).await?;
sander2 marked this conversation as resolved.
Show resolved Hide resolved
bitcoin_core.sync().await?;

// only open connection to parachain after bitcoind sync to prevent timeout
Expand All @@ -87,6 +86,7 @@ impl<Config: Clone + Send + 'static, S: Service<Config>> ConnectionManager<Confi
.await?;

let config_copy = self.bitcoin_config.clone();
let network_copy = bitcoin_core.network();
let prefix = self.wallet_name.clone().unwrap_or_else(|| "vault".to_string());
let constructor = move |vault_id: VaultId| {
let collateral_currency: CurrencyId = vault_id.collateral_currency();
Expand All @@ -98,7 +98,7 @@ impl<Config: Clone + Send + 'static, S: Service<Config>> ConnectionManager<Confi
collateral_currency.inner().symbol(),
wrapped_currency.inner().symbol()
);
config_copy.new_client(Some(wallet_name))
config_copy.new_client_with_network(Some(wallet_name), network_copy)
};

let service = S::new_service(btc_parachain, bitcoin_core, config, shutdown_tx, Box::new(constructor));
Expand Down