1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

//! Runtime-checked blockchain types
//!
//! This module provides the implementation of [`AnyBlockchain`] which allows switching the
//! inner [`Blockchain`] type at runtime.
//!
//! ## Example
//!
//! In this example both `wallet_electrum` and `wallet_esplora` have the same type of
//! `Wallet<AnyBlockchain, MemoryDatabase>`. This means that they could both, for instance, be
//! assigned to a struct member.
//!
//! ```no_run
//! # use bitcoin::Network;
//! # use bdk::blockchain::*;
//! # use bdk::database::MemoryDatabase;
//! # use bdk::Wallet;
//! # #[cfg(feature = "electrum")]
//! # {
//! let electrum_blockchain = ElectrumBlockchain::from(electrum_client::Client::new("...")?);
//! let wallet_electrum: Wallet<AnyBlockchain, _> = Wallet::new(
//!     "...",
//!     None,
//!     Network::Testnet,
//!     MemoryDatabase::default(),
//!     electrum_blockchain.into(),
//! )?;
//! # }
//!
//! # #[cfg(feature = "esplora")]
//! # {
//! let esplora_blockchain = EsploraBlockchain::new("...", None);
//! let wallet_esplora: Wallet<AnyBlockchain, _> = Wallet::new(
//!     "...",
//!     None,
//!     Network::Testnet,
//!     MemoryDatabase::default(),
//!     esplora_blockchain.into(),
//! )?;
//! # }
//!
//! # Ok::<(), bdk::Error>(())
//! ```
//!
//! When paired with the use of [`ConfigurableBlockchain`], it allows creating wallets with any
//! blockchain type supported using a single line of code:
//!
//! ```no_run
//! # use bitcoin::Network;
//! # use bdk::blockchain::*;
//! # use bdk::database::MemoryDatabase;
//! # use bdk::Wallet;
//! let config = serde_json::from_str("...")?;
//! let blockchain = AnyBlockchain::from_config(&config)?;
//! let wallet = Wallet::new(
//!     "...",
//!     None,
//!     Network::Testnet,
//!     MemoryDatabase::default(),
//!     blockchain,
//! )?;
//! # Ok::<(), bdk::Error>(())
//! ```

use super::*;

macro_rules! impl_from {
    ( $from:ty, $to:ty, $variant:ident, $( $cfg:tt )* ) => {
        $( $cfg )*
        impl From<$from> for $to {
            fn from(inner: $from) -> Self {
                <$to>::$variant(inner)
            }
        }
    };
}

macro_rules! impl_inner_method {
    ( $self:expr, $name:ident $(, $args:expr)* ) => {
        match $self {
            #[cfg(feature = "electrum")]
            AnyBlockchain::Electrum(inner) => inner.$name( $($args, )* ),
            #[cfg(feature = "esplora")]
            AnyBlockchain::Esplora(inner) => inner.$name( $($args, )* ),
            #[cfg(feature = "compact_filters")]
            AnyBlockchain::CompactFilters(inner) => inner.$name( $($args, )* ),
        }
    }
}

/// Type that can contain any of the [`Blockchain`] types defined by the library
///
/// It allows switching backend at runtime
///
/// See [this module](crate::blockchain::any)'s documentation for a usage example.
pub enum AnyBlockchain {
    #[cfg(feature = "electrum")]
    #[cfg_attr(docsrs, doc(cfg(feature = "electrum")))]
    /// Electrum client
    Electrum(electrum::ElectrumBlockchain),
    #[cfg(feature = "esplora")]
    #[cfg_attr(docsrs, doc(cfg(feature = "esplora")))]
    /// Esplora client
    Esplora(esplora::EsploraBlockchain),
    #[cfg(feature = "compact_filters")]
    #[cfg_attr(docsrs, doc(cfg(feature = "compact_filters")))]
    /// Compact filters client
    CompactFilters(compact_filters::CompactFiltersBlockchain),
}

#[maybe_async]
impl Blockchain for AnyBlockchain {
    fn get_capabilities(&self) -> HashSet<Capability> {
        maybe_await!(impl_inner_method!(self, get_capabilities))
    }

    fn setup<D: BatchDatabase, P: 'static + Progress>(
        &self,
        stop_gap: Option<usize>,
        database: &mut D,
        progress_update: P,
    ) -> Result<(), Error> {
        maybe_await!(impl_inner_method!(
            self,
            setup,
            stop_gap,
            database,
            progress_update
        ))
    }
    fn sync<D: BatchDatabase, P: 'static + Progress>(
        &self,
        stop_gap: Option<usize>,
        database: &mut D,
        progress_update: P,
    ) -> Result<(), Error> {
        maybe_await!(impl_inner_method!(
            self,
            sync,
            stop_gap,
            database,
            progress_update
        ))
    }

    fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
        maybe_await!(impl_inner_method!(self, get_tx, txid))
    }
    fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
        maybe_await!(impl_inner_method!(self, broadcast, tx))
    }

    fn get_height(&self) -> Result<u32, Error> {
        maybe_await!(impl_inner_method!(self, get_height))
    }
    fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
        maybe_await!(impl_inner_method!(self, estimate_fee, target))
    }
}

impl_from!(electrum::ElectrumBlockchain, AnyBlockchain, Electrum, #[cfg(feature = "electrum")]);
impl_from!(esplora::EsploraBlockchain, AnyBlockchain, Esplora, #[cfg(feature = "esplora")]);
impl_from!(compact_filters::CompactFiltersBlockchain, AnyBlockchain, CompactFilters, #[cfg(feature = "compact_filters")]);

/// Type that can contain any of the blockchain configurations defined by the library
///
/// This allows storing a single configuration that can be loaded into an [`AnyBlockchain`]
/// instance. Wallets that plan to offer users the ability to switch blockchain backend at runtime
/// will find this particularly useful.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub enum AnyBlockchainConfig {
    #[cfg(feature = "electrum")]
    #[cfg_attr(docsrs, doc(cfg(feature = "electrum")))]
    /// Electrum client
    Electrum(electrum::ElectrumBlockchainConfig),
    #[cfg(feature = "esplora")]
    #[cfg_attr(docsrs, doc(cfg(feature = "esplora")))]
    /// Esplora client
    Esplora(esplora::EsploraBlockchainConfig),
    #[cfg(feature = "compact_filters")]
    #[cfg_attr(docsrs, doc(cfg(feature = "compact_filters")))]
    /// Compact filters client
    CompactFilters(compact_filters::CompactFiltersBlockchainConfig),
}

impl ConfigurableBlockchain for AnyBlockchain {
    type Config = AnyBlockchainConfig;

    fn from_config(config: &Self::Config) -> Result<Self, Error> {
        Ok(match config {
            #[cfg(feature = "electrum")]
            AnyBlockchainConfig::Electrum(inner) => {
                AnyBlockchain::Electrum(electrum::ElectrumBlockchain::from_config(inner)?)
            }
            #[cfg(feature = "esplora")]
            AnyBlockchainConfig::Esplora(inner) => {
                AnyBlockchain::Esplora(esplora::EsploraBlockchain::from_config(inner)?)
            }
            #[cfg(feature = "compact_filters")]
            AnyBlockchainConfig::CompactFilters(inner) => AnyBlockchain::CompactFilters(
                compact_filters::CompactFiltersBlockchain::from_config(inner)?,
            ),
        })
    }
}

impl_from!(electrum::ElectrumBlockchainConfig, AnyBlockchainConfig, Electrum, #[cfg(feature = "electrum")]);
impl_from!(esplora::EsploraBlockchainConfig, AnyBlockchainConfig, Esplora, #[cfg(feature = "esplora")]);
impl_from!(compact_filters::CompactFiltersBlockchainConfig, AnyBlockchainConfig, CompactFilters, #[cfg(feature = "compact_filters")]);