Add BIP32 key support; unify array newtyping; improve base58 trait
Sorry for so many things in one commit ... it was an iterative process depending as I worked on BIP32 to get the other stuff working. (And I was too lazy to separate it out after the fact.) A breaking change by the array newtyping is that Show for Sha256dHash now outputs the slice Show. You have to use `{:x}` to get the old hex output.
This commit is contained in:
parent
4ab69b8a77
commit
6bf553c6fe
|
@ -69,3 +69,99 @@ macro_rules! impl_json(
|
||||||
);
|
);
|
||||||
)
|
)
|
||||||
|
|
||||||
|
macro_rules! impl_array_newtype(
|
||||||
|
($thing:ident, $ty:ty, $len:expr) => {
|
||||||
|
impl $thing {
|
||||||
|
#[inline]
|
||||||
|
/// Provides an immutable view into the object
|
||||||
|
pub fn as_slice<'a>(&'a self) -> &'a [$ty] {
|
||||||
|
let &$thing(ref dat) = self;
|
||||||
|
dat.as_slice()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
/// Provides an immutable view into the object from index `s` inclusive to `e` exclusive
|
||||||
|
pub fn slice<'a>(&'a self, s: uint, e: uint) -> &'a [$ty] {
|
||||||
|
let &$thing(ref dat) = self;
|
||||||
|
dat.slice(s, e)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
/// Provides an immutable view into the object, up to index `n` exclusive
|
||||||
|
pub fn slice_to<'a>(&'a self, n: uint) -> &'a [$ty] {
|
||||||
|
let &$thing(ref dat) = self;
|
||||||
|
dat.slice_to(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
/// Provides an immutable view into the object, starting from index `n`
|
||||||
|
pub fn slice_from<'a>(&'a self, n: uint) -> &'a [$ty] {
|
||||||
|
let &$thing(ref dat) = self;
|
||||||
|
dat.slice_from(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
/// Converts the object to a raw pointer
|
||||||
|
pub fn as_ptr(&self) -> *const $ty {
|
||||||
|
let &$thing(ref dat) = self;
|
||||||
|
dat.as_ptr()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
/// Converts the object to a mutable raw pointer
|
||||||
|
pub fn as_mut_ptr(&mut self) -> *mut $ty {
|
||||||
|
let &$thing(ref mut dat) = self;
|
||||||
|
dat.as_mut_ptr()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
/// Returns the length of the object as an array
|
||||||
|
pub fn len(&self) -> uint { $len }
|
||||||
|
|
||||||
|
/// Constructs a new object from raw data
|
||||||
|
pub fn from_slice(data: &[$ty]) -> $thing {
|
||||||
|
assert_eq!(data.len(), $len);
|
||||||
|
unsafe {
|
||||||
|
use std::intrinsics::copy_nonoverlapping_memory;
|
||||||
|
use std::mem;
|
||||||
|
let mut ret: $thing = mem::uninitialized();
|
||||||
|
copy_nonoverlapping_memory(ret.as_mut_ptr(),
|
||||||
|
data.as_ptr(),
|
||||||
|
mem::size_of::<$thing>());
|
||||||
|
ret
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Index<uint, $ty> for $thing {
|
||||||
|
#[inline]
|
||||||
|
fn index<'a>(&'a self, idx: &uint) -> &'a $ty {
|
||||||
|
let &$thing(ref data) = self;
|
||||||
|
&data[*idx]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for $thing {
|
||||||
|
#[inline]
|
||||||
|
fn eq(&self, other: &$thing) -> bool {
|
||||||
|
self.as_slice() == other.as_slice()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for $thing {}
|
||||||
|
|
||||||
|
impl Clone for $thing {
|
||||||
|
#[inline]
|
||||||
|
fn clone(&self) -> $thing {
|
||||||
|
$thing::from_slice(self.as_slice())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ::std::fmt::Show for $thing {
|
||||||
|
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
|
||||||
|
write!(f, concat!(stringify!($thing), "({})"), self.as_slice())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
|
@ -63,4 +63,5 @@ pub mod macros;
|
||||||
pub mod network;
|
pub mod network;
|
||||||
pub mod blockdata;
|
pub mod blockdata;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
pub mod wallet;
|
||||||
|
|
||||||
|
|
|
@ -463,7 +463,7 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn serialize_vector_test() {
|
fn serialize_vector_test() {
|
||||||
assert_eq!(serialize(&vec![1u8, 2, 3]), Ok(vec![3u8, 1, 2, 3]));
|
assert_eq!(serialize(&vec![1u8, 2, 3]), Ok(vec![3u8, 1, 2, 3]));
|
||||||
assert_eq!(serialize(&&[1u8, 2, 3]), Ok(vec![3u8, 1, 2, 3]));
|
assert_eq!(serialize(&[1u8, 2, 3].as_slice()), Ok(vec![3u8, 1, 2, 3]));
|
||||||
// TODO: test vectors of more interesting objects
|
// TODO: test vectors of more interesting objects
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -481,8 +481,7 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn serialize_option_test() {
|
fn serialize_option_test() {
|
||||||
let none: Option<u8> = None;
|
let none_ser = serialize(&None::<u8>);
|
||||||
let none_ser = serialize(&none);
|
|
||||||
let some_ser = serialize(&Some(0xFFu8));
|
let some_ser = serialize(&Some(0xFFu8));
|
||||||
assert_eq!(none_ser, Ok(vec![0]));
|
assert_eq!(none_ser, Ok(vec![0]));
|
||||||
assert_eq!(some_ser, Ok(vec![1, 0xFF]));
|
assert_eq!(some_ser, Ok(vec![1, 0xFF]));
|
||||||
|
|
|
@ -51,7 +51,7 @@ impl<D:SimpleDecoder<E>, E> ConsensusDecodable<D, E> for CommandString {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn consensus_decode(d: &mut D) -> Result<CommandString, E> {
|
fn consensus_decode(d: &mut D) -> Result<CommandString, E> {
|
||||||
let rawbytes: [u8, ..12] = try!(ConsensusDecodable::consensus_decode(d));
|
let rawbytes: [u8, ..12] = try!(ConsensusDecodable::consensus_decode(d));
|
||||||
let rv: String = FromIterator::from_iter(rawbytes.iter().filter_map(|&u| if u > 0 { Some(u as char) } else { None }));
|
let rv = FromIterator::from_iter(rawbytes.iter().filter_map(|&u| if u > 0 { Some(u as char) } else { None }));
|
||||||
Ok(CommandString(rv))
|
Ok(CommandString(rv))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,6 +17,7 @@
|
||||||
use std::io::extensions::{u64_to_le_bytes, u64_from_be_bytes};
|
use std::io::extensions::{u64_to_le_bytes, u64_from_be_bytes};
|
||||||
use std::string;
|
use std::string;
|
||||||
|
|
||||||
|
use util::thinvec::ThinVec;
|
||||||
use util::hash::Sha256dHash;
|
use util::hash::Sha256dHash;
|
||||||
|
|
||||||
/// An error that might occur during base58 decoding
|
/// An error that might occur during base58 decoding
|
||||||
|
@ -26,8 +27,14 @@ pub enum Base58Error {
|
||||||
BadByte(u8),
|
BadByte(u8),
|
||||||
/// Checksum was not correct (expected, actual)
|
/// Checksum was not correct (expected, actual)
|
||||||
BadChecksum(u32, u32),
|
BadChecksum(u32, u32),
|
||||||
|
/// The length (in bytes) of the object was not correct
|
||||||
|
InvalidLength(uint),
|
||||||
|
/// Version byte(s) were not recognized
|
||||||
|
InvalidVersion(Vec<u8>),
|
||||||
/// Checked data was less than 4 bytes
|
/// Checked data was less than 4 bytes
|
||||||
TooShort(uint)
|
TooShort(uint),
|
||||||
|
/// Any other error
|
||||||
|
OtherBase58Error(String)
|
||||||
}
|
}
|
||||||
|
|
||||||
static BASE58_CHARS: &'static [u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
static BASE58_CHARS: &'static [u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
||||||
|
@ -53,70 +60,12 @@ static BASE58_DIGITS: [Option<u8>, ..128] = [
|
||||||
|
|
||||||
/// Trait for objects which can be read as base58
|
/// Trait for objects which can be read as base58
|
||||||
pub trait FromBase58 {
|
pub trait FromBase58 {
|
||||||
|
/// Constructs an object flrom the byte-encoding (base 256)
|
||||||
|
/// representation of its base58 format
|
||||||
|
fn from_base58_layout(data: Vec<u8>) -> Result<Self, Base58Error>;
|
||||||
|
|
||||||
/// Obtain an object from its base58 encoding
|
/// Obtain an object from its base58 encoding
|
||||||
fn from_base58(&str) -> Result<Self, Base58Error>;
|
fn from_base58(data: &str) -> Result<Self, Base58Error> {
|
||||||
|
|
||||||
/// Obtain an object from its base58check encoding
|
|
||||||
fn from_base58check(&str) -> Result<Self, Base58Error>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Trait for objects which can be written as base58
|
|
||||||
pub trait ToBase58 {
|
|
||||||
/// Obtain a string with the base58 encoding of the object
|
|
||||||
fn to_base58(&self) -> String;
|
|
||||||
|
|
||||||
/// Obtain a string with the base58check encoding of the object
|
|
||||||
/// (Tack the first 4 256-digits of the object's Bitcoin hash onto the end.)
|
|
||||||
fn to_base58check(&self) -> String;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> ToBase58 for &'a [u8] {
|
|
||||||
fn to_base58(&self) -> String {
|
|
||||||
// 7/5 is just over log_58(256)
|
|
||||||
let mut scratch = Vec::from_elem(1 + self.len() * 7 / 5, 0u8);
|
|
||||||
// Build in base 58
|
|
||||||
for &d256 in self.iter() {
|
|
||||||
// Compute "X = X * 256 + next_digit" in base 58
|
|
||||||
let mut carry = d256 as u32;
|
|
||||||
for d58 in scratch.mut_iter().rev() {
|
|
||||||
carry += *d58 as u32 << 8;
|
|
||||||
*d58 = (carry % 58) as u8;
|
|
||||||
carry /= 58;
|
|
||||||
}
|
|
||||||
assert_eq!(carry, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unsafely translate the bytes to a utf8 string
|
|
||||||
unsafe {
|
|
||||||
// Copy leading zeroes directly
|
|
||||||
let mut ret = string::raw::from_utf8(self.iter().take_while(|&&x| x == 0)
|
|
||||||
.map(|_| BASE58_CHARS[0])
|
|
||||||
.collect());
|
|
||||||
// Copy rest of string
|
|
||||||
ret.as_mut_vec().extend(scratch.move_iter().skip_while(|&x| x == 0)
|
|
||||||
.map(|x| BASE58_CHARS[x as uint]));
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_base58check(&self) -> String {
|
|
||||||
let checksum = Sha256dHash::from_data(*self).into_le().low_u32();
|
|
||||||
u64_to_le_bytes(checksum as u64, 4, |ck| Vec::from_slice(*self).append(ck).to_base58())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToBase58 for Vec<u8> {
|
|
||||||
fn to_base58(&self) -> String {
|
|
||||||
self.as_slice().to_base58()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_base58check(&self) -> String {
|
|
||||||
self.as_slice().to_base58check()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromBase58 for Vec<u8> {
|
|
||||||
fn from_base58(data: &str) -> Result<Vec<u8>, Base58Error> {
|
|
||||||
// 11/15 is just over log_256(58)
|
// 11/15 is just over log_256(58)
|
||||||
let mut scratch = Vec::from_elem(1 + data.len() * 11 / 15, 0u8);
|
let mut scratch = Vec::from_elem(1 + data.len() * 11 / 15, 0u8);
|
||||||
// Build in base 256
|
// Build in base 256
|
||||||
|
@ -143,10 +92,11 @@ impl FromBase58 for Vec<u8> {
|
||||||
.collect();
|
.collect();
|
||||||
// Copy rest of string
|
// Copy rest of string
|
||||||
ret.extend(scratch.move_iter().skip_while(|&x| x == 0));
|
ret.extend(scratch.move_iter().skip_while(|&x| x == 0));
|
||||||
Ok(ret)
|
FromBase58::from_base58_layout(ret)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_base58check(data: &str) -> Result<Vec<u8>, Base58Error> {
|
/// Obtain an object from its base58check encoding
|
||||||
|
fn from_base58check(data: &str) -> Result<Self, Base58Error> {
|
||||||
let mut ret: Vec<u8> = try!(FromBase58::from_base58(data));
|
let mut ret: Vec<u8> = try!(FromBase58::from_base58(data));
|
||||||
if ret.len() < 4 {
|
if ret.len() < 4 {
|
||||||
return Err(TooShort(ret.len()));
|
return Err(TooShort(ret.len()));
|
||||||
|
@ -159,7 +109,84 @@ impl FromBase58 for Vec<u8> {
|
||||||
}
|
}
|
||||||
|
|
||||||
ret.truncate(ck_start);
|
ret.truncate(ck_start);
|
||||||
Ok(ret)
|
FromBase58::from_base58_layout(ret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Directly encode a slice as base58
|
||||||
|
pub fn base58_encode_slice(data: &[u8]) -> String {
|
||||||
|
// 7/5 is just over log_58(256)
|
||||||
|
let mut scratch = Vec::from_elem(1 + data.len() * 7 / 5, 0u8);
|
||||||
|
// Build in base 58
|
||||||
|
for &d256 in data.base58_layout().iter() {
|
||||||
|
// Compute "X = X * 256 + next_digit" in base 58
|
||||||
|
let mut carry = d256 as u32;
|
||||||
|
for d58 in scratch.mut_iter().rev() {
|
||||||
|
carry += *d58 as u32 << 8;
|
||||||
|
*d58 = (carry % 58) as u8;
|
||||||
|
carry /= 58;
|
||||||
|
}
|
||||||
|
assert_eq!(carry, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unsafely translate the bytes to a utf8 string
|
||||||
|
unsafe {
|
||||||
|
// Copy leading zeroes directly
|
||||||
|
let mut ret = string::raw::from_utf8(data.iter().take_while(|&&x| x == 0)
|
||||||
|
.map(|_| BASE58_CHARS[0])
|
||||||
|
.collect());
|
||||||
|
// Copy rest of string
|
||||||
|
ret.as_mut_vec().extend(scratch.move_iter().skip_while(|&x| x == 0)
|
||||||
|
.map(|x| BASE58_CHARS[x as uint]));
|
||||||
|
ret
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Trait for objects which can be written as base58
|
||||||
|
pub trait ToBase58 {
|
||||||
|
/// The serialization to be converted into base58
|
||||||
|
fn base58_layout(&self) -> Vec<u8>;
|
||||||
|
|
||||||
|
/// Obtain a string with the base58 encoding of the object
|
||||||
|
fn to_base58(&self) -> String {
|
||||||
|
base58_encode_slice(self.base58_layout().as_slice())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Obtain a string with the base58check encoding of the object
|
||||||
|
/// (Tack the first 4 256-digits of the object's Bitcoin hash onto the end.)
|
||||||
|
fn to_base58check(&self) -> String {
|
||||||
|
let mut data = self.base58_layout();
|
||||||
|
let checksum = Sha256dHash::from_data(data.as_slice()).into_le().low_u32();
|
||||||
|
u64_to_le_bytes(checksum as u64, 4,
|
||||||
|
|ck| { data.push_all(ck); base58_encode_slice(data.as_slice()) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trivial implementations for slices and vectors
|
||||||
|
impl<'a> ToBase58 for &'a [u8] {
|
||||||
|
fn base58_layout(&self) -> Vec<u8> { Vec::from_slice(*self) }
|
||||||
|
fn to_base58(&self) -> String { base58_encode_slice(*self) }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToBase58 for Vec<u8> {
|
||||||
|
fn base58_layout(&self) -> Vec<u8> { self.clone() }
|
||||||
|
fn to_base58(&self) -> String { base58_encode_slice(self.as_slice()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToBase58 for ThinVec<u8> {
|
||||||
|
fn base58_layout(&self) -> Vec<u8> { Vec::from_slice(self.as_slice()) }
|
||||||
|
fn to_base58(&self) -> String { base58_encode_slice(self.as_slice()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromBase58 for Vec<u8> {
|
||||||
|
fn from_base58_layout(data: Vec<u8>) -> Result<Vec<u8>, Base58Error> {
|
||||||
|
Ok(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromBase58 for ThinVec<u8> {
|
||||||
|
fn from_base58_layout(data: Vec<u8>) -> Result<ThinVec<u8>, Base58Error> {
|
||||||
|
Ok(ThinVec::from_vec(data))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -204,5 +231,13 @@ mod tests {
|
||||||
assert_eq!(FromBase58::from_base58check("1PfJpZsjreyVrqeoAfabrRwwjQyoSQMmHH"),
|
assert_eq!(FromBase58::from_base58check("1PfJpZsjreyVrqeoAfabrRwwjQyoSQMmHH"),
|
||||||
Ok("00f8917303bfa8ef24f292e8fa1419b20460ba064d".from_hex().unwrap()))
|
Ok("00f8917303bfa8ef24f292e8fa1419b20460ba064d".from_hex().unwrap()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_base58_roundtrip() {
|
||||||
|
let s = "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs";
|
||||||
|
let v: Vec<u8> = FromBase58::from_base58check(s).unwrap();
|
||||||
|
assert_eq!(v.to_base58check().as_slice(), s);
|
||||||
|
assert_eq!(FromBase58::from_base58check(v.to_base58check().as_slice()), Ok(v));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -34,9 +34,7 @@ use util::uint::Uint256;
|
||||||
|
|
||||||
/// A Bitcoin hash, 32-bytes, computed from x as SHA256(SHA256(x))
|
/// A Bitcoin hash, 32-bytes, computed from x as SHA256(SHA256(x))
|
||||||
pub struct Sha256dHash([u8, ..32]);
|
pub struct Sha256dHash([u8, ..32]);
|
||||||
|
impl_array_newtype!(Sha256dHash, u8, 32)
|
||||||
/// A boring old Sha256 hash
|
|
||||||
pub struct Sha256Hash([u8, ..32]);
|
|
||||||
|
|
||||||
/// A RIPEMD-160 hash
|
/// A RIPEMD-160 hash
|
||||||
pub struct Ripemd160Hash([u8, ..20]);
|
pub struct Ripemd160Hash([u8, ..20]);
|
||||||
|
@ -207,48 +205,6 @@ impl Sha256dHash {
|
||||||
}
|
}
|
||||||
ret
|
ret
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a view into the hash
|
|
||||||
pub fn as_slice<'a>(&'a self) -> &'a [u8] {
|
|
||||||
let &Sha256dHash(ref data) = self;
|
|
||||||
data.as_slice()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a view of the first `n` bytes of the hash
|
|
||||||
pub fn slice_to<'a>(&'a self, n: uint) -> &'a [u8] {
|
|
||||||
let &Sha256dHash(ref data) = self;
|
|
||||||
data.slice_to(n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Clone for Sha256dHash {
|
|
||||||
#[inline]
|
|
||||||
fn clone(&self) -> Sha256dHash {
|
|
||||||
*self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialEq for Sha256dHash {
|
|
||||||
fn eq(&self, other: &Sha256dHash) -> bool {
|
|
||||||
let &Sha256dHash(ref mydata) = self;
|
|
||||||
let &Sha256dHash(ref yourdata) = other;
|
|
||||||
for i in range(0u, 32) {
|
|
||||||
if mydata[i] != yourdata[i] {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Eq for Sha256dHash {}
|
|
||||||
|
|
||||||
impl Index<uint, u8> for Sha256dHash {
|
|
||||||
#[inline]
|
|
||||||
fn index<'a>(&'a self, idx: &uint) -> &'a u8 {
|
|
||||||
let &Sha256dHash(ref data) = self;
|
|
||||||
&data[*idx]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Note that this outputs hashes as big endian hex numbers, so this should be
|
// Note that this outputs hashes as big endian hex numbers, so this should be
|
||||||
|
@ -308,12 +264,6 @@ impl fmt::LowerHex for Sha256dHash {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Show for Sha256dHash {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
write!(f, "{:x}", *self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Any collection of objects for which a merkle root makes sense to calculate
|
/// Any collection of objects for which a merkle root makes sense to calculate
|
||||||
pub trait MerkleRoot {
|
pub trait MerkleRoot {
|
||||||
/// Construct a merkle tree from a collection, with elements ordered as
|
/// Construct a merkle tree from a collection, with elements ordered as
|
||||||
|
|
|
@ -0,0 +1,463 @@
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
|
||||||
|
//! # BIP32 Implementation
|
||||||
|
//!
|
||||||
|
//! 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::extensions::{u64_to_be_bytes, u64_from_be_bytes};
|
||||||
|
|
||||||
|
use crypto::digest::Digest;
|
||||||
|
use crypto::hmac::Hmac;
|
||||||
|
use crypto::mac::Mac;
|
||||||
|
use crypto::ripemd160::Ripemd160;
|
||||||
|
use crypto::sha2::Sha256;
|
||||||
|
use crypto::sha2::Sha512;
|
||||||
|
use secp256k1::key::{PublicKey, SecretKey};
|
||||||
|
use secp256k1;
|
||||||
|
|
||||||
|
use network::constants::{Network, Bitcoin, BitcoinTestnet};
|
||||||
|
use util::base58::{Base58Error,
|
||||||
|
InvalidLength, InvalidVersion, OtherBase58Error,
|
||||||
|
FromBase58, ToBase58};
|
||||||
|
|
||||||
|
/// A chain code
|
||||||
|
pub struct ChainCode([u8, ..32]);
|
||||||
|
impl_array_newtype!(ChainCode, u8, 32)
|
||||||
|
|
||||||
|
/// A fingerprint
|
||||||
|
pub struct Fingerprint([u8, ..4]);
|
||||||
|
impl_array_newtype!(Fingerprint, u8, 4)
|
||||||
|
|
||||||
|
impl Default for Fingerprint {
|
||||||
|
fn default() -> Fingerprint { Fingerprint([0, 0, 0, 0]) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extended private key
|
||||||
|
#[deriving(Clone, PartialEq, Eq, Show)]
|
||||||
|
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: uint,
|
||||||
|
/// 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
|
||||||
|
#[deriving(Clone, PartialEq, Eq, Show)]
|
||||||
|
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: uint,
|
||||||
|
/// 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
|
||||||
|
#[deriving(Clone, PartialEq, Eq, Show)]
|
||||||
|
pub enum ChildNumber {
|
||||||
|
/// Hardened key index, within [0, 2^31 - 1]
|
||||||
|
Hardened(u32),
|
||||||
|
/// Non-hardened key, within [0, 2^31 - 1]
|
||||||
|
Normal(u32),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A BIP32 error
|
||||||
|
#[deriving(Clone, PartialEq, Eq, Show)]
|
||||||
|
pub enum Error {
|
||||||
|
/// A pk->pk derivation was attempted on a hardened key
|
||||||
|
CannotDeriveFromHardenedKey,
|
||||||
|
/// A secp256k1 error occured
|
||||||
|
EcdsaError(secp256k1::Error),
|
||||||
|
/// A child number was provided that was out of range
|
||||||
|
InvalidChildNumber(ChildNumber)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExtendedPrivKey {
|
||||||
|
/// Construct a new master key from a seed value
|
||||||
|
pub fn new_master(network: Network, seed: &[u8]) -> Result<ExtendedPrivKey, Error> {
|
||||||
|
let mut result = [0, ..64];
|
||||||
|
let mut hmac = Hmac::new(Sha512::new(), b"Bitcoin seed".as_slice());
|
||||||
|
hmac.input(seed);
|
||||||
|
hmac.raw_result(result.as_mut_slice());
|
||||||
|
|
||||||
|
Ok(ExtendedPrivKey {
|
||||||
|
network: network,
|
||||||
|
depth: 0,
|
||||||
|
parent_fingerprint: Default::default(),
|
||||||
|
child_number: Normal(0),
|
||||||
|
secret_key: try!(SecretKey::from_slice(result.slice_to(32)).map_err(EcdsaError)),
|
||||||
|
chain_code: ChainCode::from_slice(result.slice_from(32))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Private->Private child key derivation
|
||||||
|
pub fn ckd_priv(&self, i: ChildNumber) -> Result<ExtendedPrivKey, Error> {
|
||||||
|
let mut result = [0, ..64];
|
||||||
|
let mut hmac = Hmac::new(Sha512::new(), self.chain_code.as_slice());
|
||||||
|
match i {
|
||||||
|
Normal(n) => {
|
||||||
|
if n >= (1 << 31) { return Err(InvalidChildNumber(i)) }
|
||||||
|
// Non-hardened key: compute public data and use that
|
||||||
|
secp256k1::init();
|
||||||
|
// Unsafety just because I have to call the init() function
|
||||||
|
hmac.input(unsafe { PublicKey::from_secret_key(&self.secret_key, true).as_slice() });
|
||||||
|
u64_to_be_bytes(n as u64, 4, |raw| hmac.input(raw));
|
||||||
|
}
|
||||||
|
Hardened(n) => {
|
||||||
|
if n >= (1 << 31) { return Err(InvalidChildNumber(i)) }
|
||||||
|
// Hardened key: use only secret data to prevent public derivation
|
||||||
|
hmac.input([0]);
|
||||||
|
hmac.input(self.secret_key.as_slice());
|
||||||
|
u64_to_be_bytes(n as u64 + (1 << 31), 4, |raw| hmac.input(raw));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hmac.raw_result(result.as_mut_slice());
|
||||||
|
let mut sk = try!(SecretKey::from_slice(result.slice_to(32)).map_err(EcdsaError));
|
||||||
|
try!(sk.add_assign(&self.secret_key).map_err(EcdsaError));
|
||||||
|
|
||||||
|
Ok(ExtendedPrivKey {
|
||||||
|
network: self.network,
|
||||||
|
depth: self.depth + 1,
|
||||||
|
parent_fingerprint: self.fingerprint(),
|
||||||
|
child_number: i,
|
||||||
|
secret_key: sk,
|
||||||
|
chain_code: ChainCode::from_slice(result.slice_from(32))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the HASH160 of the chaincode
|
||||||
|
pub fn identifier(&self) -> [u8, ..20] {
|
||||||
|
let mut sha2_res = [0, ..32];
|
||||||
|
let mut ripemd_res = [0, ..20];
|
||||||
|
// Compute extended public key
|
||||||
|
let pk = ExtendedPubKey::from_private(self);
|
||||||
|
// Do SHA256 of just the ECDSA pubkey
|
||||||
|
let mut sha2 = Sha256::new();
|
||||||
|
sha2.input(pk.public_key.as_slice());
|
||||||
|
sha2.result(sha2_res.as_mut_slice());
|
||||||
|
// do RIPEMD160
|
||||||
|
let mut ripemd = Ripemd160::new();
|
||||||
|
ripemd.input(sha2_res.as_slice());
|
||||||
|
ripemd.result(ripemd_res.as_mut_slice());
|
||||||
|
// Return
|
||||||
|
ripemd_res
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the first four bytes of the identifier
|
||||||
|
pub fn fingerprint(&self) -> Fingerprint {
|
||||||
|
Fingerprint::from_slice(self.identifier().slice_to(4))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExtendedPubKey {
|
||||||
|
/// Derives a public key from a private key
|
||||||
|
pub fn from_private(sk: &ExtendedPrivKey) -> ExtendedPubKey {
|
||||||
|
secp256k1::init();
|
||||||
|
ExtendedPubKey {
|
||||||
|
network: sk.network,
|
||||||
|
depth: sk.depth,
|
||||||
|
parent_fingerprint: sk.parent_fingerprint,
|
||||||
|
child_number: sk.child_number,
|
||||||
|
// Unsafety because we needed to run `init` above first
|
||||||
|
public_key: unsafe { PublicKey::from_secret_key(&sk.secret_key, true) },
|
||||||
|
chain_code: sk.chain_code
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Public->Public child key derivation
|
||||||
|
pub fn ckd_pub(&self, i: ChildNumber) -> Result<ExtendedPubKey, Error> {
|
||||||
|
match i {
|
||||||
|
Hardened(n) => {
|
||||||
|
if n >= (1 << 31) {
|
||||||
|
Err(InvalidChildNumber(i))
|
||||||
|
} else {
|
||||||
|
Err(CannotDeriveFromHardenedKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Normal(n) => {
|
||||||
|
let mut hmac = Hmac::new(Sha512::new(), self.chain_code.as_slice());
|
||||||
|
hmac.input(self.public_key.as_slice());
|
||||||
|
u64_to_be_bytes(n as u64, 4, |raw| hmac.input(raw));
|
||||||
|
|
||||||
|
let mut result = [0, ..64];
|
||||||
|
hmac.raw_result(result.as_mut_slice());
|
||||||
|
|
||||||
|
let sk = try!(SecretKey::from_slice(result.slice_to(32)).map_err(EcdsaError));
|
||||||
|
let mut pk = self.public_key.clone();
|
||||||
|
try!(pk.add_exp_assign(&sk).map_err(EcdsaError));
|
||||||
|
|
||||||
|
Ok(ExtendedPubKey {
|
||||||
|
network: self.network,
|
||||||
|
depth: self.depth + 1,
|
||||||
|
parent_fingerprint: self.fingerprint(),
|
||||||
|
child_number: i,
|
||||||
|
public_key: pk,
|
||||||
|
chain_code: ChainCode::from_slice(result.slice_from(32))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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();
|
||||||
|
sha2.input(self.public_key.as_slice());
|
||||||
|
sha2.result(sha2_res.as_mut_slice());
|
||||||
|
// do RIPEMD160
|
||||||
|
let mut ripemd = Ripemd160::new();
|
||||||
|
ripemd.input(sha2_res.as_slice());
|
||||||
|
ripemd.result(ripemd_res.as_mut_slice());
|
||||||
|
// Return
|
||||||
|
ripemd_res
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the first four bytes of the identifier
|
||||||
|
pub fn fingerprint(&self) -> Fingerprint {
|
||||||
|
Fingerprint::from_slice(self.identifier().slice_to(4))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToBase58 for ExtendedPrivKey {
|
||||||
|
fn base58_layout(&self) -> Vec<u8> {
|
||||||
|
let mut ret = Vec::with_capacity(78);
|
||||||
|
ret.push_all(match self.network {
|
||||||
|
Bitcoin => [0x04, 0x88, 0xAD, 0xE4],
|
||||||
|
BitcoinTestnet => [0x04, 0x35, 0x83, 0x94]
|
||||||
|
});
|
||||||
|
ret.push(self.depth as u8);
|
||||||
|
ret.push_all(self.parent_fingerprint.as_slice());
|
||||||
|
match self.child_number {
|
||||||
|
Hardened(n) => {
|
||||||
|
u64_to_be_bytes(n as u64 + (1 << 31), 4, |raw| ret.push_all(raw));
|
||||||
|
}
|
||||||
|
Normal(n) => {
|
||||||
|
u64_to_be_bytes(n as u64, 4, |raw| ret.push_all(raw));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ret.push_all(self.chain_code.as_slice());
|
||||||
|
ret.push(0);
|
||||||
|
ret.push_all(self.secret_key.as_slice());
|
||||||
|
ret
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromBase58 for ExtendedPrivKey {
|
||||||
|
fn from_base58_layout(data: Vec<u8>) -> Result<ExtendedPrivKey, Base58Error> {
|
||||||
|
if data.len() != 78 {
|
||||||
|
return Err(InvalidLength(data.len()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let cn_int = u64_from_be_bytes(data.as_slice(), 9, 4) as u32;
|
||||||
|
let child_number = if cn_int < (1 << 31) { Normal(cn_int) }
|
||||||
|
else { Hardened(cn_int - (1 << 31)) };
|
||||||
|
|
||||||
|
Ok(ExtendedPrivKey {
|
||||||
|
network: match data.slice_to(4) {
|
||||||
|
[0x04, 0x88, 0xAD, 0xE4] => Bitcoin,
|
||||||
|
[0x04, 0x35, 0x83, 0x94] => BitcoinTestnet,
|
||||||
|
_ => { return Err(InvalidVersion(Vec::from_slice(data.slice_to(4)))); }
|
||||||
|
},
|
||||||
|
depth: data[4] as uint,
|
||||||
|
parent_fingerprint: Fingerprint::from_slice(data.slice(5, 9)),
|
||||||
|
child_number: child_number,
|
||||||
|
chain_code: ChainCode::from_slice(data.slice(13, 45)),
|
||||||
|
secret_key: try!(SecretKey::from_slice(
|
||||||
|
data.slice(46, 78)).map_err(|e|
|
||||||
|
OtherBase58Error(e.to_string())))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToBase58 for ExtendedPubKey {
|
||||||
|
fn base58_layout(&self) -> Vec<u8> {
|
||||||
|
assert!(self.public_key.is_compressed());
|
||||||
|
let mut ret = Vec::with_capacity(78);
|
||||||
|
ret.push_all(match self.network {
|
||||||
|
Bitcoin => [0x04, 0x88, 0xB2, 0x1E],
|
||||||
|
BitcoinTestnet => [0x04, 0x35, 0x87, 0xCF]
|
||||||
|
});
|
||||||
|
ret.push(self.depth as u8);
|
||||||
|
ret.push_all(self.parent_fingerprint.as_slice());
|
||||||
|
match self.child_number {
|
||||||
|
Hardened(n) => {
|
||||||
|
u64_to_be_bytes(n as u64 + (1 << 31), 4, |raw| ret.push_all(raw));
|
||||||
|
}
|
||||||
|
Normal(n) => {
|
||||||
|
u64_to_be_bytes(n as u64, 4, |raw| ret.push_all(raw));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ret.push_all(self.chain_code.as_slice());
|
||||||
|
ret.push_all(self.public_key.as_slice());
|
||||||
|
ret
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromBase58 for ExtendedPubKey {
|
||||||
|
fn from_base58_layout(data: Vec<u8>) -> Result<ExtendedPubKey, Base58Error> {
|
||||||
|
if data.len() != 78 {
|
||||||
|
return Err(InvalidLength(data.len()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let cn_int = u64_from_be_bytes(data.as_slice(), 9, 4) as u32;
|
||||||
|
let child_number = if cn_int < (1 << 31) { Normal(cn_int) }
|
||||||
|
else { Hardened(cn_int - (1 << 31)) };
|
||||||
|
|
||||||
|
Ok(ExtendedPubKey {
|
||||||
|
network: match data.slice_to(4) {
|
||||||
|
[0x04, 0x88, 0xB2, 0x1E] => Bitcoin,
|
||||||
|
[0x04, 0x35, 0x87, 0xCF] => BitcoinTestnet,
|
||||||
|
_ => { return Err(InvalidVersion(Vec::from_slice(data.slice_to(4)))); }
|
||||||
|
},
|
||||||
|
depth: data[4] as uint,
|
||||||
|
parent_fingerprint: Fingerprint::from_slice(data.slice(5, 9)),
|
||||||
|
child_number: child_number,
|
||||||
|
chain_code: ChainCode::from_slice(data.slice(13, 45)),
|
||||||
|
public_key: try!(PublicKey::from_slice(
|
||||||
|
data.slice(45, 78)).map_err(|e|
|
||||||
|
OtherBase58Error(e.to_string())))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use serialize::hex::FromHex;
|
||||||
|
|
||||||
|
use network::constants::{Network, Bitcoin};
|
||||||
|
use util::base58::{FromBase58, ToBase58};
|
||||||
|
|
||||||
|
use super::{ChildNumber, ExtendedPrivKey, ExtendedPubKey, Hardened, Normal};
|
||||||
|
|
||||||
|
fn test_path(network: Network,
|
||||||
|
seed: &[u8],
|
||||||
|
path: &[ChildNumber],
|
||||||
|
expected_sk: &str,
|
||||||
|
expected_pk: &str) {
|
||||||
|
|
||||||
|
let mut sk = ExtendedPrivKey::new_master(network, seed).unwrap();
|
||||||
|
let mut pk = ExtendedPubKey::from_private(&sk);
|
||||||
|
// Derive keys, checking hardened and non-hardened derivation
|
||||||
|
for &num in path.iter() {
|
||||||
|
sk = sk.ckd_priv(num).unwrap();
|
||||||
|
match num {
|
||||||
|
Normal(_) => {
|
||||||
|
let pk2 = pk.ckd_pub(num).unwrap();
|
||||||
|
pk = ExtendedPubKey::from_private(&sk);
|
||||||
|
assert_eq!(pk, pk2);
|
||||||
|
}
|
||||||
|
Hardened(_) => {
|
||||||
|
pk = ExtendedPubKey::from_private(&sk);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check result against expected base58
|
||||||
|
assert_eq!(sk.to_base58check().as_slice(), expected_sk);
|
||||||
|
assert_eq!(pk.to_base58check().as_slice(), expected_pk);
|
||||||
|
// Check decoded base58 against result
|
||||||
|
let decoded_sk = FromBase58::from_base58check(expected_sk);
|
||||||
|
let decoded_pk = FromBase58::from_base58check(expected_pk);
|
||||||
|
assert_eq!(Ok(sk), decoded_sk);
|
||||||
|
assert_eq!(Ok(pk), decoded_pk);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_vector_1() {
|
||||||
|
let seed = "000102030405060708090a0b0c0d0e0f".from_hex().unwrap();
|
||||||
|
// m
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [],
|
||||||
|
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
|
||||||
|
"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8");
|
||||||
|
|
||||||
|
// m/0h
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Hardened(0)],
|
||||||
|
"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
|
||||||
|
"xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw");
|
||||||
|
|
||||||
|
// m/0h/1
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Hardened(0), Normal(1)],
|
||||||
|
"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
|
||||||
|
"xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ");
|
||||||
|
|
||||||
|
// m/0h/1/2h
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Hardened(0), Normal(1), Hardened(2)],
|
||||||
|
"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
|
||||||
|
"xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5");
|
||||||
|
|
||||||
|
// m/0h/1/2h/2
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Hardened(0), Normal(1), Hardened(2), Normal(2)],
|
||||||
|
"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
|
||||||
|
"xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV");
|
||||||
|
|
||||||
|
// m/0h/1/2h/2/1000000000
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Hardened(0), Normal(1), Hardened(2), Normal(2), Normal(1000000000)],
|
||||||
|
"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
|
||||||
|
"xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_vector_2() {
|
||||||
|
let seed = "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542".from_hex().unwrap();
|
||||||
|
|
||||||
|
// m
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [],
|
||||||
|
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
|
||||||
|
"xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB");
|
||||||
|
|
||||||
|
// m/0
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Normal(0)],
|
||||||
|
"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
|
||||||
|
"xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH");
|
||||||
|
|
||||||
|
// m/0/2147483647h
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Normal(0), Hardened(2147483647)],
|
||||||
|
"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
|
||||||
|
"xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a");
|
||||||
|
|
||||||
|
// m/0/2147483647h/1
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Normal(0), Hardened(2147483647), Normal(1)],
|
||||||
|
"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
|
||||||
|
"xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon");
|
||||||
|
|
||||||
|
// m/0/2147483647h/1/2147483646h
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Normal(0), Hardened(2147483647), Normal(1), Hardened(2147483646)],
|
||||||
|
"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
|
||||||
|
"xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL");
|
||||||
|
|
||||||
|
// m/0/2147483647h/1/2147483646h/2
|
||||||
|
test_path(Bitcoin, seed.as_slice(), [Normal(0), Hardened(2147483647), Normal(1), Hardened(2147483646), Normal(2)],
|
||||||
|
"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
|
||||||
|
"xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,20 @@
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
|
||||||
|
//! # Wallet functionality
|
||||||
|
//!
|
||||||
|
//! Wallet, keys and addresses
|
||||||
|
|
||||||
|
pub mod bip32;
|
||||||
|
|
Loading…
Reference in New Issue