use std::{fmt, str::FromStr};
use bitcoin::{Network as BitcoinNetwork, address::NetworkUnchecked};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::{
domain::valid_label,
error::{Error, ValidationError},
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Network {
Mainnet,
Testnet3,
Testnet4,
Signet,
Regtest,
}
impl Network {
pub(super) const fn primitive(self) -> BitcoinNetwork {
match self {
Self::Mainnet => BitcoinNetwork::Bitcoin,
Self::Testnet3 => BitcoinNetwork::Testnet,
Self::Testnet4 => BitcoinNetwork::Testnet4,
Self::Signet => BitcoinNetwork::Signet,
Self::Regtest => BitcoinNetwork::Regtest,
}
}
#[must_use]
pub fn genesis_hash(self) -> BlockHash {
BlockHash(bitcoin::constants::genesis_block(self.primitive()).block_hash())
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "NetworkFields")]
pub struct NetworkId {
network: Network,
genesis_hash: BlockHash,
alias: String,
}
impl NetworkId {
pub fn new(network: Network, alias: impl Into<String>) -> Result<Self, Error> {
let alias = alias.into();
if !valid_label(&alias, 64) {
return Err(ValidationError::InvalidNetworkAlias.into());
}
Ok(Self {
network,
genesis_hash: network.genesis_hash(),
alias,
})
}
#[must_use]
pub const fn network(&self) -> Network {
self.network
}
#[must_use]
pub const fn genesis_hash(&self) -> &BlockHash {
&self.genesis_hash
}
#[must_use]
pub fn alias(&self) -> &str {
&self.alias
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NetworkFields {
network: Network,
genesis_hash: BlockHash,
alias: String,
}
impl TryFrom<NetworkFields> for NetworkId {
type Error = Error;
fn try_from(fields: NetworkFields) -> Result<Self, Error> {
let network = Self::new(fields.network, fields.alias)?;
if network.genesis_hash != fields.genesis_hash {
return Err(ValidationError::NetworkMismatch.into());
}
Ok(network)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "AddressFields", into = "AddressFields")]
pub struct Address {
network: Network,
address: bitcoin::Address,
}
impl Address {
pub(super) fn from_script(script: &bitcoin::Script, network: Network) -> Option<Self> {
bitcoin::Address::from_script(script, network.primitive())
.ok()
.map(|address| Self { network, address })
}
pub fn parse(value: &str, network: Network) -> Result<Self, Error> {
let address = bitcoin::Address::<NetworkUnchecked>::from_str(value)
.map_err(|_| Error::Validation(ValidationError::InvalidBitcoinAddress))?
.require_network(network.primitive())
.map_err(|_| Error::Validation(ValidationError::BitcoinAddressNetworkMismatch))?;
Ok(Self { network, address })
}
#[must_use]
pub const fn network(&self) -> Network {
self.network
}
}
impl fmt::Display for Address {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.address.fmt(formatter)
}
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct AddressFields {
network: Network,
encoded: String,
}
impl From<Address> for AddressFields {
fn from(value: Address) -> Self {
Self {
network: value.network,
encoded: value.to_string(),
}
}
}
impl TryFrom<AddressFields> for Address {
type Error = Error;
fn try_from(value: AddressFields) -> Result<Self, Error> {
Self::parse(&value.encoded, value.network)
}
}
macro_rules! hash_type {
($name:ident, $primitive:ty, $reason:ident, $description:literal) => {
#[doc = $description]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct $name($primitive);
impl $name {
pub fn parse(value: &str) -> Result<Self, Error> {
if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(ValidationError::$reason.into());
}
<$primitive>::from_str(value)
.map(Self)
.map_err(|_| ValidationError::$reason.into())
}
}
impl fmt::Display for $name {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
impl Serialize for $name {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::parse(&String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
};
}
hash_type!(
BlockHash,
bitcoin::BlockHash,
InvalidBitcoinHash,
"A complete Bitcoin block hash with canonical lowercase hexadecimal serialization."
);
hash_type!(
Txid,
bitcoin::Txid,
InvalidBitcoinTxid,
"A complete Bitcoin transaction identifier with canonical lowercase hexadecimal serialization."
);
hash_type!(
Wtxid,
bitcoin::Wtxid,
InvalidBitcoinTxid,
"A complete witness transaction identifier computed including witness data."
);
impl Txid {
pub(super) const fn from_native(value: bitcoin::Txid) -> Self {
Self(value)
}
}
impl Wtxid {
pub(super) const fn from_native(value: bitcoin::Wtxid) -> Self {
Self(value)
}
}