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
12 changes: 8 additions & 4 deletions .github/workflows/cont_integration.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,15 +78,20 @@ jobs:
run: cargo test --features test-md-docs --no-default-features -- doctest::ReadmeDoctests

test-blockchains:
name: Test ${{ matrix.blockchain.name }}
name: Blockchain ${{ matrix.blockchain.features }}
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
blockchain:
- name: electrum
features: test-electrum
- name: rpc
features: test-rpc
- name: esplora
features: test-esplora,use-esplora-reqwest
- name: esplora
features: test-esplora,use-esplora-ureq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

steps:
- name: Checkout
uses: actions/checkout@v2
Expand All@@ -104,8 +109,8 @@ jobs:
toolchain: stable
override: true
- name: Test
run: cargo test --features test-${{ matrix.blockchain.name }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

run: cargo test --no-default-features --features ${{ matrix.blockchain.features }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

check-wasm:
name: Check WASM
runs-on: ubuntu-16.04
Expand DownExpand Up@@ -139,7 +144,6 @@ jobs:
- name: Check
run: cargo check --target wasm32-unknown-unknown --features use-esplora-reqwest --no-default-features


fmt:
name: Rust fmt
runs-on: ubuntu-latest
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"

[dependencies]
bdk-macros = "0.5"
bdk-macros = { path = "macros"} # TODO: Change this to version number after next release.
log = "^0.4"
miniscript = "^6.0"
bitcoin = { version = "^0.27", features = ["use-serde", "base64"] }
Expand All@@ -38,6 +38,10 @@ bitcoinconsensus = { version = "0.19.0-3", optional = true }
# Needed by bdk_blockchain_tests macro
core-rpc = { version = "0.14", optional = true }

# Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please correct me if I'm wrong, but this PR re-introduces a hard dependency on tokio just so we can test esplora-reqwest feature, that seems like a bad choice to me. A user of bdk that wishes to use reqwest will always be using async, why do we want to introduce a hard dependency on tokio just to be able to test in a manner that the library will not be used?

The esplora-reqwest feature can be tested coupled with either async-interface feature or using WASM target.


[target.'cfg(target_arch = "wasm32")'.dependencies]
async-trait = "0.1"
js-sys = "0.3"
Expand DownExpand Up@@ -70,7 +74,7 @@ rpc = ["core-rpc"]
async-interface = ["async-trait"]
electrum = ["electrum-client"]
# MUST ALSO USE `--no-default-features`.
use-esplora-reqwest = ["async-interface", "esplora", "reqwest", "futures"]
use-esplora-reqwest = ["esplora", "reqwest", "futures"]
use-esplora-ureq = ["esplora", "ureq"]
# Typical configurations will not need to use `esplora` feature directly.
esplora = []
Expand All@@ -80,7 +84,7 @@ esplora = []
test-blockchains = ["core-rpc", "electrum-client"]
test-electrum = ["electrum", "electrsd/electrs_0_8_10", "test-blockchains"]
test-rpc = ["rpc", "electrsd/electrs_0_8_10", "test-blockchains"]
test-esplora = ["esplora", "ureq", "electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-esplora = ["electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-md-docs = ["electrum"]

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions macros/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,3 +121,26 @@ pub fn maybe_await(expr: TokenStream) -> TokenStream {

quoted.into()
}

/// Awaits if target_arch is "wasm32", uses `tokio::Runtime::block_on()` otherwise
///
/// Requires the `tokio` crate as a dependecy with `rt-core` or `rt-threaded` to build on non-wasm32 platforms.
#[proc_macro]
pub fn await_or_block(expr: TokenStream) -> TokenStream {
let expr: proc_macro2::TokenStream = expr.into();
let quoted = quote! {
{
#[cfg(all(not(target_arch = "wasm32"), not(feature = "async-interface")))]
{
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(#expr)
}

#[cfg(any(target_arch = "wasm32", feature = "async-interface"))]
{
#expr.await
}
}
};

quoted.into()
}
38 changes: 12 additions & 26 deletions src/blockchain/esplora/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,38 +29,16 @@ use bitcoin::{BlockHash, Txid};
use crate::error::Error;
use crate::FeeRate;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
mod reqwest;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
pub use self::reqwest::*;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
mod ureq;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
pub use self::ureq::*;

fn into_fee_rate(target: usize, estimates: HashMap<String, f64>) -> Result<FeeRate, Error> {
Expand DownExpand Up@@ -141,3 +119,11 @@ impl_error!(io::Error, Io, EsploraError);
impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), 20)
}
}
28 changes: 10 additions & 18 deletions src/blockchain/esplora/reqwest.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,19 +106,19 @@ impl Blockchain for EsploraBlockchain {
}

fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
Ok(self.url_client._get_tx(txid).await?)
Ok(await_or_block!(self.url_client._get_tx(txid))?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I do not like this usage of await_or_block because there is no reason to use reqwest in a blocking environment, we have ureq for that.

}

fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
Ok(self.url_client._broadcast(tx).await?)
Ok(await_or_block!(self.url_client._broadcast(tx))?)
}

fn get_height(&self) -> Result<u32, Error> {
Ok(self.url_client._get_height().await?)
Ok(await_or_block!(self.url_client._get_height())?)
}

fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
let estimates = self.url_client._get_fee_estimates().await?;
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
super::into_fee_rate(target, estimates)
}
}
Expand DownExpand Up@@ -287,10 +287,10 @@ impl ElectrumLikeSync for UrlClient {
for script in chunk {
futs.push(self._script_get_history(script));
}
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
let partial_results: Vec<Vec<ElsGetHistoryRes>> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
Expand All@@ -303,10 +303,10 @@ impl ElectrumLikeSync for UrlClient {
for txid in chunk {
futs.push(self._get_tx_no_opt(txid));
}
let partial_results: Vec<Transaction> = futs.try_collect().await?;
let partial_results: Vec<Transaction> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_block_header<I: IntoIterator<Item = u32>>(
Expand All@@ -319,10 +319,10 @@ impl ElectrumLikeSync for UrlClient {
for height in chunk {
futs.push(self._get_header(height));
}
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
let partial_results: Vec<BlockHeader> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}
}

Expand DownExpand Up@@ -350,11 +350,3 @@ impl ConfigurableBlockchain for EsploraBlockchain {
Ok(blockchain)
}
}

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
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
12 changes: 8 additions & 4 deletions .github/workflows/cont_integration.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,15 +78,20 @@ jobs:
run: cargo test --features test-md-docs --no-default-features -- doctest::ReadmeDoctests

test-blockchains:
name: Test ${{ matrix.blockchain.name }}
name: Blockchain ${{ matrix.blockchain.features }}
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
blockchain:
- name: electrum
features: test-electrum
- name: rpc
features: test-rpc
- name: esplora
features: test-esplora,use-esplora-reqwest
- name: esplora
features: test-esplora,use-esplora-ureq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

steps:
- name: Checkout
uses: actions/checkout@v2
Expand All@@ -104,8 +109,8 @@ jobs:
toolchain: stable
override: true
- name: Test
run: cargo test --features test-${{ matrix.blockchain.name }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

run: cargo test --no-default-features --features ${{ matrix.blockchain.features }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

check-wasm:
name: Check WASM
runs-on: ubuntu-16.04
Expand DownExpand Up@@ -139,7 +144,6 @@ jobs:
- name: Check
run: cargo check --target wasm32-unknown-unknown --features use-esplora-reqwest --no-default-features


fmt:
name: Rust fmt
runs-on: ubuntu-latest
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"

[dependencies]
bdk-macros = "0.5"
bdk-macros = { path = "macros"} # TODO: Change this to version number after next release.
log = "^0.4"
miniscript = "^6.0"
bitcoin = { version = "^0.27", features = ["use-serde", "base64"] }
Expand All@@ -38,6 +38,10 @@ bitcoinconsensus = { version = "0.19.0-3", optional = true }
# Needed by bdk_blockchain_tests macro
core-rpc = { version = "0.14", optional = true }

# Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please correct me if I'm wrong, but this PR re-introduces a hard dependency on tokio just so we can test esplora-reqwest feature, that seems like a bad choice to me. A user of bdk that wishes to use reqwest will always be using async, why do we want to introduce a hard dependency on tokio just to be able to test in a manner that the library will not be used?

The esplora-reqwest feature can be tested coupled with either async-interface feature or using WASM target.


[target.'cfg(target_arch = "wasm32")'.dependencies]
async-trait = "0.1"
js-sys = "0.3"
Expand DownExpand Up@@ -70,7 +74,7 @@ rpc = ["core-rpc"]
async-interface = ["async-trait"]
electrum = ["electrum-client"]
# MUST ALSO USE `--no-default-features`.
use-esplora-reqwest = ["async-interface", "esplora", "reqwest", "futures"]
use-esplora-reqwest = ["esplora", "reqwest", "futures"]
use-esplora-ureq = ["esplora", "ureq"]
# Typical configurations will not need to use `esplora` feature directly.
esplora = []
Expand All@@ -80,7 +84,7 @@ esplora = []
test-blockchains = ["core-rpc", "electrum-client"]
test-electrum = ["electrum", "electrsd/electrs_0_8_10", "test-blockchains"]
test-rpc = ["rpc", "electrsd/electrs_0_8_10", "test-blockchains"]
test-esplora = ["esplora", "ureq", "electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-esplora = ["electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-md-docs = ["electrum"]

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions macros/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,3 +121,26 @@ pub fn maybe_await(expr: TokenStream) -> TokenStream {

quoted.into()
}

/// Awaits if target_arch is "wasm32", uses `tokio::Runtime::block_on()` otherwise
///
/// Requires the `tokio` crate as a dependecy with `rt-core` or `rt-threaded` to build on non-wasm32 platforms.
#[proc_macro]
pub fn await_or_block(expr: TokenStream) -> TokenStream {
let expr: proc_macro2::TokenStream = expr.into();
let quoted = quote! {
{
#[cfg(all(not(target_arch = "wasm32"), not(feature = "async-interface")))]
{
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(#expr)
}

#[cfg(any(target_arch = "wasm32", feature = "async-interface"))]
{
#expr.await
}
}
};

quoted.into()
}
38 changes: 12 additions & 26 deletions src/blockchain/esplora/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,38 +29,16 @@ use bitcoin::{BlockHash, Txid};
use crate::error::Error;
use crate::FeeRate;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
mod reqwest;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
pub use self::reqwest::*;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
mod ureq;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
pub use self::ureq::*;

fn into_fee_rate(target: usize, estimates: HashMap<String, f64>) -> Result<FeeRate, Error> {
Expand DownExpand Up@@ -141,3 +119,11 @@ impl_error!(io::Error, Io, EsploraError);
impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), 20)
}
}
28 changes: 10 additions & 18 deletions src/blockchain/esplora/reqwest.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,19 +106,19 @@ impl Blockchain for EsploraBlockchain {
}

fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
Ok(self.url_client._get_tx(txid).await?)
Ok(await_or_block!(self.url_client._get_tx(txid))?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I do not like this usage of await_or_block because there is no reason to use reqwest in a blocking environment, we have ureq for that.

}

fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
Ok(self.url_client._broadcast(tx).await?)
Ok(await_or_block!(self.url_client._broadcast(tx))?)
}

fn get_height(&self) -> Result<u32, Error> {
Ok(self.url_client._get_height().await?)
Ok(await_or_block!(self.url_client._get_height())?)
}

fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
let estimates = self.url_client._get_fee_estimates().await?;
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
super::into_fee_rate(target, estimates)
}
}
Expand DownExpand Up@@ -287,10 +287,10 @@ impl ElectrumLikeSync for UrlClient {
for script in chunk {
futs.push(self._script_get_history(script));
}
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
let partial_results: Vec<Vec<ElsGetHistoryRes>> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
Expand All@@ -303,10 +303,10 @@ impl ElectrumLikeSync for UrlClient {
for txid in chunk {
futs.push(self._get_tx_no_opt(txid));
}
let partial_results: Vec<Transaction> = futs.try_collect().await?;
let partial_results: Vec<Transaction> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_block_header<I: IntoIterator<Item = u32>>(
Expand All@@ -319,10 +319,10 @@ impl ElectrumLikeSync for UrlClient {
for height in chunk {
futs.push(self._get_header(height));
}
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
let partial_results: Vec<BlockHeader> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}
}

Expand DownExpand Up@@ -350,11 +350,3 @@ impl ConfigurableBlockchain for EsploraBlockchain {
Ok(blockchain)
}
}

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
12 changes: 8 additions & 4 deletions .github/workflows/cont_integration.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,15 +78,20 @@ jobs:
run: cargo test --features test-md-docs --no-default-features -- doctest::ReadmeDoctests

test-blockchains:
name: Test ${{ matrix.blockchain.name }}
name: Blockchain ${{ matrix.blockchain.features }}
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
blockchain:
- name: electrum
features: test-electrum
- name: rpc
features: test-rpc
- name: esplora
features: test-esplora,use-esplora-reqwest
- name: esplora
features: test-esplora,use-esplora-ureq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

steps:
- name: Checkout
uses: actions/checkout@v2
Expand All@@ -104,8 +109,8 @@ jobs:
toolchain: stable
override: true
- name: Test
run: cargo test --features test-${{ matrix.blockchain.name }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

run: cargo test --no-default-features --features ${{ matrix.blockchain.features }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

check-wasm:
name: Check WASM
runs-on: ubuntu-16.04
Expand DownExpand Up@@ -139,7 +144,6 @@ jobs:
- name: Check
run: cargo check --target wasm32-unknown-unknown --features use-esplora-reqwest --no-default-features


fmt:
name: Rust fmt
runs-on: ubuntu-latest
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"

[dependencies]
bdk-macros = "0.5"
bdk-macros = { path = "macros"} # TODO: Change this to version number after next release.
log = "^0.4"
miniscript = "^6.0"
bitcoin = { version = "^0.27", features = ["use-serde", "base64"] }
Expand All@@ -38,6 +38,10 @@ bitcoinconsensus = { version = "0.19.0-3", optional = true }
# Needed by bdk_blockchain_tests macro
core-rpc = { version = "0.14", optional = true }

# Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please correct me if I'm wrong, but this PR re-introduces a hard dependency on tokio just so we can test esplora-reqwest feature, that seems like a bad choice to me. A user of bdk that wishes to use reqwest will always be using async, why do we want to introduce a hard dependency on tokio just to be able to test in a manner that the library will not be used?

The esplora-reqwest feature can be tested coupled with either async-interface feature or using WASM target.


[target.'cfg(target_arch = "wasm32")'.dependencies]
async-trait = "0.1"
js-sys = "0.3"
Expand DownExpand Up@@ -70,7 +74,7 @@ rpc = ["core-rpc"]
async-interface = ["async-trait"]
electrum = ["electrum-client"]
# MUST ALSO USE `--no-default-features`.
use-esplora-reqwest = ["async-interface", "esplora", "reqwest", "futures"]
use-esplora-reqwest = ["esplora", "reqwest", "futures"]
use-esplora-ureq = ["esplora", "ureq"]
# Typical configurations will not need to use `esplora` feature directly.
esplora = []
Expand All@@ -80,7 +84,7 @@ esplora = []
test-blockchains = ["core-rpc", "electrum-client"]
test-electrum = ["electrum", "electrsd/electrs_0_8_10", "test-blockchains"]
test-rpc = ["rpc", "electrsd/electrs_0_8_10", "test-blockchains"]
test-esplora = ["esplora", "ureq", "electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-esplora = ["electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-md-docs = ["electrum"]

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions macros/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,3 +121,26 @@ pub fn maybe_await(expr: TokenStream) -> TokenStream {

quoted.into()
}

/// Awaits if target_arch is "wasm32", uses `tokio::Runtime::block_on()` otherwise
///
/// Requires the `tokio` crate as a dependecy with `rt-core` or `rt-threaded` to build on non-wasm32 platforms.
#[proc_macro]
pub fn await_or_block(expr: TokenStream) -> TokenStream {
let expr: proc_macro2::TokenStream = expr.into();
let quoted = quote! {
{
#[cfg(all(not(target_arch = "wasm32"), not(feature = "async-interface")))]
{
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(#expr)
}

#[cfg(any(target_arch = "wasm32", feature = "async-interface"))]
{
#expr.await
}
}
};

quoted.into()
}
38 changes: 12 additions & 26 deletions src/blockchain/esplora/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,38 +29,16 @@ use bitcoin::{BlockHash, Txid};
use crate::error::Error;
use crate::FeeRate;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
mod reqwest;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
pub use self::reqwest::*;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
mod ureq;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
pub use self::ureq::*;

fn into_fee_rate(target: usize, estimates: HashMap<String, f64>) -> Result<FeeRate, Error> {
Expand DownExpand Up@@ -141,3 +119,11 @@ impl_error!(io::Error, Io, EsploraError);
impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), 20)
}
}
28 changes: 10 additions & 18 deletions src/blockchain/esplora/reqwest.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,19 +106,19 @@ impl Blockchain for EsploraBlockchain {
}

fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
Ok(self.url_client._get_tx(txid).await?)
Ok(await_or_block!(self.url_client._get_tx(txid))?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I do not like this usage of await_or_block because there is no reason to use reqwest in a blocking environment, we have ureq for that.

}

fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
Ok(self.url_client._broadcast(tx).await?)
Ok(await_or_block!(self.url_client._broadcast(tx))?)
}

fn get_height(&self) -> Result<u32, Error> {
Ok(self.url_client._get_height().await?)
Ok(await_or_block!(self.url_client._get_height())?)
}

fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
let estimates = self.url_client._get_fee_estimates().await?;
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
super::into_fee_rate(target, estimates)
}
}
Expand DownExpand Up@@ -287,10 +287,10 @@ impl ElectrumLikeSync for UrlClient {
for script in chunk {
futs.push(self._script_get_history(script));
}
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
let partial_results: Vec<Vec<ElsGetHistoryRes>> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
Expand All@@ -303,10 +303,10 @@ impl ElectrumLikeSync for UrlClient {
for txid in chunk {
futs.push(self._get_tx_no_opt(txid));
}
let partial_results: Vec<Transaction> = futs.try_collect().await?;
let partial_results: Vec<Transaction> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_block_header<I: IntoIterator<Item = u32>>(
Expand All@@ -319,10 +319,10 @@ impl ElectrumLikeSync for UrlClient {
for height in chunk {
futs.push(self._get_header(height));
}
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
let partial_results: Vec<BlockHeader> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}
}

Expand DownExpand Up@@ -350,11 +350,3 @@ impl ConfigurableBlockchain for EsploraBlockchain {
Ok(blockchain)
}
}

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
12 changes: 8 additions & 4 deletions .github/workflows/cont_integration.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,15 +78,20 @@ jobs:
run: cargo test --features test-md-docs --no-default-features -- doctest::ReadmeDoctests

test-blockchains:
name: Test ${{ matrix.blockchain.name }}
name: Blockchain ${{ matrix.blockchain.features }}
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
blockchain:
- name: electrum
features: test-electrum
- name: rpc
features: test-rpc
- name: esplora
features: test-esplora,use-esplora-reqwest
- name: esplora
features: test-esplora,use-esplora-ureq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

steps:
- name: Checkout
uses: actions/checkout@v2
Expand All@@ -104,8 +109,8 @@ jobs:
toolchain: stable
override: true
- name: Test
run: cargo test --features test-${{ matrix.blockchain.name }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

run: cargo test --no-default-features --features ${{ matrix.blockchain.features }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

check-wasm:
name: Check WASM
runs-on: ubuntu-16.04
Expand DownExpand Up@@ -139,7 +144,6 @@ jobs:
- name: Check
run: cargo check --target wasm32-unknown-unknown --features use-esplora-reqwest --no-default-features


fmt:
name: Rust fmt
runs-on: ubuntu-latest
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"

[dependencies]
bdk-macros = "0.5"
bdk-macros = { path = "macros"} # TODO: Change this to version number after next release.
log = "^0.4"
miniscript = "^6.0"
bitcoin = { version = "^0.27", features = ["use-serde", "base64"] }
Expand All@@ -38,6 +38,10 @@ bitcoinconsensus = { version = "0.19.0-3", optional = true }
# Needed by bdk_blockchain_tests macro
core-rpc = { version = "0.14", optional = true }

# Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please correct me if I'm wrong, but this PR re-introduces a hard dependency on tokio just so we can test esplora-reqwest feature, that seems like a bad choice to me. A user of bdk that wishes to use reqwest will always be using async, why do we want to introduce a hard dependency on tokio just to be able to test in a manner that the library will not be used?

The esplora-reqwest feature can be tested coupled with either async-interface feature or using WASM target.


[target.'cfg(target_arch = "wasm32")'.dependencies]
async-trait = "0.1"
js-sys = "0.3"
Expand DownExpand Up@@ -70,7 +74,7 @@ rpc = ["core-rpc"]
async-interface = ["async-trait"]
electrum = ["electrum-client"]
# MUST ALSO USE `--no-default-features`.
use-esplora-reqwest = ["async-interface", "esplora", "reqwest", "futures"]
use-esplora-reqwest = ["esplora", "reqwest", "futures"]
use-esplora-ureq = ["esplora", "ureq"]
# Typical configurations will not need to use `esplora` feature directly.
esplora = []
Expand All@@ -80,7 +84,7 @@ esplora = []
test-blockchains = ["core-rpc", "electrum-client"]
test-electrum = ["electrum", "electrsd/electrs_0_8_10", "test-blockchains"]
test-rpc = ["rpc", "electrsd/electrs_0_8_10", "test-blockchains"]
test-esplora = ["esplora", "ureq", "electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-esplora = ["electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-md-docs = ["electrum"]

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions macros/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,3 +121,26 @@ pub fn maybe_await(expr: TokenStream) -> TokenStream {

quoted.into()
}

/// Awaits if target_arch is "wasm32", uses `tokio::Runtime::block_on()` otherwise
///
/// Requires the `tokio` crate as a dependecy with `rt-core` or `rt-threaded` to build on non-wasm32 platforms.
#[proc_macro]
pub fn await_or_block(expr: TokenStream) -> TokenStream {
let expr: proc_macro2::TokenStream = expr.into();
let quoted = quote! {
{
#[cfg(all(not(target_arch = "wasm32"), not(feature = "async-interface")))]
{
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(#expr)
}

#[cfg(any(target_arch = "wasm32", feature = "async-interface"))]
{
#expr.await
}
}
};

quoted.into()
}
38 changes: 12 additions & 26 deletions src/blockchain/esplora/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,38 +29,16 @@ use bitcoin::{BlockHash, Txid};
use crate::error::Error;
use crate::FeeRate;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
mod reqwest;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
pub use self::reqwest::*;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
mod ureq;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
pub use self::ureq::*;

fn into_fee_rate(target: usize, estimates: HashMap<String, f64>) -> Result<FeeRate, Error> {
Expand DownExpand Up@@ -141,3 +119,11 @@ impl_error!(io::Error, Io, EsploraError);
impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), 20)
}
}
28 changes: 10 additions & 18 deletions src/blockchain/esplora/reqwest.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,19 +106,19 @@ impl Blockchain for EsploraBlockchain {
}

fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
Ok(self.url_client._get_tx(txid).await?)
Ok(await_or_block!(self.url_client._get_tx(txid))?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I do not like this usage of await_or_block because there is no reason to use reqwest in a blocking environment, we have ureq for that.

}

fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
Ok(self.url_client._broadcast(tx).await?)
Ok(await_or_block!(self.url_client._broadcast(tx))?)
}

fn get_height(&self) -> Result<u32, Error> {
Ok(self.url_client._get_height().await?)
Ok(await_or_block!(self.url_client._get_height())?)
}

fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
let estimates = self.url_client._get_fee_estimates().await?;
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
super::into_fee_rate(target, estimates)
}
}
Expand DownExpand Up@@ -287,10 +287,10 @@ impl ElectrumLikeSync for UrlClient {
for script in chunk {
futs.push(self._script_get_history(script));
}
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
let partial_results: Vec<Vec<ElsGetHistoryRes>> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
Expand All@@ -303,10 +303,10 @@ impl ElectrumLikeSync for UrlClient {
for txid in chunk {
futs.push(self._get_tx_no_opt(txid));
}
let partial_results: Vec<Transaction> = futs.try_collect().await?;
let partial_results: Vec<Transaction> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_block_header<I: IntoIterator<Item = u32>>(
Expand All@@ -319,10 +319,10 @@ impl ElectrumLikeSync for UrlClient {
for height in chunk {
futs.push(self._get_header(height));
}
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
let partial_results: Vec<BlockHeader> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}
}

Expand DownExpand Up@@ -350,11 +350,3 @@ impl ConfigurableBlockchain for EsploraBlockchain {
Ok(blockchain)
}
}

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
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
12 changes: 8 additions & 4 deletions .github/workflows/cont_integration.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,15 +78,20 @@ jobs:
run: cargo test --features test-md-docs --no-default-features -- doctest::ReadmeDoctests

test-blockchains:
name: Test ${{ matrix.blockchain.name }}
name: Blockchain ${{ matrix.blockchain.features }}
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
blockchain:
- name: electrum
features: test-electrum
- name: rpc
features: test-rpc
- name: esplora
features: test-esplora,use-esplora-reqwest
- name: esplora
features: test-esplora,use-esplora-ureq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

steps:
- name: Checkout
uses: actions/checkout@v2
Expand All@@ -104,8 +109,8 @@ jobs:
toolchain: stable
override: true
- name: Test
run: cargo test --features test-${{ matrix.blockchain.name }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

run: cargo test --no-default-features --features ${{ matrix.blockchain.features }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

check-wasm:
name: Check WASM
runs-on: ubuntu-16.04
Expand DownExpand Up@@ -139,7 +144,6 @@ jobs:
- name: Check
run: cargo check --target wasm32-unknown-unknown --features use-esplora-reqwest --no-default-features


fmt:
name: Rust fmt
runs-on: ubuntu-latest
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"

[dependencies]
bdk-macros = "0.5"
bdk-macros = { path = "macros"} # TODO: Change this to version number after next release.
log = "^0.4"
miniscript = "^6.0"
bitcoin = { version = "^0.27", features = ["use-serde", "base64"] }
Expand All@@ -38,6 +38,10 @@ bitcoinconsensus = { version = "0.19.0-3", optional = true }
# Needed by bdk_blockchain_tests macro
core-rpc = { version = "0.14", optional = true }

# Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please correct me if I'm wrong, but this PR re-introduces a hard dependency on tokio just so we can test esplora-reqwest feature, that seems like a bad choice to me. A user of bdk that wishes to use reqwest will always be using async, why do we want to introduce a hard dependency on tokio just to be able to test in a manner that the library will not be used?

The esplora-reqwest feature can be tested coupled with either async-interface feature or using WASM target.


[target.'cfg(target_arch = "wasm32")'.dependencies]
async-trait = "0.1"
js-sys = "0.3"
Expand DownExpand Up@@ -70,7 +74,7 @@ rpc = ["core-rpc"]
async-interface = ["async-trait"]
electrum = ["electrum-client"]
# MUST ALSO USE `--no-default-features`.
use-esplora-reqwest = ["async-interface", "esplora", "reqwest", "futures"]
use-esplora-reqwest = ["esplora", "reqwest", "futures"]
use-esplora-ureq = ["esplora", "ureq"]
# Typical configurations will not need to use `esplora` feature directly.
esplora = []
Expand All@@ -80,7 +84,7 @@ esplora = []
test-blockchains = ["core-rpc", "electrum-client"]
test-electrum = ["electrum", "electrsd/electrs_0_8_10", "test-blockchains"]
test-rpc = ["rpc", "electrsd/electrs_0_8_10", "test-blockchains"]
test-esplora = ["esplora", "ureq", "electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-esplora = ["electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-md-docs = ["electrum"]

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions macros/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,3 +121,26 @@ pub fn maybe_await(expr: TokenStream) -> TokenStream {

quoted.into()
}

/// Awaits if target_arch is "wasm32", uses `tokio::Runtime::block_on()` otherwise
///
/// Requires the `tokio` crate as a dependecy with `rt-core` or `rt-threaded` to build on non-wasm32 platforms.
#[proc_macro]
pub fn await_or_block(expr: TokenStream) -> TokenStream {
let expr: proc_macro2::TokenStream = expr.into();
let quoted = quote! {
{
#[cfg(all(not(target_arch = "wasm32"), not(feature = "async-interface")))]
{
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(#expr)
}

#[cfg(any(target_arch = "wasm32", feature = "async-interface"))]
{
#expr.await
}
}
};

quoted.into()
}
38 changes: 12 additions & 26 deletions src/blockchain/esplora/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,38 +29,16 @@ use bitcoin::{BlockHash, Txid};
use crate::error::Error;
use crate::FeeRate;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
mod reqwest;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
pub use self::reqwest::*;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
mod ureq;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
pub use self::ureq::*;

fn into_fee_rate(target: usize, estimates: HashMap<String, f64>) -> Result<FeeRate, Error> {
Expand DownExpand Up@@ -141,3 +119,11 @@ impl_error!(io::Error, Io, EsploraError);
impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), 20)
}
}
28 changes: 10 additions & 18 deletions src/blockchain/esplora/reqwest.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,19 +106,19 @@ impl Blockchain for EsploraBlockchain {
}

fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
Ok(self.url_client._get_tx(txid).await?)
Ok(await_or_block!(self.url_client._get_tx(txid))?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I do not like this usage of await_or_block because there is no reason to use reqwest in a blocking environment, we have ureq for that.

}

fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
Ok(self.url_client._broadcast(tx).await?)
Ok(await_or_block!(self.url_client._broadcast(tx))?)
}

fn get_height(&self) -> Result<u32, Error> {
Ok(self.url_client._get_height().await?)
Ok(await_or_block!(self.url_client._get_height())?)
}

fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
let estimates = self.url_client._get_fee_estimates().await?;
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
super::into_fee_rate(target, estimates)
}
}
Expand DownExpand Up@@ -287,10 +287,10 @@ impl ElectrumLikeSync for UrlClient {
for script in chunk {
futs.push(self._script_get_history(script));
}
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
let partial_results: Vec<Vec<ElsGetHistoryRes>> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
Expand All@@ -303,10 +303,10 @@ impl ElectrumLikeSync for UrlClient {
for txid in chunk {
futs.push(self._get_tx_no_opt(txid));
}
let partial_results: Vec<Transaction> = futs.try_collect().await?;
let partial_results: Vec<Transaction> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_block_header<I: IntoIterator<Item = u32>>(
Expand All@@ -319,10 +319,10 @@ impl ElectrumLikeSync for UrlClient {
for height in chunk {
futs.push(self._get_header(height));
}
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
let partial_results: Vec<BlockHeader> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}
}

Expand DownExpand Up@@ -350,11 +350,3 @@ impl ConfigurableBlockchain for EsploraBlockchain {
Ok(blockchain)
}
}

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
12 changes: 8 additions & 4 deletions .github/workflows/cont_integration.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,15 +78,20 @@ jobs:
run: cargo test --features test-md-docs --no-default-features -- doctest::ReadmeDoctests

test-blockchains:
name: Test ${{ matrix.blockchain.name }}
name: Blockchain ${{ matrix.blockchain.features }}
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
blockchain:
- name: electrum
features: test-electrum
- name: rpc
features: test-rpc
- name: esplora
features: test-esplora,use-esplora-reqwest
- name: esplora
features: test-esplora,use-esplora-ureq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

steps:
- name: Checkout
uses: actions/checkout@v2
Expand All@@ -104,8 +109,8 @@ jobs:
toolchain: stable
override: true
- name: Test
run: cargo test --features test-${{ matrix.blockchain.name }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

run: cargo test --no-default-features --features ${{ matrix.blockchain.features }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

check-wasm:
name: Check WASM
runs-on: ubuntu-16.04
Expand DownExpand Up@@ -139,7 +144,6 @@ jobs:
- name: Check
run: cargo check --target wasm32-unknown-unknown --features use-esplora-reqwest --no-default-features


fmt:
name: Rust fmt
runs-on: ubuntu-latest
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"

[dependencies]
bdk-macros = "0.5"
bdk-macros = { path = "macros"} # TODO: Change this to version number after next release.
log = "^0.4"
miniscript = "^6.0"
bitcoin = { version = "^0.27", features = ["use-serde", "base64"] }
Expand All@@ -38,6 +38,10 @@ bitcoinconsensus = { version = "0.19.0-3", optional = true }
# Needed by bdk_blockchain_tests macro
core-rpc = { version = "0.14", optional = true }

# Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please correct me if I'm wrong, but this PR re-introduces a hard dependency on tokio just so we can test esplora-reqwest feature, that seems like a bad choice to me. A user of bdk that wishes to use reqwest will always be using async, why do we want to introduce a hard dependency on tokio just to be able to test in a manner that the library will not be used?

The esplora-reqwest feature can be tested coupled with either async-interface feature or using WASM target.


[target.'cfg(target_arch = "wasm32")'.dependencies]
async-trait = "0.1"
js-sys = "0.3"
Expand DownExpand Up@@ -70,7 +74,7 @@ rpc = ["core-rpc"]
async-interface = ["async-trait"]
electrum = ["electrum-client"]
# MUST ALSO USE `--no-default-features`.
use-esplora-reqwest = ["async-interface", "esplora", "reqwest", "futures"]
use-esplora-reqwest = ["esplora", "reqwest", "futures"]
use-esplora-ureq = ["esplora", "ureq"]
# Typical configurations will not need to use `esplora` feature directly.
esplora = []
Expand All@@ -80,7 +84,7 @@ esplora = []
test-blockchains = ["core-rpc", "electrum-client"]
test-electrum = ["electrum", "electrsd/electrs_0_8_10", "test-blockchains"]
test-rpc = ["rpc", "electrsd/electrs_0_8_10", "test-blockchains"]
test-esplora = ["esplora", "ureq", "electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-esplora = ["electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-md-docs = ["electrum"]

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions macros/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,3 +121,26 @@ pub fn maybe_await(expr: TokenStream) -> TokenStream {

quoted.into()
}

/// Awaits if target_arch is "wasm32", uses `tokio::Runtime::block_on()` otherwise
///
/// Requires the `tokio` crate as a dependecy with `rt-core` or `rt-threaded` to build on non-wasm32 platforms.
#[proc_macro]
pub fn await_or_block(expr: TokenStream) -> TokenStream {
let expr: proc_macro2::TokenStream = expr.into();
let quoted = quote! {
{
#[cfg(all(not(target_arch = "wasm32"), not(feature = "async-interface")))]
{
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(#expr)
}

#[cfg(any(target_arch = "wasm32", feature = "async-interface"))]
{
#expr.await
}
}
};

quoted.into()
}
38 changes: 12 additions & 26 deletions src/blockchain/esplora/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,38 +29,16 @@ use bitcoin::{BlockHash, Txid};
use crate::error::Error;
use crate::FeeRate;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
mod reqwest;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
pub use self::reqwest::*;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
mod ureq;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
pub use self::ureq::*;

fn into_fee_rate(target: usize, estimates: HashMap<String, f64>) -> Result<FeeRate, Error> {
Expand DownExpand Up@@ -141,3 +119,11 @@ impl_error!(io::Error, Io, EsploraError);
impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), 20)
}
}
28 changes: 10 additions & 18 deletions src/blockchain/esplora/reqwest.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,19 +106,19 @@ impl Blockchain for EsploraBlockchain {
}

fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
Ok(self.url_client._get_tx(txid).await?)
Ok(await_or_block!(self.url_client._get_tx(txid))?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I do not like this usage of await_or_block because there is no reason to use reqwest in a blocking environment, we have ureq for that.

}

fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
Ok(self.url_client._broadcast(tx).await?)
Ok(await_or_block!(self.url_client._broadcast(tx))?)
}

fn get_height(&self) -> Result<u32, Error> {
Ok(self.url_client._get_height().await?)
Ok(await_or_block!(self.url_client._get_height())?)
}

fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
let estimates = self.url_client._get_fee_estimates().await?;
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
super::into_fee_rate(target, estimates)
}
}
Expand DownExpand Up@@ -287,10 +287,10 @@ impl ElectrumLikeSync for UrlClient {
for script in chunk {
futs.push(self._script_get_history(script));
}
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
let partial_results: Vec<Vec<ElsGetHistoryRes>> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
Expand All@@ -303,10 +303,10 @@ impl ElectrumLikeSync for UrlClient {
for txid in chunk {
futs.push(self._get_tx_no_opt(txid));
}
let partial_results: Vec<Transaction> = futs.try_collect().await?;
let partial_results: Vec<Transaction> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_block_header<I: IntoIterator<Item = u32>>(
Expand All@@ -319,10 +319,10 @@ impl ElectrumLikeSync for UrlClient {
for height in chunk {
futs.push(self._get_header(height));
}
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
let partial_results: Vec<BlockHeader> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}
}

Expand DownExpand Up@@ -350,11 +350,3 @@ impl ConfigurableBlockchain for EsploraBlockchain {
Ok(blockchain)
}
}

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
12 changes: 8 additions & 4 deletions .github/workflows/cont_integration.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,15 +78,20 @@ jobs:
run: cargo test --features test-md-docs --no-default-features -- doctest::ReadmeDoctests

test-blockchains:
name: Test ${{ matrix.blockchain.name }}
name: Blockchain ${{ matrix.blockchain.features }}
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
blockchain:
- name: electrum
features: test-electrum
- name: rpc
features: test-rpc
- name: esplora
features: test-esplora,use-esplora-reqwest
- name: esplora
features: test-esplora,use-esplora-ureq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

steps:
- name: Checkout
uses: actions/checkout@v2
Expand All@@ -104,8 +109,8 @@ jobs:
toolchain: stable
override: true
- name: Test
run: cargo test --features test-${{ matrix.blockchain.name }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

run: cargo test --no-default-features --features ${{ matrix.blockchain.features }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

check-wasm:
name: Check WASM
runs-on: ubuntu-16.04
Expand DownExpand Up@@ -139,7 +144,6 @@ jobs:
- name: Check
run: cargo check --target wasm32-unknown-unknown --features use-esplora-reqwest --no-default-features


fmt:
name: Rust fmt
runs-on: ubuntu-latest
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"

[dependencies]
bdk-macros = "0.5"
bdk-macros = { path = "macros"} # TODO: Change this to version number after next release.
log = "^0.4"
miniscript = "^6.0"
bitcoin = { version = "^0.27", features = ["use-serde", "base64"] }
Expand All@@ -38,6 +38,10 @@ bitcoinconsensus = { version = "0.19.0-3", optional = true }
# Needed by bdk_blockchain_tests macro
core-rpc = { version = "0.14", optional = true }

# Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please correct me if I'm wrong, but this PR re-introduces a hard dependency on tokio just so we can test esplora-reqwest feature, that seems like a bad choice to me. A user of bdk that wishes to use reqwest will always be using async, why do we want to introduce a hard dependency on tokio just to be able to test in a manner that the library will not be used?

The esplora-reqwest feature can be tested coupled with either async-interface feature or using WASM target.


[target.'cfg(target_arch = "wasm32")'.dependencies]
async-trait = "0.1"
js-sys = "0.3"
Expand DownExpand Up@@ -70,7 +74,7 @@ rpc = ["core-rpc"]
async-interface = ["async-trait"]
electrum = ["electrum-client"]
# MUST ALSO USE `--no-default-features`.
use-esplora-reqwest = ["async-interface", "esplora", "reqwest", "futures"]
use-esplora-reqwest = ["esplora", "reqwest", "futures"]
use-esplora-ureq = ["esplora", "ureq"]
# Typical configurations will not need to use `esplora` feature directly.
esplora = []
Expand All@@ -80,7 +84,7 @@ esplora = []
test-blockchains = ["core-rpc", "electrum-client"]
test-electrum = ["electrum", "electrsd/electrs_0_8_10", "test-blockchains"]
test-rpc = ["rpc", "electrsd/electrs_0_8_10", "test-blockchains"]
test-esplora = ["esplora", "ureq", "electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-esplora = ["electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-md-docs = ["electrum"]

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions macros/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,3 +121,26 @@ pub fn maybe_await(expr: TokenStream) -> TokenStream {

quoted.into()
}

/// Awaits if target_arch is "wasm32", uses `tokio::Runtime::block_on()` otherwise
///
/// Requires the `tokio` crate as a dependecy with `rt-core` or `rt-threaded` to build on non-wasm32 platforms.
#[proc_macro]
pub fn await_or_block(expr: TokenStream) -> TokenStream {
let expr: proc_macro2::TokenStream = expr.into();
let quoted = quote! {
{
#[cfg(all(not(target_arch = "wasm32"), not(feature = "async-interface")))]
{
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(#expr)
}

#[cfg(any(target_arch = "wasm32", feature = "async-interface"))]
{
#expr.await
}
}
};

quoted.into()
}
38 changes: 12 additions & 26 deletions src/blockchain/esplora/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,38 +29,16 @@ use bitcoin::{BlockHash, Txid};
use crate::error::Error;
use crate::FeeRate;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
mod reqwest;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
pub use self::reqwest::*;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
mod ureq;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
pub use self::ureq::*;

fn into_fee_rate(target: usize, estimates: HashMap<String, f64>) -> Result<FeeRate, Error> {
Expand DownExpand Up@@ -141,3 +119,11 @@ impl_error!(io::Error, Io, EsploraError);
impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), 20)
}
}
28 changes: 10 additions & 18 deletions src/blockchain/esplora/reqwest.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,19 +106,19 @@ impl Blockchain for EsploraBlockchain {
}

fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
Ok(self.url_client._get_tx(txid).await?)
Ok(await_or_block!(self.url_client._get_tx(txid))?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I do not like this usage of await_or_block because there is no reason to use reqwest in a blocking environment, we have ureq for that.

}

fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
Ok(self.url_client._broadcast(tx).await?)
Ok(await_or_block!(self.url_client._broadcast(tx))?)
}

fn get_height(&self) -> Result<u32, Error> {
Ok(self.url_client._get_height().await?)
Ok(await_or_block!(self.url_client._get_height())?)
}

fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
let estimates = self.url_client._get_fee_estimates().await?;
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
super::into_fee_rate(target, estimates)
}
}
Expand DownExpand Up@@ -287,10 +287,10 @@ impl ElectrumLikeSync for UrlClient {
for script in chunk {
futs.push(self._script_get_history(script));
}
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
let partial_results: Vec<Vec<ElsGetHistoryRes>> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
Expand All@@ -303,10 +303,10 @@ impl ElectrumLikeSync for UrlClient {
for txid in chunk {
futs.push(self._get_tx_no_opt(txid));
}
let partial_results: Vec<Transaction> = futs.try_collect().await?;
let partial_results: Vec<Transaction> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_block_header<I: IntoIterator<Item = u32>>(
Expand All@@ -319,10 +319,10 @@ impl ElectrumLikeSync for UrlClient {
for height in chunk {
futs.push(self._get_header(height));
}
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
let partial_results: Vec<BlockHeader> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}
}

Expand DownExpand Up@@ -350,11 +350,3 @@ impl ConfigurableBlockchain for EsploraBlockchain {
Ok(blockchain)
}
}

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
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
12 changes: 8 additions & 4 deletions .github/workflows/cont_integration.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,15 +78,20 @@ jobs:
run: cargo test --features test-md-docs --no-default-features -- doctest::ReadmeDoctests

test-blockchains:
name: Test ${{ matrix.blockchain.name }}
name: Blockchain ${{ matrix.blockchain.features }}
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
blockchain:
- name: electrum
features: test-electrum
- name: rpc
features: test-rpc
- name: esplora
features: test-esplora,use-esplora-reqwest
- name: esplora
features: test-esplora,use-esplora-ureq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

steps:
- name: Checkout
uses: actions/checkout@v2
Expand All@@ -104,8 +109,8 @@ jobs:
toolchain: stable
override: true
- name: Test
run: cargo test --features test-${{ matrix.blockchain.name }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

run: cargo test --no-default-features --features ${{ matrix.blockchain.features }} ${{ matrix.blockchain.name }}::bdk_blockchain_tests

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line has trailing whitespace.

check-wasm:
name: Check WASM
runs-on: ubuntu-16.04
Expand DownExpand Up@@ -139,7 +144,6 @@ jobs:
- name: Check
run: cargo check --target wasm32-unknown-unknown --features use-esplora-reqwest --no-default-features


fmt:
name: Rust fmt
runs-on: ubuntu-latest
Expand Down
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ readme = "README.md"
license = "MIT OR Apache-2.0"

[dependencies]
bdk-macros = "0.5"
bdk-macros = { path = "macros"} # TODO: Change this to version number after next release.
log = "^0.4"
miniscript = "^6.0"
bitcoin = { version = "^0.27", features = ["use-serde", "base64"] }
Expand All@@ -38,6 +38,10 @@ bitcoinconsensus = { version = "0.19.0-3", optional = true }
# Needed by bdk_blockchain_tests macro
core-rpc = { version = "0.14", optional = true }

# Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please correct me if I'm wrong, but this PR re-introduces a hard dependency on tokio just so we can test esplora-reqwest feature, that seems like a bad choice to me. A user of bdk that wishes to use reqwest will always be using async, why do we want to introduce a hard dependency on tokio just to be able to test in a manner that the library will not be used?

The esplora-reqwest feature can be tested coupled with either async-interface feature or using WASM target.


[target.'cfg(target_arch = "wasm32")'.dependencies]
async-trait = "0.1"
js-sys = "0.3"
Expand DownExpand Up@@ -70,7 +74,7 @@ rpc = ["core-rpc"]
async-interface = ["async-trait"]
electrum = ["electrum-client"]
# MUST ALSO USE `--no-default-features`.
use-esplora-reqwest = ["async-interface", "esplora", "reqwest", "futures"]
use-esplora-reqwest = ["esplora", "reqwest", "futures"]
use-esplora-ureq = ["esplora", "ureq"]
# Typical configurations will not need to use `esplora` feature directly.
esplora = []
Expand All@@ -80,7 +84,7 @@ esplora = []
test-blockchains = ["core-rpc", "electrum-client"]
test-electrum = ["electrum", "electrsd/electrs_0_8_10", "test-blockchains"]
test-rpc = ["rpc", "electrsd/electrs_0_8_10", "test-blockchains"]
test-esplora = ["esplora", "ureq", "electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-esplora = ["electrsd/legacy", "electrsd/esplora_a33e97e1", "test-blockchains"]
test-md-docs = ["electrum"]

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions macros/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,3 +121,26 @@ pub fn maybe_await(expr: TokenStream) -> TokenStream {

quoted.into()
}

/// Awaits if target_arch is "wasm32", uses `tokio::Runtime::block_on()` otherwise
///
/// Requires the `tokio` crate as a dependecy with `rt-core` or `rt-threaded` to build on non-wasm32 platforms.
#[proc_macro]
pub fn await_or_block(expr: TokenStream) -> TokenStream {
let expr: proc_macro2::TokenStream = expr.into();
let quoted = quote! {
{
#[cfg(all(not(target_arch = "wasm32"), not(feature = "async-interface")))]
{
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(#expr)
}

#[cfg(any(target_arch = "wasm32", feature = "async-interface"))]
{
#expr.await
}
}
};

quoted.into()
}
38 changes: 12 additions & 26 deletions src/blockchain/esplora/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,38 +29,16 @@ use bitcoin::{BlockHash, Txid};
use crate::error::Error;
use crate::FeeRate;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
mod reqwest;

#[cfg(all(
feature = "esplora",
feature = "reqwest",
any(feature = "async-interface", target_arch = "wasm32"),
))]
#[cfg(feature = "reqwest")]
pub use self::reqwest::*;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
mod ureq;

#[cfg(all(
feature = "esplora",
not(any(
feature = "async-interface",
feature = "reqwest",
target_arch = "wasm32"
)),
))]
#[cfg(feature = "ureq")]
pub use self::ureq::*;

fn into_fee_rate(target: usize, estimates: HashMap<String, f64>) -> Result<FeeRate, Error> {
Expand DownExpand Up@@ -141,3 +119,11 @@ impl_error!(io::Error, Io, EsploraError);
impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), 20)
}
}
28 changes: 10 additions & 18 deletions src/blockchain/esplora/reqwest.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,19 +106,19 @@ impl Blockchain for EsploraBlockchain {
}

fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
Ok(self.url_client._get_tx(txid).await?)
Ok(await_or_block!(self.url_client._get_tx(txid))?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I do not like this usage of await_or_block because there is no reason to use reqwest in a blocking environment, we have ureq for that.

}

fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
Ok(self.url_client._broadcast(tx).await?)
Ok(await_or_block!(self.url_client._broadcast(tx))?)
}

fn get_height(&self) -> Result<u32, Error> {
Ok(self.url_client._get_height().await?)
Ok(await_or_block!(self.url_client._get_height())?)
}

fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
let estimates = self.url_client._get_fee_estimates().await?;
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
super::into_fee_rate(target, estimates)
}
}
Expand DownExpand Up@@ -287,10 +287,10 @@ impl ElectrumLikeSync for UrlClient {
for script in chunk {
futs.push(self._script_get_history(script));
}
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
let partial_results: Vec<Vec<ElsGetHistoryRes>> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
Expand All@@ -303,10 +303,10 @@ impl ElectrumLikeSync for UrlClient {
for txid in chunk {
futs.push(self._get_tx_no_opt(txid));
}
let partial_results: Vec<Transaction> = futs.try_collect().await?;
let partial_results: Vec<Transaction> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}

fn els_batch_block_header<I: IntoIterator<Item = u32>>(
Expand All@@ -319,10 +319,10 @@ impl ElectrumLikeSync for UrlClient {
for height in chunk {
futs.push(self._get_header(height));
}
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
let partial_results: Vec<BlockHeader> = await_or_block!(futs.try_collect())?;
results.extend(partial_results);
}
Ok(stream::iter(results).collect().await)
Ok(await_or_block!(stream::iter(results).collect()))
}
}

Expand DownExpand Up@@ -350,11 +350,3 @@ impl ConfigurableBlockchain for EsploraBlockchain {
Ok(blockchain)
}
}

#[cfg(test)]
#[cfg(feature = "test-esplora")]
crate::bdk_blockchain_tests! {
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
}
}