bitcoin/util/
privkey.rs

1// Rust Bitcoin Library
2// Written in 2014 by
3//     Andrew Poelstra <apoelstra@wpsoftware.net>
4// To the extent possible under law, the author(s) have dedicated all
5// copyright and related and neighboring rights to this software to
6// the public domain worldwide. This software is distributed without
7// any warranty.
8//
9// You should have received a copy of the CC0 Public Domain Dedication
10// along with this software.
11// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
12//
13
14//! Private key
15//!
16//! A private key represents the secret data associated with its proposed use
17//!
18
19use std::fmt::{self, Write};
20use std::str::FromStr;
21use secp256k1::{self, Secp256k1};
22use secp256k1::key::{PublicKey, SecretKey};
23use util::address::Address;
24use consensus::encode;
25use network::constants::Network;
26use util::base58;
27
28#[derive(Clone, PartialEq, Eq)]
29/// A Bitcoin ECDSA private key
30pub struct Privkey {
31    /// Whether this private key represents a compressed address
32    pub compressed: bool,
33    /// The network on which this key should be used
34    pub network: Network,
35    /// The actual ECDSA key
36    pub key: SecretKey
37}
38
39impl Privkey {
40    /// Creates a `Privkey` from a raw secp256k1 secret key
41    #[inline]
42    pub fn from_secret_key(key: SecretKey, compressed: bool, network: Network) -> Privkey {
43        Privkey {
44            compressed: compressed,
45            network: network,
46            key: key,
47        }
48    }
49
50    /// Computes the public key as supposed to be used with this secret
51    pub fn public_key<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> PublicKey {
52        PublicKey::from_secret_key(secp, &self.key)
53    }
54
55    /// Converts a private key to a segwit address
56    #[inline]
57    pub fn to_address<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> Address {
58        Address::p2wpkh(&self.public_key(secp), self.network)
59    }
60
61    /// Converts a private key to a legacy (non-segwit) address
62    #[inline]
63    pub fn to_legacy_address<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> Address {
64        if self.compressed {
65            Address::p2pkh(&self.public_key(secp), self.network)
66        }
67        else {
68            Address::p2upkh(&self.public_key(secp), self.network)
69        }
70    }
71
72    /// Accessor for the underlying secp key
73    #[inline]
74    pub fn secret_key(&self) -> &SecretKey {
75        &self.key
76    }
77
78    /// Accessor for the underlying secp key that consumes the privkey
79    #[inline]
80    pub fn into_secret_key(self) -> SecretKey {
81        self.key
82    }
83
84    /// Accessor for the network type
85    #[inline]
86    pub fn network(&self) -> Network {
87        self.network
88    }
89
90    /// Accessor for the compressed flag
91    #[inline]
92    pub fn is_compressed(&self) -> bool {
93        self.compressed
94    }
95
96    /// Format the private key to WIF format.
97    pub fn fmt_wif(&self, fmt: &mut fmt::Write) -> fmt::Result {
98        let mut ret = [0; 34];
99        ret[0] = match self.network {
100            Network::Bitcoin => 128,
101            Network::Testnet | Network::Regtest => 239,
102        };
103        ret[1..33].copy_from_slice(&self.key[..]);
104        let privkey = if self.compressed {
105            ret[33] = 1;
106            base58::check_encode_slice(&ret[..])
107        } else {
108            base58::check_encode_slice(&ret[..33])
109        };
110        fmt.write_str(&privkey)
111    }
112
113    /// Get WIF encoding of this private key.
114    #[inline]
115    pub fn to_wif(&self) -> String {
116        let mut buf = String::new();
117        buf.write_fmt(format_args!("{}", self)).unwrap();
118        buf.shrink_to_fit();
119        buf
120    }
121
122    /// Parse WIF encoded private key.
123    pub fn from_wif(wif: &str) -> Result<Privkey, encode::Error> {
124        let data = base58::from_check(wif)?;
125
126        let compressed = match data.len() {
127            33 => false,
128            34 => true,
129            _ => { return Err(encode::Error::Base58(base58::Error::InvalidLength(data.len()))); }
130        };
131
132        let network = match data[0] {
133            128 => Network::Bitcoin,
134            239 => Network::Testnet,
135            x   => { return Err(encode::Error::Base58(base58::Error::InvalidVersion(vec![x]))); }
136        };
137
138        let key = SecretKey::from_slice(&data[1..33])
139            .map_err(|_| base58::Error::Other("Secret key out of range".to_owned()))?;
140
141        Ok(Privkey {
142            compressed: compressed,
143            network: network,
144            key: key
145        })
146    }
147}
148
149impl fmt::Display for Privkey {
150    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
151        self.fmt_wif(f)
152    }
153}
154
155impl fmt::Debug for Privkey {
156    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157        write!(f, "[private key data]")
158    }
159}
160
161impl FromStr for Privkey {
162    type Err = encode::Error;
163    fn from_str(s: &str) -> Result<Privkey, encode::Error> {
164        Privkey::from_wif(s)
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::Privkey;
171    use secp256k1::Secp256k1;
172    use std::str::FromStr;
173    use network::constants::Network::Testnet;
174    use network::constants::Network::Bitcoin;
175
176    #[test]
177    fn test_key_derivation() {
178        // testnet compressed
179        let sk = Privkey::from_wif("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
180        assert_eq!(sk.network(), Testnet);
181        assert_eq!(sk.is_compressed(), true);
182        assert_eq!(&sk.to_wif(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
183
184        let secp = Secp256k1::new();
185        let pk = sk.to_legacy_address(&secp);
186        assert_eq!(&pk.to_string(), "mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx");
187
188        // test string conversion
189        assert_eq!(&sk.to_string(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
190        let sk_str =
191            Privkey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
192        assert_eq!(&sk.to_wif(), &sk_str.to_wif());
193
194        // mainnet uncompressed
195        let sk = Privkey::from_wif("5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3").unwrap();
196        assert_eq!(sk.network(), Bitcoin);
197        assert_eq!(sk.is_compressed(), false);
198        assert_eq!(&sk.to_wif(), "5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3");
199
200        let secp = Secp256k1::new();
201        let pk = sk.to_legacy_address(&secp);
202        assert_eq!(&pk.to_string(), "1GhQvF6dL8xa6wBxLnWmHcQsurx9RxiMc8");
203    }
204}