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

Sync #166

Merged
merged 16 commits into from
Nov 18, 2020
Merged

Sync #166

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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
Cargo.lock

*.swp
.idea
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ env_logger = "0.7"

[[example]]
name = "repl"
required-features = ["cli-utils"]
required-features = ["cli-utils", "esplora"]
[[example]]
name = "parse_descriptor"
[[example]]
Expand Down
38 changes: 23 additions & 15 deletions examples/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,15 @@ use log::{debug, error, info, trace, LevelFilter};
use bitcoin::Network;

use bdk::bitcoin;
use bdk::blockchain::ConfigurableBlockchain;
use bdk::blockchain::ElectrumBlockchain;
use bdk::blockchain::ElectrumBlockchainConfig;
use bdk::blockchain::{
AnyBlockchain, AnyBlockchainConfig, ConfigurableBlockchain, ElectrumBlockchainConfig,
};
use bdk::cli;
use bdk::sled;
use bdk::Wallet;

use bdk::blockchain::esplora::EsploraBlockchainConfig;
afilini marked this conversation as resolved.
Show resolved Hide resolved

fn prepare_home_dir() -> PathBuf {
let mut dir = PathBuf::new();
dir.push(&dirs::home_dir().unwrap());
Expand Down Expand Up @@ -90,19 +92,25 @@ fn main() {
.unwrap();
debug!("database opened successfully");

let blockchain_config = ElectrumBlockchainConfig {
url: matches.value_of("server").unwrap().to_string(),
socks5: matches.value_of("proxy").map(ToString::to_string),
let config = match matches.value_of("esplora") {
afilini marked this conversation as resolved.
Show resolved Hide resolved
Some(base_url) => AnyBlockchainConfig::Esplora(EsploraBlockchainConfig {
base_url: base_url.to_string(),
}),
None => AnyBlockchainConfig::Electrum(ElectrumBlockchainConfig {
url: matches.value_of("server").unwrap().to_string(),
socks5: matches.value_of("proxy").map(ToString::to_string),
}),
};
let wallet = Wallet::new(
descriptor,
change_descriptor,
network,
tree,
ElectrumBlockchain::from_config(&blockchain_config).unwrap(),
)
.unwrap();
let wallet = Arc::new(wallet);
let wallet = Arc::new(
Wallet::new(
descriptor,
change_descriptor,
network,
tree,
AnyBlockchain::from_config(&config).unwrap(),
)
.unwrap(),
);

if let Some(_sub_matches) = matches.subcommand_matches("repl") {
let mut rl = Editor::<()>::new();
Expand Down
40 changes: 11 additions & 29 deletions src/blockchain/electrum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ use std::collections::HashSet;
#[allow(unused_imports)]
use log::{debug, error, info, trace};

use bitcoin::{Script, Transaction, Txid};
use bitcoin::{BlockHeader, Script, Transaction, Txid};

use electrum_client::{Client, ElectrumApi};

use self::utils::{ELSGetHistoryRes, ELSListUnspentRes, ElectrumLikeSync};
use self::utils::{ELSGetHistoryRes, ElectrumLikeSync};
use super::*;
use crate::database::BatchDatabase;
use crate::error::Error;
Expand Down Expand Up @@ -141,36 +141,18 @@ impl ElectrumLikeSync for Client {
.map_err(Error::Electrum)
}

fn els_batch_script_list_unspent<'s, I: IntoIterator<Item = &'s Script>>(
fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
&self,
scripts: I,
) -> Result<Vec<Vec<ELSListUnspentRes>>, Error> {
self.batch_script_list_unspent(scripts)
.map(|v| {
v.into_iter()
.map(|v| {
v.into_iter()
.map(
|electrum_client::ListUnspentRes {
height,
tx_hash,
tx_pos,
..
}| ELSListUnspentRes {
height,
tx_hash,
tx_pos,
},
)
.collect()
})
.collect()
})
.map_err(Error::Electrum)
txids: I,
) -> Result<Vec<Transaction>, Error> {
self.batch_transaction_get(txids).map_err(Error::Electrum)
}

fn els_transaction_get(&self, txid: &Txid) -> Result<Transaction, Error> {
self.transaction_get(txid).map_err(Error::Electrum)
fn els_batch_block_header<I: IntoIterator<Item = u32>>(
&self,
heights: I,
) -> Result<Vec<BlockHeader>, Error> {
self.batch_block_header(heights).map_err(Error::Electrum)
}
}

Expand Down
142 changes: 102 additions & 40 deletions src/blockchain/esplora.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ use reqwest::{Client, StatusCode};
use bitcoin::consensus::{deserialize, serialize};
use bitcoin::hashes::hex::ToHex;
use bitcoin::hashes::{sha256, Hash};
use bitcoin::{Script, Transaction, Txid};
use bitcoin::{BlockHash, BlockHeader, Script, Transaction, TxMerkleNode, Txid};

use self::utils::{ELSGetHistoryRes, ELSListUnspentRes, ElectrumLikeSync};
use self::utils::{ELSGetHistoryRes, ElectrumLikeSync};
use super::*;
use crate::database::BatchDatabase;
use crate::error::Error;
Expand Down Expand Up @@ -161,6 +161,39 @@ impl UrlClient {
Ok(Some(deserialize(&resp.error_for_status()?.bytes().await?)?))
}

async fn _get_tx_no_opt(&self, txid: &Txid) -> Result<Transaction, EsploraError> {
match self._get_tx(txid).await {
Ok(Some(tx)) => Ok(tx),
Ok(None) => Err(EsploraError::TransactionNotFound(*txid)),
Err(e) => Err(e),
}
}

async fn _get_header(&self, block_height: u32) -> Result<BlockHeader, EsploraError> {
let resp = self
.client
.get(&format!("{}/block-height/{}", self.url, block_height))
.send()
.await?;

if let StatusCode::NOT_FOUND = resp.status() {
return Err(EsploraError::HeaderHeightNotFound(block_height));
}
let bytes = resp.bytes().await?;
let hash = std::str::from_utf8(&bytes)
.map_err(|_| EsploraError::HeaderHeightNotFound(block_height))?;

let resp = self
.client
.get(&format!("{}/block/{}", self.url, hash))
.send()
.await?;

let esplora_header = resp.json::<EsploraHeader>().await?;

Ok(esplora_header.into())
}

async fn _broadcast(&self, transaction: &Transaction) -> Result<(), EsploraError> {
self.client
.post(&format!("{}/tx", self.url))
Expand Down Expand Up @@ -249,31 +282,6 @@ impl UrlClient {
Ok(result)
}

async fn _script_list_unspent(
&self,
script: &Script,
) -> Result<Vec<ELSListUnspentRes>, EsploraError> {
Ok(self
.client
.get(&format!(
"{}/scripthash/{}/utxo",
self.url,
Self::script_to_scripthash(script)
))
.send()
.await?
.error_for_status()?
.json::<Vec<EsploraListUnspent>>()
.await?
.into_iter()
.map(|x| ELSListUnspentRes {
tx_hash: x.txid,
height: x.status.block_height.unwrap_or(0),
tx_pos: x.vout,
})
.collect())
}

async fn _get_fee_estimates(&self) -> Result<HashMap<String, f64>, EsploraError> {
Ok(self
.client
Expand Down Expand Up @@ -302,23 +310,32 @@ impl ElectrumLikeSync for UrlClient {
await_or_block!(future)
}

fn els_batch_script_list_unspent<'s, I: IntoIterator<Item = &'s Script>>(
fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
&self,
scripts: I,
) -> Result<Vec<Vec<ELSListUnspentRes>>, Error> {
txids: I,
) -> Result<Vec<Transaction>, Error> {
let future = async {
Ok(stream::iter(scripts)
.then(|script| self._script_list_unspent(&script))
Ok(stream::iter(txids)
.then(|txid| self._get_tx_no_opt(&txid))
.try_collect()
.await?)
};

await_or_block!(future)
}

fn els_transaction_get(&self, txid: &Txid) -> Result<Transaction, Error> {
Ok(await_or_block!(self._get_tx(txid))?
.ok_or_else(|| EsploraError::TransactionNotFound(*txid))?)
fn els_batch_block_header<I: IntoIterator<Item = u32>>(
&self,
heights: I,
) -> Result<Vec<BlockHeader>, Error> {
let future = async {
Ok(stream::iter(heights)
.then(|h| self._get_header(h))
.try_collect()
.await?)
};

await_or_block!(future)
}
}

Expand All @@ -333,11 +350,33 @@ struct EsploraGetHistory {
status: EsploraGetHistoryStatus,
}

#[derive(Deserialize)]
struct EsploraListUnspent {
txid: Txid,
vout: usize,
status: EsploraGetHistoryStatus,
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
pub struct EsploraHeader {
pub id: String,
pub height: u32,
pub version: i32,
pub timestamp: u32,
pub tx_count: u32,
pub size: u32,
pub weight: u32,
pub merkle_root: TxMerkleNode,
pub previousblockhash: BlockHash,
pub nonce: u32,
pub bits: u32,
pub difficulty: u32,
}

impl Into<BlockHeader> for EsploraHeader {
fn into(self) -> BlockHeader {
BlockHeader {
version: self.version,
prev_blockhash: self.previousblockhash,
merkle_root: self.merkle_root,
time: self.timestamp,
bits: self.bits,
nonce: self.nonce,
}
}
}

/// Configuration for an [`EsploraBlockchain`]
Expand Down Expand Up @@ -366,6 +405,10 @@ pub enum EsploraError {

/// Transaction not found
TransactionNotFound(Txid),
/// Header height not found
HeaderHeightNotFound(u32),
/// Header hash not found
HeaderHashNotFound(BlockHash),
}

impl fmt::Display for EsploraError {
Expand Down Expand Up @@ -393,3 +436,22 @@ impl From<bitcoin::consensus::encode::Error> for EsploraError {
EsploraError::BitcoinEncoding(other)
}
}

#[cfg(test)]
mod test {
use crate::blockchain::esplora::EsploraHeader;
use bitcoin::hashes::hex::FromHex;
use bitcoin::{BlockHash, BlockHeader};

#[test]
fn test_esplora_header() {
let json_str = r#"{"id":"00000000b873e79784647a6c82962c70d228557d24a747ea4d1b8bbe878e1206","height":1,"version":1,"timestamp":1296688928,"tx_count":1,"size":190,"weight":760,"merkle_root":"f0315ffc38709d70ad5647e22048358dd3745f3ce3874223c80a7c92fab0c8ba","previousblockhash":"000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943","nonce":1924588547,"bits":486604799,"difficulty":1}"#;
let json: EsploraHeader = serde_json::from_str(&json_str).unwrap();
let header: BlockHeader = json.into();
assert_eq!(
header.block_hash(),
BlockHash::from_hex("00000000b873e79784647a6c82962c70d228557d24a747ea4d1b8bbe878e1206")
.unwrap()
);
}
}
1 change: 1 addition & 0 deletions src/blockchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ use crate::database::BatchDatabase;
use crate::error::Error;
use crate::FeeRate;

#[cfg(any(feature = "electrum", feature = "esplora"))]
pub(crate) mod utils;

#[cfg(any(feature = "electrum", feature = "esplora", feature = "compact_filters"))]
Expand Down
Loading