1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use base58::ToBase58;
use bitcoin_hashes::sha256d::Hash as SHA256d;
use bitcoin_hashes::Hash;
use strum_macros::{Display, EnumString};

use super::{AddressFormat, Error, Result};

/// Format specification for formatting a private key as
/// [WIF](https://en.bitcoin.it/wiki/Wallet_import_format).
///
/// Currently, this just specifies the blockchain network for which the WIF is intended to be used
/// because for each blockchain network there is exactly one supported way to serialize the private
/// key as a string.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, Display)]
pub enum WIFFormat {
    Bitcoin = 0x80,
    BitcoinTestnet = 0xEF,
    Litecoin = 0xB0,
    Dash = 0xCC,
    Dogecoin = 0x9E,
    Europecoin = 0xA8,
    Peercoin = 0xB7,
    Feathercoin = 0x8E,
    Fujicoin = 0xA4,
    VCash = 0xC7,
    Stratis = 0xBF,
    Clams = 0x85,
    Blackcoin = 0x99,
    Asiacoin = 0x97,
    /// Format the private key directly as a hex string representing the raw private key bytes
    Hex,
}

impl From<&AddressFormat> for WIFFormat {
    /// Obtain a `WIFFormat` using the same blockchain network as an AddressFormat
    fn from(opts: &AddressFormat) -> Self {
        match opts {
            AddressFormat::Bitcoin(_) => Self::Bitcoin,
            AddressFormat::BitcoinTestnet => Self::BitcoinTestnet,
            AddressFormat::BitcoinGold => Self::Bitcoin,
            AddressFormat::BitcoinCash(_) => Self::Bitcoin,
            AddressFormat::Litecoin => Self::Litecoin,
            AddressFormat::LitecoinCash => Self::Litecoin,
            AddressFormat::Dogecoin => Self::Dogecoin,
            AddressFormat::Dash => Self::Dash,
            AddressFormat::Europecoin => Self::Europecoin,
            AddressFormat::Peercoin => Self::Peercoin,
            AddressFormat::Syscoin => Self::Bitcoin,
            AddressFormat::Feathercoin => Self::Feathercoin,
            AddressFormat::Potcoin => Self::Peercoin,
            AddressFormat::Namecoin => Self::Bitcoin,
            AddressFormat::Fujicoin => Self::Fujicoin,
            AddressFormat::Verge => Self::Dogecoin,
            AddressFormat::Hempcoin => Self::Europecoin,
            AddressFormat::VCash => Self::VCash,
            AddressFormat::ZCash => Self::Bitcoin,
            AddressFormat::Vertcoin => Self::Bitcoin,
            AddressFormat::Ripple => Self::Hex,
            AddressFormat::Stratis => Self::Stratis,
            AddressFormat::Clams => Self::Clams,
            AddressFormat::Blackcoin => Self::Blackcoin,
            AddressFormat::ShadowCash => Self::Stratis,
            AddressFormat::Beetlecoin => Self::Blackcoin,
            AddressFormat::Asiacoin => Self::Asiacoin,
            #[cfg(feature = "eth")]
            AddressFormat::Ethereum => Self::Hex,
        }
    }
}

impl WIFFormat {
    /// Encode private key bytes as a WIF string
    pub(crate) fn encode(&self, private_key_bytes: impl AsRef<[u8]>) -> Result<String> {
        if let Self::Hex = self {
            return Ok(hex::encode(private_key_bytes));
        }
        // First check that the input slice is exactly 32 bytes long;
        let private_key_slice = private_key_bytes.as_ref();
        if private_key_slice.len() != 32 {
            return Err(Error::InvalidLength {
                received: private_key_slice.len(),
                expected: 32,
            });
        }
        // allocated on the stack, no biggie
        let mut buf = [0; 38];
        buf[0] = *self as u8;
        buf[1..33].copy_from_slice(private_key_slice);
        buf[33] = 1;

        let checksum = SHA256d::hash(&buf[..34]);
        buf[34..].copy_from_slice(&checksum[..4]);
        Ok(buf.to_base58())
    }
}

/// Encode a private key using WIF format
///
/// ### Usage
/// WIFs are generated using [`WIF::wif`]
/// ```
/// use crypto_addr::{WIF, WIFFormat as WF};
/// use hex_literal::hex;
///
/// const PRVKEY_BYTES: [u8; 32] =
///     hex!("fdd662f90c0ad0e8c44fcbeb991365b1a66965265d3b1d1231e988150f3fb4bf");
///
/// assert_eq!(PRVKEY_BYTES.wif(WF::Bitcoin).as_deref(),  Ok("L5j8wWT18PsT4uUQPrQmHaG8dbsGTdC6PkEvyngK96QGd1FJXfVt"));
/// assert_eq!(PRVKEY_BYTES.wif(WF::Litecoin).as_deref(), Ok("TBZQPFkBXmr3qk7GwVMdVvoWaTWaXiCzCx9BqbJri4aS8trGJjAj"));
/// assert_eq!(PRVKEY_BYTES.wif(WF::Dogecoin).as_deref(), Ok("QX846MFzP1MaJRsSz8FZAo6k6dtqWBKuGzvqmR59sT1d4wJfoMbU"));
/// assert_eq!(PRVKEY_BYTES.wif(WF::Dash).as_deref(),     Ok("XKo4PmqNS5Vu8EUnRcQdnoT9Yd8quRoLmKaqWK1WTTgN2ASdVNfh"));
/// assert_eq!(PRVKEY_BYTES.wif(WF::Hex).as_deref(),      Ok("fdd662f90c0ad0e8c44fcbeb991365b1a66965265d3b1d1231e988150f3fb4bf"));
pub trait WIF {
    /// Encode private key bytes as a WIF using blockchain parameters given by `opts`
    fn wif(&self, opts: WIFFormat) -> Result<String>;
}


/// The input bytes are interpreted as the raw private key in big-endian format.
impl WIF for [u8] {
    fn wif(&self, opts: WIFFormat) -> Result<String> {
        opts.encode(self)
    }
}

/// The input bytes are interpreted as the raw private key in big-endian format.
impl WIF for crate::PrvkeyBytes {
    fn wif(&self, opts: WIFFormat) -> Result<String> {
        opts.encode(self)
    }
}

#[cfg(feature = "k256")]
impl WIF for k256::SecretKey {
    fn wif(&self, opts: WIFFormat) -> Result<String> {
        opts.encode(&self.to_bytes())
    }
}

#[cfg(feature = "k256")]
impl WIF for k256::ecdsa::SigningKey {
    fn wif(&self, opts: WIFFormat) -> Result<String> {
        opts.encode(&self.to_bytes())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{BitcoinFormat, test_vectors::wif::*};

    fn testfun(vectors: &str, opts: WIFFormat) {
        for tc in vectors.lines().map(TestCase::from) {
            assert_eq!(tc.prv.wif(opts).as_deref(), Ok(tc.wif));
        }
    }

    #[test]
    fn btc_wif() {
        testfun(BTC_TEST_VECTORS, WIFFormat::Bitcoin)
    }
    #[test]
    fn ltc_wif() {
        testfun(LTC_TEST_VECTORS, WIFFormat::Litecoin)
    }
    #[test]
    fn doge_wif() {
        testfun(DOGE_TEST_VECTORS, WIFFormat::Dogecoin)
    }
    #[test]
    fn dash_wif() {
        testfun(DASH_TEST_VECTORS, WIFFormat::Dash)
    }
    #[test]
    fn erc_wif() {
        testfun(ERC_TEST_VECTORS, WIFFormat::Europecoin)
    }

    #[test]
    fn from_addr_opts() {
        assert_eq!(
            WIFFormat::from(&AddressFormat::Bitcoin(BitcoinFormat::Legacy)),
            WIFFormat::Bitcoin
        );
        assert_eq!(
            WIFFormat::from(&AddressFormat::BitcoinCash(None)),
            WIFFormat::Bitcoin
        );
        assert_eq!(
            WIFFormat::from(&AddressFormat::BitcoinCash(Some("ligma".to_owned()))),
            WIFFormat::Bitcoin
        );
        assert_eq!(
            WIFFormat::from(&AddressFormat::Litecoin),
            WIFFormat::Litecoin
        );
        assert_eq!(
            WIFFormat::from(&AddressFormat::Dogecoin),
            WIFFormat::Dogecoin
        );
        assert_eq!(WIFFormat::from(&AddressFormat::Dash), WIFFormat::Dash);
        assert_eq!(
            WIFFormat::from(&AddressFormat::Europecoin),
            WIFFormat::Europecoin
        );
        assert_eq!(
            WIFFormat::from(&AddressFormat::Peercoin),
            WIFFormat::Peercoin
        );
    }
}