From: w0xlt <94266259+w0xlt@users.noreply.github.com> Date: Fri, 24 Dec 2021 23:02:40 +0000 (-0300) Subject: Add descriptor code sample X-Git-Url: http://internal-gitweb-vhost/script/%22https:/database/scripts/enum.AddressValidatorError.html?a=commitdiff_plain;h=734a74cd1f6cb0a513b109bbe4d0dd4b363f9917;p=bitcoindevkit.org Add descriptor code sample --- diff --git a/docs/getting-started.md b/docs/getting-started.md index cdcf953251..fb46b73b7b 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -29,3 +29,53 @@ The author of this project strongly believes descriptors will be a big part of t technology and tooling of Bitcoin evolves and changes (Schnorr signatures, Taproot, etc). To learn more, check out the specific [Descriptors section](/descriptors). + +The following code shows how to generate a random mnemonic, the extended (and deterministic) keys from that mnemonic and finally the descriptors from the extended private keys. + +To be able to run this code, the `bdk` dependency in `Cargo.toml` must be set as follows: + +``` +[dependencies] +bdk = { version = "0.15.0", default-feature = false, features = ["all-keys"] } +``` + +```rust +use bdk::bitcoin::Network; +use bdk::database::MemoryDatabase; +use bdk::keys::{DerivableKey, GeneratableKey, GeneratedKey, ExtendedKey, bip39::{Mnemonic, WordCount, Language}}; +use bdk::template::Bip84; +use bdk::{miniscript, Wallet, KeychainKind}; + +fn main() { + println!("Hello, world!"); + + let network = Network::Testnet; // Or this can be Network::Bitcoin, Network::Signet or Network::Regtest + + // Generate fresh mnemonic + let mnemonic: GeneratedKey<_, miniscript::Segwitv0> = Mnemonic::generate((WordCount::Words12, Language::English)).unwrap(); + // Convert mnemonic to string + let mnemonic_words = mnemonic.to_string(); + // Parse a mnemonic + let mnemonic = Mnemonic::parse(&mnemonic_words).unwrap(); + // Generate the extended key + let xkey: ExtendedKey = mnemonic.into_extended_key().unwrap(); + // Get xprv from the extended key + let xprv = xkey.into_xprv(network).unwrap(); + + // Create a BDK wallet structure using BIP 84 descriptor ("m/84h/1h/0h/0" and "m/84h/1h/0h/1") + let wallet = Wallet::new_offline( + Bip84(xprv, KeychainKind::External), + Some(Bip84(xprv, KeychainKind::Internal)), + network, + MemoryDatabase::default(), + ) + .unwrap(); + + println!("mnemonic: {}\n\nrecv desc (pub key): {:#?}\n\nchng desc (pub key): {:#?}", + mnemonic_words, + wallet.get_descriptor_for_keychain(KeychainKind::External).to_string(), + wallet.get_descriptor_for_keychain(KeychainKind::Internal).to_string()); +} +``` + +More information about each component used in the code can be found in [BDK Documentation](https://docs.rs/bdk/0.15.0/bdk/index.html). \ No newline at end of file