|
| 1 | +// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers |
| 2 | +// |
| 3 | +// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE |
| 4 | +// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 5 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. |
| 6 | +// You may not use this file except in accordance with one or both of these |
| 7 | +// licenses. |
| 8 | + |
| 9 | +use bdk::bitcoin::secp256k1::Secp256k1; |
| 10 | +use bdk::bitcoin::util::bip32::DerivationPath; |
| 11 | +use bdk::bitcoin::Network; |
| 12 | +use bdk::descriptor; |
| 13 | +use bdk::descriptor::IntoWalletDescriptor; |
| 14 | +use bdk::keys::bip39::{Language, Mnemonic, WordCount}; |
| 15 | +use bdk::keys::{GeneratableKey, GeneratedKey}; |
| 16 | +use bdk::miniscript::Tap; |
| 17 | +use bdk::Error as BDK_Error; |
| 18 | +use std::error::Error; |
| 19 | +use std::str::FromStr; |
| 20 | + |
| 21 | +/// This example demonstrates how to generate a mnemonic phrase |
| 22 | +/// using BDK and use that to generate a descriptor string. |
| 23 | +fn main() -> Result<(), Box<dyn Error>> { |
| 24 | + let secp = Secp256k1::new(); |
| 25 | + |
| 26 | + // In this example we are generating a 12 words mnemonic phrase |
| 27 | + // but it is also possible generate 15, 18, 21 and 24 words |
| 28 | + // using their respective `WordCount` variant. |
| 29 | + let mnemonic: GeneratedKey<_, Tap> = |
| 30 | + Mnemonic::generate((WordCount::Words12, Language::English)) |
| 31 | + .map_err(|_| BDK_Error::Generic("Mnemonic generation error".to_string()))?; |
| 32 | + |
| 33 | + println!("Mnemonic phrase: {}", mnemonic.to_string()); |
| 34 | + let mnemonic_with_passphrase = (mnemonic, None); |
| 35 | + |
| 36 | + // define external and internal derivation key path |
| 37 | + let external_path = DerivationPath::from_str("m/86h/0h/0h/0").unwrap(); |
| 38 | + let internal_path = DerivationPath::from_str("m/86h/0h/0h/1").unwrap(); |
| 39 | + |
| 40 | + // generate external and internal descriptor from mnemonic |
| 41 | + let (external_descriptor, ext_keymap) = |
| 42 | + descriptor!(tr((mnemonic_with_passphrase.clone(), external_path)))? |
| 43 | + .into_wallet_descriptor(&secp, Network::Testnet)?; |
| 44 | + let (internal_descriptor, int_keymap) = |
| 45 | + descriptor!(tr((mnemonic_with_passphrase, internal_path)))? |
| 46 | + .into_wallet_descriptor(&secp, Network::Testnet)?; |
| 47 | + |
| 48 | + println!("xpub external descriptor: {}", external_descriptor); |
| 49 | + println!("xpub internal descriptor: {}", internal_descriptor); |
| 50 | + println!( |
| 51 | + "xprv external descriptor: {}", |
| 52 | + external_descriptor.to_string_with_secret(&ext_keymap) |
| 53 | + ); |
| 54 | + println!( |
| 55 | + "xprv internal descriptor: {}", |
| 56 | + internal_descriptor.to_string_with_secret(&int_keymap) |
| 57 | + ); |
| 58 | + |
| 59 | + Ok(()) |
| 60 | +} |
0 commit comments