anychain_bitcoin/network/
bitcoin_testnet.rs1use crate::{BitcoinFormat, BitcoinNetwork, Prefix};
2use anychain_core::no_std::*;
3use anychain_core::{AddressError, Network, NetworkError};
4
5use core::{fmt, str::FromStr};
6use serde::Serialize;
7
8#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
9pub struct BitcoinTestnet;
10
11impl Network for BitcoinTestnet {
12 const NAME: &'static str = "bitcoin testnet";
13}
14
15impl BitcoinNetwork for BitcoinTestnet {
16 fn to_address_prefix(format: BitcoinFormat) -> Result<Prefix, AddressError> {
18 match format {
19 BitcoinFormat::P2PKH => Ok(Prefix::Version(0x6f)),
20 BitcoinFormat::P2WSH => Ok(Prefix::Version(0x00)),
21 BitcoinFormat::P2SH_P2WPKH => Ok(Prefix::Version(0xc4)),
22 BitcoinFormat::Bech32 => Ok(Prefix::AddressPrefix("tb".to_string())),
23 f => Err(AddressError::Message(format!(
24 "{} does not support address format {}",
25 Self::NAME,
26 f,
27 ))),
28 }
29 }
30
31 fn from_address_prefix(prefix: Prefix) -> Result<Self, AddressError> {
33 match prefix {
34 Prefix::Version(version) => match version {
35 0x6f | 0xc4 => Ok(Self),
36 _ => Err(AddressError::Message(format!(
37 "Invalid version byte {:#0x} for {} network",
38 version,
39 Self::NAME,
40 ))),
41 },
42 Prefix::AddressPrefix(prefix) => match prefix.as_str() {
43 "tb" => Ok(Self),
44 _ => Err(AddressError::Message(format!(
45 "Invalid Bech32 prefix for {} network",
46 Self::NAME,
47 ))),
48 },
49 }
50 }
51}
52
53impl FromStr for BitcoinTestnet {
54 type Err = NetworkError;
55
56 fn from_str(s: &str) -> Result<Self, Self::Err> {
57 match s {
58 Self::NAME => Ok(Self),
59 _ => Err(NetworkError::InvalidNetwork(s.into())),
60 }
61 }
62}
63
64impl fmt::Display for BitcoinTestnet {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 write!(f, "{}", Self::NAME)
67 }
68}