├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── hdwallet-bitcoin ├── Cargo.toml └── src │ ├── error.rs │ ├── lib.rs │ └── serialize.rs ├── rust-toolchain └── src ├── error.rs ├── extended_key.rs ├── extended_key └── key_index.rs ├── key_chain.rs ├── key_chain └── chain_path.rs ├── lib.rs └── traits.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Install Rust components 13 | run: rustup component add rustfmt && rustup component add clippy 14 | - name: Run CI checks 15 | run: make 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | .idea 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hdwallet" 3 | version = "0.4.1" 4 | authors = ["jjy "] 5 | edition = "2021" 6 | license = "MIT" 7 | repository = "https://github.com/jjyr/hdwallet" 8 | keywords = [ "hdwallet", "BIP32", "wallet", "bitcoin", "crypto" ] 9 | readme = "README.md" 10 | description = "Hierarchical deterministic wallet (BIP-32)" 11 | 12 | [workspace] 13 | members = [ 14 | "hdwallet-bitcoin" 15 | ] 16 | 17 | [dependencies] 18 | secp256k1 = "0.26" 19 | rand_core = "0.6.4" 20 | ring = "0.16" 21 | lazy_static = "1.4" 22 | thiserror = "1.0.38" 23 | 24 | [dev-dependencies] 25 | hex = "0.4" 26 | base58 = "0.1" 27 | ripemd160 = "0.8" 28 | rand = "0.8.3" 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Jiang Jinyang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: clippy build test 2 | 3 | build: 4 | cargo build --verbose --all 5 | 6 | test: 7 | cargo test --verbose --all 8 | 9 | clippy: 10 | cargo clippy --all --all-targets --all-features -- -D warnings 11 | 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HDWallet 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/hdwallet.svg)](https://crates.io/crates/hdwallet) 4 | [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) 5 | [Docs](https://docs.rs/hdwallet) 6 | 7 | HD wallet([BIP-32]) key derivation utilities. 8 | 9 | This crate is build upon [secp256k1] crate, this crate only provides [BIP-32] related features, for signature features see the [secp256k1 documentation](https://docs.rs/secp256k1). 10 | 11 | * [`ChainPath`] and [`KeyChain`] are used to derive HD wallet keys. 12 | * [`Derivation`] describes key derivation info. 13 | * [`ExtendedPrivKey`] and [`ExtendedPubKey`] represent extended keys according to [BIP-32], which can derives child keys. 14 | * [`KeyIndex`] indicates child key's index and type(Normal key or Hardened key). 15 | * [`Error`] errors. 16 | 17 | `hdwallet` itself is a key derivation framework. 18 | Check `hdwallet-bitcoin` if you want to derive bitcoin keys; you can find or submit other crypto currencies on [hdwallet homepage](https://github.com/jjyr/hdwallet). 19 | 20 | ## Documentation 21 | 22 | * [HDWallet](https://docs.rs/hdwallet) 23 | * [HDWallet Bitcoin](https://docs.rs/hdwallet-bitcoin) 24 | 25 | ## License 26 | 27 | MIT 28 | 29 | [BIP-32]: https://github.com/bitcoin/bips/blob/0042dec548f8c819df7ea48fdeec78af21974384/bip-0032.mediawiki "BIP 32" 30 | [secp256k1]: https://github.com/rust-bitcoin/rust-secp256k1/ "secp256k1" 31 | -------------------------------------------------------------------------------- /hdwallet-bitcoin/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hdwallet-bitcoin" 3 | version = "0.4.1" 4 | authors = ["jjy "] 5 | edition = "2021" 6 | license = "MIT" 7 | repository = "https://github.com/jjyr/hdwallet" 8 | keywords = [ "hdwallet", "BIP32", "wallet", "bitcoin", "crypto" ] 9 | description = "Bitcoin BIP-32 key derivation" 10 | 11 | [dependencies] 12 | hdwallet = { path = "..", version = "0.4" } 13 | hex = "0.4" 14 | base58 = "0.2" 15 | ripemd = "0.1" 16 | 17 | 18 | [dev-dependencies] 19 | rand = "0.8" 20 | -------------------------------------------------------------------------------- /hdwallet-bitcoin/src/error.rs: -------------------------------------------------------------------------------- 1 | use hdwallet::secp256k1; 2 | 3 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 4 | pub enum Error { 5 | MisChecksum, 6 | UnknownVersion, 7 | Secp(secp256k1::Error), 8 | InvalidBase58, 9 | } 10 | 11 | impl From for Error { 12 | fn from(err: secp256k1::Error) -> Self { 13 | Error::Secp(err) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /hdwallet-bitcoin/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! HD wallet Bitcoin extention. 2 | //! 3 | //! This crate extend the `hdwallet` crate, provide Bitcoin key derivation and serialization according to BIP-32. 4 | //! See [hdwallet documentation](https://docs.rs/hdwallet) to learn how to derive HD keys. See [secp256k1 documentation](https://docs.rs/secp256k1) to learn how to signature. 5 | //! 6 | //! # Examples 7 | //! 8 | //! ```rust 9 | //! # extern crate hdwallet; 10 | //! # extern crate hdwallet_bitcoin; 11 | //! use hdwallet::{KeyChain, DefaultKeyChain, ExtendedPrivKey, traits::Serialize}; 12 | //! use hdwallet_bitcoin::{PrivKey as BitcoinPrivKey, Network as BitcoinNetwork}; 13 | //! 14 | //! let mut rng = rand::thread_rng(); 15 | //! let master_key = ExtendedPrivKey::random(&mut rng).expect("master key"); 16 | //! let key_chain = DefaultKeyChain::new(master_key); 17 | //! let (extended_key, derivation) = key_chain.derive_private_key("m/1H/0".into()).expect("derive ExtendedPrivKey"); 18 | //! let key = BitcoinPrivKey { 19 | //! network: BitcoinNetwork::MainNet, 20 | //! derivation, 21 | //! extended_key, 22 | //! }; 23 | //! let serialized_key: String = key.serialize(); 24 | //! println!("derive m/1H/0 key: {}", serialized_key); 25 | //! ``` 26 | //! 27 | 28 | mod error; 29 | mod serialize; 30 | 31 | use hdwallet::{Derivation, ExtendedPrivKey, ExtendedPubKey}; 32 | 33 | pub use error::Error; 34 | 35 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 36 | pub enum Network { 37 | MainNet, 38 | TestNet, 39 | } 40 | 41 | #[derive(Clone, Debug, PartialEq, Eq)] 42 | pub struct PrivKey { 43 | pub network: Network, 44 | pub derivation: Derivation, 45 | pub extended_key: ExtendedPrivKey, 46 | } 47 | 48 | impl PrivKey { 49 | pub fn from_master_key(extended_key: ExtendedPrivKey, network: Network) -> Self { 50 | PrivKey { 51 | extended_key, 52 | network, 53 | derivation: Derivation::master(), 54 | } 55 | } 56 | } 57 | 58 | #[derive(Clone, Debug, PartialEq, Eq)] 59 | pub struct PubKey { 60 | pub network: Network, 61 | pub derivation: Derivation, 62 | pub extended_key: ExtendedPubKey, 63 | } 64 | 65 | impl PubKey { 66 | pub fn from_private_key(priv_key: &PrivKey) -> PubKey { 67 | let extended_pub_key = ExtendedPubKey::from_private_key(&priv_key.extended_key); 68 | PubKey { 69 | network: priv_key.network, 70 | derivation: priv_key.derivation.clone(), 71 | extended_key: extended_pub_key, 72 | } 73 | } 74 | } 75 | 76 | #[cfg(test)] 77 | mod tests { 78 | use super::*; 79 | use hdwallet::{traits::Serialize, ChainPath, DefaultKeyChain, KeyChain}; 80 | 81 | #[test] 82 | fn test_bip32_vector_1() { 83 | let seed = hex::decode("000102030405060708090a0b0c0d0e0f").expect("decode"); 84 | let key_chain = 85 | DefaultKeyChain::new(ExtendedPrivKey::with_seed(&seed).expect("master key")); 86 | for (chain_path, hex_priv_key, hex_pub_key) in &[ 87 | ("m", "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8"), 88 | ("m/0H", "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7", "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw"), 89 | ("m/0H/1", "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs", "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ"), 90 | ("m/0H/1/2H", "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM", "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5"), 91 | ("m/0H/1/2H/2", "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334", "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV"), 92 | ("m/0H/1/2H/2/1000000000", "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76", "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy") 93 | ] { 94 | let (extended_key, derivation) = key_chain.derive_private_key(ChainPath::from(*chain_path)).expect("fetch key"); 95 | let priv_key = PrivKey{ 96 | network: Network::MainNet, 97 | derivation, 98 | extended_key 99 | }; 100 | assert_eq!(&Serialize::::serialize(&priv_key), hex_priv_key); 101 | assert_eq!(&Serialize::::serialize(&PubKey::from_private_key(&priv_key)), hex_pub_key); 102 | } 103 | } 104 | 105 | #[test] 106 | fn test_bip32_vector_2() { 107 | let seed = hex::decode("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542").expect("decode"); 108 | let key_chain = 109 | DefaultKeyChain::new(ExtendedPrivKey::with_seed(&seed).expect("master key")); 110 | for (chain_path, hex_priv_key, hex_pub_key) in &[ 111 | ("m", "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB"), 112 | ("m/0", "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt", "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH"), 113 | ("m/0/2147483647H", "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9", "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a"), 114 | ("m/0/2147483647H/1", "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef", "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon"), 115 | ("m/0/2147483647H/1/2147483646H", "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc", "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL"), 116 | ("m/0/2147483647H/1/2147483646H/2", "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j", "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt") 117 | ] { 118 | let (extended_key, derivation) = key_chain.derive_private_key(ChainPath::from(*chain_path)).expect("fetch key"); 119 | let priv_key = PrivKey{ 120 | network: Network::MainNet, 121 | derivation, 122 | extended_key 123 | }; 124 | assert_eq!(&Serialize::::serialize(&priv_key), hex_priv_key); 125 | assert_eq!(&Serialize::::serialize(&PubKey::from_private_key(&priv_key)), hex_pub_key); 126 | } 127 | } 128 | 129 | #[test] 130 | fn test_bip32_vector_3() { 131 | let seed = hex::decode("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be").expect("decode"); 132 | let key_chain = 133 | DefaultKeyChain::new(ExtendedPrivKey::with_seed(&seed).expect("master key")); 134 | for (chain_path, hex_priv_key, hex_pub_key) in &[ 135 | ("m", "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6", "xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13"), 136 | ("m/0H", "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L", "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y") 137 | ] { 138 | let (extended_key, derivation) = key_chain.derive_private_key(ChainPath::from(*chain_path)).expect("fetch key"); 139 | let priv_key = PrivKey{ 140 | network: Network::MainNet, 141 | derivation, 142 | extended_key 143 | }; 144 | assert_eq!(&Serialize::::serialize(&priv_key), hex_priv_key); 145 | assert_eq!(&Serialize::::serialize(&PubKey::from_private_key(&priv_key)), hex_pub_key); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /hdwallet-bitcoin/src/serialize.rs: -------------------------------------------------------------------------------- 1 | use crate::{Error, Network, PrivKey, PubKey}; 2 | use base58::{FromBase58, ToBase58}; 3 | use hdwallet::ring::digest; 4 | use hdwallet::{ 5 | secp256k1::{PublicKey, SecretKey}, 6 | traits::{Deserialize, Serialize}, 7 | Derivation, ExtendedPrivKey, ExtendedPubKey, KeyIndex, 8 | }; 9 | use ripemd::{Digest, Ripemd160}; 10 | 11 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 12 | enum KeyType { 13 | PrivKey, 14 | PubKey, 15 | } 16 | 17 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 18 | struct Version { 19 | network: Network, 20 | key_type: KeyType, 21 | } 22 | 23 | impl Version { 24 | #[allow(dead_code)] 25 | fn from_bytes(data: &[u8]) -> Result { 26 | let version = match hex::encode(data).to_uppercase().as_ref() { 27 | "0488ADE4" => Version { 28 | network: Network::MainNet, 29 | key_type: KeyType::PrivKey, 30 | }, 31 | "0488B21E" => Version { 32 | network: Network::MainNet, 33 | key_type: KeyType::PubKey, 34 | }, 35 | "04358394" => Version { 36 | network: Network::TestNet, 37 | key_type: KeyType::PrivKey, 38 | }, 39 | "043587CF" => Version { 40 | network: Network::TestNet, 41 | key_type: KeyType::PubKey, 42 | }, 43 | _ => { 44 | return Err(Error::UnknownVersion); 45 | } 46 | }; 47 | Ok(version) 48 | } 49 | 50 | fn to_bytes(self) -> Vec { 51 | let hex_str = match self.network { 52 | Network::MainNet => match self.key_type { 53 | KeyType::PrivKey => "0488ADE4", 54 | KeyType::PubKey => "0488B21E", 55 | }, 56 | Network::TestNet => match self.key_type { 57 | KeyType::PrivKey => "04358394", 58 | KeyType::PubKey => "043587CF", 59 | }, 60 | }; 61 | hex::decode(hex_str).expect("bitcoin network") 62 | } 63 | } 64 | 65 | trait DerivationExt { 66 | fn parent_fingerprint(&self) -> Vec; 67 | } 68 | 69 | impl DerivationExt for Derivation { 70 | fn parent_fingerprint(&self) -> Vec { 71 | match self.parent_key { 72 | Some(ref key) => { 73 | let pubkey = ExtendedPubKey::from_private_key(key); 74 | let buf = digest::digest(&digest::SHA256, &pubkey.public_key.serialize()); 75 | let mut hasher = Ripemd160::new(); 76 | hasher.update(&buf.as_ref()); 77 | hasher.finalize()[0..4].to_vec() 78 | } 79 | None => vec![0; 4], 80 | } 81 | } 82 | } 83 | 84 | fn encode_derivation(buf: &mut Vec, version: Version, derivation: &Derivation) { 85 | buf.extend_from_slice(&version.to_bytes()); 86 | buf.extend_from_slice(&derivation.depth.to_be_bytes()); 87 | buf.extend_from_slice(&derivation.parent_fingerprint()); 88 | match derivation.key_index { 89 | Some(key_index) => { 90 | buf.extend_from_slice(&key_index.raw_index().to_be_bytes()); 91 | } 92 | None => buf.extend_from_slice(&[0; 4]), 93 | } 94 | } 95 | 96 | fn decode_derivation(buf: &[u8]) -> Result<(Version, Derivation), Error> { 97 | let version = Version::from_bytes(&buf[0..4])?; 98 | let depth = u8::from_be_bytes([buf[4]; 1]); 99 | let parent_fingerprint = &buf[5..=8]; 100 | let key_index = { 101 | // is master key 102 | if parent_fingerprint == [0; 4] { 103 | None 104 | } else { 105 | let mut key_index_buf = [0u8; 4]; 106 | key_index_buf.copy_from_slice(&buf[9..=12]); 107 | let raw_index = u32::from_be_bytes(key_index_buf); 108 | Some(KeyIndex::from(raw_index)) 109 | } 110 | }; 111 | Ok(( 112 | version, 113 | Derivation { 114 | depth, 115 | parent_key: None, 116 | key_index, 117 | }, 118 | )) 119 | } 120 | 121 | fn encode_checksum(buf: &mut Vec) { 122 | let check_sum = { 123 | let buf = digest::digest(&digest::SHA256, buf); 124 | digest::digest(&digest::SHA256, buf.as_ref()) 125 | }; 126 | 127 | buf.extend_from_slice(&check_sum.as_ref()[0..4]); 128 | } 129 | 130 | fn verify_checksum(buf: &[u8]) -> Result<(), Error> { 131 | let check_sum = { 132 | let buf = digest::digest(&digest::SHA256, &buf[0..78]); 133 | digest::digest(&digest::SHA256, buf.as_ref()) 134 | }; 135 | if check_sum.as_ref()[0..4] == buf[78..82] { 136 | Ok(()) 137 | } else { 138 | Err(Error::MisChecksum) 139 | } 140 | } 141 | 142 | impl Serialize> for PrivKey { 143 | fn serialize(&self) -> Vec { 144 | let mut buf: Vec = Vec::with_capacity(112); 145 | encode_derivation( 146 | &mut buf, 147 | Version { 148 | network: self.network, 149 | key_type: KeyType::PrivKey, 150 | }, 151 | &self.derivation, 152 | ); 153 | buf.extend_from_slice(&self.extended_key.chain_code); 154 | buf.extend_from_slice(&[0]); 155 | buf.extend_from_slice(&self.extended_key.private_key[..]); 156 | assert_eq!(buf.len(), 78); 157 | encode_checksum(&mut buf); 158 | buf 159 | } 160 | } 161 | 162 | impl Serialize for PrivKey { 163 | fn serialize(&self) -> String { 164 | Serialize::>::serialize(self).to_base58() 165 | } 166 | } 167 | 168 | impl Serialize> for PubKey { 169 | fn serialize(&self) -> Vec { 170 | let mut buf: Vec = Vec::with_capacity(112); 171 | encode_derivation( 172 | &mut buf, 173 | Version { 174 | network: self.network, 175 | key_type: KeyType::PubKey, 176 | }, 177 | &self.derivation, 178 | ); 179 | buf.extend_from_slice(&self.extended_key.chain_code); 180 | buf.extend_from_slice(&self.extended_key.public_key.serialize()); 181 | assert_eq!(buf.len(), 78); 182 | encode_checksum(&mut buf); 183 | buf 184 | } 185 | } 186 | 187 | impl Serialize for PubKey { 188 | fn serialize(&self) -> String { 189 | Serialize::>::serialize(self).to_base58() 190 | } 191 | } 192 | 193 | impl Deserialize, Error> for PrivKey { 194 | fn deserialize(data: Vec) -> Result { 195 | verify_checksum(&data)?; 196 | let (version, derivation) = decode_derivation(&data)?; 197 | let chain_code = data[13..45].to_vec(); 198 | let private_key = SecretKey::from_slice(&data[46..78])?; 199 | Ok(PrivKey { 200 | network: version.network, 201 | derivation, 202 | extended_key: ExtendedPrivKey { 203 | chain_code, 204 | private_key, 205 | }, 206 | }) 207 | } 208 | } 209 | 210 | impl Deserialize for PrivKey { 211 | fn deserialize(data: String) -> Result { 212 | let data = data.from_base58().map_err(|_| Error::InvalidBase58)?; 213 | PrivKey::deserialize(data) 214 | } 215 | } 216 | 217 | impl Deserialize, Error> for PubKey { 218 | fn deserialize(data: Vec) -> Result { 219 | verify_checksum(&data)?; 220 | let (version, derivation) = decode_derivation(&data)?; 221 | let chain_code = data[13..45].to_vec(); 222 | let public_key = PublicKey::from_slice(&data[45..78])?; 223 | Ok(PubKey { 224 | network: version.network, 225 | derivation, 226 | extended_key: ExtendedPubKey { 227 | chain_code, 228 | public_key, 229 | }, 230 | }) 231 | } 232 | } 233 | 234 | impl Deserialize for PubKey { 235 | fn deserialize(data: String) -> Result { 236 | let data = data.from_base58().map_err(|_| Error::InvalidBase58)?; 237 | PubKey::deserialize(data) 238 | } 239 | } 240 | 241 | #[cfg(test)] 242 | mod tests { 243 | use super::*; 244 | use hdwallet::{DefaultKeyChain, KeyChain}; 245 | 246 | #[test] 247 | fn test_deserialize_priv_key() { 248 | let mut rng = rand::thread_rng(); 249 | let key_chain = 250 | DefaultKeyChain::new(ExtendedPrivKey::random(&mut rng).expect("master key")); 251 | let (extended_key, derivation) = 252 | key_chain.derive_private_key("m".into()).expect("fetch key"); 253 | let key = PrivKey { 254 | network: Network::MainNet, 255 | derivation, 256 | extended_key, 257 | }; 258 | let serialized_key: String = key.serialize(); 259 | let key2 = PrivKey::deserialize(serialized_key).expect("deserialize"); 260 | assert_eq!(key, key2); 261 | } 262 | 263 | #[test] 264 | fn test_deserialize_pub_key() { 265 | let mut rng = rand::thread_rng(); 266 | let key_chain = 267 | DefaultKeyChain::new(ExtendedPrivKey::random(&mut rng).expect("master key")); 268 | let (extended_key, derivation) = 269 | key_chain.derive_private_key("m".into()).expect("fetch key"); 270 | let key = PrivKey { 271 | network: Network::MainNet, 272 | derivation, 273 | extended_key, 274 | }; 275 | let key = PubKey::from_private_key(&key); 276 | let serialized_key: String = key.serialize(); 277 | let key2 = PubKey::deserialize(serialized_key).expect("deserialize"); 278 | assert_eq!(key, key2); 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | 1.63.0 2 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | pub use crate::ChainPathError; 2 | 3 | use rand_core; 4 | use thiserror::Error; 5 | 6 | #[derive(Error, Debug)] 7 | pub enum Error { 8 | #[error("Key index out of range")] 9 | KeyIndexOutOfRange, 10 | #[error("Chain path {0}")] 11 | ChainPath(ChainPathError), 12 | #[error("Secp256k1 error {0}")] 13 | Secp(secp256k1::Error), 14 | #[error("rand error {0}")] 15 | Rng(rand_core::Error), 16 | } 17 | 18 | impl From for Error { 19 | fn from(err: ChainPathError) -> Error { 20 | Error::ChainPath(err) 21 | } 22 | } 23 | 24 | impl From for Error { 25 | fn from(err: secp256k1::Error) -> Error { 26 | Error::Secp(err) 27 | } 28 | } 29 | 30 | impl From for Error { 31 | fn from(err: rand_core::Error) -> Self { 32 | Error::Rng(err) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/extended_key.rs: -------------------------------------------------------------------------------- 1 | pub mod key_index; 2 | 3 | use crate::{ 4 | error::Error, 5 | traits::{Deserialize, Serialize}, 6 | }; 7 | use key_index::KeyIndex; 8 | use rand_core::{CryptoRng, RngCore}; 9 | use ring::hmac::{Context, Key, HMAC_SHA512}; 10 | use secp256k1::{PublicKey, Secp256k1, SecretKey, SignOnly, VerifyOnly}; 11 | 12 | lazy_static! { 13 | static ref SECP256K1_SIGN_ONLY: Secp256k1 = Secp256k1::signing_only(); 14 | static ref SECP256K1_VERIFY_ONLY: Secp256k1 = Secp256k1::verification_only(); 15 | } 16 | 17 | /// Random entropy, part of extended key. 18 | type ChainCode = Vec; 19 | 20 | /// ExtendedPrivKey is used for child key derivation. 21 | /// See [secp256k1 crate documentation](https://docs.rs/secp256k1) for SecretKey signatures usage. 22 | /// 23 | /// # Examples 24 | /// 25 | /// ```rust 26 | /// # extern crate hdwallet; 27 | /// use hdwallet::{ExtendedPrivKey, KeyIndex}; 28 | /// use rand; 29 | /// 30 | /// let mut rng = rand::thread_rng(); 31 | /// let master_key = ExtendedPrivKey::random(&mut rng).unwrap(); 32 | /// let hardened_key_index = KeyIndex::hardened_from_normalize_index(0).unwrap(); 33 | /// let hardended_child_priv_key = master_key.derive_private_key(hardened_key_index).unwrap(); 34 | /// let normal_key_index = KeyIndex::Normal(0); 35 | /// let noamal_child_priv_key = master_key.derive_private_key(normal_key_index).unwrap(); 36 | /// ``` 37 | #[derive(Debug, Clone, PartialEq, Eq)] 38 | pub struct ExtendedPrivKey { 39 | pub private_key: SecretKey, 40 | pub chain_code: ChainCode, 41 | } 42 | 43 | /// Indicate bits of random seed used to generate private key, 256 is recommended. 44 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 45 | pub enum KeySeed { 46 | S128 = 128, 47 | S256 = 256, 48 | S512 = 512, 49 | } 50 | 51 | impl ExtendedPrivKey { 52 | /// Generate an ExtendedPrivKey, use 256 size random seed. 53 | pub fn random(rng: &mut R) -> Result { 54 | ExtendedPrivKey::random_with_seed_size(rng, KeySeed::S256) 55 | } 56 | 57 | /// Generate an ExtendedPrivKey which use 128 or 256 or 512 bits random seed. 58 | pub fn random_with_seed_size( 59 | rng: &mut R, 60 | seed_size: KeySeed, 61 | ) -> Result { 62 | let seed = { 63 | let mut seed = vec![0u8; seed_size as usize / 8]; 64 | rng.try_fill_bytes(seed.as_mut_slice())?; 65 | seed 66 | }; 67 | Self::with_seed(&seed) 68 | } 69 | 70 | /// Generate an ExtendedPrivKey from seed 71 | pub fn with_seed(seed: &[u8]) -> Result { 72 | let signature = { 73 | let signing_key = Key::new(HMAC_SHA512, b"Bitcoin seed"); 74 | let mut h = Context::with_key(&signing_key); 75 | h.update(seed); 76 | h.sign() 77 | }; 78 | let sig_bytes = signature.as_ref(); 79 | let (key, chain_code) = sig_bytes.split_at(sig_bytes.len() / 2); 80 | let private_key = SecretKey::from_slice(key)?; 81 | Ok(ExtendedPrivKey { 82 | private_key, 83 | chain_code: chain_code.to_vec(), 84 | }) 85 | } 86 | 87 | fn sign_hardended_key(&self, index: u32) -> ring::hmac::Tag { 88 | let signing_key = Key::new(HMAC_SHA512, &self.chain_code); 89 | let mut h = Context::with_key(&signing_key); 90 | h.update(&[0x00]); 91 | h.update(&self.private_key[..]); 92 | h.update(&index.to_be_bytes()); 93 | h.sign() 94 | } 95 | 96 | fn sign_normal_key(&self, index: u32) -> ring::hmac::Tag { 97 | let signing_key = Key::new(HMAC_SHA512, &self.chain_code); 98 | let mut h = Context::with_key(&signing_key); 99 | let public_key = PublicKey::from_secret_key(&*SECP256K1_SIGN_ONLY, &self.private_key); 100 | h.update(&public_key.serialize()); 101 | h.update(&index.to_be_bytes()); 102 | h.sign() 103 | } 104 | 105 | /// Derive a child key from ExtendedPrivKey. 106 | pub fn derive_private_key(&self, key_index: KeyIndex) -> Result { 107 | if !key_index.is_valid() { 108 | return Err(Error::KeyIndexOutOfRange); 109 | } 110 | let signature = match key_index { 111 | KeyIndex::Hardened(index) => self.sign_hardended_key(index), 112 | KeyIndex::Normal(index) => self.sign_normal_key(index), 113 | }; 114 | let sig_bytes = signature.as_ref(); 115 | let (key, chain_code) = sig_bytes.split_at(sig_bytes.len() / 2); 116 | let private_key = SecretKey::from_slice(key)?; 117 | let private_key = private_key.add_tweak(&self.private_key.into())?; 118 | Ok(ExtendedPrivKey { 119 | private_key, 120 | chain_code: chain_code.to_vec(), 121 | }) 122 | } 123 | } 124 | 125 | /// ExtendedPubKey is used for public child key derivation. 126 | /// See [secp256k1 crate documentation](https://docs.rs/secp256k1) for PublicKey signatures usage. 127 | /// 128 | /// # Examples 129 | /// 130 | /// ```rust 131 | /// # extern crate hdwallet; 132 | /// use hdwallet::{ExtendedPrivKey, ExtendedPubKey, KeyIndex}; 133 | /// use rand; 134 | /// 135 | /// let mut rng = rand::thread_rng(); 136 | /// let priv_key = ExtendedPrivKey::random(&mut rng).unwrap(); 137 | /// let pub_key = ExtendedPubKey::from_private_key(&priv_key); 138 | /// 139 | /// // Public hardened child key derivation from parent public key is impossible 140 | /// let hardened_key_index = KeyIndex::hardened_from_normalize_index(0).unwrap(); 141 | /// assert!(pub_key.derive_public_key(hardened_key_index).is_err()); 142 | /// 143 | /// // Derive public normal child key 144 | /// let normal_key_index = KeyIndex::Normal(0); 145 | /// assert!(pub_key.derive_public_key(normal_key_index).is_ok()); 146 | /// ``` 147 | #[derive(Debug, Clone, PartialEq, Eq)] 148 | pub struct ExtendedPubKey { 149 | pub public_key: PublicKey, 150 | pub chain_code: ChainCode, 151 | } 152 | 153 | impl ExtendedPubKey { 154 | /// Derive public normal child key from ExtendedPubKey, 155 | /// will return error if key_index is a hardened key. 156 | pub fn derive_public_key(&self, key_index: KeyIndex) -> Result { 157 | if !key_index.is_valid() { 158 | return Err(Error::KeyIndexOutOfRange); 159 | } 160 | 161 | let index = match key_index { 162 | KeyIndex::Normal(i) => i, 163 | KeyIndex::Hardened(_) => return Err(Error::KeyIndexOutOfRange), 164 | }; 165 | 166 | let signature = { 167 | let signing_key = Key::new(HMAC_SHA512, &self.chain_code); 168 | let mut h = Context::with_key(&signing_key); 169 | h.update(&self.public_key.serialize()); 170 | h.update(&index.to_be_bytes()); 171 | h.sign() 172 | }; 173 | let sig_bytes = signature.as_ref(); 174 | let (key, chain_code) = sig_bytes.split_at(sig_bytes.len() / 2); 175 | let private_key = SecretKey::from_slice(key)?; 176 | let public_key = self.public_key; 177 | let public_key = public_key.add_exp_tweak(&*SECP256K1_VERIFY_ONLY, &private_key.into())?; 178 | Ok(ExtendedPubKey { 179 | public_key, 180 | chain_code: chain_code.to_vec(), 181 | }) 182 | } 183 | 184 | /// ExtendedPubKey from ExtendedPrivKey 185 | pub fn from_private_key(extended_key: &ExtendedPrivKey) -> Self { 186 | let public_key = 187 | PublicKey::from_secret_key(&*SECP256K1_SIGN_ONLY, &extended_key.private_key); 188 | ExtendedPubKey { 189 | public_key, 190 | chain_code: extended_key.chain_code.clone(), 191 | } 192 | } 193 | } 194 | 195 | impl Serialize> for ExtendedPrivKey { 196 | fn serialize(&self) -> Vec { 197 | let mut buf = self.private_key[..].to_vec(); 198 | buf.extend(&self.chain_code); 199 | buf 200 | } 201 | } 202 | impl Deserialize<&[u8], Error> for ExtendedPrivKey { 203 | fn deserialize(data: &[u8]) -> Result { 204 | let private_key = SecretKey::from_slice(&data[..32])?; 205 | let chain_code = data[32..].to_vec(); 206 | Ok(ExtendedPrivKey { 207 | private_key, 208 | chain_code, 209 | }) 210 | } 211 | } 212 | 213 | impl Serialize> for ExtendedPubKey { 214 | fn serialize(&self) -> Vec { 215 | let mut buf = self.public_key.serialize().to_vec(); 216 | buf.extend(&self.chain_code); 217 | buf 218 | } 219 | } 220 | impl Deserialize<&[u8], Error> for ExtendedPubKey { 221 | fn deserialize(data: &[u8]) -> Result { 222 | let public_key = PublicKey::from_slice(&data[..33])?; 223 | let chain_code = data[33..].to_vec(); 224 | Ok(ExtendedPubKey { 225 | public_key, 226 | chain_code, 227 | }) 228 | } 229 | } 230 | 231 | #[cfg(test)] 232 | mod tests { 233 | use super::{ExtendedPrivKey, ExtendedPubKey, KeyIndex}; 234 | use crate::traits::{Deserialize, Serialize}; 235 | use rand; 236 | 237 | fn fetch_random_key() -> ExtendedPrivKey { 238 | let mut rng = rand::thread_rng(); 239 | loop { 240 | if let Ok(key) = ExtendedPrivKey::random(&mut rng) { 241 | return key; 242 | } 243 | } 244 | } 245 | 246 | #[test] 247 | fn random_extended_priv_key() { 248 | let mut rng = rand::thread_rng(); 249 | for _ in 0..10 { 250 | if ExtendedPrivKey::random(&mut rng).is_ok() { 251 | return; 252 | } 253 | } 254 | panic!("can't generate valid ExtendedPrivKey"); 255 | } 256 | 257 | #[test] 258 | fn random_seed_not_empty() { 259 | assert_ne!( 260 | fetch_random_key(), 261 | ExtendedPrivKey::with_seed(&[]).expect("privkey") 262 | ); 263 | } 264 | 265 | #[test] 266 | fn extended_priv_key_derive_child_priv_key() { 267 | let master_key = fetch_random_key(); 268 | master_key 269 | .derive_private_key(KeyIndex::hardened_from_normalize_index(0).unwrap()) 270 | .expect("hardended_key"); 271 | master_key 272 | .derive_private_key(KeyIndex::Normal(0)) 273 | .expect("normal_key"); 274 | } 275 | 276 | #[test] 277 | fn extended_pub_key_derive_child_pub_key() { 278 | let parent_priv_key = fetch_random_key(); 279 | let child_pub_key_from_child_priv_key = { 280 | let child_priv_key = parent_priv_key 281 | .derive_private_key(KeyIndex::Normal(0)) 282 | .expect("hardended_key"); 283 | ExtendedPubKey::from_private_key(&child_priv_key) 284 | }; 285 | let child_pub_key_from_parent_pub_key = { 286 | let parent_pub_key = ExtendedPubKey::from_private_key(&parent_priv_key); 287 | parent_pub_key 288 | .derive_public_key(KeyIndex::Normal(0)) 289 | .expect("public key") 290 | }; 291 | assert_eq!( 292 | child_pub_key_from_child_priv_key, 293 | child_pub_key_from_parent_pub_key 294 | ) 295 | } 296 | 297 | #[test] 298 | fn priv_key_serialize_deserialize() { 299 | let key = fetch_random_key(); 300 | let buf = key.serialize(); 301 | assert_eq!(ExtendedPrivKey::deserialize(&buf).expect("de"), key); 302 | } 303 | 304 | #[test] 305 | fn pub_key_serialize_deserialize() { 306 | let key = ExtendedPubKey::from_private_key(&fetch_random_key()); 307 | let buf = key.serialize(); 308 | assert_eq!(ExtendedPubKey::deserialize(&buf).expect("de"), key); 309 | } 310 | } 311 | -------------------------------------------------------------------------------- /src/extended_key/key_index.rs: -------------------------------------------------------------------------------- 1 | use crate::error::Error; 2 | 3 | const HARDENED_KEY_START_INDEX: u32 = 2_147_483_648; // 2 ** 31 4 | 5 | /// KeyIndex indicates the key type and index of a child key. 6 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] 7 | pub enum KeyIndex { 8 | /// Normal key, index range is from 0 to 2 ** 31 - 1 9 | Normal(u32), 10 | /// Hardened key, index range is from 2 ** 31 to 2 ** 32 - 1 11 | Hardened(u32), 12 | } 13 | 14 | impl KeyIndex { 15 | /// Return raw index value 16 | pub fn raw_index(self) -> u32 { 17 | match self { 18 | KeyIndex::Normal(i) => i, 19 | KeyIndex::Hardened(i) => i, 20 | } 21 | } 22 | 23 | /// Return normalize index, it will return index subtract 2 ** 31 for hardended key. 24 | /// 25 | /// # Examples 26 | /// 27 | /// ```rust 28 | /// # extern crate hdwallet; 29 | /// use hdwallet::KeyIndex; 30 | /// 31 | /// assert_eq!(KeyIndex::Normal(0).normalize_index(), 0); 32 | /// assert_eq!(KeyIndex::Hardened(2_147_483_648).normalize_index(), 0); 33 | /// ``` 34 | pub fn normalize_index(self) -> u32 { 35 | match self { 36 | KeyIndex::Normal(i) => i, 37 | KeyIndex::Hardened(i) => i - HARDENED_KEY_START_INDEX, 38 | } 39 | } 40 | 41 | /// Check index range. 42 | /// 43 | /// # Examples 44 | /// 45 | /// ```rust 46 | /// # extern crate hdwallet; 47 | /// use hdwallet::KeyIndex; 48 | /// 49 | /// assert!(KeyIndex::Normal(0).is_valid()); 50 | /// assert!(!KeyIndex::Normal(2_147_483_648).is_valid()); 51 | /// assert!(KeyIndex::Hardened(2_147_483_648).is_valid()); 52 | /// ``` 53 | pub fn is_valid(self) -> bool { 54 | match self { 55 | KeyIndex::Normal(i) => i < HARDENED_KEY_START_INDEX, 56 | KeyIndex::Hardened(i) => i >= HARDENED_KEY_START_INDEX, 57 | } 58 | } 59 | 60 | /// Generate Hardened KeyIndex from normalize index value. 61 | /// 62 | /// # Examples 63 | /// 64 | /// ```rust 65 | /// # extern crate hdwallet; 66 | /// use hdwallet::KeyIndex; 67 | /// 68 | /// // hardended key from zero 69 | /// let hardened_index_zero = KeyIndex::hardened_from_normalize_index(0).unwrap(); 70 | /// assert_eq!(hardened_index_zero, KeyIndex::Hardened(2_147_483_648)); 71 | /// // also allow raw index for convernient 72 | /// let hardened_index_zero = KeyIndex::hardened_from_normalize_index(2_147_483_648).unwrap(); 73 | /// assert_eq!(hardened_index_zero, KeyIndex::Hardened(2_147_483_648)); 74 | /// ``` 75 | pub fn hardened_from_normalize_index(i: u32) -> Result { 76 | if i < HARDENED_KEY_START_INDEX { 77 | Ok(KeyIndex::Hardened(HARDENED_KEY_START_INDEX + i)) 78 | } else { 79 | Ok(KeyIndex::Hardened(i)) 80 | } 81 | } 82 | 83 | /// Generate KeyIndex from raw index value. 84 | /// 85 | /// # Examples 86 | /// 87 | /// ```rust 88 | /// # extern crate hdwallet; 89 | /// use hdwallet::KeyIndex; 90 | /// 91 | /// let normal_key = KeyIndex::from_index(0).unwrap(); 92 | /// assert_eq!(normal_key, KeyIndex::Normal(0)); 93 | /// let hardened_key = KeyIndex::from_index(2_147_483_648).unwrap(); 94 | /// assert_eq!(hardened_key, KeyIndex::Hardened(2_147_483_648)); 95 | /// ``` 96 | pub fn from_index(i: u32) -> Result { 97 | if i < HARDENED_KEY_START_INDEX { 98 | Ok(KeyIndex::Normal(i)) 99 | } else { 100 | Ok(KeyIndex::Hardened(i)) 101 | } 102 | } 103 | } 104 | 105 | impl From for KeyIndex { 106 | fn from(index: u32) -> Self { 107 | KeyIndex::from_index(index).expect("KeyIndex") 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/key_chain.rs: -------------------------------------------------------------------------------- 1 | pub mod chain_path; 2 | 3 | use crate::{error::Error, ChainPath, ChainPathError, ExtendedPrivKey, KeyIndex, SubPath}; 4 | 5 | /// KeyChain derivation info 6 | #[derive(Debug, Clone, PartialEq, Eq)] 7 | pub struct Derivation { 8 | /// depth, 0 if it is master key 9 | pub depth: u8, 10 | /// parent key 11 | pub parent_key: Option, 12 | /// key_index which used with parent key to derive this key 13 | pub key_index: Option, 14 | } 15 | 16 | impl Derivation { 17 | pub fn master() -> Self { 18 | Derivation { 19 | depth: 0, 20 | parent_key: None, 21 | key_index: None, 22 | } 23 | } 24 | } 25 | 26 | impl Default for Derivation { 27 | fn default() -> Self { 28 | Derivation::master() 29 | } 30 | } 31 | 32 | /// KeyChain is used for derivation HDKey from master_key and chain_path. 33 | /// 34 | /// # Examples 35 | /// 36 | /// ```rust 37 | /// # extern crate hdwallet; 38 | /// use hdwallet::{KeyChain, DefaultKeyChain, ChainPath, ExtendedPrivKey}; 39 | /// use rand; 40 | /// 41 | /// let mut rng = rand::thread_rng(); 42 | /// let master_key = ExtendedPrivKey::random(&mut rng).unwrap(); 43 | /// let key_chain = DefaultKeyChain::new(master_key); 44 | /// let child_key = key_chain.derive_private_key("m/0H/1".into()).unwrap(); 45 | /// assert_eq!(child_key, key_chain.derive_private_key("m/0'/1".into()).unwrap()); 46 | /// dbg!(child_key); 47 | /// ``` 48 | pub trait KeyChain { 49 | fn derive_private_key( 50 | &self, 51 | chain_path: ChainPath, 52 | ) -> Result<(ExtendedPrivKey, Derivation), Error>; 53 | } 54 | 55 | pub struct DefaultKeyChain { 56 | master_key: ExtendedPrivKey, 57 | } 58 | 59 | impl DefaultKeyChain { 60 | pub fn new(master_key: ExtendedPrivKey) -> Self { 61 | DefaultKeyChain { master_key } 62 | } 63 | } 64 | 65 | impl KeyChain for DefaultKeyChain { 66 | fn derive_private_key( 67 | &self, 68 | chain_path: ChainPath, 69 | ) -> Result<(ExtendedPrivKey, Derivation), Error> { 70 | let mut iter = chain_path.iter(); 71 | // chain_path must start with root 72 | if iter.next() != Some(Ok(SubPath::Root)) { 73 | return Err(ChainPathError::Invalid.into()); 74 | } 75 | let mut key = self.master_key.clone(); 76 | let mut depth = 0; 77 | let mut parent_key = None; 78 | let mut key_index = None; 79 | for sub_path in iter { 80 | match sub_path? { 81 | SubPath::Child(child_key_index) => { 82 | depth += 1; 83 | key_index = Some(child_key_index); 84 | let child_key = key.derive_private_key(child_key_index)?; 85 | parent_key = Some(key); 86 | key = child_key; 87 | } 88 | _ => return Err(ChainPathError::Invalid.into()), 89 | } 90 | } 91 | Ok(( 92 | key, 93 | Derivation { 94 | depth, 95 | parent_key, 96 | key_index, 97 | }, 98 | )) 99 | } 100 | } 101 | 102 | #[cfg(test)] 103 | mod tests { 104 | use super::*; 105 | use crate::{traits::Serialize, ExtendedPubKey}; 106 | use base58::ToBase58; 107 | use ring::digest; 108 | use ripemd160::{Digest, Ripemd160}; 109 | 110 | #[derive(Debug, Clone, PartialEq, Eq)] 111 | pub enum ExtendedKey { 112 | PrivKey(ExtendedPrivKey), 113 | PubKey(ExtendedPubKey), 114 | } 115 | 116 | #[allow(dead_code)] 117 | #[derive(Clone, Copy, Debug)] 118 | enum Network { 119 | MainNet, 120 | TestNet, 121 | } 122 | 123 | #[derive(Clone, Debug)] 124 | struct BitcoinKey { 125 | pub network: Network, 126 | pub depth: u8, 127 | pub parent_key: Option, 128 | pub key_index: Option, 129 | pub key: ExtendedKey, 130 | } 131 | 132 | impl BitcoinKey { 133 | fn version_bytes(&self) -> Vec { 134 | let hex_str = match self.network { 135 | Network::MainNet => match self.key { 136 | ExtendedKey::PrivKey(..) => "0x0488ADE4", 137 | ExtendedKey::PubKey(..) => "0x0488B21E", 138 | }, 139 | Network::TestNet => match self.key { 140 | ExtendedKey::PrivKey(..) => "0x04358394", 141 | ExtendedKey::PubKey(..) => "0x043587CF", 142 | }, 143 | }; 144 | from_hex(hex_str) 145 | } 146 | 147 | fn parent_fingerprint(&self) -> Vec { 148 | match self.parent_key { 149 | Some(ref key) => { 150 | let pubkey = ExtendedPubKey::from_private_key(key); 151 | let buf = digest::digest(&digest::SHA256, &pubkey.public_key.serialize()); 152 | let mut hasher = Ripemd160::new(); 153 | hasher.input(&buf.as_ref()); 154 | hasher.result()[0..4].to_vec() 155 | } 156 | None => vec![0; 4], 157 | } 158 | } 159 | 160 | fn public_key(&self) -> BitcoinKey { 161 | match self.key { 162 | ExtendedKey::PrivKey(ref key) => { 163 | let pubkey = ExtendedPubKey::from_private_key(key); 164 | let mut bitcoin_key = self.clone(); 165 | bitcoin_key.key = ExtendedKey::PubKey(pubkey); 166 | bitcoin_key 167 | } 168 | ExtendedKey::PubKey(..) => self.clone(), 169 | } 170 | } 171 | } 172 | 173 | impl Serialize for BitcoinKey { 174 | fn serialize(&self) -> String { 175 | let mut buf: Vec = Vec::with_capacity(112); 176 | buf.extend_from_slice(&self.version_bytes()); 177 | buf.extend_from_slice(&self.depth.to_be_bytes()); 178 | buf.extend_from_slice(&self.parent_fingerprint()); 179 | match self.key_index { 180 | Some(key_index) => { 181 | buf.extend_from_slice(&key_index.raw_index().to_be_bytes()); 182 | } 183 | None => buf.extend_from_slice(&[0; 4]), 184 | } 185 | match self.key { 186 | ExtendedKey::PrivKey(ref key) => { 187 | buf.extend_from_slice(&key.chain_code); 188 | buf.extend_from_slice(&[0]); 189 | buf.extend_from_slice(&key.private_key[..]); 190 | } 191 | ExtendedKey::PubKey(ref key) => { 192 | buf.extend_from_slice(&key.chain_code); 193 | buf.extend_from_slice(&key.public_key.serialize()); 194 | } 195 | } 196 | assert_eq!(buf.len(), 78); 197 | 198 | let check_sum = { 199 | let buf = digest::digest(&digest::SHA256, &buf); 200 | digest::digest(&digest::SHA256, buf.as_ref()) 201 | }; 202 | 203 | buf.extend_from_slice(&check_sum.as_ref()[0..4]); 204 | (&buf).to_base58() 205 | } 206 | } 207 | 208 | fn from_hex(hex_string: &str) -> Vec { 209 | if let Some(hex_string) = hex_string.strip_prefix("0x") { 210 | hex::decode(hex_string).expect("decode") 211 | } else { 212 | hex::decode(hex_string).expect("decode") 213 | } 214 | } 215 | 216 | #[test] 217 | fn test_bip32_vector_1() { 218 | let seed = from_hex("000102030405060708090a0b0c0d0e0f"); 219 | let key_chain = 220 | DefaultKeyChain::new(ExtendedPrivKey::with_seed(&seed).expect("master key")); 221 | for (chain_path, hex_priv_key, hex_pub_key) in &[ 222 | ("m", "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8"), 223 | ("m/0H", "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7", "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw"), 224 | ("m/0H/1", "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs", "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ"), 225 | ("m/0H/1/2H", "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM", "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5"), 226 | ("m/0H/1/2H/2", "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334", "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV"), 227 | ("m/0H/1/2H/2/1000000000", "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76", "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy") 228 | ] { 229 | let (key, derivation) = key_chain.derive_private_key(ChainPath::from(*chain_path)).expect("fetch key"); 230 | let priv_key = BitcoinKey{ 231 | network: Network::MainNet, 232 | depth: derivation.depth, 233 | parent_key: derivation.parent_key, 234 | key_index: derivation.key_index, 235 | key: ExtendedKey::PrivKey(key), 236 | }; 237 | assert_eq!(&priv_key.serialize(), hex_priv_key); 238 | assert_eq!(&priv_key.public_key().serialize(), hex_pub_key); 239 | } 240 | } 241 | 242 | #[test] 243 | fn test_bip32_vector_2() { 244 | let seed = from_hex("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542"); 245 | let key_chain = 246 | DefaultKeyChain::new(ExtendedPrivKey::with_seed(&seed).expect("master key")); 247 | for (chain_path, hex_priv_key, hex_pub_key) in &[ 248 | ("m", "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB"), 249 | ("m/0", "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt", "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH"), 250 | ("m/0/2147483647H", "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9", "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a"), 251 | ("m/0/2147483647H/1", "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef", "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon"), 252 | ("m/0/2147483647H/1/2147483646H", "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc", "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL"), 253 | ("m/0/2147483647H/1/2147483646H/2", "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j", "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt") 254 | ] { 255 | let (key, derivation) = key_chain.derive_private_key(ChainPath::from(*chain_path)).expect("fetch key"); 256 | let priv_key = BitcoinKey{ 257 | network: Network::MainNet, 258 | depth: derivation.depth, 259 | parent_key: derivation.parent_key, 260 | key_index: derivation.key_index, 261 | key: ExtendedKey::PrivKey(key), 262 | }; 263 | assert_eq!(&priv_key.serialize(), hex_priv_key); 264 | assert_eq!(&priv_key.public_key().serialize(), hex_pub_key); 265 | } 266 | } 267 | 268 | #[test] 269 | fn test_bip32_vector_3() { 270 | let seed = from_hex("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be"); 271 | let key_chain = 272 | DefaultKeyChain::new(ExtendedPrivKey::with_seed(&seed).expect("master key")); 273 | for (chain_path, hex_priv_key, hex_pub_key) in &[ 274 | ("m", "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6", "xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13"), 275 | ("m/0H", "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L", "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y") 276 | ] { 277 | let (key, derivation) = key_chain.derive_private_key(ChainPath::from(*chain_path)).expect("fetch key"); 278 | let priv_key = BitcoinKey{ 279 | network: Network::MainNet, 280 | depth: derivation.depth, 281 | parent_key: derivation.parent_key, 282 | key_index: derivation.key_index, 283 | key: ExtendedKey::PrivKey(key), 284 | }; 285 | assert_eq!(&priv_key.serialize(), hex_priv_key); 286 | assert_eq!(&priv_key.public_key().serialize(), hex_pub_key); 287 | } 288 | } 289 | } 290 | -------------------------------------------------------------------------------- /src/key_chain/chain_path.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | 3 | use crate::KeyIndex; 4 | use std::borrow::Cow; 5 | use std::fmt; 6 | 7 | const MASTER_SYMBOL: &str = "m"; 8 | const HARDENED_SYMBOLS: [&str; 2] = ["H", "'"]; 9 | const SEPARATOR: char = '/'; 10 | 11 | #[derive(Error, Clone, Debug, Copy, PartialEq, Eq)] 12 | pub enum Error { 13 | #[error("Invalid key path")] 14 | Invalid, 15 | #[error("blank")] 16 | Blank, 17 | #[error("Key index is out of range")] 18 | KeyIndexOutOfRange, 19 | } 20 | 21 | /// ChainPath is used to describe BIP-32 KeyChain path. 22 | /// 23 | /// # Examples 24 | /// 25 | /// ``` rust 26 | /// # extern crate hdwallet; 27 | /// use hdwallet::{ChainPath, SubPath, KeyIndex}; 28 | /// 29 | /// let chain_path = ChainPath::from("m/2147483649H/1".to_string()) 30 | /// .iter() 31 | /// .collect::, _>>() 32 | /// .unwrap(); 33 | /// assert_eq!(chain_path, vec![ 34 | /// SubPath::Root, 35 | /// SubPath::Child(KeyIndex::hardened_from_normalize_index(1).unwrap()), 36 | /// SubPath::Child(KeyIndex::Normal(1)) 37 | /// ]); 38 | /// ``` 39 | #[derive(Debug, PartialEq, Eq)] 40 | pub struct ChainPath<'a> { 41 | path: Cow<'a, str>, 42 | } 43 | 44 | impl<'a> ChainPath<'a> { 45 | pub fn new(path: S) -> Self 46 | where 47 | S: Into>, 48 | { 49 | Self { path: path.into() } 50 | } 51 | 52 | /// An SubPath iterator over the ChainPath from Root to child keys. 53 | pub fn iter(&self) -> impl Iterator> + '_ { 54 | Iter(self.path.split_terminator(SEPARATOR)) 55 | } 56 | 57 | pub fn into_string(self) -> String { 58 | self.path.into() 59 | } 60 | 61 | /// Convert ChainPath to &str represent format 62 | fn to_string(&self) -> &str { 63 | &self.path 64 | } 65 | } 66 | 67 | #[derive(Debug, PartialEq, Eq)] 68 | pub enum SubPath { 69 | Root, 70 | Child(KeyIndex), 71 | } 72 | 73 | pub struct Iter<'a, I: Iterator>(I); 74 | 75 | impl<'a, I: Iterator> Iterator for Iter<'a, I> { 76 | type Item = Result; 77 | 78 | fn next(&mut self) -> Option { 79 | self.0.next().map(|sub_path| { 80 | if sub_path == MASTER_SYMBOL { 81 | return Ok(SubPath::Root); 82 | } 83 | if sub_path.is_empty() { 84 | return Err(Error::Blank); 85 | } 86 | let last_char = &sub_path[(sub_path.len() - 1)..]; 87 | let is_hardened = HARDENED_SYMBOLS.contains(&last_char); 88 | let key_index = { 89 | let key_index_result = if is_hardened { 90 | sub_path[..sub_path.len() - 1] 91 | .parse::() 92 | .map_err(|_| Error::Invalid) 93 | .and_then(|index| { 94 | KeyIndex::hardened_from_normalize_index(index) 95 | .map_err(|_| Error::KeyIndexOutOfRange) 96 | }) 97 | } else { 98 | sub_path[..] 99 | .parse::() 100 | .map_err(|_| Error::Invalid) 101 | .and_then(|index| { 102 | KeyIndex::from_index(index).map_err(|_| Error::KeyIndexOutOfRange) 103 | }) 104 | }; 105 | key_index_result? 106 | }; 107 | Ok(SubPath::Child(key_index)) 108 | }) 109 | } 110 | } 111 | 112 | impl<'a> From for ChainPath<'a> { 113 | fn from(path: String) -> Self { 114 | ChainPath::new(path) 115 | } 116 | } 117 | 118 | impl<'a> From<&'a str> for ChainPath<'a> { 119 | fn from(path: &'a str) -> Self { 120 | ChainPath::new(path) 121 | } 122 | } 123 | 124 | impl fmt::Display for ChainPath<'_> { 125 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 126 | write!(f, "{}", self.to_string()) 127 | } 128 | } 129 | 130 | #[cfg(test)] 131 | mod tests { 132 | use super::*; 133 | 134 | #[test] 135 | fn test_chain_path() { 136 | assert_eq!( 137 | ChainPath::from("m") 138 | .iter() 139 | .collect::, _>>() 140 | .unwrap(), 141 | vec![SubPath::Root] 142 | ); 143 | assert_eq!( 144 | ChainPath::from("m/1") 145 | .iter() 146 | .collect::, _>>() 147 | .unwrap(), 148 | vec![SubPath::Root, SubPath::Child(KeyIndex::Normal(1))], 149 | ); 150 | assert_eq!( 151 | ChainPath::from("m/2147483649H/1") 152 | .iter() 153 | .collect::, _>>() 154 | .unwrap(), 155 | vec![ 156 | SubPath::Root, 157 | SubPath::Child(KeyIndex::hardened_from_normalize_index(1).unwrap()), 158 | SubPath::Child(KeyIndex::Normal(1)) 159 | ], 160 | ); 161 | // alternative hardened key represent 162 | assert_eq!( 163 | ChainPath::from("m/2147483649'/1") 164 | .iter() 165 | .collect::, _>>() 166 | .unwrap(), 167 | vec![ 168 | SubPath::Root, 169 | SubPath::Child(KeyIndex::hardened_from_normalize_index(1).unwrap()), 170 | SubPath::Child(KeyIndex::Normal(1)) 171 | ], 172 | ); 173 | // from invalid string 174 | assert!(ChainPath::from("m/2147483649h/1") 175 | .iter() 176 | .collect::, _>>() 177 | .is_err()); 178 | assert!(ChainPath::from("/2147483649H/1") 179 | .iter() 180 | .collect::, _>>() 181 | .is_err()); 182 | assert!(ChainPath::from("a") 183 | .iter() 184 | .collect::, _>>() 185 | .is_err()); 186 | } 187 | 188 | #[test] 189 | fn test_chain_path_new() { 190 | // new from string slice 191 | assert_eq!("m/1", ChainPath::new("m/1").to_string()); 192 | // new from a runtime String 193 | assert_eq!("m/1", ChainPath::new(String::from("m/1")).to_string()); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! HD wallet(BIP-32) related key derivation utilities. 2 | //! 3 | //! This crate is build upon secp256k1 crate, only provide BIP-32 related features, for signatures 4 | //! see the [secp256k1 documentation](https://docs.rs/secp256k1). 5 | //! 6 | //! * [`ChainPath`] and [`KeyChain`] used to derive HD wallet keys. 7 | //! * [`Derivation`] contains key derivation info. 8 | //! * [`ExtendedPrivKey`] and [`ExtendedPubKey`] according to BIP-32 described represents a key 9 | //! that can derives child keys. 10 | //! * [`KeyIndex`] indicate index and type in a child key derivation (Normal key or Hardened key). 11 | //! * [`Error`] errors. 12 | //! 13 | //! `hdwallet` crate itself is a key derivation framework. 14 | //! Check `hdwallet-bitcoin` if you want to derive bitcoin keys, and you can find or submit other crypto 15 | //! currencies support on [hdwallet homepage](https://github.com/jjyr/hdwallet). 16 | //! 17 | 18 | #[macro_use] 19 | extern crate lazy_static; 20 | 21 | pub mod error; 22 | pub mod extended_key; 23 | pub mod key_chain; 24 | pub mod traits; 25 | 26 | pub use crate::extended_key::{key_index::KeyIndex, ExtendedPrivKey, ExtendedPubKey, KeySeed}; 27 | pub use crate::key_chain::{ 28 | chain_path::{ChainPath, Error as ChainPathError, SubPath}, 29 | DefaultKeyChain, Derivation, KeyChain, 30 | }; 31 | 32 | // re-exports 33 | pub use rand_core; 34 | pub use ring; 35 | pub use secp256k1; 36 | -------------------------------------------------------------------------------- /src/traits.rs: -------------------------------------------------------------------------------- 1 | pub trait Serialize { 2 | fn serialize(&self) -> T; 3 | } 4 | 5 | pub trait Deserialize: Sized { 6 | fn deserialize(t: T) -> Result; 7 | } 8 | --------------------------------------------------------------------------------