Skip to content

Commit

Permalink
Add segwit key derivation as a feature
Browse files Browse the repository at this point in the history
  • Loading branch information
cryptoquick committed Jan 14, 2024
1 parent 6d751d6 commit 5e3fd34
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ required-features = ["server"]
all = []
default = []
web = []
segwit = []
server = ["tokio/full", "tower-http/cors"]

[dependencies]
Expand Down
12 changes: 11 additions & 1 deletion src/bitcoin/keys.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
use std::str::FromStr;

#[cfg(feature = "segwit")]
use bdk::miniscript::Segwitv0;
#[cfg(not(feature = "segwit"))]
use bdk::miniscript::Tap;
use bdk::{
bitcoin::{
secp256k1::Secp256k1,
util::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey, KeySource},
},
keys::{DerivableKey, DescriptorKey, DescriptorKey::Secret as SecretDesc, DescriptorSecretKey},
miniscript::{descriptor::DescriptorKeyParseError, Tap},
miniscript::descriptor::DescriptorKeyParseError,
};
use bip39::{Language, Mnemonic};
use bitcoin::{KeyPair, Network};
Expand Down Expand Up @@ -70,10 +74,16 @@ fn get_descriptor(
let deriv_descriptor = DerivationPath::from_str(path)?;
let derived_xprv = &xprv.derive_priv(&secp, &deriv_descriptor)?;
let origin: KeySource = (xprv.fingerprint(&secp), deriv_descriptor);
#[cfg(not(feature = "segwit"))]
let derived_xprv_desc_key: DescriptorKey<Tap> = derived_xprv.into_descriptor_key(
Some(origin),
DerivationPath::default().child(ChildNumber::from_normal_idx(change)?),
)?;
#[cfg(feature = "segwit")]
let derived_xprv_desc_key: DescriptorKey<Segwitv0> = derived_xprv.into_descriptor_key(
Some(origin),
DerivationPath::default().child(ChildNumber::from_normal_idx(change)?),
)?;

if let SecretDesc(desc_seckey, _, _) = derived_xprv_desc_key {
Ok(desc_seckey)
Expand Down
7 changes: 7 additions & 0 deletions src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,15 @@ pub async fn get_udas_utxo() -> String {
}

// Descriptor strings
#[cfg(not(feature = "segwit"))]
pub const BTC_MAINNET_PATH: &str = "m/86h/0h/0h";
#[cfg(not(feature = "segwit"))]
pub const BTC_TESTNET_PATH: &str = "m/86h/1h/0h";
#[cfg(feature = "segwit")]
pub const BTC_MAINNET_PATH: &str = "m/84h/0h/0h";
#[cfg(feature = "segwit")]
pub const BTC_TESTNET_PATH: &str = "m/84h/1h/0h";

pub static BTC_PATH: Lazy<RwLock<String>> = Lazy::new(|| {
RwLock::new(if dot_env("BITCOIN_NETWORK") == "bitcoin" {
BTC_MAINNET_PATH.to_owned()
Expand Down

0 comments on commit 5e3fd34

Please sign in to comment.