bitcoindevkit / bdk

A modern, lightweight, descriptor-based wallet library written in Rust!
Other
871 stars 312 forks source link

How would I get the Extended public key as a zpub for a given mnemonic? #973

Open spicefarer opened 1 year ago

spicefarer commented 1 year ago

Describe the enhancement
I've been looking into this for hours now and I can't figure out how to get the zpub for a given mnemonic. I'm using this website as a reference.

Here, the given mnemonic (elegant aerobic pony glare science valid tool power toast effort loud bomb) leads to this xpub:

xpub661MyMwAqRbcFnVHjPTLtR5ZHJkg3iHG4uymkHkTPWveNvLxxjjHyAM5RwPstw1rvC1wk2Ls7b38qp9rriGUSwHPwWZhyBf7HkKV9yekFtB

and this zpub (when selecting BIP84):

zpub6jftahH18ngZxNsXQ72bJbGZdF3ZvxGFu92DK5YE9XgQV7yRU44RDHfMUMK3tkKhjUFZEyXz2ukEcPNzJ76W3QebgBxZ91J5qCSmw5AgA1S

I can successfully get the xpub with bdk, but all my attempts at getting an xpub failed. This is my current code:

use std::str::FromStr;

use bdk::{
    bitcoin::secp256k1::Secp256k1,
    keys::{
        bip39::{Language, Mnemonic},
        DerivableKey, ExtendedKey,
    },
    miniscript::Legacy,
};
use bitcoin::{
    util::bip32::{DerivationPath, ExtendedPubKey},
    Network,
};

pub fn derive_zpub_from_mnemonic() -> Result<String, Box<dyn std::error::Error>> {
    let mnemonic_string = "test walk nut penalty hip pave soap entry language right filter choice";
    let mnemonic = Mnemonic::parse_in(Language::English, mnemonic_string)?;
    let network = Network::Bitcoin;
    let secp = Secp256k1::new();

    let extdk: ExtendedKey<Legacy> = mnemonic.into_extended_key()?;
    let xpriv = extdk.into_xprv(network).unwrap();

    // Derive zPriv from xPriv
    let zpriv_derivation_path = "m/84'/0'/0'";
    let path: Vec<_> = DerivationPath::from_str(zpriv_derivation_path)?.into();
    let zpriv = xpriv.derive_priv(&secp, &path)?;

    let zpub = ExtendedPubKey::from_priv(&secp, &zpriv);
    Ok(zpub.to_string())
}

Thanks in advance!

nondiremanuel commented 1 year ago

Hi! I reposted this request to the discussion section in order to understand if there is already a way to get what you are requesting :) here's the link to the discussion: https://github.com/bitcoindevkit/bdk/discussions/977