bip32/
lib.rs

1#![no_std]
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3#![doc = include_str!("../README.md")]
4#![forbid(unsafe_code)]
5#![warn(
6    clippy::unwrap_used,
7    missing_docs,
8    rust_2018_idioms,
9    unused_qualifications
10)]
11
12//! ## Backends
13//! This crate provides a generic implementation of BIP32 which can be used
14//! with any backing provider which implements the [`PrivateKey`] and
15//! [`PublicKey`] traits. The following providers are built into this crate,
16//! under the following crate features:
17//!
18//! - `secp256k1` (enabled by default): support for the pure Rust [`k256`]
19//!   crate, with [`XPrv`] and [`XPub`] type aliases.
20//! - `secp256k1-ffi`: support for Bitcoin Core's [libsecp256k1 C library],
21//!   as wrapped by the [`secp256k1` Rust crate].
22//!
23//! ## Limitations and further work
24//! - Only 24-word BIP39 mnemonics are supported
25//! - BIP43, BIP44, BIP49, BIP84 not yet properly supported
26//!
27//! # Usage
28//! The following is an end-to-end example of how to generate a random BIP39
29//! mnemonic and use it to derive child keys according to a provided BIP32
30//! derivation path.
31//!
32//! ## Accessing `OsRng`
33//! The following example uses `OsRng` for cryptographically secure random
34//! number generation. To use it, you need to include `rand_core` with the
35//! `std` feature by adding the following to `Cargo.toml`:
36//!
37//! ```toml
38//! rand_core = { version = "0.6", features = ["std"] }
39//! ```
40//!
41//! (on embedded platforms, you will need to supply our own RNG)
42//!
43//! ## Rust code example
44//! ```
45//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
46//! # #[cfg(all(feature = "bip39", feature = "secp256k1"))]
47//! # {
48//! use bip32::{Mnemonic, Prefix, XPrv};
49//! use rand_core::OsRng;
50//!
51//! // Generate random Mnemonic using the default language (English)
52//! let mnemonic = Mnemonic::random(&mut OsRng, Default::default());
53//!
54//! // Derive a BIP39 seed value using the given password
55//! let seed = mnemonic.to_seed("password");
56//!
57//! // Derive the root `XPrv` from the `seed` value
58//! let root_xprv = XPrv::new(&seed)?;
59//! assert_eq!(root_xprv, XPrv::derive_from_path(&seed, &"m".parse()?)?);
60//!
61//! // Derive a child `XPrv` using the provided BIP32 derivation path
62//! let child_path = "m/0/2147483647'/1/2147483646'";
63//! let child_xprv = XPrv::derive_from_path(&seed, &child_path.parse()?)?;
64//!
65//! // Get the `XPub` associated with `child_xprv`.
66//! let child_xpub = child_xprv.public_key();
67//!
68//! // Serialize `child_xprv` as a string with the `xprv` prefix.
69//! let child_xprv_str = child_xprv.to_string(Prefix::XPRV);
70//! assert!(child_xprv_str.starts_with("xprv"));
71//!
72//! // Serialize `child_xpub` as a string with the `xpub` prefix.
73//! let child_xpub_str = child_xpub.to_string(Prefix::XPUB);
74//! assert!(child_xpub_str.starts_with("xpub"));
75//!
76//! // Get the ECDSA/secp256k1 signing and verification keys for the xprv and xpub
77//! let signing_key = child_xprv.private_key();
78//! let verification_key = child_xpub.public_key();
79//!
80//! // Sign and verify an example message using the derived keys.
81//! use bip32::secp256k1::ecdsa::{
82//!     signature::{Signer, Verifier},
83//!     Signature
84//! };
85//!
86//! let example_msg = b"Hello, world!";
87//! let signature: Signature = signing_key.sign(example_msg);
88//! assert!(verification_key.verify(example_msg, &signature).is_ok());
89//! # }
90//! # Ok(())
91//! # }
92//! ```
93//!
94//! [bip32]: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
95//! [libsecp256k1 C library]: https://github.com/bitcoin-core/secp256k1
96//! [`secp256k1` Rust crate]: https://github.com/rust-bitcoin/rust-secp256k1/
97
98#[cfg(feature = "alloc")]
99extern crate alloc;
100
101#[cfg(feature = "std")]
102extern crate std;
103
104mod child_number;
105mod error;
106mod extended_key;
107mod prefix;
108mod private_key;
109mod public_key;
110
111#[cfg(feature = "alloc")]
112mod derivation_path;
113
114#[cfg(feature = "mnemonic")]
115mod mnemonic;
116
117pub use crate::{
118    child_number::ChildNumber,
119    error::{Error, Result},
120    extended_key::{
121        attrs::ExtendedKeyAttrs, private_key::ExtendedPrivateKey, public_key::ExtendedPublicKey,
122        ExtendedKey,
123    },
124    prefix::Prefix,
125    private_key::{PrivateKey, PrivateKeyBytes},
126    public_key::{PublicKey, PublicKeyBytes},
127};
128
129#[cfg(feature = "alloc")]
130pub use crate::derivation_path::DerivationPath;
131
132#[cfg(feature = "bip39")]
133pub use crate::mnemonic::{Language, Phrase as Mnemonic, Seed};
134
135#[cfg(feature = "secp256k1")]
136pub use {
137    crate::extended_key::{private_key::XPrv, public_key::XPub},
138    k256 as secp256k1,
139};
140
141/// Chain code: extension for both private and public keys which provides an
142/// additional 256-bits of entropy.
143pub type ChainCode = [u8; KEY_SIZE];
144
145/// Derivation depth.
146pub type Depth = u8;
147
148/// BIP32 key fingerprints.
149pub type KeyFingerprint = [u8; 4];
150
151/// BIP32 "versions": integer representation of the key prefix.
152pub type Version = u32;
153
154/// HMAC with SHA-512
155type HmacSha512 = hmac::Hmac<sha2::Sha512>;
156
157/// Size of input key material and derived keys.
158pub const KEY_SIZE: usize = 32;