2021-03-03 13:22:05 -08:00
|
|
|
// Bitcoin Dev Kit
|
|
|
|
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
|
2020-09-18 17:26:58 +02:00
|
|
|
//
|
2021-03-03 13:22:05 -08:00
|
|
|
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
|
2020-09-18 17:26:58 +02:00
|
|
|
//
|
2021-03-03 13:22:05 -08:00
|
|
|
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
|
|
|
|
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
|
|
|
|
// You may not use this file except in accordance with one or both of these
|
|
|
|
// licenses.
|
2020-09-18 17:26:58 +02:00
|
|
|
|
|
|
|
//! BIP-0039
|
|
|
|
|
|
|
|
// TODO: maybe write our own implementation of bip39? Seems stupid to have an extra dependency for
|
|
|
|
// something that should be fairly simple to re-implement.
|
|
|
|
|
2023-01-10 15:10:02 +11:00
|
|
|
use alloc::string::String;
|
2023-07-19 15:27:48 +02:00
|
|
|
use bitcoin::bip32;
|
2020-09-18 17:26:58 +02:00
|
|
|
use bitcoin::Network;
|
|
|
|
|
2020-09-21 15:44:07 +02:00
|
|
|
use miniscript::ScriptContext;
|
|
|
|
|
2022-04-07 19:38:46 +08:00
|
|
|
pub use bip39::{Error, Language, Mnemonic};
|
2021-10-31 20:25:00 +05:30
|
|
|
|
|
|
|
type Seed = [u8; 64];
|
|
|
|
|
|
|
|
/// Type describing entropy length (aka word count) in the mnemonic
|
2021-11-06 20:14:03 +05:30
|
|
|
pub enum WordCount {
|
2021-10-31 20:25:00 +05:30
|
|
|
/// 12 words mnemonic (128 bits entropy)
|
|
|
|
Words12 = 128,
|
|
|
|
/// 15 words mnemonic (160 bits entropy)
|
|
|
|
Words15 = 160,
|
|
|
|
/// 18 words mnemonic (192 bits entropy)
|
|
|
|
Words18 = 192,
|
|
|
|
/// 21 words mnemonic (224 bits entropy)
|
|
|
|
Words21 = 224,
|
|
|
|
/// 24 words mnemonic (256 bits entropy)
|
|
|
|
Words24 = 256,
|
|
|
|
}
|
2021-01-26 11:48:44 -05:00
|
|
|
|
|
|
|
use super::{
|
|
|
|
any_network, DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey, KeyError,
|
|
|
|
};
|
|
|
|
|
|
|
|
fn set_valid_on_any_network<Ctx: ScriptContext>(
|
|
|
|
descriptor_key: DescriptorKey<Ctx>,
|
|
|
|
) -> DescriptorKey<Ctx> {
|
|
|
|
// We have to pick one network to build the xprv, but since the bip39 standard doesn't
|
|
|
|
// encode the network, the xprv we create is actually valid everywhere. So we override the
|
|
|
|
// valid networks with `any_network()`.
|
|
|
|
descriptor_key.override_valid_networks(any_network())
|
|
|
|
}
|
2020-09-18 17:26:58 +02:00
|
|
|
|
2020-12-10 11:38:42 +01:00
|
|
|
/// Type for a BIP39 mnemonic with an optional passphrase
|
2020-09-18 17:26:58 +02:00
|
|
|
pub type MnemonicWithPassphrase = (Mnemonic, Option<String>);
|
|
|
|
|
2020-12-10 11:38:42 +01:00
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
|
2020-09-22 16:12:09 +02:00
|
|
|
impl<Ctx: ScriptContext> DerivableKey<Ctx> for Seed {
|
2021-01-26 11:48:44 -05:00
|
|
|
fn into_extended_key(self) -> Result<ExtendedKey<Ctx>, KeyError> {
|
2023-10-16 19:51:53 +11:00
|
|
|
Ok(bip32::Xpriv::new_master(Network::Bitcoin, &self[..])?.into())
|
2021-01-26 11:48:44 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn into_descriptor_key(
|
2020-09-22 16:12:09 +02:00
|
|
|
self,
|
2020-12-11 11:14:30 +01:00
|
|
|
source: Option<bip32::KeySource>,
|
2020-09-22 16:12:09 +02:00
|
|
|
derivation_path: bip32::DerivationPath,
|
|
|
|
) -> Result<DescriptorKey<Ctx>, KeyError> {
|
2021-01-26 11:48:44 -05:00
|
|
|
let descriptor_key = self
|
|
|
|
.into_extended_key()?
|
|
|
|
.into_descriptor_key(source, derivation_path)?;
|
2020-09-21 15:44:07 +02:00
|
|
|
|
2021-01-26 11:48:44 -05:00
|
|
|
Ok(set_valid_on_any_network(descriptor_key))
|
2020-09-18 17:26:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-10 11:38:42 +01:00
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
|
2020-09-22 16:12:09 +02:00
|
|
|
impl<Ctx: ScriptContext> DerivableKey<Ctx> for MnemonicWithPassphrase {
|
2021-01-26 11:48:44 -05:00
|
|
|
fn into_extended_key(self) -> Result<ExtendedKey<Ctx>, KeyError> {
|
|
|
|
let (mnemonic, passphrase) = self;
|
2021-10-31 20:25:00 +05:30
|
|
|
let seed: Seed = mnemonic.to_seed(passphrase.as_deref().unwrap_or(""));
|
2021-01-26 11:48:44 -05:00
|
|
|
|
|
|
|
seed.into_extended_key()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn into_descriptor_key(
|
2020-09-22 16:12:09 +02:00
|
|
|
self,
|
2020-12-11 11:14:30 +01:00
|
|
|
source: Option<bip32::KeySource>,
|
2020-09-22 16:12:09 +02:00
|
|
|
derivation_path: bip32::DerivationPath,
|
|
|
|
) -> Result<DescriptorKey<Ctx>, KeyError> {
|
2021-01-26 11:48:44 -05:00
|
|
|
let descriptor_key = self
|
|
|
|
.into_extended_key()?
|
|
|
|
.into_descriptor_key(source, derivation_path)?;
|
|
|
|
|
|
|
|
Ok(set_valid_on_any_network(descriptor_key))
|
2020-09-18 17:26:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
[keys] Implement `DerivableKey<Ctx>` for `(GeneratedKey<Mnemonic, Ctx>, Option<String>)`
This lets us use a tuple of (generated mnemonic, optional passphrase) as
a `DerivableKey` directly, without extracting the inner mnemonic from the
`GeneratedKey` wrapper. For BIP39 keys specifically it doesn't make much
difference because the mnemonic format doesn't encode the network, but in
general this is not the case and having a consistent API will make it
harder for people to make mistakes.
To explain why we should not extract the key: some key formats (like
BIP32 extended keys) are network-specific, meaning that if somebody
tries to use a Testnet key on a Mainnet BDK wallet, it won't work.
However, when we generate a new key we would like to be able to use that
key on any network, but we need to set some kind of placeholder for the
`network` field in the structure. This is why (or at least one of the
reasons why) we wrap the key in the `GeneratedKey` struct: we keep track
of the "valid_networks" separately, which means that even if we set our
BIP32 xprv to be a "Mainnet" key, once we go try creating a wallet with
that key BDK is smart enough to understand that `GeneratedKey`s have
their own separate set of valid networks and it will use that set to
validate whether the key can be used in the wallet or not.
2022-04-13 12:37:27 +02:00
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
|
|
|
|
impl<Ctx: ScriptContext> DerivableKey<Ctx> for (GeneratedKey<Mnemonic, Ctx>, Option<String>) {
|
|
|
|
fn into_extended_key(self) -> Result<ExtendedKey<Ctx>, KeyError> {
|
|
|
|
let (mnemonic, passphrase) = self;
|
|
|
|
(mnemonic.into_key(), passphrase).into_extended_key()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn into_descriptor_key(
|
|
|
|
self,
|
|
|
|
source: Option<bip32::KeySource>,
|
|
|
|
derivation_path: bip32::DerivationPath,
|
|
|
|
) -> Result<DescriptorKey<Ctx>, KeyError> {
|
|
|
|
let (mnemonic, passphrase) = self;
|
|
|
|
(mnemonic.into_key(), passphrase).into_descriptor_key(source, derivation_path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-10 11:38:42 +01:00
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
|
2020-09-22 16:12:09 +02:00
|
|
|
impl<Ctx: ScriptContext> DerivableKey<Ctx> for Mnemonic {
|
2021-01-26 11:48:44 -05:00
|
|
|
fn into_extended_key(self) -> Result<ExtendedKey<Ctx>, KeyError> {
|
|
|
|
(self, None).into_extended_key()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn into_descriptor_key(
|
2020-09-22 16:12:09 +02:00
|
|
|
self,
|
2020-12-11 11:14:30 +01:00
|
|
|
source: Option<bip32::KeySource>,
|
2020-09-22 16:12:09 +02:00
|
|
|
derivation_path: bip32::DerivationPath,
|
|
|
|
) -> Result<DescriptorKey<Ctx>, KeyError> {
|
2021-01-26 11:48:44 -05:00
|
|
|
let descriptor_key = self
|
|
|
|
.into_extended_key()?
|
|
|
|
.into_descriptor_key(source, derivation_path)?;
|
|
|
|
|
|
|
|
Ok(set_valid_on_any_network(descriptor_key))
|
2020-09-18 17:26:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-10 11:38:42 +01:00
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
|
2020-09-24 09:52:59 +02:00
|
|
|
impl<Ctx: ScriptContext> GeneratableKey<Ctx> for Mnemonic {
|
2020-09-30 08:17:49 +10:00
|
|
|
type Entropy = [u8; 32];
|
2020-09-24 09:52:59 +02:00
|
|
|
|
2021-11-06 20:14:03 +05:30
|
|
|
type Options = (WordCount, Language);
|
2021-10-31 20:25:00 +05:30
|
|
|
type Error = Option<bip39::Error>;
|
2020-09-24 09:52:59 +02:00
|
|
|
|
2020-09-30 08:17:49 +10:00
|
|
|
fn generate_with_entropy(
|
2021-10-31 20:25:00 +05:30
|
|
|
(word_count, language): Self::Options,
|
2020-09-30 08:17:49 +10:00
|
|
|
entropy: Self::Entropy,
|
2020-09-24 09:52:59 +02:00
|
|
|
) -> Result<GeneratedKey<Self, Ctx>, Self::Error> {
|
2023-07-19 15:27:48 +02:00
|
|
|
let entropy = &entropy[..(word_count as usize / 8)];
|
2021-10-31 20:25:00 +05:30
|
|
|
let mnemonic = Mnemonic::from_entropy_in(language, entropy)?;
|
2020-09-24 09:52:59 +02:00
|
|
|
|
|
|
|
Ok(GeneratedKey::new(mnemonic, any_network()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-18 17:26:58 +02:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
2023-01-10 15:10:02 +11:00
|
|
|
use alloc::string::ToString;
|
|
|
|
use core::str::FromStr;
|
2020-09-18 17:26:58 +02:00
|
|
|
|
2023-07-19 15:27:48 +02:00
|
|
|
use bitcoin::bip32;
|
2020-09-18 17:26:58 +02:00
|
|
|
|
2021-10-31 20:25:00 +05:30
|
|
|
use bip39::{Language, Mnemonic};
|
2020-09-24 09:52:59 +02:00
|
|
|
|
|
|
|
use crate::keys::{any_network, GeneratableKey, GeneratedKey};
|
2020-09-18 17:26:58 +02:00
|
|
|
|
2021-11-06 20:14:03 +05:30
|
|
|
use super::WordCount;
|
2021-10-31 20:25:00 +05:30
|
|
|
|
2020-09-18 17:26:58 +02:00
|
|
|
#[test]
|
|
|
|
fn test_keys_bip39_mnemonic() {
|
|
|
|
let mnemonic =
|
|
|
|
"aim bunker wash balance finish force paper analyst cabin spoon stable organ";
|
2021-10-31 20:25:00 +05:30
|
|
|
let mnemonic = Mnemonic::parse_in(Language::English, mnemonic).unwrap();
|
2020-09-18 17:26:58 +02:00
|
|
|
let path = bip32::DerivationPath::from_str("m/44'/0'/0'/0").unwrap();
|
|
|
|
|
|
|
|
let key = (mnemonic, path);
|
2020-09-21 15:44:07 +02:00
|
|
|
let (desc, keys, networks) = crate::descriptor!(wpkh(key)).unwrap();
|
2021-02-02 20:06:40 -05:00
|
|
|
assert_eq!(desc.to_string(), "wpkh([be83839f/44'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/0/*)#0r8v4nkv");
|
2020-09-18 17:26:58 +02:00
|
|
|
assert_eq!(keys.len(), 1);
|
2021-02-05 10:23:17 -05:00
|
|
|
assert_eq!(networks.len(), 4);
|
2020-09-18 17:26:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_keys_bip39_mnemonic_passphrase() {
|
|
|
|
let mnemonic =
|
|
|
|
"aim bunker wash balance finish force paper analyst cabin spoon stable organ";
|
2021-10-31 20:25:00 +05:30
|
|
|
let mnemonic = Mnemonic::parse_in(Language::English, mnemonic).unwrap();
|
2020-09-18 17:26:58 +02:00
|
|
|
let path = bip32::DerivationPath::from_str("m/44'/0'/0'/0").unwrap();
|
|
|
|
|
|
|
|
let key = ((mnemonic, Some("passphrase".into())), path);
|
2020-09-21 15:44:07 +02:00
|
|
|
let (desc, keys, networks) = crate::descriptor!(wpkh(key)).unwrap();
|
2021-02-02 20:06:40 -05:00
|
|
|
assert_eq!(desc.to_string(), "wpkh([8f6cb80c/44'/0'/0']xpub6DWYS8bbihFevy29M4cbw4ZR3P5E12jB8R88gBDWCTCNpYiDHhYWNywrCF9VZQYagzPmsZpxXpytzSoxynyeFr4ZyzheVjnpLKuse4fiwZw/0/*)#h0j0tg5m");
|
2020-09-18 17:26:58 +02:00
|
|
|
assert_eq!(keys.len(), 1);
|
2021-02-05 10:23:17 -05:00
|
|
|
assert_eq!(networks.len(), 4);
|
2020-09-18 17:26:58 +02:00
|
|
|
}
|
2020-09-24 09:52:59 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_keys_generate_bip39() {
|
|
|
|
let generated_mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
|
|
|
|
Mnemonic::generate_with_entropy(
|
2021-11-06 20:14:03 +05:30
|
|
|
(WordCount::Words12, Language::English),
|
2020-10-28 21:34:04 -07:00
|
|
|
crate::keys::test::TEST_ENTROPY,
|
2020-09-24 09:52:59 +02:00
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(generated_mnemonic.valid_networks, any_network());
|
|
|
|
assert_eq!(
|
|
|
|
generated_mnemonic.to_string(),
|
|
|
|
"primary fetch primary fetch primary fetch primary fetch primary fetch primary fever"
|
|
|
|
);
|
|
|
|
|
|
|
|
let generated_mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
|
|
|
|
Mnemonic::generate_with_entropy(
|
2021-11-06 20:14:03 +05:30
|
|
|
(WordCount::Words24, Language::English),
|
2020-10-28 21:34:04 -07:00
|
|
|
crate::keys::test::TEST_ENTROPY,
|
2020-09-24 09:52:59 +02:00
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(generated_mnemonic.valid_networks, any_network());
|
|
|
|
assert_eq!(generated_mnemonic.to_string(), "primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary foster");
|
|
|
|
}
|
2020-09-24 15:59:46 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_keys_generate_bip39_random() {
|
|
|
|
let generated_mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
|
2024-06-19 16:35:04 -05:00
|
|
|
Mnemonic::generate((WordCount::Words12, Language::English)).unwrap();
|
2020-09-24 15:59:46 +02:00
|
|
|
assert_eq!(generated_mnemonic.valid_networks, any_network());
|
2024-06-19 16:35:04 -05:00
|
|
|
|
2020-09-24 15:59:46 +02:00
|
|
|
let generated_mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
|
2024-06-19 16:35:04 -05:00
|
|
|
Mnemonic::generate((WordCount::Words24, Language::English)).unwrap();
|
2020-09-24 15:59:46 +02:00
|
|
|
assert_eq!(generated_mnemonic.valid_networks, any_network());
|
|
|
|
}
|
2020-09-18 17:26:58 +02:00
|
|
|
}
|