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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// 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 database types
//!
//! This module provides the implementation of [`AnyDatabase`] which allows switching the
//! inner [`Database`] type at runtime.
//!
//! ## Example
//!
//! In this example, `wallet_memory` and `wallet_sled` have the same type of `Wallet<(), AnyDatabase>`.
//!
//! ```no_run
//! # use bitcoin::Network;
//! # use bdk::database::{AnyDatabase, MemoryDatabase};
//! # use bdk::{Wallet};
//! let memory = MemoryDatabase::default();
//! let wallet_memory = Wallet::new_offline("...", None, Network::Testnet, memory)?;
//!
//! # #[cfg(feature = "key-value-db")]
//! # {
//! let sled = sled::open("my-database")?.open_tree("default_tree")?;
//! let wallet_sled = Wallet::new_offline("...", None, Network::Testnet, sled)?;
//! # }
//! # Ok::<(), bdk::Error>(())
//! ```
//!
//! When paired with the use of [`ConfigurableDatabase`], it allows creating wallets with any
//! database supported using a single line of code:
//!
//! ```no_run
//! # use bitcoin::Network;
//! # use bdk::database::*;
//! # use bdk::{Wallet};
//! let config = serde_json::from_str("...")?;
//! let database = AnyDatabase::from_config(&config)?;
//! let wallet = Wallet::new_offline("...", None, Network::Testnet, database)?;
//! # 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 {
    ( $enum_name:ident, $self:expr, $name:ident $(, $args:expr)* ) => {
        match $self {
            $enum_name::Memory(inner) => inner.$name( $($args, )* ),
            #[cfg(feature = "key-value-db")]
            $enum_name::Sled(inner) => inner.$name( $($args, )* ),
        }
    }
}

/// Type that can contain any of the [`Database`] types defined by the library
///
/// It allows switching database type at runtime.
///
/// See [this module](crate::database::any)'s documentation for a usage example.
#[derive(Debug)]
pub enum AnyDatabase {
    /// In-memory ephemeral database
    Memory(memory::MemoryDatabase),
    #[cfg(feature = "key-value-db")]
    #[cfg_attr(docsrs, doc(cfg(feature = "key-value-db")))]
    /// Simple key-value embedded database based on [`sled`]
    Sled(sled::Tree),
}

impl_from!(memory::MemoryDatabase, AnyDatabase, Memory,);
impl_from!(sled::Tree, AnyDatabase, Sled, #[cfg(feature = "key-value-db")]);

/// Type that contains any of the [`BatchDatabase::Batch`] types defined by the library
pub enum AnyBatch {
    /// In-memory ephemeral database
    Memory(<memory::MemoryDatabase as BatchDatabase>::Batch),
    #[cfg(feature = "key-value-db")]
    #[cfg_attr(docsrs, doc(cfg(feature = "key-value-db")))]
    /// Simple key-value embedded database based on [`sled`]
    Sled(<sled::Tree as BatchDatabase>::Batch),
}

impl_from!(
    <memory::MemoryDatabase as BatchDatabase>::Batch,
    AnyBatch,
    Memory,
);
impl_from!(<sled::Tree as BatchDatabase>::Batch, AnyBatch, Sled, #[cfg(feature = "key-value-db")]);

impl BatchOperations for AnyDatabase {
    fn set_script_pubkey(
        &mut self,
        script: &Script,
        keychain: KeychainKind,
        child: u32,
    ) -> Result<(), Error> {
        impl_inner_method!(
            AnyDatabase,
            self,
            set_script_pubkey,
            script,
            keychain,
            child
        )
    }
    fn set_utxo(&mut self, utxo: &LocalUtxo) -> Result<(), Error> {
        impl_inner_method!(AnyDatabase, self, set_utxo, utxo)
    }
    fn set_raw_tx(&mut self, transaction: &Transaction) -> Result<(), Error> {
        impl_inner_method!(AnyDatabase, self, set_raw_tx, transaction)
    }
    fn set_tx(&mut self, transaction: &TransactionDetails) -> Result<(), Error> {
        impl_inner_method!(AnyDatabase, self, set_tx, transaction)
    }
    fn set_last_index(&mut self, keychain: KeychainKind, value: u32) -> Result<(), Error> {
        impl_inner_method!(AnyDatabase, self, set_last_index, keychain, value)
    }

    fn del_script_pubkey_from_path(
        &mut self,
        keychain: KeychainKind,
        child: u32,
    ) -> Result<Option<Script>, Error> {
        impl_inner_method!(
            AnyDatabase,
            self,
            del_script_pubkey_from_path,
            keychain,
            child
        )
    }
    fn del_path_from_script_pubkey(
        &mut self,
        script: &Script,
    ) -> Result<Option<(KeychainKind, u32)>, Error> {
        impl_inner_method!(AnyDatabase, self, del_path_from_script_pubkey, script)
    }
    fn del_utxo(&mut self, outpoint: &OutPoint) -> Result<Option<LocalUtxo>, Error> {
        impl_inner_method!(AnyDatabase, self, del_utxo, outpoint)
    }
    fn del_raw_tx(&mut self, txid: &Txid) -> Result<Option<Transaction>, Error> {
        impl_inner_method!(AnyDatabase, self, del_raw_tx, txid)
    }
    fn del_tx(
        &mut self,
        txid: &Txid,
        include_raw: bool,
    ) -> Result<Option<TransactionDetails>, Error> {
        impl_inner_method!(AnyDatabase, self, del_tx, txid, include_raw)
    }
    fn del_last_index(&mut self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
        impl_inner_method!(AnyDatabase, self, del_last_index, keychain)
    }
}

impl Database for AnyDatabase {
    fn check_descriptor_checksum<B: AsRef<[u8]>>(
        &mut self,
        keychain: KeychainKind,
        bytes: B,
    ) -> Result<(), Error> {
        impl_inner_method!(
            AnyDatabase,
            self,
            check_descriptor_checksum,
            keychain,
            bytes
        )
    }

    fn iter_script_pubkeys(&self, keychain: Option<KeychainKind>) -> Result<Vec<Script>, Error> {
        impl_inner_method!(AnyDatabase, self, iter_script_pubkeys, keychain)
    }
    fn iter_utxos(&self) -> Result<Vec<LocalUtxo>, Error> {
        impl_inner_method!(AnyDatabase, self, iter_utxos)
    }
    fn iter_raw_txs(&self) -> Result<Vec<Transaction>, Error> {
        impl_inner_method!(AnyDatabase, self, iter_raw_txs)
    }
    fn iter_txs(&self, include_raw: bool) -> Result<Vec<TransactionDetails>, Error> {
        impl_inner_method!(AnyDatabase, self, iter_txs, include_raw)
    }

    fn get_script_pubkey_from_path(
        &self,
        keychain: KeychainKind,
        child: u32,
    ) -> Result<Option<Script>, Error> {
        impl_inner_method!(
            AnyDatabase,
            self,
            get_script_pubkey_from_path,
            keychain,
            child
        )
    }
    fn get_path_from_script_pubkey(
        &self,
        script: &Script,
    ) -> Result<Option<(KeychainKind, u32)>, Error> {
        impl_inner_method!(AnyDatabase, self, get_path_from_script_pubkey, script)
    }
    fn get_utxo(&self, outpoint: &OutPoint) -> Result<Option<LocalUtxo>, Error> {
        impl_inner_method!(AnyDatabase, self, get_utxo, outpoint)
    }
    fn get_raw_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
        impl_inner_method!(AnyDatabase, self, get_raw_tx, txid)
    }
    fn get_tx(&self, txid: &Txid, include_raw: bool) -> Result<Option<TransactionDetails>, Error> {
        impl_inner_method!(AnyDatabase, self, get_tx, txid, include_raw)
    }
    fn get_last_index(&self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
        impl_inner_method!(AnyDatabase, self, get_last_index, keychain)
    }

    fn increment_last_index(&mut self, keychain: KeychainKind) -> Result<u32, Error> {
        impl_inner_method!(AnyDatabase, self, increment_last_index, keychain)
    }
}

impl BatchOperations for AnyBatch {
    fn set_script_pubkey(
        &mut self,
        script: &Script,
        keychain: KeychainKind,
        child: u32,
    ) -> Result<(), Error> {
        impl_inner_method!(AnyBatch, self, set_script_pubkey, script, keychain, child)
    }
    fn set_utxo(&mut self, utxo: &LocalUtxo) -> Result<(), Error> {
        impl_inner_method!(AnyBatch, self, set_utxo, utxo)
    }
    fn set_raw_tx(&mut self, transaction: &Transaction) -> Result<(), Error> {
        impl_inner_method!(AnyBatch, self, set_raw_tx, transaction)
    }
    fn set_tx(&mut self, transaction: &TransactionDetails) -> Result<(), Error> {
        impl_inner_method!(AnyBatch, self, set_tx, transaction)
    }
    fn set_last_index(&mut self, keychain: KeychainKind, value: u32) -> Result<(), Error> {
        impl_inner_method!(AnyBatch, self, set_last_index, keychain, value)
    }

    fn del_script_pubkey_from_path(
        &mut self,
        keychain: KeychainKind,
        child: u32,
    ) -> Result<Option<Script>, Error> {
        impl_inner_method!(AnyBatch, self, del_script_pubkey_from_path, keychain, child)
    }
    fn del_path_from_script_pubkey(
        &mut self,
        script: &Script,
    ) -> Result<Option<(KeychainKind, u32)>, Error> {
        impl_inner_method!(AnyBatch, self, del_path_from_script_pubkey, script)
    }
    fn del_utxo(&mut self, outpoint: &OutPoint) -> Result<Option<LocalUtxo>, Error> {
        impl_inner_method!(AnyBatch, self, del_utxo, outpoint)
    }
    fn del_raw_tx(&mut self, txid: &Txid) -> Result<Option<Transaction>, Error> {
        impl_inner_method!(AnyBatch, self, del_raw_tx, txid)
    }
    fn del_tx(
        &mut self,
        txid: &Txid,
        include_raw: bool,
    ) -> Result<Option<TransactionDetails>, Error> {
        impl_inner_method!(AnyBatch, self, del_tx, txid, include_raw)
    }
    fn del_last_index(&mut self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
        impl_inner_method!(AnyBatch, self, del_last_index, keychain)
    }
}

impl BatchDatabase for AnyDatabase {
    type Batch = AnyBatch;

    fn begin_batch(&self) -> Self::Batch {
        match self {
            AnyDatabase::Memory(inner) => inner.begin_batch().into(),
            #[cfg(feature = "key-value-db")]
            AnyDatabase::Sled(inner) => inner.begin_batch().into(),
        }
    }
    fn commit_batch(&mut self, batch: Self::Batch) -> Result<(), Error> {
        match self {
            AnyDatabase::Memory(db) => match batch {
                AnyBatch::Memory(batch) => db.commit_batch(batch),
                #[cfg(feature = "key-value-db")]
                _ => unimplemented!("Sled batch shouldn't be used with Memory db."),
            },
            #[cfg(feature = "key-value-db")]
            AnyDatabase::Sled(db) => match batch {
                AnyBatch::Sled(batch) => db.commit_batch(batch),
                _ => unimplemented!("Memory batch shouldn't be used with Sled db."),
            },
        }
    }
}

/// Configuration type for a [`sled::Tree`] database
#[cfg(feature = "key-value-db")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct SledDbConfiguration {
    /// Main directory of the db
    pub path: String,
    /// Name of the database tree, a separated namespace for the data
    pub tree_name: String,
}

#[cfg(feature = "key-value-db")]
impl ConfigurableDatabase for sled::Tree {
    type Config = SledDbConfiguration;

    fn from_config(config: &Self::Config) -> Result<Self, Error> {
        Ok(sled::open(&config.path)?.open_tree(&config.tree_name)?)
    }
}

/// Type that can contain any of the database configurations defined by the library
///
/// This allows storing a single configuration that can be loaded into an [`AnyDatabase`]
/// 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 AnyDatabaseConfig {
    /// Memory database has no config
    Memory(()),
    #[cfg(feature = "key-value-db")]
    #[cfg_attr(docsrs, doc(cfg(feature = "key-value-db")))]
    /// Simple key-value embedded database based on [`sled`]
    Sled(SledDbConfiguration),
}

impl ConfigurableDatabase for AnyDatabase {
    type Config = AnyDatabaseConfig;

    fn from_config(config: &Self::Config) -> Result<Self, Error> {
        Ok(match config {
            AnyDatabaseConfig::Memory(inner) => {
                AnyDatabase::Memory(memory::MemoryDatabase::from_config(inner)?)
            }
            #[cfg(feature = "key-value-db")]
            AnyDatabaseConfig::Sled(inner) => AnyDatabase::Sled(sled::Tree::from_config(inner)?),
        })
    }
}

impl_from!((), AnyDatabaseConfig, Memory,);
impl_from!(SledDbConfiguration, AnyDatabaseConfig, Sled, #[cfg(feature = "key-value-db")]);