anychain_bitcoin/network/
bitcoincash.rs

1use 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 BitcoinCash;
10
11impl Network for BitcoinCash {
12    const NAME: &'static str = "bitcoin cash";
13}
14
15impl BitcoinNetwork for BitcoinCash {
16    /// Returns the address prefix of the given network.
17    fn to_address_prefix(format: BitcoinFormat) -> Result<Prefix, AddressError> {
18        match format {
19            BitcoinFormat::P2PKH => Ok(Prefix::Version(0x00)),
20            BitcoinFormat::P2WSH => Ok(Prefix::Version(0x00)),
21            BitcoinFormat::P2SH_P2WPKH => Ok(Prefix::Version(0x05)),
22            BitcoinFormat::Bech32 => Ok(Prefix::AddressPrefix("bc".to_string())),
23            BitcoinFormat::CashAddr => Ok(Prefix::AddressPrefix("bitcoincash".to_string())),
24        }
25    }
26
27    /// Returns the network of the given address prefix.
28    fn from_address_prefix(prefix: Prefix) -> Result<Self, AddressError> {
29        match prefix {
30            Prefix::Version(version) => match version {
31                0x00 | 0x05 => Ok(Self),
32                _ => Err(AddressError::Message(format!(
33                    "Invalid version byte {:#0x} for {} network",
34                    version,
35                    Self::NAME,
36                ))),
37            },
38            Prefix::AddressPrefix(prefix) => match prefix.as_str() {
39                "bc" | "bitcoincash" => Ok(Self),
40                _ => Err(AddressError::Message(format!(
41                    "Invalid Bech32 or CashAddr prefix for {} network",
42                    Self::NAME,
43                ))),
44            },
45        }
46    }
47}
48
49impl FromStr for BitcoinCash {
50    type Err = NetworkError;
51
52    fn from_str(s: &str) -> Result<Self, Self::Err> {
53        match s {
54            Self::NAME => Ok(Self),
55            _ => Err(NetworkError::InvalidNetwork(s.into())),
56        }
57    }
58}
59
60impl fmt::Display for BitcoinCash {
61    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62        write!(f, "{}", Self::NAME)
63    }
64}