bdk_wallet/wallet/
export.rs

1// Bitcoin Dev Kit
2// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
3//
4// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
5//
6// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
7// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
9// You may not use this file except in accordance with one or both of these
10// licenses.
11
12//! Wallet export
13//!
14//! This modules implements the wallet export format used by [FullyNoded](https://github.com/Fonta1n3/FullyNoded/blob/10b7808c8b929b171cca537fb50522d015168ac9/Docs/Wallets/Wallet-Export-Spec.md).
15//!
16//! ## Examples
17//!
18//! ### Import from JSON
19//!
20//! ```
21//! # use std::str::FromStr;
22//! # use bitcoin::*;
23//! # use bdk_wallet::export::*;
24//! # use bdk_wallet::*;
25//! let import = r#"{
26//!     "descriptor": "wpkh([c258d2e4\/84h\/1h\/0h]tpubDD3ynpHgJQW8VvWRzQ5WFDCrs4jqVFGHB3vLC3r49XHJSqP8bHKdK4AriuUKLccK68zfzowx7YhmDN8SiSkgCDENUFx9qVw65YyqM78vyVe\/0\/*)",
27//!     "blockheight":1782088,
28//!     "label":"testnet"
29//! }"#;
30//!
31//! let import = FullyNodedExport::from_str(import)?;
32//! let wallet = Wallet::create(
33//!     import.descriptor(),
34//!     import.change_descriptor().expect("change descriptor"),
35//! )
36//! .network(Network::Testnet)
37//! .create_wallet_no_persist()?;
38//! # Ok::<_, Box<dyn std::error::Error>>(())
39//! ```
40//!
41//! ### Export a `Wallet`
42//! ```
43//! # use bitcoin::*;
44//! # use bdk_wallet::export::*;
45//! # use bdk_wallet::*;
46//! let wallet = Wallet::create(
47//!     "wpkh([c258d2e4/84h/1h/0h]tpubDD3ynpHgJQW8VvWRzQ5WFDCrs4jqVFGHB3vLC3r49XHJSqP8bHKdK4AriuUKLccK68zfzowx7YhmDN8SiSkgCDENUFx9qVw65YyqM78vyVe/0/*)",
48//!     "wpkh([c258d2e4/84h/1h/0h]tpubDD3ynpHgJQW8VvWRzQ5WFDCrs4jqVFGHB3vLC3r49XHJSqP8bHKdK4AriuUKLccK68zfzowx7YhmDN8SiSkgCDENUFx9qVw65YyqM78vyVe/1/*)",
49//! )
50//! .network(Network::Testnet)
51//! .create_wallet_no_persist()?;
52//! let export = FullyNodedExport::export_wallet(&wallet, "exported wallet", true).unwrap();
53//!
54//! println!("Exported: {}", export.to_string());
55//! # Ok::<_, Box<dyn std::error::Error>>(())
56//! ```
57
58use alloc::string::String;
59use core::fmt;
60use core::str::FromStr;
61use serde::{Deserialize, Serialize};
62
63use miniscript::descriptor::{ShInner, WshInner};
64use miniscript::{Descriptor, ScriptContext, Terminal};
65
66use crate::types::KeychainKind;
67use crate::wallet::Wallet;
68
69/// Alias for [`FullyNodedExport`]
70#[deprecated(since = "0.18.0", note = "Please use [`FullyNodedExport`] instead")]
71pub type WalletExport = FullyNodedExport;
72
73/// Structure that contains the export of a wallet
74///
75/// For a usage example see [this module](crate::wallet::export)'s documentation.
76#[derive(Debug, Serialize, Deserialize)]
77pub struct FullyNodedExport {
78    descriptor: String,
79    /// Earliest block to rescan when looking for the wallet's transactions
80    pub blockheight: u32,
81    /// Arbitrary label for the wallet
82    pub label: String,
83}
84
85impl fmt::Display for FullyNodedExport {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(f, "{}", serde_json::to_string(self).unwrap())
88    }
89}
90
91impl FromStr for FullyNodedExport {
92    type Err = serde_json::Error;
93
94    fn from_str(s: &str) -> Result<Self, Self::Err> {
95        serde_json::from_str(s)
96    }
97}
98
99fn remove_checksum(s: String) -> String {
100    s.split_once('#').map(|(a, _)| String::from(a)).unwrap()
101}
102
103impl FullyNodedExport {
104    /// Export a wallet
105    ///
106    /// This function returns an error if it determines that the `wallet`'s descriptor(s) are not
107    /// supported by Bitcoin Core or don't follow the standard derivation paths defined by BIP44
108    /// and others.
109    ///
110    /// If `include_blockheight` is `true`, this function will look into the `wallet`'s database
111    /// for the oldest transaction it knows and use that as the earliest block to rescan.
112    ///
113    /// If the database is empty or `include_blockheight` is false, the `blockheight` field
114    /// returned will be `0`.
115    pub fn export_wallet(
116        wallet: &Wallet,
117        label: &str,
118        include_blockheight: bool,
119    ) -> Result<Self, &'static str> {
120        let descriptor = wallet
121            .public_descriptor(KeychainKind::External)
122            .to_string_with_secret(
123                &wallet
124                    .get_signers(KeychainKind::External)
125                    .as_key_map(wallet.secp_ctx()),
126            );
127        let descriptor = remove_checksum(descriptor);
128        Self::is_compatible_with_core(&descriptor)?;
129
130        let blockheight = if include_blockheight {
131            wallet.transactions().next().map_or(0, |canonical_tx| {
132                canonical_tx
133                    .chain_position
134                    .confirmation_height_upper_bound()
135                    .unwrap_or(0)
136            })
137        } else {
138            0
139        };
140
141        let export = FullyNodedExport {
142            descriptor,
143            label: label.into(),
144            blockheight,
145        };
146
147        let change_descriptor = {
148            let descriptor = wallet
149                .public_descriptor(KeychainKind::Internal)
150                .to_string_with_secret(
151                    &wallet
152                        .get_signers(KeychainKind::Internal)
153                        .as_key_map(wallet.secp_ctx()),
154                );
155            Some(remove_checksum(descriptor))
156        };
157
158        if export.change_descriptor() != change_descriptor {
159            return Err("Incompatible change descriptor");
160        }
161
162        Ok(export)
163    }
164
165    fn is_compatible_with_core(descriptor: &str) -> Result<(), &'static str> {
166        fn check_ms<Ctx: ScriptContext>(
167            terminal: &Terminal<String, Ctx>,
168        ) -> Result<(), &'static str> {
169            if let Terminal::Multi(_) = terminal {
170                Ok(())
171            } else {
172                Err("The descriptor contains operators not supported by Bitcoin Core")
173            }
174        }
175
176        // pkh(), wpkh(), sh(wpkh()) are always fine, as well as multi() and sortedmulti()
177        match Descriptor::<String>::from_str(descriptor).map_err(|_| "Invalid descriptor")? {
178            Descriptor::Pkh(_) | Descriptor::Wpkh(_) => Ok(()),
179            Descriptor::Sh(sh) => match sh.as_inner() {
180                ShInner::Wpkh(_) => Ok(()),
181                ShInner::SortedMulti(_) => Ok(()),
182                ShInner::Wsh(wsh) => match wsh.as_inner() {
183                    WshInner::SortedMulti(_) => Ok(()),
184                    WshInner::Ms(ms) => check_ms(&ms.node),
185                },
186                ShInner::Ms(ms) => check_ms(&ms.node),
187            },
188            Descriptor::Wsh(wsh) => match wsh.as_inner() {
189                WshInner::SortedMulti(_) => Ok(()),
190                WshInner::Ms(ms) => check_ms(&ms.node),
191            },
192            Descriptor::Tr(_) => Ok(()),
193            _ => Err("The descriptor is not compatible with Bitcoin Core"),
194        }
195    }
196
197    /// Return the external descriptor
198    pub fn descriptor(&self) -> String {
199        self.descriptor.clone()
200    }
201
202    /// Return the internal descriptor, if present
203    pub fn change_descriptor(&self) -> Option<String> {
204        let replaced = self.descriptor.replace("/0/*", "/1/*");
205
206        if replaced != self.descriptor {
207            Some(replaced)
208        } else {
209            None
210        }
211    }
212}
213
214#[cfg(test)]
215mod test {
216    use alloc::string::ToString;
217    use bitcoin::Amount;
218    use core::str::FromStr;
219
220    use bdk_chain::BlockId;
221    use bitcoin::{hashes::Hash, BlockHash, Network};
222
223    use super::*;
224    use crate::test_utils::*;
225    use crate::Wallet;
226
227    fn get_test_wallet(descriptor: &str, change_descriptor: &str, network: Network) -> Wallet {
228        let mut wallet = Wallet::create(descriptor.to_string(), change_descriptor.to_string())
229            .network(network)
230            .create_wallet_no_persist()
231            .expect("must create wallet");
232        let block = BlockId {
233            height: 5000,
234            hash: BlockHash::all_zeros(),
235        };
236        insert_checkpoint(&mut wallet, block);
237        receive_output_in_latest_block(&mut wallet, Amount::from_sat(10_000));
238
239        wallet
240    }
241
242    #[test]
243    fn test_export_bip44() {
244        let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
245        let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/1/*)";
246
247        let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin);
248        let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
249
250        assert_eq!(export.descriptor(), descriptor);
251        assert_eq!(export.change_descriptor(), Some(change_descriptor.into()));
252        assert_eq!(export.blockheight, 5000);
253        assert_eq!(export.label, "Test Label");
254    }
255
256    #[test]
257    #[should_panic(expected = "Incompatible change descriptor")]
258    fn test_export_no_change() {
259        // The wallet's change descriptor has no wildcard. It should be impossible to
260        // export, because exporting this kind of external descriptor normally implies the
261        // existence of a compatible internal descriptor
262
263        let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
264        let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/1/0)";
265
266        let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin);
267        FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
268    }
269
270    #[test]
271    #[should_panic(expected = "Incompatible change descriptor")]
272    fn test_export_incompatible_change() {
273        // This wallet has a change descriptor, but the derivation path is not in the "standard"
274        // bip44/49/etc format
275
276        let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
277        let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/50'/0'/1/*)";
278
279        let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin);
280        FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
281    }
282
283    #[test]
284    fn test_export_multi() {
285        let descriptor = "wsh(multi(2,\
286                                [73756c7f/48'/0'/0'/2']tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3/0/*,\
287                                [f9f62194/48'/0'/0'/2']tpubDDp3ZSH1yCwusRppH7zgSxq2t1VEUyXSeEp8E5aFS8m43MknUjiF1bSLo3CGWAxbDyhF1XowA5ukPzyJZjznYk3kYi6oe7QxtX2euvKWsk4/0/*,\
288                                [c98b1535/48'/0'/0'/2']tpubDCDi5W4sP6zSnzJeowy8rQDVhBdRARaPhK1axABi8V1661wEPeanpEXj4ZLAUEoikVtoWcyK26TKKJSecSfeKxwHCcRrge9k1ybuiL71z4a/0/*\
289                          ))";
290        let change_descriptor = "wsh(multi(2,\
291                                       [73756c7f/48'/0'/0'/2']tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3/1/*,\
292                                       [f9f62194/48'/0'/0'/2']tpubDDp3ZSH1yCwusRppH7zgSxq2t1VEUyXSeEp8E5aFS8m43MknUjiF1bSLo3CGWAxbDyhF1XowA5ukPzyJZjznYk3kYi6oe7QxtX2euvKWsk4/1/*,\
293                                       [c98b1535/48'/0'/0'/2']tpubDCDi5W4sP6zSnzJeowy8rQDVhBdRARaPhK1axABi8V1661wEPeanpEXj4ZLAUEoikVtoWcyK26TKKJSecSfeKxwHCcRrge9k1ybuiL71z4a/1/*\
294                                 ))";
295
296        let wallet = get_test_wallet(descriptor, change_descriptor, Network::Testnet);
297        let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
298
299        assert_eq!(export.descriptor(), descriptor);
300        assert_eq!(export.change_descriptor(), Some(change_descriptor.into()));
301        assert_eq!(export.blockheight, 5000);
302        assert_eq!(export.label, "Test Label");
303    }
304
305    #[test]
306    fn test_export_tr() {
307        let descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/0/*)";
308        let change_descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/1/*)";
309        let wallet = get_test_wallet(descriptor, change_descriptor, Network::Testnet);
310        let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
311        assert_eq!(export.descriptor(), descriptor);
312        assert_eq!(export.change_descriptor(), Some(change_descriptor.into()));
313        assert_eq!(export.blockheight, 5000);
314        assert_eq!(export.label, "Test Label");
315    }
316
317    #[test]
318    fn test_export_to_json() {
319        let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
320        let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/1/*)";
321
322        let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin);
323        let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
324
325        assert_eq!(export.to_string(), "{\"descriptor\":\"wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44\'/0\'/0\'/0/*)\",\"blockheight\":5000,\"label\":\"Test Label\"}");
326    }
327
328    #[test]
329    fn test_export_from_json() {
330        let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
331        let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/1/*)";
332
333        let import_str = "{\"descriptor\":\"wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44\'/0\'/0\'/0/*)\",\"blockheight\":5000,\"label\":\"Test Label\"}";
334        let export = FullyNodedExport::from_str(import_str).unwrap();
335
336        assert_eq!(export.descriptor(), descriptor);
337        assert_eq!(export.change_descriptor(), Some(change_descriptor.into()));
338        assert_eq!(export.blockheight, 5000);
339        assert_eq!(export.label, "Test Label");
340    }
341}