2016-06-24 19:15:57 +00:00
|
|
|
// Rust Bitcoin Library
|
|
|
|
// Written in 2014 by
|
|
|
|
// Andrew Poelstra <apoelstra@wpsoftware.net>
|
|
|
|
// To the extent possible under law, the author(s) have dedicated all
|
|
|
|
// copyright and related and neighboring rights to this software to
|
|
|
|
// the public domain worldwide. This software is distributed without
|
|
|
|
// any warranty.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the CC0 Public Domain Dedication
|
|
|
|
// along with this software.
|
|
|
|
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
|
|
|
|
//
|
|
|
|
|
2018-08-08 21:38:50 +00:00
|
|
|
//! BIP32 Implementation
|
2016-06-24 19:15:57 +00:00
|
|
|
//!
|
|
|
|
//! Implementation of BIP32 hierarchical deterministic wallets, as defined
|
|
|
|
//! at https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
|
|
|
|
|
|
|
|
use std::default::Default;
|
|
|
|
use std::io::Cursor;
|
2016-06-24 19:45:42 +00:00
|
|
|
use std::{error, fmt};
|
2018-03-09 17:53:20 +00:00
|
|
|
use std::str::FromStr;
|
2016-06-24 19:15:57 +00:00
|
|
|
use serde::{Serialize, Deserialize, Serializer, Deserializer};
|
|
|
|
|
2018-03-09 17:53:20 +00:00
|
|
|
use byteorder::{BigEndian, ByteOrder, ReadBytesExt};
|
2016-06-24 19:15:57 +00:00
|
|
|
use crypto::digest::Digest;
|
|
|
|
use crypto::hmac::Hmac;
|
|
|
|
use crypto::mac::Mac;
|
|
|
|
use crypto::ripemd160::Ripemd160;
|
|
|
|
use secp256k1::key::{PublicKey, SecretKey};
|
|
|
|
use secp256k1::{self, Secp256k1};
|
|
|
|
|
|
|
|
use network::constants::Network;
|
|
|
|
use util::base58;
|
|
|
|
|
2018-03-20 16:05:33 +00:00
|
|
|
#[cfg(feature="fuzztarget")] use util::sha2::{Sha256, Sha512};
|
|
|
|
#[cfg(not(feature="fuzztarget"))] use crypto::sha2::{Sha256, Sha512};
|
|
|
|
|
2016-06-24 19:15:57 +00:00
|
|
|
/// A chain code
|
|
|
|
pub struct ChainCode([u8; 32]);
|
|
|
|
impl_array_newtype!(ChainCode, u8, 32);
|
|
|
|
impl_array_newtype_show!(ChainCode);
|
|
|
|
impl_array_newtype_encodable!(ChainCode, u8, 32);
|
|
|
|
|
|
|
|
/// A fingerprint
|
|
|
|
pub struct Fingerprint([u8; 4]);
|
|
|
|
impl_array_newtype!(Fingerprint, u8, 4);
|
|
|
|
impl_array_newtype_show!(Fingerprint);
|
|
|
|
impl_array_newtype_encodable!(Fingerprint, u8, 4);
|
|
|
|
|
|
|
|
impl Default for Fingerprint {
|
|
|
|
fn default() -> Fingerprint { Fingerprint([0, 0, 0, 0]) }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Extended private key
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
|
|
|
pub struct ExtendedPrivKey {
|
|
|
|
/// The network this key is to be used on
|
|
|
|
pub network: Network,
|
|
|
|
/// How many derivations this key is from the master (which is 0)
|
|
|
|
pub depth: u8,
|
|
|
|
/// Fingerprint of the parent key (0 for master)
|
|
|
|
pub parent_fingerprint: Fingerprint,
|
|
|
|
/// Child number of the key used to derive from parent (0 for master)
|
|
|
|
pub child_number: ChildNumber,
|
|
|
|
/// Secret key
|
|
|
|
pub secret_key: SecretKey,
|
|
|
|
/// Chain code
|
|
|
|
pub chain_code: ChainCode
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Extended public key
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
|
|
|
pub struct ExtendedPubKey {
|
|
|
|
/// The network this key is to be used on
|
|
|
|
pub network: Network,
|
|
|
|
/// How many derivations this key is from the master (which is 0)
|
|
|
|
pub depth: u8,
|
|
|
|
/// Fingerprint of the parent key
|
|
|
|
pub parent_fingerprint: Fingerprint,
|
|
|
|
/// Child number of the key used to derive from parent (0 for master)
|
|
|
|
pub child_number: ChildNumber,
|
|
|
|
/// Public key
|
|
|
|
pub public_key: PublicKey,
|
|
|
|
/// Chain code
|
|
|
|
pub chain_code: ChainCode
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A child number for a derived key
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
|
|
|
pub enum ChildNumber {
|
2018-08-11 19:30:38 +00:00
|
|
|
/// Non-hardened key
|
|
|
|
Normal {
|
|
|
|
/// Key index, within [0, 2^31 - 1]
|
|
|
|
index: u32
|
|
|
|
},
|
|
|
|
/// Hardened key
|
|
|
|
Hardened {
|
|
|
|
/// Key index, within [0, 2^31 - 1]
|
|
|
|
index: u32
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ChildNumber {
|
2018-08-11 20:29:10 +00:00
|
|
|
/// Create a [`Normal`] from an index, panics if the index is not within
|
|
|
|
/// [0, 2^31 - 1].
|
|
|
|
///
|
|
|
|
/// [`Normal`]: #variant.Normal
|
2018-08-11 19:30:38 +00:00
|
|
|
pub fn from_normal_idx(index: u32) -> Self {
|
|
|
|
assert_eq!(index & (1 << 31), 0, "ChildNumber indices have to be within [0, 2^31 - 1], is: {}", index);
|
|
|
|
ChildNumber::Normal { index: index }
|
|
|
|
}
|
|
|
|
|
2018-08-11 20:29:10 +00:00
|
|
|
/// Create a [`Hardened`] from an index, panics if the index is not within
|
|
|
|
/// [0, 2^31 - 1].
|
|
|
|
///
|
|
|
|
/// [`Hardened`]: #variant.Hardened
|
2018-08-11 19:30:38 +00:00
|
|
|
pub fn from_hardened_idx(index: u32) -> Self {
|
|
|
|
assert_eq!(index & (1 << 31), 0, "ChildNumber indices have to be within [0, 2^31 - 1], is: {}", index);
|
|
|
|
ChildNumber::Hardened { index: index }
|
|
|
|
}
|
2018-08-11 20:29:10 +00:00
|
|
|
|
|
|
|
/// Returns `true` if the child number is a [`Normal`] value.
|
|
|
|
///
|
|
|
|
/// [`Normal`]: #variant.Normal
|
|
|
|
pub fn is_normal(&self) -> bool {
|
|
|
|
!self.is_hardened()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `true` if the child number is a [`Hardened`] value.
|
|
|
|
///
|
|
|
|
/// [`Hardened`]: #variant.Hardened
|
|
|
|
pub fn is_hardened(&self) -> bool {
|
|
|
|
match *self {
|
|
|
|
ChildNumber::Hardened {..} => true,
|
|
|
|
ChildNumber::Normal {..} => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-08 06:00:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl From<u32> for ChildNumber {
|
2018-08-11 19:30:38 +00:00
|
|
|
fn from(number: u32) -> Self {
|
|
|
|
if number & (1 << 31) != 0 {
|
|
|
|
ChildNumber::Hardened { index: number ^ (1 << 31) }
|
2018-08-08 06:00:47 +00:00
|
|
|
} else {
|
2018-08-11 19:30:38 +00:00
|
|
|
ChildNumber::Normal { index: number }
|
2018-08-08 06:00:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<ChildNumber> for u32 {
|
|
|
|
fn from(cnum: ChildNumber) -> Self {
|
|
|
|
match cnum {
|
2018-08-11 19:30:38 +00:00
|
|
|
ChildNumber::Normal { index } => index,
|
|
|
|
ChildNumber::Hardened { index } => index | (1 << 31),
|
2018-08-08 06:00:47 +00:00
|
|
|
}
|
|
|
|
}
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
|
|
|
|
2016-06-24 19:45:42 +00:00
|
|
|
impl fmt::Display for ChildNumber {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match *self {
|
2018-08-11 19:30:38 +00:00
|
|
|
ChildNumber::Hardened { index } => write!(f, "{}'", index),
|
|
|
|
ChildNumber::Normal { index } => write!(f, "{}", index),
|
2016-06-24 19:45:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-24 19:15:57 +00:00
|
|
|
impl Serialize for ChildNumber {
|
2018-08-11 19:30:38 +00:00
|
|
|
fn serialize<S: Serializer>(&self, s: &mut S) -> Result<(), S::Error> {
|
|
|
|
u32::from(*self).serialize(s)
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Deserialize for ChildNumber {
|
2018-08-11 19:30:38 +00:00
|
|
|
fn deserialize<D: Deserializer>(d: &mut D) -> Result<ChildNumber, D::Error> {
|
|
|
|
let n: u32 = Deserialize::deserialize(d)?;
|
|
|
|
|
|
|
|
Ok(ChildNumber::from(n))
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A BIP32 error
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
|
|
|
pub enum Error {
|
|
|
|
/// A pk->pk derivation was attempted on a hardened key
|
|
|
|
CannotDeriveFromHardenedKey,
|
|
|
|
/// A secp256k1 error occured
|
|
|
|
Ecdsa(secp256k1::Error),
|
|
|
|
/// A child number was provided that was out of range
|
|
|
|
InvalidChildNumber(ChildNumber),
|
|
|
|
/// Error creating a master seed --- for application use
|
|
|
|
RngError(String)
|
|
|
|
}
|
|
|
|
|
2016-06-24 19:45:42 +00:00
|
|
|
impl fmt::Display for Error {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match *self {
|
|
|
|
Error::CannotDeriveFromHardenedKey => f.write_str("cannot derive hardened key from public key"),
|
|
|
|
Error::Ecdsa(ref e) => fmt::Display::fmt(e, f),
|
|
|
|
Error::InvalidChildNumber(ref n) => write!(f, "child number {} is invalid", n),
|
|
|
|
Error::RngError(ref s) => write!(f, "rng error {}", s)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl error::Error for Error {
|
|
|
|
fn cause(&self) -> Option<&error::Error> {
|
|
|
|
if let Error::Ecdsa(ref e) = *self {
|
|
|
|
Some(e)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn description(&self) -> &str {
|
|
|
|
match *self {
|
|
|
|
Error::CannotDeriveFromHardenedKey => "cannot derive hardened key from public key",
|
|
|
|
Error::Ecdsa(ref e) => error::Error::description(e),
|
|
|
|
Error::InvalidChildNumber(_) => "child number is invalid",
|
|
|
|
Error::RngError(_) => "rng error"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-24 19:25:47 +00:00
|
|
|
impl From<secp256k1::Error> for Error {
|
|
|
|
fn from(e: secp256k1::Error) -> Error { Error::Ecdsa(e) }
|
|
|
|
}
|
|
|
|
|
2016-06-24 19:15:57 +00:00
|
|
|
impl ExtendedPrivKey {
|
|
|
|
/// Construct a new master key from a seed value
|
|
|
|
pub fn new_master(secp: &Secp256k1, network: Network, seed: &[u8]) -> Result<ExtendedPrivKey, Error> {
|
|
|
|
let mut result = [0; 64];
|
|
|
|
let mut hmac = Hmac::new(Sha512::new(), b"Bitcoin seed");
|
|
|
|
hmac.input(seed);
|
|
|
|
hmac.raw_result(&mut result);
|
|
|
|
|
|
|
|
Ok(ExtendedPrivKey {
|
|
|
|
network: network,
|
|
|
|
depth: 0,
|
|
|
|
parent_fingerprint: Default::default(),
|
2018-08-11 19:30:38 +00:00
|
|
|
child_number: ChildNumber::from_normal_idx(0),
|
2016-06-24 19:15:57 +00:00
|
|
|
secret_key: try!(SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)),
|
|
|
|
chain_code: ChainCode::from(&result[32..])
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a privkey from a path
|
|
|
|
pub fn from_path(secp: &Secp256k1, master: &ExtendedPrivKey, path: &[ChildNumber])
|
|
|
|
-> Result<ExtendedPrivKey, Error> {
|
|
|
|
let mut sk = *master;
|
|
|
|
for &num in path.iter() {
|
|
|
|
sk = try!(sk.ckd_priv(secp, num));
|
|
|
|
}
|
|
|
|
Ok(sk)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Private->Private child key derivation
|
|
|
|
pub fn ckd_priv(&self, secp: &Secp256k1, i: ChildNumber) -> Result<ExtendedPrivKey, Error> {
|
|
|
|
let mut result = [0; 64];
|
|
|
|
let mut hmac = Hmac::new(Sha512::new(), &self.chain_code[..]);
|
|
|
|
let mut be_n = [0; 4];
|
|
|
|
match i {
|
2018-08-11 19:30:38 +00:00
|
|
|
ChildNumber::Normal {..} => {
|
2016-06-24 19:15:57 +00:00
|
|
|
// Non-hardened key: compute public data and use that
|
2018-02-18 15:45:35 +00:00
|
|
|
hmac.input(&PublicKey::from_secret_key(secp, &self.secret_key).unwrap().serialize()[..]);
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
2018-08-11 19:30:38 +00:00
|
|
|
ChildNumber::Hardened {..} => {
|
2016-06-24 19:15:57 +00:00
|
|
|
// Hardened key: use only secret data to prevent public derivation
|
|
|
|
hmac.input(&[0u8]);
|
|
|
|
hmac.input(&self.secret_key[..]);
|
|
|
|
}
|
|
|
|
}
|
2018-08-11 19:30:38 +00:00
|
|
|
BigEndian::write_u32(&mut be_n, u32::from(i));
|
|
|
|
|
2016-06-24 19:15:57 +00:00
|
|
|
hmac.input(&be_n);
|
|
|
|
hmac.raw_result(&mut result);
|
|
|
|
let mut sk = try!(SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa));
|
|
|
|
try!(sk.add_assign(secp, &self.secret_key).map_err(Error::Ecdsa));
|
|
|
|
|
|
|
|
Ok(ExtendedPrivKey {
|
|
|
|
network: self.network,
|
|
|
|
depth: self.depth + 1,
|
|
|
|
parent_fingerprint: self.fingerprint(secp),
|
|
|
|
child_number: i,
|
|
|
|
secret_key: sk,
|
|
|
|
chain_code: ChainCode::from(&result[32..])
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the HASH160 of the chaincode
|
|
|
|
pub fn identifier(&self, secp: &Secp256k1) -> [u8; 20] {
|
|
|
|
let mut sha2_res = [0; 32];
|
|
|
|
let mut ripemd_res = [0; 20];
|
|
|
|
// Compute extended public key
|
|
|
|
let pk = ExtendedPubKey::from_private(secp, self);
|
|
|
|
// Do SHA256 of just the ECDSA pubkey
|
|
|
|
let mut sha2 = Sha256::new();
|
2018-02-18 15:45:35 +00:00
|
|
|
sha2.input(&pk.public_key.serialize()[..]);
|
2016-06-24 19:15:57 +00:00
|
|
|
sha2.result(&mut sha2_res);
|
|
|
|
// do RIPEMD160
|
|
|
|
let mut ripemd = Ripemd160::new();
|
|
|
|
ripemd.input(&sha2_res);
|
|
|
|
ripemd.result(&mut ripemd_res);
|
|
|
|
// Return
|
|
|
|
ripemd_res
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the first four bytes of the identifier
|
|
|
|
pub fn fingerprint(&self, secp: &Secp256k1) -> Fingerprint {
|
|
|
|
Fingerprint::from(&self.identifier(secp)[0..4])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ExtendedPubKey {
|
|
|
|
/// Derives a public key from a private key
|
|
|
|
pub fn from_private(secp: &Secp256k1, sk: &ExtendedPrivKey) -> ExtendedPubKey {
|
|
|
|
ExtendedPubKey {
|
|
|
|
network: sk.network,
|
|
|
|
depth: sk.depth,
|
|
|
|
parent_fingerprint: sk.parent_fingerprint,
|
|
|
|
child_number: sk.child_number,
|
|
|
|
public_key: PublicKey::from_secret_key(secp, &sk.secret_key).unwrap(),
|
|
|
|
chain_code: sk.chain_code
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-24 19:25:47 +00:00
|
|
|
/// Compute the scalar tweak added to this key to get a child key
|
|
|
|
pub fn ckd_pub_tweak(&self, secp: &Secp256k1, i: ChildNumber) -> Result<(SecretKey, ChainCode), Error> {
|
2016-06-24 19:15:57 +00:00
|
|
|
match i {
|
2018-08-11 19:30:38 +00:00
|
|
|
ChildNumber::Hardened {..} => {
|
|
|
|
Err(Error::CannotDeriveFromHardenedKey)
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
2018-08-11 19:30:38 +00:00
|
|
|
ChildNumber::Normal { index: n } => {
|
2016-06-24 19:15:57 +00:00
|
|
|
let mut hmac = Hmac::new(Sha512::new(), &self.chain_code[..]);
|
2018-02-18 15:45:35 +00:00
|
|
|
hmac.input(&self.public_key.serialize()[..]);
|
2016-06-24 19:15:57 +00:00
|
|
|
let mut be_n = [0; 4];
|
|
|
|
BigEndian::write_u32(&mut be_n, n);
|
|
|
|
hmac.input(&be_n);
|
|
|
|
|
|
|
|
let mut result = [0; 64];
|
|
|
|
hmac.raw_result(&mut result);
|
|
|
|
|
2016-06-24 19:25:47 +00:00
|
|
|
let secret_key = try!(SecretKey::from_slice(secp, &result[..32]));
|
|
|
|
let chain_code = ChainCode::from(&result[32..]);
|
|
|
|
Ok((secret_key, chain_code))
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-24 19:25:47 +00:00
|
|
|
/// Public->Public child key derivation
|
|
|
|
pub fn ckd_pub(&self, secp: &Secp256k1, i: ChildNumber) -> Result<ExtendedPubKey, Error> {
|
|
|
|
let (sk, chain_code) = try!(self.ckd_pub_tweak(secp, i));
|
|
|
|
let mut pk = self.public_key.clone();
|
|
|
|
try!(pk.add_exp_assign(secp, &sk).map_err(Error::Ecdsa));
|
|
|
|
|
|
|
|
Ok(ExtendedPubKey {
|
|
|
|
network: self.network,
|
|
|
|
depth: self.depth + 1,
|
|
|
|
parent_fingerprint: self.fingerprint(),
|
|
|
|
child_number: i,
|
|
|
|
public_key: pk,
|
|
|
|
chain_code: chain_code
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-06-24 19:15:57 +00:00
|
|
|
/// Returns the HASH160 of the chaincode
|
|
|
|
pub fn identifier(&self) -> [u8; 20] {
|
|
|
|
let mut sha2_res = [0; 32];
|
|
|
|
let mut ripemd_res = [0; 20];
|
|
|
|
// Do SHA256 of just the ECDSA pubkey
|
|
|
|
let mut sha2 = Sha256::new();
|
2018-02-18 15:45:35 +00:00
|
|
|
sha2.input(&self.public_key.serialize()[..]);
|
2016-06-24 19:15:57 +00:00
|
|
|
sha2.result(&mut sha2_res);
|
|
|
|
// do RIPEMD160
|
|
|
|
let mut ripemd = Ripemd160::new();
|
|
|
|
ripemd.input(&sha2_res);
|
|
|
|
ripemd.result(&mut ripemd_res);
|
|
|
|
// Return
|
|
|
|
ripemd_res
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the first four bytes of the identifier
|
|
|
|
pub fn fingerprint(&self) -> Fingerprint {
|
|
|
|
Fingerprint::from(&self.identifier()[0..4])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-08 23:11:16 +00:00
|
|
|
impl fmt::Display for ExtendedPrivKey {
|
|
|
|
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
2018-03-09 17:53:20 +00:00
|
|
|
let mut ret = [0; 78];
|
|
|
|
ret[0..4].copy_from_slice(&match self.network {
|
2016-06-24 19:15:57 +00:00
|
|
|
Network::Bitcoin => [0x04, 0x88, 0xAD, 0xE4],
|
2018-05-17 13:08:02 +00:00
|
|
|
Network::Testnet | Network::Regtest => [0x04, 0x35, 0x83, 0x94],
|
2018-03-09 17:53:20 +00:00
|
|
|
}[..]);
|
|
|
|
ret[4] = self.depth as u8;
|
|
|
|
ret[5..9].copy_from_slice(&self.parent_fingerprint[..]);
|
2018-08-11 19:30:38 +00:00
|
|
|
|
|
|
|
BigEndian::write_u32(&mut ret[9..13], u32::from(self.child_number));
|
|
|
|
|
2018-03-09 17:53:20 +00:00
|
|
|
ret[13..45].copy_from_slice(&self.chain_code[..]);
|
|
|
|
ret[45] = 0;
|
|
|
|
ret[46..78].copy_from_slice(&self.secret_key[..]);
|
2018-08-08 23:11:16 +00:00
|
|
|
fmt.write_str(&base58::check_encode_slice(&ret[..]))
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-09 17:53:20 +00:00
|
|
|
impl FromStr for ExtendedPrivKey {
|
|
|
|
type Err = base58::Error;
|
|
|
|
|
|
|
|
fn from_str(inp: &str) -> Result<ExtendedPrivKey, base58::Error> {
|
2016-06-24 19:15:57 +00:00
|
|
|
let s = Secp256k1::with_caps(secp256k1::ContextFlag::None);
|
2018-03-09 17:53:20 +00:00
|
|
|
let data = try!(base58::from_check(inp));
|
2016-06-24 19:15:57 +00:00
|
|
|
|
|
|
|
if data.len() != 78 {
|
|
|
|
return Err(base58::Error::InvalidLength(data.len()));
|
|
|
|
}
|
|
|
|
|
2018-08-11 19:30:38 +00:00
|
|
|
let cn_int: u32 = Cursor::new(&data[9..13]).read_u32::<BigEndian>().unwrap();
|
|
|
|
let child_number: ChildNumber = ChildNumber::from(cn_int);
|
2016-06-24 19:15:57 +00:00
|
|
|
|
|
|
|
Ok(ExtendedPrivKey {
|
|
|
|
network: if &data[0..4] == [0x04u8, 0x88, 0xAD, 0xE4] {
|
|
|
|
Network::Bitcoin
|
|
|
|
} else if &data[0..4] == [0x04u8, 0x35, 0x83, 0x94] {
|
|
|
|
Network::Testnet
|
|
|
|
} else {
|
|
|
|
return Err(base58::Error::InvalidVersion((&data[0..4]).to_vec()));
|
|
|
|
},
|
|
|
|
depth: data[4],
|
|
|
|
parent_fingerprint: Fingerprint::from(&data[5..9]),
|
|
|
|
child_number: child_number,
|
|
|
|
chain_code: ChainCode::from(&data[13..45]),
|
|
|
|
secret_key: try!(SecretKey::from_slice(&s,
|
2018-03-09 17:53:20 +00:00
|
|
|
&data[46..78]).map_err(|e|
|
|
|
|
base58::Error::Other(e.to_string())))
|
2016-06-24 19:15:57 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-08 23:11:16 +00:00
|
|
|
impl fmt::Display for ExtendedPubKey {
|
|
|
|
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
2018-03-09 17:53:20 +00:00
|
|
|
let mut ret = [0; 78];
|
|
|
|
ret[0..4].copy_from_slice(&match self.network {
|
2016-06-24 19:15:57 +00:00
|
|
|
Network::Bitcoin => [0x04u8, 0x88, 0xB2, 0x1E],
|
2018-05-17 13:08:02 +00:00
|
|
|
Network::Testnet | Network::Regtest => [0x04u8, 0x35, 0x87, 0xCF],
|
2018-03-09 17:53:20 +00:00
|
|
|
}[..]);
|
|
|
|
ret[4] = self.depth as u8;
|
|
|
|
ret[5..9].copy_from_slice(&self.parent_fingerprint[..]);
|
2018-08-11 19:30:38 +00:00
|
|
|
|
|
|
|
BigEndian::write_u32(&mut ret[9..13], u32::from(self.child_number));
|
|
|
|
|
2018-03-09 17:53:20 +00:00
|
|
|
ret[13..45].copy_from_slice(&self.chain_code[..]);
|
|
|
|
ret[45..78].copy_from_slice(&self.public_key.serialize()[..]);
|
2018-08-08 23:11:16 +00:00
|
|
|
fmt.write_str(&base58::check_encode_slice(&ret[..]))
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-09 17:53:20 +00:00
|
|
|
impl FromStr for ExtendedPubKey {
|
|
|
|
type Err = base58::Error;
|
|
|
|
|
|
|
|
fn from_str(inp: &str) -> Result<ExtendedPubKey, base58::Error> {
|
2016-06-24 19:15:57 +00:00
|
|
|
let s = Secp256k1::with_caps(secp256k1::ContextFlag::None);
|
2018-03-09 17:53:20 +00:00
|
|
|
let data = try!(base58::from_check(inp));
|
2016-06-24 19:15:57 +00:00
|
|
|
|
|
|
|
if data.len() != 78 {
|
|
|
|
return Err(base58::Error::InvalidLength(data.len()));
|
|
|
|
}
|
|
|
|
|
2018-08-11 19:30:38 +00:00
|
|
|
let cn_int: u32 = Cursor::new(&data[9..13]).read_u32::<BigEndian>().unwrap();
|
|
|
|
let child_number: ChildNumber = ChildNumber::from(cn_int);
|
2016-06-24 19:15:57 +00:00
|
|
|
|
|
|
|
Ok(ExtendedPubKey {
|
|
|
|
network: if &data[0..4] == [0x04u8, 0x88, 0xB2, 0x1E] {
|
|
|
|
Network::Bitcoin
|
|
|
|
} else if &data[0..4] == [0x04u8, 0x35, 0x87, 0xCF] {
|
|
|
|
Network::Testnet
|
|
|
|
} else {
|
|
|
|
return Err(base58::Error::InvalidVersion((&data[0..4]).to_vec()));
|
|
|
|
},
|
|
|
|
depth: data[4],
|
|
|
|
parent_fingerprint: Fingerprint::from(&data[5..9]),
|
|
|
|
child_number: child_number,
|
|
|
|
chain_code: ChainCode::from(&data[13..45]),
|
|
|
|
public_key: try!(PublicKey::from_slice(&s,
|
2018-03-09 17:53:20 +00:00
|
|
|
&data[45..78]).map_err(|e|
|
|
|
|
base58::Error::Other(e.to_string())))
|
2016-06-24 19:15:57 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2018-03-09 17:53:20 +00:00
|
|
|
use std::str::FromStr;
|
|
|
|
use std::string::ToString;
|
|
|
|
|
2016-06-24 19:15:57 +00:00
|
|
|
use secp256k1::Secp256k1;
|
2018-07-24 18:43:03 +00:00
|
|
|
use hex::decode as hex_decode;
|
2016-06-24 19:15:57 +00:00
|
|
|
|
|
|
|
use network::constants::Network::{self, Bitcoin};
|
|
|
|
|
|
|
|
use super::{ChildNumber, ExtendedPrivKey, ExtendedPubKey};
|
|
|
|
use super::ChildNumber::{Hardened, Normal};
|
|
|
|
|
|
|
|
fn test_path(secp: &Secp256k1,
|
|
|
|
network: Network,
|
|
|
|
seed: &[u8],
|
|
|
|
path: &[ChildNumber],
|
|
|
|
expected_sk: &str,
|
|
|
|
expected_pk: &str) {
|
|
|
|
|
|
|
|
let mut sk = ExtendedPrivKey::new_master(secp, network, seed).unwrap();
|
|
|
|
let mut pk = ExtendedPubKey::from_private(secp, &sk);
|
|
|
|
// Derive keys, checking hardened and non-hardened derivation
|
|
|
|
for &num in path.iter() {
|
|
|
|
sk = sk.ckd_priv(secp, num).unwrap();
|
|
|
|
match num {
|
2018-08-11 19:30:38 +00:00
|
|
|
Normal {..} => {
|
2016-06-24 19:15:57 +00:00
|
|
|
let pk2 = pk.ckd_pub(secp, num).unwrap();
|
|
|
|
pk = ExtendedPubKey::from_private(secp, &sk);
|
|
|
|
assert_eq!(pk, pk2);
|
|
|
|
}
|
2018-08-11 19:30:38 +00:00
|
|
|
Hardened {..} => {
|
2016-06-24 19:15:57 +00:00
|
|
|
pk = ExtendedPubKey::from_private(secp, &sk);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check result against expected base58
|
2018-03-09 17:53:20 +00:00
|
|
|
assert_eq!(&sk.to_string()[..], expected_sk);
|
|
|
|
assert_eq!(&pk.to_string()[..], expected_pk);
|
2016-06-24 19:15:57 +00:00
|
|
|
// Check decoded base58 against result
|
2018-03-09 17:53:20 +00:00
|
|
|
let decoded_sk = ExtendedPrivKey::from_str(expected_sk);
|
|
|
|
let decoded_pk = ExtendedPubKey::from_str(expected_pk);
|
2016-06-24 19:15:57 +00:00
|
|
|
assert_eq!(Ok(sk), decoded_sk);
|
|
|
|
assert_eq!(Ok(pk), decoded_pk);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_vector_1() {
|
|
|
|
let secp = Secp256k1::new();
|
2018-07-24 18:43:03 +00:00
|
|
|
let seed = hex_decode("000102030405060708090a0b0c0d0e0f").unwrap();
|
2016-06-24 19:15:57 +00:00
|
|
|
// m
|
|
|
|
test_path(&secp, Bitcoin, &seed, &[],
|
|
|
|
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
|
|
|
|
"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8");
|
|
|
|
|
|
|
|
// m/0h
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_hardened_idx(0)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
|
|
|
|
"xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw");
|
|
|
|
|
|
|
|
// m/0h/1
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
|
|
|
|
"xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ");
|
|
|
|
|
|
|
|
// m/0h/1/2h
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
|
|
|
|
"xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5");
|
|
|
|
|
|
|
|
// m/0h/1/2h/2
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2), ChildNumber::from_normal_idx(2)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
|
|
|
|
"xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV");
|
|
|
|
|
|
|
|
// m/0h/1/2h/2/1000000000
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2), ChildNumber::from_normal_idx(2), ChildNumber::from_normal_idx(1000000000)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
|
|
|
|
"xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_vector_2() {
|
|
|
|
let secp = Secp256k1::new();
|
2018-07-24 18:43:03 +00:00
|
|
|
let seed = hex_decode("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542").unwrap();
|
2016-06-24 19:15:57 +00:00
|
|
|
|
|
|
|
// m
|
|
|
|
test_path(&secp, Bitcoin, &seed, &[],
|
|
|
|
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
|
|
|
|
"xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB");
|
|
|
|
|
|
|
|
// m/0
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_normal_idx(0)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
|
|
|
|
"xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH");
|
|
|
|
|
|
|
|
// m/0/2147483647h
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
|
|
|
|
"xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a");
|
|
|
|
|
|
|
|
// m/0/2147483647h/1
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
|
|
|
|
"xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon");
|
|
|
|
|
|
|
|
// m/0/2147483647h/1/2147483646h
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2147483646)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
|
|
|
|
"xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL");
|
|
|
|
|
|
|
|
// m/0/2147483647h/1/2147483646h/2
|
2018-08-11 19:30:38 +00:00
|
|
|
test_path(&secp, Bitcoin, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2147483646), ChildNumber::from_normal_idx(2)],
|
2016-06-24 19:15:57 +00:00
|
|
|
"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
|
|
|
|
"xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
pub fn encode_decode_childnumber() {
|
2018-08-11 19:30:38 +00:00
|
|
|
serde_round_trip!(ChildNumber::from_normal_idx(0));
|
|
|
|
serde_round_trip!(ChildNumber::from_normal_idx(1));
|
|
|
|
serde_round_trip!(ChildNumber::from_normal_idx((1 << 31) - 1));
|
|
|
|
serde_round_trip!(ChildNumber::from_hardened_idx(0));
|
|
|
|
serde_round_trip!(ChildNumber::from_hardened_idx(1));
|
|
|
|
serde_round_trip!(ChildNumber::from_hardened_idx((1 << 31) - 1));
|
2016-06-24 19:15:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|