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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use std::fmt;
use std::str::FromStr;

use base58::ToBase58;
use bitcoin_hashes::hash160::Hash as Hash160;
use bitcoin_hashes::sha256d::Hash as SHA256d;
use bitcoin_hashes::Hash;
use cashaddr::CashEnc;
#[cfg(feature = "eth")]
use k256::elliptic_curve::sec1::ToEncodedPoint;
#[cfg(feature = "eth")]
use sha3::{Digest, Keccak256};

use super::{Error, Result};

/// Format specification for generating addresses from public keys.
///
/// Specifies how a public key should be formatted into an address. Unit-like variants
/// merely specify the blockchain network for which the address is intended to be used. No further
/// information is needed for unit-like variants because this crate only supports one way to
/// format the public key into an address string for that blockchain network.
///
/// Non-unit-like variants specify a blockchain network, but also contain additional user options
/// that further specify how the address should be formatted.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AddressFormat {
    /// Bitcoin mainnet.
    // Bitcoin is the default value because it has the highest market capitalization at the time of
    // writing
    Bitcoin(BitcoinFormat),
    BitcoinTestnet,
    #[cfg(feature = "eth")]
    Ethereum,
    /// Bitcoin cash mainnet. Inner value is the human-readable prefix to use in the address. If it
    /// is `Some`, the contained `String` will be used as the prefix to calculate with the cashaddr
    /// string with and it will be included in the cashaddr. If it is `None`, `"bitcoincash"` will
    /// be used as the prefix, but it will be omitted from the cashaddr as it is implied.
    BitcoinCash(Option<String>),
    Litecoin,
    LitecoinCash,
    Dogecoin,
    Dash,
    Ripple,
    Namecoin,
    Asiacoin,
    BitcoinGold,
    Beetlecoin,
    Blackcoin,
    Clams,
    Europecoin,
    Feathercoin,
    Fujicoin,
    Hempcoin,
    Peercoin,
    Potcoin,
    ShadowCash,
    Stratis,
    Syscoin,
    VCash,
    Verge,
    Vertcoin,
    ZCash,
}

impl Default for AddressFormat {
    fn default() -> Self {
        Self::Bitcoin(Default::default())
    }
}

/// Bitcoin Address format type
///
/// Bitcoin public keys can generate addresses in differeent formats. Bitcoin is special among the
/// other `AddressFormat` variants in that there is more the one way to format the public key. This
/// enum is used to specify which of the supported formats to use for Bitcoin addresses.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum BitcoinFormat {
    #[default]
    /// Legacy P2PKH format
    Legacy,
    /// Pay to script address that embeds a witness pay to public key. This is a segwit address
    /// type that looks familiar (as p2sh) to legacy clients.
    P2SHWPKH,
}

impl FromStr for AddressFormat {
    type Err = Error;

    /// Parse a string `s` to return an `AddressFormat` instance. `s` must be either the common
    /// ticker symbol which represents the cryptocurrency or the name of the blockchain network.
    /// Parsing is case-insensitive: e.g. `"btc"`, `"bitcoin"`, `"BTC"`, and `"Bitcoin"` all parse
    /// to `Bitcoin`, `"ltc"` and `"litecoin"` parse to `Litecoin`, etc.
    ///
    /// In the case of Bitcoin Cash addresses, the optional human-readable prefix can be specified
    /// after a `:`, e.g. `"bch"` parses to `BitcoinCash(None)` and `"bch:hrpref` parses to
    /// `BitcoinCash(Some(String::from("hrpref")))`
    fn from_str(s: &str) -> Result<Self> {
        if s.to_lowercase().starts_with("bch") {
            return match s.find(':') {
                None => Ok(Self::BitcoinCash(None)),
                Some(position) => Ok(Self::BitcoinCash(Some(s[position + 1..].to_owned()))),
            };
        }
        match s.to_lowercase().as_ref() {
            "btc" | "bitcoin" => Ok(Self::Bitcoin(BitcoinFormat::Legacy)),
            "btc:sw" => Ok(Self::Bitcoin(BitcoinFormat::P2SHWPKH)),
            "btctest" | "bitcointestnet" => Ok(Self::BitcoinTestnet),
            "ltc" | "litecoin" => Ok(Self::Litecoin),
            "lcc" | "litecoincash" => Ok(Self::LitecoinCash),
            "doge" | "dogecoin" => Ok(Self::Dogecoin),
            "dash" => Ok(Self::Dash),
            "btg" | "bitcoingold" => Ok(Self::BitcoinGold),
            "xrp" => Ok(Self::Ripple),
            "erc" | "europecoin" => Ok(Self::Europecoin),
            "ppc" | "peercoin" => Ok(Self::Peercoin),
            "sys" | "syscoin" => Ok(Self::Syscoin),
            "ftc" | "feathercoin" => Ok(Self::Feathercoin),
            "pot" | "potcoin" => Ok(Self::Potcoin),
            "nmc" | "namecoin" => Ok(Self::Namecoin),
            "fjc" | "fujicoin" => Ok(Self::Fujicoin),
            "xvg" | "verge" => Ok(Self::Verge),
            "thc" | "hempcoin" => Ok(Self::Hempcoin),
            "xvc" | "vcash" => Ok(Self::VCash),
            "zec" | "zcash" => Ok(Self::ZCash),
            "vtc" | "vertcoin" => Ok(Self::Vertcoin),
            "strat" | "stratis" => Ok(Self::Stratis),
            "clam" | "clams" => Ok(Self::Clams),
            "blk" | "blackcoin" => Ok(Self::Blackcoin),
            "sdc" | "shadowcash" => Ok(Self::ShadowCash),
            "beet" | "beetlecoin" => Ok(Self::Beetlecoin),
            "ac" | "asiacoin" => Ok(Self::Asiacoin),
            #[cfg(feature = "eth")]
            "eth" | "ethereum" => Ok(Self::Ethereum),
            _ => Err(Error::ParseFailure(format!(
                "Could not parse {} to AddressFormat",
                s
            ))),
        }
    }
}

impl fmt::Display for AddressFormat {
    /// Write the name of the blockchain network this AddressFormat is associated with
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bitcoin(_) => write!(f, "Bitcoin"),
            Self::BitcoinTestnet => write!(f, "Bitcoin Testnet"),
            Self::BitcoinCash(_) => write!(f, "Bitcoin Cash"),
            Self::BitcoinGold => write!(f, "Bitcoin Gold"),
            Self::Litecoin => write!(f, "Litecoin"),
            Self::LitecoinCash => write!(f, "Litecoin Cash"),
            Self::Dogecoin => write!(f, "Dogecoin"),
            Self::Dash => write!(f, "Dash"),
            Self::Europecoin => write!(f, "Europecoin"),
            Self::Ripple => write!(f, "Ripple"),
            Self::Peercoin => write!(f, "Peercoin"),
            Self::Syscoin => write!(f, "Syscoin"),
            Self::Feathercoin => write!(f, "Feathercoin"),
            Self::Potcoin => write!(f, "Potcoin"),
            Self::Namecoin => write!(f, "Namecoin"),
            Self::Fujicoin => write!(f, "Fujicoin"),
            Self::Verge => write!(f, "Verge"),
            Self::Hempcoin => write!(f, "Hempcoin"),
            Self::VCash => write!(f, "VCash"),
            Self::ZCash => write!(f, "ZCash"),
            Self::Vertcoin => write!(f, "Vertcoin"),
            Self::Stratis => write!(f, "Stratis"),
            Self::Clams => write!(f, "Clams"),
            Self::Blackcoin => write!(f, "Blackcoin"),
            Self::ShadowCash => write!(f, "ShadowCash"),
            Self::Beetlecoin => write!(f, "Beetlecoin"),
            Self::Asiacoin => write!(f, "Asiacoin"),
            #[cfg(feature = "eth")]
            Self::Ethereum => write!(f, "Ethereum"),
        }
    }
}

fn pubkey_hash(pubkey: &[u8], prefix: u8) -> [u8; 25] {
    let pubkey_hash = Hash160::hash(pubkey);
    let mut raw_final = [prefix; 25];
    raw_final[1..21].copy_from_slice(&pubkey_hash);
    let checksum = SHA256d::hash(&raw_final[..21]);
    raw_final[21..].copy_from_slice(&checksum[..4]);
    raw_final
}

impl AddressFormat {
    /// get the address's prefix byte if it exists
    pub fn address_prefix(&self) -> Option<u8> {
        use AddressFormat::*;
        match self {
            Bitcoin(BitcoinFormat::Legacy) => Some(0),
            Bitcoin(BitcoinFormat::P2SHWPKH) => None,
            BitcoinTestnet => Some(0x6F),
            BitcoinCash(_) => Some(0),
            Litecoin => Some(0x30),
            LitecoinCash => Some(0x1C),
            Dogecoin => Some(0x1E),
            Dash => Some(0x4C),
            BitcoinGold => Some(0x26),
            Europecoin => Some(0x21),
            Ripple => Some(0x00),
            Peercoin => Some(0x37),
            Syscoin => Some(0x3F),
            Feathercoin => Some(0x0E),
            Potcoin => Some(0x37),
            Namecoin => Some(0x34),
            Fujicoin => Some(0x24),
            Verge => Some(0x1E),
            Hempcoin => Some(0x28),
            VCash => Some(0x47),
            Vertcoin => Some(0x47),
            Stratis => Some(0x3F),
            Clams => Some(0x89),
            Blackcoin => Some(0x19),
            ShadowCash => Some(0x3F),
            Beetlecoin => Some(0x1A),
            Asiacoin => Some(0x17),
            ZCash => None, // Zcash used a 2-byte prefix so it is a special case
            #[cfg(feature = "eth")]
            Ethereum => None,
        }
    }
    /// Get the name of the network associated with these options
    pub fn network_name(&self) -> String {
        self.to_string()
    }
    /// Get the maximum string length of the address generated for the given address options. This
    /// is useful for formatting.
    pub fn length(&self) -> usize {
        match self {
            Self::BitcoinCash(prefix) => match prefix {
                Some(prefix) => 43 + prefix.len(),
                None => 42,
            },
            #[cfg(feature = "eth")]
            Self::Ethereum => 42,
            _ => 34,
        }
    }
    fn verify_len(actual: usize, expected: usize) -> Result<()> {
        if actual != expected {
            Err(Error::InvalidLength { received: actual, expected})
        } else {
            Ok(())
        }
    }
    /// Compute the P2PKH address of a public encoded as SEC 1 compressed public key bytes
    pub(crate) fn derive(&self, pubkey_bytes: impl AsRef<[u8]>) -> Result<String> {
        use AddressFormat::*;
        let bytes = pubkey_bytes.as_ref();

        match self {
            Ripple => {
                Self::verify_len(bytes.len(), 33)?;
                let pkh = pubkey_hash(bytes, self.address_prefix().unwrap());
                Ok(bs58::encode(pkh)
                    .with_alphabet(bs58::Alphabet::RIPPLE)
                    .into_string())
            }
            BitcoinCash(prefix) => {
                let keyhash = Hash160::hash(bytes);
                let string = match prefix {
                    Some(prefix) => keyhash.encode_p2pkh(prefix).unwrap(),
                    None => {
                        let mut string = keyhash.encode_p2pkh("bitcoincash").unwrap();
                        let position = string.find(':').unwrap();
                        string.replace_range(..position + 1, "");
                        string
                    }
                };
                Ok(string)
            }
            ZCash => {
                let pubkey_hash = Hash160::hash(bytes);
                let mut raw_final: [u8; 26] = [0; 26];
                raw_final[..2].copy_from_slice(&[0x1C, 0xB8]);
                raw_final[2..22].copy_from_slice(&pubkey_hash);
                let checksum = SHA256d::hash(&raw_final[..22]);
                raw_final[22..].copy_from_slice(&checksum[..4]);
                Ok(raw_final.to_base58())
            }
            Bitcoin(BitcoinFormat::P2SHWPKH) => {
                let pubkey_hash = Hash160::hash(bytes);
                let mut raw_final: [u8; 25] = [0x05; 25];
                let mut buf: [u8; 22] = [0; 22];
                buf[..2].copy_from_slice(&[0x00, 0x14]);
                buf[2..].copy_from_slice(&pubkey_hash);
                raw_final[1..21].copy_from_slice(&Hash160::hash(&buf));
                let (l, r) = raw_final.split_at_mut(21);
                r.copy_from_slice(&SHA256d::hash(l)[..4]);
                Ok(raw_final.to_base58())
            }
            #[cfg(feature = "eth")]
            Ethereum => {
                let pubkey =
                    k256::PublicKey::from_sec1_bytes(bytes).expect("failed parsing eth bytes");
                let addr = Keccak256::digest(&pubkey.to_encoded_point(false).as_bytes()[1..]);
                Ok(eip55::checksum(&hex::encode(&addr[12..])))
            }
            // Bitcoin style address format. These formats differ from each other only in the
            // version byte used
            _ => {
                Self::verify_len(bytes.len(), 33)?;
                Ok(pubkey_hash(bytes, self.address_prefix().unwrap()).to_base58())
            }
        }
    }
}


/// Generate an Address string from existing Public Key
///
/// This trait provides the main functionality of the crate. The `addr` method implements encoding
/// a public key as an address.
///
/// ### Usage
/// Addresses are generated from public keys using [`Address::addr`]
///
/// ```
/// use crypto_addr::{Address, AddressFormat as AF, Error};
/// use hex_literal::hex;
///
/// // This is a compressed public key in SEC 1 standard format
/// const PUBKEY_BYTES: [u8; 33] =
///     hex!("029d08f65e6aac041328edaeddba9c682356f81b37b052728fd8637c14eddb7ff1");
///
/// // Generate a Bitcoin P2PKH address
///
/// // Derive a legacy P2PKH Bitcoin Address from the Public Key (this is the Default AddressFormat)
/// assert_eq!(PUBKEY_BYTES.addr(&AF::default()).as_deref(), Ok("14cWWeAYZmA9oGgLpjekay9xLwHew3Ni34"));
///
/// // Derive Addresses from public key bytes in various other formats
/// assert_eq!(PUBKEY_BYTES.addr(&AF::Litecoin).as_deref(), Ok("LNqTmrUNeRQD45NVzse3rzDiZ9ew7HMYDY"));
/// assert_eq!(PUBKEY_BYTES.addr(&AF::Dogecoin).as_deref(), Ok("D8kc3u7BsB4SLGrwZKeK8jKZE51xKNc3FF"));
/// assert_eq!(PUBKEY_BYTES.addr(&AF::Ripple).as_deref(),   Ok("rhcWWewYZmw9oGgLFjek2y9xLAHeAs45sh"));
/// assert_eq!(PUBKEY_BYTES.addr(&AF::Dash).as_deref(),     Ok("XeJMLtpSXUNjxDGvgcxySVqkBGsM1d5LRg"));
/// assert_eq!(PUBKEY_BYTES.addr(&AF::ZCash).as_deref(),    Ok("t1MV7WyagY5wkPujEmATsinFsbbUjoMy6b3"));
/// assert_eq!(PUBKEY_BYTES.addr(&AF::BitcoinGold).as_deref(),   Ok("GMTRvmVVYcmSsjydkgJs1jVrG75W2Zc7dR"));
///
/// // Generate a Bitcoin Cash P2PKH address with elided "bitcoincash" prefix
/// assert_eq!(
///     PUBKEY_BYTES.addr(&AF::BitcoinCash(None)).as_deref(),
///     Ok("qqnelysjjjyrn4eywr04vf4v9nydrqdk6vep2tp2g9")
/// );
///
/// // Generate a Bitcoin Cash P2PKH address with a custom prefix
/// assert_eq!(
///     PUBKEY_BYTES.addr(&AF::BitcoinCash(Some("foo".to_owned()))).as_deref(),
///     Ok("foo:qqnelysjjjyrn4eywr04vf4v9nydrqdk6v730zmhs6")
/// );
///
/// // Errors are detected
/// let partial_pubkey = &PUBKEY_BYTES[..30];
/// assert_eq!(
///     partial_pubkey.addr(&Default::default()).unwrap_err(),
///     Error::InvalidLength{expected: 33, received: 30}
/// );
/// ```
pub trait Address {
    /// Derive an address string from a public key (`self`). Parameters for the address format
    /// are given by `opts`. Returns `Err` if public key is not able to derive an address, i.e. if
    /// it is not the correct length.
    fn addr(&self, opts: &AddressFormat) -> Result<String>;
}

/// Array of input bytes is interpreted as a compressed public key encoded with encoding described
/// in [SEC 1: Elliptic Curve Cryptography (Version 2.0)](http://www.secg.org/sec1-v2.pdf) section
/// 2.3.3 (page 10).
impl Address for crate::PubkeyBytes {
    fn addr(&self, opts: &AddressFormat) -> Result<String> {
        opts.derive(self)
    }
}

/// Slice of input bytes is interpreted as a compressed public key encoded with encoding described
/// in [SEC 1: Elliptic Curve Cryptography (Version 2.0)](http://www.secg.org/sec1-v2.pdf) section
/// 2.3.3 (page 10).
impl Address for [u8] {
    fn addr(&self, opts: &AddressFormat) -> Result<String> {
        opts.derive(self)
    }
}


#[cfg(feature = "secp256k1")]
impl Address for secp256k1::PublicKey {
    fn addr(&self, opts: &AddressFormat) -> Result<String> {
        opts.derive(self.serialize())
    }
}

#[cfg(feature = "k256")]
impl Address for k256::PublicKey {
    fn addr(&self, opts: &AddressFormat) -> Result<String> {
        opts.derive(self.to_encoded_point(true).as_bytes())
    }
}

#[cfg(feature = "k256")]
impl Address for k256::ecdsa::VerifyingKey {
    fn addr(&self, opts: &AddressFormat) -> Result<String> {
        opts.derive(self.to_encoded_point(true)) }
}

#[cfg(test)]
mod tests {
    use super::{AddressFormat::{self, *}, BitcoinFormat::*, Address};
    use crate::test_vectors::addr::*;
    #[cfg(feature = "k256")]
    use hex_literal::hex;

    #[test]
    fn parse_network() {
        assert_eq!("Bitcoin".parse(), Ok(Bitcoin(Legacy)));
        assert_eq!("BTC".parse(), Ok(Bitcoin(Legacy)));
        assert_eq!("btc".parse(), Ok(Bitcoin(Legacy)));
        assert_eq!("litecoin".parse(), Ok(Litecoin));
        assert_eq!("Litecoin".parse(), Ok(Litecoin));
        assert_eq!("ltc".parse(), Ok(Litecoin));
        assert_eq!("LTC".parse(), Ok(Litecoin));
        assert_eq!("dogecoin".parse(), Ok(Dogecoin));
        assert_eq!("Dogecoin".parse(), Ok(Dogecoin));
        assert_eq!("doge".parse(), Ok(Dogecoin));
        assert_eq!("DOGE".parse(), Ok(Dogecoin));
        assert_eq!("bch".parse(), Ok(BitcoinCash(None)));
        assert_eq!(
            "bch:ligma".parse(),
            Ok(BitcoinCash(Some("ligma".to_owned())))
        );
        #[cfg(feature = "eth")]
        assert_eq!("eth".parse(), Ok(Ethereum));
        #[cfg(feature = "eth")]
        assert_eq!("etheReUm".parse(), Ok(Ethereum));
    }
    #[test]
    fn network_name() {
        assert_eq!(Bitcoin(Legacy).network_name(), "Bitcoin");
        assert_eq!(Bitcoin(P2SHWPKH).network_name(), "Bitcoin");
        assert_eq!(BitcoinCash(None).network_name(), "Bitcoin Cash");
        assert_eq!(
            BitcoinCash(Some(String::from("test"))).network_name(),
            "Bitcoin Cash"
        );
        assert_eq!(Litecoin.network_name(), "Litecoin");
        assert_eq!(Dogecoin.network_name(), "Dogecoin");
        assert_eq!(Dash.network_name(), "Dash");
        #[cfg(feature = "eth")]
        assert_eq!(Ethereum.network_name(), "Ethereum");
    }

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

    #[test]
    fn format_doge() {
        testfun(DOGE_TEST_VECTORS, &Dogecoin)
    }
    #[test]
    fn format_btc() {
        testfun(BTC_TEST_VECTORS, &Bitcoin(Legacy))
    }
    #[test]
    fn format_ltc() {
        testfun(LTC_TEST_VECTORS, &Litecoin)
    }
    #[test]
    fn format_dash() {
        testfun(DASH_TEST_VECTORS, &Dash)
    }
    #[test]
    fn format_btg() {
        testfun(BTG_TEST_VECTORS, &BitcoinGold)
    }
    #[test]
    fn format_erc() {
        testfun(ERC_TEST_VECTORS, &Europecoin)
    }
    #[test]
    fn format_xrp() {
        testfun(XRP_TEST_VECTORS, &Ripple)
    }
    #[test]
    fn format_ppc() {
        testfun(PPC_TEST_VECTORS, &Peercoin)
    }
    #[test]
    fn format_bch() {
        testfun(BCH_TEST_VECTORS, &BitcoinCash(None))
    }
    #[test]
    fn format_sys() {
        testfun(SYS_TEST_VECTORS, &Syscoin);
    }
    #[test]
    fn format_ftc() {
        testfun(FTC_TEST_VECTORS, &Feathercoin);
    }
    #[test]
    fn format_pot() {
        testfun(POT_TEST_VECTORS, &Potcoin);
    }
    #[test]
    fn format_nmc() {
        testfun(NMC_TEST_VECTORS, &Namecoin);
    }
    #[test]
    fn format_btc_testnet() {
        testfun(BTCTESTNET_TEST_VECTORS, &BitcoinTestnet);
    }
    #[test]
    fn format_lcc() {
        testfun(LCC_TEST_VECTORS, &LitecoinCash);
    }
    #[test]
    fn format_fjc() {
        testfun(FJC_TEST_VECTORS, &Fujicoin);
    }
    #[test]
    fn format_xvg() {
        testfun(XVG_TEST_VECTORS, &Verge);
    }
    #[test]
    fn format_thc() {
        testfun(THC_TEST_VECTORS, &Hempcoin);
    }
    #[test]
    fn format_xvc() {
        testfun(XVC_TEST_VECTORS, &VCash);
    }
    #[test]
    fn format_zec() {
        testfun(ZEC_TEST_VECTORS, &ZCash);
    }
    #[test]
    fn format_vtc() {
        testfun(VTC_TEST_VECTORS, &Vertcoin);
    }
    #[test]
    fn format_strat() {
        testfun(STRAT_TEST_VECTORS, &Stratis);
    }
    #[test]
    fn format_clams() {
        testfun(CLAMS_TEST_VECTORS, &Clams);
    }
    #[test]
    fn format_blk() {
        testfun(BLK_TEST_VECTORS, &Blackcoin);
    }
    #[test]
    fn format_btc_swp2sh() {
        testfun(BTC_SWP2SH_TEST_VECTORS, &Bitcoin(P2SHWPKH));
    }
    #[test]
    fn format_sdc() {
        testfun(SDC_TEST_VECTORS, &ShadowCash);
    }
    #[test]
    fn format_beet() {
        testfun(BEET_TEST_VECTORS, &Beetlecoin);
    }
    #[test]
    fn format_ac() {
        testfun(AC_TEST_VECTORS, &Asiacoin);
    }
    #[cfg(feature = "eth")]
    #[test]
    fn format_eth() {
        testfun(ETH_TEST_VECTORS, &Ethereum)
    }

    #[test]
    fn format_bch_prefix() {
        for tc in BCH_PREFIXED_VECTORS.lines().map(TestCase::from) {
            let prefix = &tc.addr[..5];
            let addr = BitcoinCash(Some(prefix.to_owned())).derive(tc.pubkey);
            assert_eq!(addr.as_deref(), Ok(tc.addr))
        }
    }
    #[cfg(feature = "secp256k1")]
    #[test]
    fn addr_for_secp_pubkey() {
        let public_key: secp256k1::PublicKey =
            "029d08f65e6aac041328edaeddba9c682356f81b37b052728fd8637c14eddb7ff1".parse().unwrap();
        let addr = public_key.addr(&Default::default());
        assert_eq!(addr.as_deref(), Ok("14cWWeAYZmA9oGgLpjekay9xLwHew3Ni34"));
    }
    #[cfg(feature = "k256")]
    #[test]
    fn addr_for_k256_pubkey() {
        let pubkey_bytes = hex!("029d08f65e6aac041328edaeddba9c682356f81b37b052728fd8637c14eddb7ff1");
        let pubkey = k256::PublicKey::from_sec1_bytes(&pubkey_bytes).unwrap();
        assert_eq!(
            pubkey.addr(&Default::default()).as_deref(),
            Ok("14cWWeAYZmA9oGgLpjekay9xLwHew3Ni34")
        )
    }
    #[cfg(feature = "k256")]
    #[test]
    fn addr_for_k256_verifying() {
        let pubkey_bytes = hex!("029d08f65e6aac041328edaeddba9c682356f81b37b052728fd8637c14eddb7ff1");
        let pubkey = k256::ecdsa::VerifyingKey::from_sec1_bytes(&pubkey_bytes).unwrap();
        assert_eq!(
            pubkey.addr(&Default::default()).as_deref(),
            Ok("14cWWeAYZmA9oGgLpjekay9xLwHew3Ni34")
        )
    }
}