Remove broken wallet components
This was a fairly small change and gets all unit tests to pass.
This commit is contained in:
parent
0389eb1c52
commit
2320f099c1
|
@ -30,6 +30,5 @@ rand = "*"
|
|||
rust-crypto = "*"
|
||||
rustc-serialize = "*"
|
||||
serde = "*"
|
||||
serde_macros = "*"
|
||||
time = "*"
|
||||
|
||||
|
|
|
@ -1586,8 +1586,9 @@ fn check_signature(secp: &Secp256k1, sig_slice: &[u8], pk_slice: &[u8], script:
|
|||
|
||||
// We can unwrap -- only failure mode is on length, which is fixed to 32
|
||||
let msg = secp256k1::Message::from_slice(&signature_hash[..]).unwrap();
|
||||
let sig = try!(secp256k1::Signature::from_der(secp, sig_slice).map_err(Error::Ecdsa));
|
||||
|
||||
Secp256k1::verify_raw(secp, &msg, sig_slice, &pubkey).map_err(Error::Ecdsa)
|
||||
Secp256k1::verify(secp, &msg, &sig, &pubkey).map_err(Error::Ecdsa)
|
||||
}
|
||||
|
||||
// Macro to translate English stack instructions into Rust code.
|
||||
|
|
|
@ -32,8 +32,6 @@ use blockdata::script::{self, Script, ScriptTrace, read_scriptbool};
|
|||
use blockdata::utxoset::UtxoSet;
|
||||
use network::encodable::ConsensusEncodable;
|
||||
use network::serialize::BitcoinHash;
|
||||
use network::constants::Network;
|
||||
use wallet::address::{Address, ToAddress};
|
||||
|
||||
/// A transaction input, which defines old coins to be consumed
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
|
@ -68,27 +66,6 @@ impl Default for TxOut {
|
|||
}
|
||||
}
|
||||
|
||||
/// A classification for script pubkeys
|
||||
pub enum ScriptPubkeyTemplate {
|
||||
/// A pay-to-address output
|
||||
PayToPubkeyHash(Address),
|
||||
/// Another kind of output
|
||||
Unknown
|
||||
}
|
||||
|
||||
impl TxOut {
|
||||
/// Determines the template that this output adheres to, if any
|
||||
pub fn classify(&self, network: Network) -> ScriptPubkeyTemplate {
|
||||
if self.script_pubkey.len() == 25 &&
|
||||
&self.script_pubkey[0..3] == &[0x76, 0xa9, 0x14] &&
|
||||
&self.script_pubkey[23..] == &[0x88, 0xac] {
|
||||
ScriptPubkeyTemplate::PayToPubkeyHash((&self.script_pubkey[3..23]).to_address(network))
|
||||
} else {
|
||||
ScriptPubkeyTemplate::Unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Bitcoin transaction, which describes an authenticated movement of coins
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Transaction {
|
||||
|
|
|
@ -31,10 +31,9 @@
|
|||
#![feature(box_patterns)]
|
||||
#![feature(concat_idents)]
|
||||
#![feature(custom_derive, plugin)]
|
||||
#![feature(hash)]
|
||||
#![feature(hashmap_hasher)]
|
||||
#![feature(ip_addr)]
|
||||
#![feature(slice_patterns)]
|
||||
#![feature(std_misc)]
|
||||
#![cfg_attr(test, feature(test))]
|
||||
|
||||
// Coding conventions
|
||||
|
@ -44,8 +43,6 @@
|
|||
#![deny(unused_mut)]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate byteorder;
|
||||
extern crate crypto;
|
||||
extern crate eventual;
|
||||
|
@ -68,5 +65,4 @@ pub mod macros;
|
|||
pub mod network;
|
||||
pub mod blockdata;
|
||||
pub mod util;
|
||||
pub mod wallet;
|
||||
|
||||
|
|
|
@ -1,218 +0,0 @@
|
|||
// 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/>.
|
||||
//
|
||||
|
||||
//! # Addresses
|
||||
//!
|
||||
//! Support for ordinary base58 Bitcoin addresses
|
||||
//!
|
||||
|
||||
use secp256k1::key::PublicKey;
|
||||
use crypto::digest::Digest;
|
||||
use crypto::sha2::Sha256;
|
||||
use std::ops;
|
||||
|
||||
use blockdata::script;
|
||||
use blockdata::opcodes;
|
||||
use network::constants::Network;
|
||||
use util::hash::Ripemd160Hash;
|
||||
use util::base58::{self, FromBase58, ToBase58};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
/// A Bitcoin address
|
||||
pub struct Address {
|
||||
/// The network on which this address is usable
|
||||
pub network: Network,
|
||||
/// The pubkeyhash that this address encodes
|
||||
pub hash: Ripemd160Hash
|
||||
}
|
||||
|
||||
impl Address {
|
||||
/// Creates an address from a public key
|
||||
#[inline]
|
||||
pub fn from_key(network: Network, pk: &PublicKey) -> Address {
|
||||
let mut sha = Sha256::new();
|
||||
let mut out = [0;32];
|
||||
sha.input(&pk[..]);
|
||||
sha.result(&mut out);
|
||||
Address {
|
||||
network: network,
|
||||
hash: Ripemd160Hash::from_data(&out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a script pubkey spending to this address
|
||||
#[inline]
|
||||
pub fn script_pubkey(&self) -> script::Script {
|
||||
let mut script = script::Builder::new();
|
||||
script.push_opcode(opcodes::All::OP_DUP);
|
||||
script.push_opcode(opcodes::All::OP_HASH160);
|
||||
script.push_slice(&self.hash[..]);
|
||||
script.push_opcode(opcodes::All::OP_EQUALVERIFY);
|
||||
script.push_opcode(opcodes::All::OP_CHECKSIG);
|
||||
script.into_script()
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Index<usize> for Address {
|
||||
type Output = u8;
|
||||
#[inline]
|
||||
fn index(&self, index: usize) -> &u8 {
|
||||
&self.hash[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Index<ops::Range<usize>> for Address {
|
||||
type Output = [u8];
|
||||
#[inline]
|
||||
fn index(&self, index: ops::Range<usize>) -> &[u8] {
|
||||
&self.hash[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Index<ops::RangeTo<usize>> for Address {
|
||||
type Output = [u8];
|
||||
#[inline]
|
||||
fn index(&self, index: ops::RangeTo<usize>) -> &[u8] {
|
||||
&self.hash[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Index<ops::RangeFrom<usize>> for Address {
|
||||
type Output = [u8];
|
||||
#[inline]
|
||||
fn index(&self, index: ops::RangeFrom<usize>) -> &[u8] {
|
||||
&self.hash[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Index<ops::RangeFull> for Address {
|
||||
type Output = [u8];
|
||||
#[inline]
|
||||
fn index(&self, _: ops::RangeFull) -> &[u8] {
|
||||
&self.hash[..]
|
||||
}
|
||||
}
|
||||
|
||||
/// Conversion from other types into an address
|
||||
pub trait ToAddress {
|
||||
/// Copies `self` into a new `Address`
|
||||
fn to_address(&self, network: Network) -> Address;
|
||||
}
|
||||
|
||||
impl<'a> ToAddress for &'a [u8] {
|
||||
#[inline]
|
||||
fn to_address(&self, network: Network) -> Address {
|
||||
Address {
|
||||
network: network,
|
||||
hash: Ripemd160Hash::from_slice(*self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToBase58 for Address {
|
||||
fn base58_layout(&self) -> Vec<u8> {
|
||||
let mut ret = vec![
|
||||
match self.network {
|
||||
Network::Bitcoin => 0,
|
||||
Network::Testnet => 111
|
||||
}
|
||||
];
|
||||
ret.extend(self.hash[..].iter().cloned());
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBase58 for Address {
|
||||
fn from_base58_layout(data: Vec<u8>) -> Result<Address, base58::Error> {
|
||||
if data.len() != 21 {
|
||||
return Err(base58::Error::InvalidLength(data.len()));
|
||||
}
|
||||
|
||||
Ok(Address {
|
||||
network: match data[0] {
|
||||
0 => Network::Bitcoin,
|
||||
111 => Network::Testnet,
|
||||
x => { return Err(base58::Error::InvalidVersion(vec![x])); }
|
||||
},
|
||||
hash: Ripemd160Hash::from_slice(&data[1..])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ::std::fmt::Debug for Address {
|
||||
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
|
||||
write!(f, "{}", self.to_base58check())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rand::Rng;
|
||||
use serialize::hex::FromHex;
|
||||
use test::{Bencher, black_box};
|
||||
|
||||
use secp256k1::Secp256k1;
|
||||
|
||||
use network::constants::Network::Bitcoin;
|
||||
use util::hash::Ripemd160Hash;
|
||||
use util::base58::{FromBase58, ToBase58};
|
||||
use super::Address;
|
||||
|
||||
#[test]
|
||||
fn test_address_58() {
|
||||
let addr = Address {
|
||||
network: Bitcoin,
|
||||
hash: Ripemd160Hash::from_slice(&"162c5ea71c0b23f5b9022ef047c4a86470a5b070".from_hex().unwrap())
|
||||
};
|
||||
|
||||
assert_eq!(&addr.to_base58check(), "132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM");
|
||||
assert_eq!(FromBase58::from_base58check("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM"), Ok(addr));
|
||||
}
|
||||
|
||||
#[bench]
|
||||
pub fn generate_address(bh: &mut Bencher) {
|
||||
struct CounterRng(u32);
|
||||
impl Rng for CounterRng {
|
||||
fn next_u32(&mut self) -> u32 { self.0 += 1; self.0 }
|
||||
}
|
||||
|
||||
let s = Secp256k1::new();
|
||||
let mut r = CounterRng(0);
|
||||
bh.iter( || {
|
||||
let (sk, pk) = s.generate_keypair(&mut r, true).unwrap();
|
||||
black_box(sk);
|
||||
black_box(pk);
|
||||
let addr = Address::from_key(Bitcoin, &pk);
|
||||
black_box(addr);
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
pub fn generate_uncompressed_address(bh: &mut Bencher) {
|
||||
struct CounterRng(u32);
|
||||
impl Rng for CounterRng {
|
||||
fn next_u32(&mut self) -> u32 { self.0 += 1; self.0 }
|
||||
}
|
||||
|
||||
let s = Secp256k1::new();
|
||||
let mut r = CounterRng(0);
|
||||
bh.iter( || {
|
||||
let (sk, pk) = s.generate_keypair(&mut r, false).unwrap();
|
||||
black_box(sk);
|
||||
black_box(pk);
|
||||
let addr = Address::from_key(Bitcoin, &pk);
|
||||
black_box(addr);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,134 +0,0 @@
|
|||
// 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/>.
|
||||
//
|
||||
|
||||
//! # Address Index
|
||||
//!
|
||||
//! Maintains an index from addresses to unspent outputs. It reduces size by
|
||||
//! checking that the first byte of HMAC(wallet key, address outscript) is
|
||||
//! zero, so that the index will be 1/256th the size of the utxoset in RAM.
|
||||
//!
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher, SipHasher};
|
||||
|
||||
use secp256k1::key::SecretKey;
|
||||
|
||||
use blockdata::transaction::TxOut;
|
||||
use blockdata::transaction::ScriptPubkeyTemplate::PayToPubkeyHash;
|
||||
use blockdata::utxoset::UtxoSet;
|
||||
use blockdata::script::Script;
|
||||
use network::constants::Network;
|
||||
use wallet::address::Address;
|
||||
use wallet::wallet::Wallet;
|
||||
use util::hash::Sha256dHash;
|
||||
|
||||
/// The type of a wallet-spendable txout
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub enum WalletTxOutType {
|
||||
/// Pay-to-address transaction redeemable using an ECDSA key
|
||||
PayToAddress(SecretKey),
|
||||
/// Undetermined
|
||||
Unknown
|
||||
}
|
||||
|
||||
|
||||
/// A txout that is spendable by the wallet
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct WalletTxOut {
|
||||
/// The TXID of the transaction this output is part of
|
||||
pub txid: Sha256dHash,
|
||||
/// The index of the output in its transaction
|
||||
pub vout: u32,
|
||||
/// The blockheight at which this output appeared in the blockchain
|
||||
pub height: u32,
|
||||
/// The actual output
|
||||
pub txo: TxOut,
|
||||
/// A classification of the output
|
||||
pub kind: WalletTxOutType
|
||||
}
|
||||
|
||||
/// An address index
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct AddressIndex {
|
||||
tentative_index: HashMap<Script, Vec<WalletTxOut>>,
|
||||
index: HashMap<(Sha256dHash, u32), Vec<WalletTxOut>>,
|
||||
network: Network,
|
||||
k1: u64,
|
||||
k2: u64
|
||||
}
|
||||
|
||||
impl AddressIndex {
|
||||
/// Creates a new address index from a wallet (which provides an authenticated
|
||||
/// hash function for prefix filtering) and UTXO set (which is what gets filtered).
|
||||
pub fn new(utxo_set: &UtxoSet, wallet: &Wallet) -> AddressIndex {
|
||||
let (k1, k2) = wallet.siphash_key();
|
||||
let mut ret = AddressIndex {
|
||||
tentative_index: HashMap::with_capacity(utxo_set.n_utxos() / 256),
|
||||
index: HashMap::new(),
|
||||
network: wallet.network(),
|
||||
k1: k1,
|
||||
k2: k2
|
||||
};
|
||||
for (key, idx, txo, height) in utxo_set.iter() {
|
||||
if ret.admissible_txo(txo) {
|
||||
let new = WalletTxOut {
|
||||
txid: key,
|
||||
vout: idx,
|
||||
height: height,
|
||||
txo: txo.clone(),
|
||||
kind: WalletTxOutType::Unknown
|
||||
};
|
||||
let entry = ret.tentative_index.entry(txo.script_pubkey.clone());
|
||||
let txos = entry.or_insert(vec![]);
|
||||
txos.push(new);
|
||||
}
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
///
|
||||
#[inline]
|
||||
pub fn index_wallet_txo(&mut self, wtx: &WalletTxOut, kind: WalletTxOutType) {
|
||||
let mut new = wtx.clone();
|
||||
new.kind = kind;
|
||||
let entry = self.index.entry((wtx.txid, wtx.vout));
|
||||
let txos = entry.or_insert(vec![]);
|
||||
txos.push(new);
|
||||
}
|
||||
|
||||
/// A filtering function used for creating a small address index.
|
||||
#[inline]
|
||||
pub fn admissible_address(&self, addr: &Address) -> bool {
|
||||
let mut hasher = SipHasher::new_with_keys(self.k1, self.k2);
|
||||
(&addr[..]).hash(&mut hasher);
|
||||
hasher.finish() & 0xFF == 0
|
||||
}
|
||||
|
||||
/// A filtering function used for creating a small address index.
|
||||
#[inline]
|
||||
pub fn admissible_txo(&self, out: &TxOut) -> bool {
|
||||
match out.classify(self.network) {
|
||||
PayToPubkeyHash(addr) => self.admissible_address(&addr),
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
|
||||
/// Lookup a txout by its scriptpubkey. Returns a slice because there
|
||||
/// may be more than one for any given scriptpubkey.
|
||||
#[inline]
|
||||
pub fn find_by_script<'a>(&'a self, pubkey: &Script) -> &'a [WalletTxOut] {
|
||||
self.tentative_index.get(pubkey).map(|v| &v[..]).unwrap_or(&[])
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,579 +0,0 @@
|
|||
// 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::Cursor;
|
||||
use serde::{Serialize, Deserialize, Serializer, Deserializer};
|
||||
|
||||
use byteorder::{BigEndian, ByteOrder, ReadBytesExt, WriteBytesExt};
|
||||
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::{self, Secp256k1};
|
||||
|
||||
use network::constants::Network;
|
||||
use util::base58;
|
||||
use util::base58::{FromBase58, ToBase58};
|
||||
|
||||
/// 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, Serialize, Deserialize, 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, Serialize, Deserialize, 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 {
|
||||
/// Hardened key index, within [0, 2^31 - 1]
|
||||
Hardened(u32),
|
||||
/// Non-hardened key, within [0, 2^31 - 1]
|
||||
Normal(u32),
|
||||
}
|
||||
|
||||
impl Serialize for ChildNumber {
|
||||
fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error>
|
||||
where S: Serializer {
|
||||
match *self {
|
||||
ChildNumber::Hardened(n) => (n + (1 << 31)).serialize(s),
|
||||
ChildNumber::Normal(n) => n.serialize(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserialize for ChildNumber {
|
||||
fn deserialize<D>(d: &mut D) -> Result<ChildNumber, D::Error>
|
||||
where D: Deserializer {
|
||||
let n: u32 = try!(Deserialize::deserialize(d));
|
||||
if n < (1 << 31) {
|
||||
Ok(ChildNumber::Normal(n))
|
||||
} else {
|
||||
Ok(ChildNumber::Hardened(n - (1 << 31)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
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(),
|
||||
child_number: ChildNumber::Normal(0),
|
||||
secret_key: try!(SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)),
|
||||
chain_code: ChainCode::from_slice(&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 {
|
||||
ChildNumber::Normal(n) => {
|
||||
if n >= (1 << 31) { return Err(Error::InvalidChildNumber(i)) }
|
||||
// Non-hardened key: compute public data and use that
|
||||
hmac.input(&PublicKey::from_secret_key(secp, &self.secret_key, true)[..]);
|
||||
BigEndian::write_u32(&mut be_n, n);
|
||||
}
|
||||
ChildNumber::Hardened(n) => {
|
||||
if n >= (1 << 31) { return Err(Error::InvalidChildNumber(i)) }
|
||||
// Hardened key: use only secret data to prevent public derivation
|
||||
hmac.input(&[0u8]);
|
||||
hmac.input(&self.secret_key[..]);
|
||||
BigEndian::write_u32(&mut be_n, n + (1 << 31));
|
||||
}
|
||||
}
|
||||
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_slice(&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();
|
||||
sha2.input(&pk.public_key[..]);
|
||||
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_slice(&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, true),
|
||||
chain_code: sk.chain_code
|
||||
}
|
||||
}
|
||||
|
||||
/// Public->Public child key derivation
|
||||
pub fn ckd_pub(&self, secp: &Secp256k1, i: ChildNumber) -> Result<ExtendedPubKey, Error> {
|
||||
match i {
|
||||
ChildNumber::Hardened(n) => {
|
||||
if n >= (1 << 31) {
|
||||
Err(Error::InvalidChildNumber(i))
|
||||
} else {
|
||||
Err(Error::CannotDeriveFromHardenedKey)
|
||||
}
|
||||
}
|
||||
ChildNumber::Normal(n) => {
|
||||
let mut hmac = Hmac::new(Sha512::new(), &self.chain_code[..]);
|
||||
hmac.input(&self.public_key[..]);
|
||||
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);
|
||||
|
||||
let sk = try!(SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa));
|
||||
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: ChainCode::from_slice(&result[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[..]);
|
||||
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_slice(&self.identifier()[0..4])
|
||||
}
|
||||
}
|
||||
|
||||
impl ToBase58 for ExtendedPrivKey {
|
||||
fn base58_layout(&self) -> Vec<u8> {
|
||||
let mut ret = Vec::with_capacity(78);
|
||||
ret.extend(match self.network {
|
||||
Network::Bitcoin => [0x04, 0x88, 0xAD, 0xE4],
|
||||
Network::Testnet => [0x04, 0x35, 0x83, 0x94]
|
||||
}.iter().cloned());
|
||||
ret.push(self.depth as u8);
|
||||
ret.extend(self.parent_fingerprint[..].iter().cloned());
|
||||
match self.child_number {
|
||||
ChildNumber::Hardened(n) => {
|
||||
ret.write_u32::<BigEndian>(n + (1 << 31)).unwrap();
|
||||
}
|
||||
ChildNumber::Normal(n) => {
|
||||
ret.write_u32::<BigEndian>(n).unwrap();
|
||||
}
|
||||
}
|
||||
ret.extend(self.chain_code[..].iter().cloned());
|
||||
ret.push(0);
|
||||
ret.extend(self.secret_key[..].iter().cloned());
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBase58 for ExtendedPrivKey {
|
||||
fn from_base58_layout(data: Vec<u8>) -> Result<ExtendedPrivKey, base58::Error> {
|
||||
let s = Secp256k1::with_caps(secp256k1::ContextFlag::None);
|
||||
|
||||
if data.len() != 78 {
|
||||
return Err(base58::Error::InvalidLength(data.len()));
|
||||
}
|
||||
|
||||
let cn_int = Cursor::new(&data[9..13]).read_u32::<BigEndian>().unwrap();
|
||||
let child_number = if cn_int < (1 << 31) { ChildNumber::Normal(cn_int) }
|
||||
else { ChildNumber::Hardened(cn_int - (1 << 31)) };
|
||||
|
||||
Ok(ExtendedPrivKey {
|
||||
network: match &data[0..4] {
|
||||
[0x04u8, 0x88, 0xAD, 0xE4] => Network::Bitcoin,
|
||||
[0x04u8, 0x35, 0x83, 0x94] => Network::Testnet,
|
||||
_ => { return Err(base58::Error::InvalidVersion((&data[0..4]).to_vec())); }
|
||||
},
|
||||
depth: data[4],
|
||||
parent_fingerprint: Fingerprint::from_slice(&data[5..9]),
|
||||
child_number: child_number,
|
||||
chain_code: ChainCode::from_slice(&data[13..45]),
|
||||
secret_key: try!(SecretKey::from_slice(&s,
|
||||
&data[46..78]).map_err(|e|
|
||||
base58::Error::Other(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.extend(match self.network {
|
||||
Network::Bitcoin => [0x04u8, 0x88, 0xB2, 0x1E],
|
||||
Network::Testnet => [0x04u8, 0x35, 0x87, 0xCF]
|
||||
}.iter().cloned());
|
||||
ret.push(self.depth as u8);
|
||||
ret.extend(self.parent_fingerprint[..].iter().cloned());
|
||||
let mut be_n = [0; 4];
|
||||
match self.child_number {
|
||||
ChildNumber::Hardened(n) => {
|
||||
BigEndian::write_u32(&mut be_n, n + (1 << 31));
|
||||
}
|
||||
ChildNumber::Normal(n) => {
|
||||
BigEndian::write_u32(&mut be_n, n);
|
||||
}
|
||||
}
|
||||
ret.extend(be_n.iter().cloned());
|
||||
ret.extend(self.chain_code[..].iter().cloned());
|
||||
ret.extend(self.public_key[..].iter().cloned());
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBase58 for ExtendedPubKey {
|
||||
fn from_base58_layout(data: Vec<u8>) -> Result<ExtendedPubKey, base58::Error> {
|
||||
let s = Secp256k1::with_caps(secp256k1::ContextFlag::None);
|
||||
|
||||
if data.len() != 78 {
|
||||
return Err(base58::Error::InvalidLength(data.len()));
|
||||
}
|
||||
|
||||
let cn_int = Cursor::new(&data[9..13]).read_u32::<BigEndian>().unwrap();
|
||||
let child_number = if cn_int < (1 << 31) { ChildNumber::Normal(cn_int) }
|
||||
else { ChildNumber::Hardened(cn_int - (1 << 31)) };
|
||||
|
||||
Ok(ExtendedPubKey {
|
||||
network: match &data[0..4] {
|
||||
[0x04, 0x88, 0xB2, 0x1E] => Network::Bitcoin,
|
||||
[0x04, 0x35, 0x87, 0xCF] => Network::Testnet,
|
||||
_ => { return Err(base58::Error::InvalidVersion((&data[0..4]).to_vec())); }
|
||||
},
|
||||
depth: data[4],
|
||||
parent_fingerprint: Fingerprint::from_slice(&data[5..9]),
|
||||
child_number: child_number,
|
||||
chain_code: ChainCode::from_slice(&data[13..45]),
|
||||
public_key: try!(PublicKey::from_slice(&s,
|
||||
&data[45..78]).map_err(|e|
|
||||
base58::Error::Other(e.to_string())))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use secp256k1::Secp256k1;
|
||||
use serialize::hex::FromHex;
|
||||
use test::{Bencher, black_box};
|
||||
|
||||
use network::constants::Network::{self, Bitcoin};
|
||||
use util::base58::{FromBase58, ToBase58};
|
||||
|
||||
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 {
|
||||
Normal(_) => {
|
||||
let pk2 = pk.ckd_pub(secp, num).unwrap();
|
||||
pk = ExtendedPubKey::from_private(secp, &sk);
|
||||
assert_eq!(pk, pk2);
|
||||
}
|
||||
Hardened(_) => {
|
||||
pk = ExtendedPubKey::from_private(secp, &sk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check result against expected base58
|
||||
assert_eq!(&sk.to_base58check()[..], expected_sk);
|
||||
assert_eq!(&pk.to_base58check()[..], 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 secp = Secp256k1::new();
|
||||
let seed = "000102030405060708090a0b0c0d0e0f".from_hex().unwrap();
|
||||
// m
|
||||
test_path(&secp, Bitcoin, &seed, &[],
|
||||
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
|
||||
"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8");
|
||||
|
||||
// m/0h
|
||||
test_path(&secp, Bitcoin, &seed, &[Hardened(0)],
|
||||
"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
|
||||
"xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw");
|
||||
|
||||
// m/0h/1
|
||||
test_path(&secp, Bitcoin, &seed, &[Hardened(0), Normal(1)],
|
||||
"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
|
||||
"xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ");
|
||||
|
||||
// m/0h/1/2h
|
||||
test_path(&secp, Bitcoin, &seed, &[Hardened(0), Normal(1), Hardened(2)],
|
||||
"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
|
||||
"xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5");
|
||||
|
||||
// m/0h/1/2h/2
|
||||
test_path(&secp, Bitcoin, &seed, &[Hardened(0), Normal(1), Hardened(2), Normal(2)],
|
||||
"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
|
||||
"xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV");
|
||||
|
||||
// m/0h/1/2h/2/1000000000
|
||||
test_path(&secp, Bitcoin, &seed, &[Hardened(0), Normal(1), Hardened(2), Normal(2), Normal(1000000000)],
|
||||
"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
|
||||
"xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vector_2() {
|
||||
let secp = Secp256k1::new();
|
||||
let seed = "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542".from_hex().unwrap();
|
||||
|
||||
// m
|
||||
test_path(&secp, Bitcoin, &seed, &[],
|
||||
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
|
||||
"xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB");
|
||||
|
||||
// m/0
|
||||
test_path(&secp, Bitcoin, &seed, &[Normal(0)],
|
||||
"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
|
||||
"xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH");
|
||||
|
||||
// m/0/2147483647h
|
||||
test_path(&secp, Bitcoin, &seed, &[Normal(0), Hardened(2147483647)],
|
||||
"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
|
||||
"xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a");
|
||||
|
||||
// m/0/2147483647h/1
|
||||
test_path(&secp, Bitcoin, &seed, &[Normal(0), Hardened(2147483647), Normal(1)],
|
||||
"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
|
||||
"xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon");
|
||||
|
||||
// m/0/2147483647h/1/2147483646h
|
||||
test_path(&secp, Bitcoin, &seed, &[Normal(0), Hardened(2147483647), Normal(1), Hardened(2147483646)],
|
||||
"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
|
||||
"xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL");
|
||||
|
||||
// m/0/2147483647h/1/2147483646h/2
|
||||
test_path(&secp, Bitcoin, &seed, &[Normal(0), Hardened(2147483647), Normal(1), Hardened(2147483646), Normal(2)],
|
||||
"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
|
||||
"xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn encode_decode_childnumber() {
|
||||
serde_round_trip!(Normal(0));
|
||||
serde_round_trip!(Normal(1));
|
||||
serde_round_trip!(Normal((1 << 31) - 1));
|
||||
serde_round_trip!(Hardened(0));
|
||||
serde_round_trip!(Hardened(1));
|
||||
serde_round_trip!(Hardened((1 << 31) - 1));
|
||||
}
|
||||
|
||||
#[bench]
|
||||
pub fn generate_sequential_normal_children(bh: &mut Bencher) {
|
||||
let secp = Secp256k1::new();
|
||||
let seed = "000102030405060708090a0b0c0d0e0f".from_hex().unwrap();
|
||||
let msk = ExtendedPrivKey::new_master(&secp, Bitcoin, &seed).unwrap();
|
||||
let mut i = 0;
|
||||
bh.iter( || {
|
||||
black_box(msk.ckd_priv(&secp, Normal(i)).unwrap());
|
||||
i += 1;
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
pub fn generate_sequential_hardened_children(bh: &mut Bencher) {
|
||||
let secp = Secp256k1::new();
|
||||
let seed = "000102030405060708090a0b0c0d0e0f".from_hex().unwrap();
|
||||
let msk = ExtendedPrivKey::new_master(&secp, Bitcoin, &seed).unwrap();
|
||||
let mut i = 0;
|
||||
bh.iter( || {
|
||||
black_box(msk.ckd_priv(&secp, Hardened(i)).unwrap());
|
||||
i += 1;
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
pub fn generate_sequential_public_children(bh: &mut Bencher) {
|
||||
let secp = Secp256k1::new();
|
||||
let seed = "000102030405060708090a0b0c0d0e0f".from_hex().unwrap();
|
||||
let msk = ExtendedPrivKey::new_master(&secp, Bitcoin, &seed).unwrap();
|
||||
let mpk = ExtendedPubKey::from_private(&secp, &msk);
|
||||
|
||||
let mut i = 0;
|
||||
bh.iter( || {
|
||||
black_box(mpk.ckd_pub(&secp, Normal(i)).unwrap());
|
||||
i += 1;
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
pub fn generate_sequential_public_child_addresses(bh: &mut Bencher) {
|
||||
use wallet::address::Address;
|
||||
|
||||
let secp = Secp256k1::new();
|
||||
let seed = "000102030405060708090a0b0c0d0e0f".from_hex().unwrap();
|
||||
let msk = ExtendedPrivKey::new_master(&secp, Bitcoin, &seed).unwrap();
|
||||
let mpk = ExtendedPubKey::from_private(&secp, &msk);
|
||||
|
||||
let mut i = 0;
|
||||
bh.iter( || {
|
||||
let epk = mpk.ckd_pub(&secp, Normal(i)).unwrap();
|
||||
black_box(Address::from_key(Bitcoin, &epk.public_key));
|
||||
i += 1;
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
// 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 address;
|
||||
pub mod address_index;
|
||||
pub mod bip32;
|
||||
pub mod wallet;
|
||||
|
|
@ -1,283 +0,0 @@
|
|||
// 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
|
||||
//!
|
||||
//! Everything to do with the wallet
|
||||
//!
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::default::Default;
|
||||
use serde::{Serialize, Deserialize, Serializer, Deserializer};
|
||||
|
||||
use secp256k1::Secp256k1;
|
||||
use secp256k1::key::PublicKey;
|
||||
|
||||
use byteorder::{ByteOrder, LittleEndian};
|
||||
use blockdata::utxoset::UtxoSet;
|
||||
use network::constants::Network;
|
||||
use wallet::bip32::{self, ChildNumber, ExtendedPrivKey, ExtendedPubKey};
|
||||
use wallet::bip32::ChildNumber::{Normal, Hardened};
|
||||
use wallet::address::Address;
|
||||
use wallet::address_index::AddressIndex;
|
||||
|
||||
/// A Wallet error
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub enum Error {
|
||||
/// Tried to lookup an account by name, but none was found
|
||||
AccountNotFound,
|
||||
/// Tried to add an account when one already exists with that name
|
||||
DuplicateAccount,
|
||||
/// An error occured in a BIP32 derivation
|
||||
Bip32Error(bip32::Error),
|
||||
/// Tried to use a wallet without an address index
|
||||
NoAddressIndex
|
||||
}
|
||||
|
||||
/// Each account has two chains, as specified in BIP32
|
||||
pub enum AccountChain {
|
||||
/// Internal addresses are used within the wallet for change, etc,
|
||||
/// and in principle every generated one will be used.
|
||||
Internal,
|
||||
/// External addresses are shared, and might not be used after generatation,
|
||||
/// complicating recreating the whole wallet from seed.
|
||||
External
|
||||
}
|
||||
|
||||
/// An account
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
|
||||
pub struct Account {
|
||||
internal_path: Vec<ChildNumber>,
|
||||
internal_used: Vec<ChildNumber>,
|
||||
internal_next: u32,
|
||||
external_path: Vec<ChildNumber>,
|
||||
external_used: Vec<ChildNumber>,
|
||||
external_next: u32
|
||||
}
|
||||
|
||||
impl Default for Account {
|
||||
fn default() -> Account {
|
||||
Account {
|
||||
internal_path: vec![Hardened(0), Normal(1)],
|
||||
internal_used: vec![],
|
||||
internal_next: 0,
|
||||
external_path: vec![Hardened(0), Normal(0)],
|
||||
external_used: vec![],
|
||||
external_next: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A wallet
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Wallet {
|
||||
secp: Secp256k1,
|
||||
master: ExtendedPrivKey,
|
||||
accounts: HashMap<String, Account>,
|
||||
index: Option<AddressIndex>
|
||||
}
|
||||
|
||||
impl Serialize for Wallet {
|
||||
fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error>
|
||||
where S: Serializer {
|
||||
try!(self.master.serialize(s));
|
||||
self.accounts.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserialize for Wallet {
|
||||
fn deserialize<D>(d: &mut D) -> Result<Wallet, D::Error>
|
||||
where D: Deserializer {
|
||||
Ok(Wallet {
|
||||
secp: Secp256k1::new(),
|
||||
master: try!(Deserialize::deserialize(d)),
|
||||
accounts: try!(Deserialize::deserialize(d)),
|
||||
index: None
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Wallet {
|
||||
/// Creates a new wallet from a BIP32 seed
|
||||
#[inline]
|
||||
pub fn from_seed(network: Network, seed: &[u8]) -> Result<Wallet, bip32::Error> {
|
||||
let mut accounts = HashMap::new();
|
||||
accounts.insert(String::new(), Default::default());
|
||||
let secp = Secp256k1::new();
|
||||
|
||||
Ok(Wallet {
|
||||
master: try!(ExtendedPrivKey::new_master(&secp, network, seed)),
|
||||
secp: Secp256k1::new(),
|
||||
accounts: accounts,
|
||||
index: None
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates the address index
|
||||
#[inline]
|
||||
pub fn build_index(&mut self, utxo_set: &UtxoSet) {
|
||||
let new = AddressIndex::new(utxo_set, self);
|
||||
self.index = Some(new);
|
||||
}
|
||||
|
||||
/// Accessor for the wallet's address index
|
||||
#[inline]
|
||||
pub fn index<'a>(&'a self) -> Option<&'a AddressIndex> {
|
||||
self.index.as_ref()
|
||||
}
|
||||
|
||||
/// Mutable accessor for the wallet's address index
|
||||
#[inline]
|
||||
pub fn index_mut<'a>(&'a mut self) -> Option<&'a mut AddressIndex> {
|
||||
self.index.as_mut()
|
||||
}
|
||||
|
||||
/// Adds an account to a wallet
|
||||
pub fn account_insert(&mut self, name: String)
|
||||
-> Result<(), Error> {
|
||||
if self.accounts.contains_key(&name) {
|
||||
return Err(Error::DuplicateAccount);
|
||||
}
|
||||
|
||||
let idx = self.accounts.len() as u32;
|
||||
self.accounts.insert(name, Account {
|
||||
internal_path: vec![Hardened(idx), Normal(1)],
|
||||
internal_used: vec![],
|
||||
internal_next: 0,
|
||||
external_path: vec![Hardened(idx), Normal(0)],
|
||||
external_used: vec![],
|
||||
external_next: 0
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Locates an account in a wallet
|
||||
#[inline]
|
||||
pub fn account_get<'a>(&'a self, name: &str) -> Option<&'a Account> {
|
||||
self.accounts.get(name)
|
||||
}
|
||||
|
||||
/// Create a new address
|
||||
pub fn new_address(&mut self,
|
||||
account: &str,
|
||||
chain: AccountChain)
|
||||
-> Result<Address, Error> {
|
||||
let account = self.accounts.get_mut(account);
|
||||
let account = match account { Some(a) => a, None => return Err(Error::AccountNotFound) };
|
||||
let index = match self.index { Some(ref i) => i, None => return Err(Error::NoAddressIndex) };
|
||||
|
||||
let (mut i, master) = match chain {
|
||||
AccountChain::Internal => (account.internal_next,
|
||||
try!(ExtendedPrivKey::from_path(
|
||||
&self.secp,
|
||||
&self.master,
|
||||
&account.internal_path).map_err(Error::Bip32Error))),
|
||||
AccountChain::External => (account.external_next,
|
||||
try!(ExtendedPrivKey::from_path(
|
||||
&self.secp,
|
||||
&self.master,
|
||||
&account.external_path).map_err(Error::Bip32Error))),
|
||||
};
|
||||
|
||||
// Scan for next admissible address
|
||||
let mut sk = try!(master.ckd_priv(&self.secp, Normal(i)).map_err(Error::Bip32Error));
|
||||
let mut address = Address::from_key(
|
||||
master.network,
|
||||
&PublicKey::from_secret_key(&self.secp, &sk.secret_key, true));
|
||||
while !index.admissible_address(&address) {
|
||||
i += 1;
|
||||
sk = try!(master.ckd_priv(&self.secp, Normal(i)).map_err(Error::Bip32Error));
|
||||
address = Address::from_key(
|
||||
master.network,
|
||||
&PublicKey::from_secret_key(&self.secp, &sk.secret_key, true));
|
||||
}
|
||||
|
||||
match chain {
|
||||
AccountChain::Internal => {
|
||||
account.internal_used.push(Normal(i));
|
||||
account.internal_next = i + 1;
|
||||
}
|
||||
AccountChain::External => {
|
||||
account.external_used.push(Normal(i));
|
||||
account.external_next = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
/// Returns the network of the wallet
|
||||
#[inline]
|
||||
pub fn network(&self) -> Network {
|
||||
self.master.network
|
||||
}
|
||||
|
||||
/// Returns a key suitable for keying hash functions for DoS protection
|
||||
#[inline]
|
||||
pub fn siphash_key(&self) -> (u64, u64) {
|
||||
(LittleEndian::read_u64(&self.master.chain_code[0..8]),
|
||||
LittleEndian::read_u64(&self.master.chain_code[8..16]))
|
||||
}
|
||||
|
||||
/// Total balance
|
||||
pub fn total_balance(&self) -> Result<u64, Error> {
|
||||
let mut ret = 0;
|
||||
for (_, account) in self.accounts.iter() {
|
||||
ret += try!(self.account_balance(account));
|
||||
}
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
/// Account balance
|
||||
pub fn balance(&self, account: &str) -> Result<u64, Error> {
|
||||
let account = self.accounts.get(account);
|
||||
let account = match account { Some(a) => a, None => return Err(Error::AccountNotFound) };
|
||||
self.account_balance(account)
|
||||
}
|
||||
|
||||
fn account_balance(&self, account: &Account) -> Result<u64, Error> {
|
||||
let index = match self.index { Some(ref i) => i, None => return Err(Error::NoAddressIndex) };
|
||||
|
||||
let mut ret = 0;
|
||||
|
||||
// Sum internal balance
|
||||
let master = try!(ExtendedPrivKey::from_path(
|
||||
&self.secp,
|
||||
&self.master,
|
||||
&account.internal_path).map_err(Error::Bip32Error));
|
||||
for &cnum in account.internal_used.iter() {
|
||||
let sk = try!(master.ckd_priv(&self.secp, cnum).map_err(Error::Bip32Error));
|
||||
let pk = ExtendedPubKey::from_private(&self.secp, &sk);
|
||||
let addr = Address::from_key(pk.network, &pk.public_key);
|
||||
for out in index.find_by_script(&addr.script_pubkey()).iter() {
|
||||
ret += out.txo.value;
|
||||
}
|
||||
}
|
||||
// Sum external balance
|
||||
let master = try!(ExtendedPrivKey::from_path(
|
||||
&self.secp,
|
||||
&self.master,
|
||||
&account.external_path).map_err(Error::Bip32Error));
|
||||
for &cnum in account.external_used.iter() {
|
||||
let sk = try!(master.ckd_priv(&self.secp, cnum).map_err(Error::Bip32Error));
|
||||
let pk = ExtendedPubKey::from_private(&self.secp, &sk);
|
||||
let addr = Address::from_key(pk.network, &pk.public_key);
|
||||
for out in index.find_by_script(&addr.script_pubkey()).iter() {
|
||||
ret += out.txo.value;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ret)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue