use std::fmt;
use cashaddr::CashEnc;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use crate::{
domain::valid_label,
error::{Error, ValidationError},
};
macro_rules! hash_identity {
($name:ident, $doc:literal) => {
#[doc = $doc]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct $name([u8; 32]);
impl $name {
#[must_use]
pub const fn from_display_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
pub fn parse(value: &str) -> Result<Self, Error> {
if value.len() != 64 {
return Err(super::invalid());
}
const_hex::decode_to_array(value)
.map(Self)
.map_err(|_| super::invalid())
}
#[must_use]
pub const fn display_bytes(self) -> [u8; 32] {
self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&const_hex::encode(self.0))
}
}
impl Serialize for $name {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let value = String::deserialize(d)?;
Self::parse(&value).map_err(serde::de::Error::custom)
}
}
};
}
hash_identity!(
Txid,
"A complete Bitcoin Cash transaction identifier in displayed hash order."
);
hash_identity!(
BlockHash,
"A complete Bitcoin Cash block identifier in displayed hash order."
);
hash_identity!(
ScriptHash,
"An Electrum-Cash SHA256 script hash in displayed reversed-byte order."
);
hash_identity!(
TokenCategory,
"A complete `CashToken` category identifier in displayed transaction-hash order."
);
pub(super) fn sha256d_display(value: &[u8]) -> [u8; 32] {
let mut bytes: [u8; 32] = Sha256::digest(Sha256::digest(value)).into();
bytes.reverse();
bytes
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AddressNamespace {
Mainnet,
Testnet,
Regtest,
}
impl AddressNamespace {
#[must_use]
pub const fn prefix(self) -> &'static str {
match self {
Self::Mainnet => "bitcoincash",
Self::Testnet => "bchtest",
Self::Regtest => "bchreg",
}
}
const fn legacy_versions(self) -> (u8, u8) {
match self {
Self::Mainnet => (0, 5),
Self::Testnet | Self::Regtest => (111, 196),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AddressKind {
PubkeyHash,
ScriptHash,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "AddressFields", into = "AddressFields")]
pub struct Address {
namespace: AddressNamespace,
encoded: String,
kind: AddressKind,
token_aware: bool,
hash: Vec<u8>,
}
impl Address {
pub fn parse(value: &str, namespace: AddressNamespace) -> Result<Self, Error> {
let invalid = || Error::Validation(ValidationError::InvalidBitcoinCashAddress);
if value.is_empty()
|| value.len() > 128
|| !value.is_ascii()
|| value
.bytes()
.any(|b| b.is_ascii_whitespace() || b.is_ascii_control())
{
return Err(invalid());
}
if !value.contains(':')
&& !matches!(
value.as_bytes()[0],
b'q' | b'p' | b'z' | b'r' | b'Q' | b'P' | b'Z' | b'R'
)
{
let bytes = bs58::decode(value)
.with_check(None)
.into_vec()
.map_err(|_| invalid())?;
if bytes.len() != 21 || bs58::encode(&bytes).with_check().into_string() != value {
return Err(invalid());
}
let (public, script) = namespace.legacy_versions();
let kind = if bytes[0] == public {
AddressKind::PubkeyHash
} else if bytes[0] == script {
AddressKind::ScriptHash
} else {
return Err(ValidationError::NetworkMismatch.into());
};
return Self::from_hash(namespace, kind, false, &bytes[1..]);
}
let upper = value.bytes().any(|b| b.is_ascii_uppercase());
let lower = value.bytes().any(|b| b.is_ascii_lowercase());
if upper && lower {
return Err(invalid());
}
let normalized = value.to_ascii_lowercase();
let full = if normalized.contains(':') {
normalized
} else {
format!("{}:{normalized}", namespace.prefix())
};
let (prefix, payload_text) = full.split_once(':').ok_or_else(invalid)?;
if prefix != namespace.prefix() {
return Err(ValidationError::NetworkMismatch.into());
}
if !matches!(payload_text.len(), 42 | 61) {
return Err(invalid());
}
let payload: cashaddr::Payload = full.parse().map_err(|_| invalid())?;
let type_bits = payload.hash_type().numeric_value();
let (kind, token_aware) = match type_bits {
0 => (AddressKind::PubkeyHash, false),
1 => (AddressKind::ScriptHash, false),
2 => (AddressKind::PubkeyHash, true),
3 => (AddressKind::ScriptHash, true),
_ => return Err(invalid()),
};
let result = Self::from_hash(namespace, kind, token_aware, payload.as_ref())?;
if result.encoded != full {
return Err(invalid());
}
Ok(result)
}
pub fn from_hash(
namespace: AddressNamespace,
kind: AddressKind,
token_aware: bool,
hash: &[u8],
) -> Result<Self, Error> {
let invalid = || Error::Validation(ValidationError::InvalidBitcoinCashAddress);
if !matches!(
(kind, hash.len()),
(AddressKind::PubkeyHash, 20) | (AddressKind::ScriptHash, 20 | 32)
) {
return Err(invalid());
}
let bits = u8::from(kind == AddressKind::ScriptHash) + 2 * u8::from(token_aware);
let encoded = hash
.encode(
namespace.prefix(),
cashaddr::HashType::try_from(bits).map_err(|_| invalid())?,
)
.map_err(|_| invalid())?;
Ok(Self {
namespace,
encoded,
kind,
token_aware,
hash: hash.to_vec(),
})
}
#[must_use]
pub const fn namespace(&self) -> AddressNamespace {
self.namespace
}
#[must_use]
pub const fn kind(&self) -> AddressKind {
self.kind
}
#[must_use]
pub const fn is_token_aware(&self) -> bool {
self.token_aware
}
#[must_use]
pub fn hash(&self) -> &[u8] {
&self.hash
}
#[must_use]
pub fn locking_bytecode(&self) -> Vec<u8> {
let (prefix, suffix): (&[u8], &[u8]) = match (self.kind, self.hash.len()) {
(AddressKind::PubkeyHash, _) => (&[0x76, 0xa9, 0x14], &[0x88, 0xac]),
(AddressKind::ScriptHash, 32) => (&[0xaa, 0x20], &[0x87]),
(AddressKind::ScriptHash, _) => (&[0xa9, 0x14], &[0x87]),
};
[prefix, &self.hash, suffix].concat()
}
#[must_use]
pub fn script_hash(&self) -> ScriptHash {
let mut bytes: [u8; 32] = Sha256::digest(self.locking_bytecode()).into();
bytes.reverse();
ScriptHash::from_display_bytes(bytes)
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.encoded)
}
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct AddressFields {
namespace: AddressNamespace,
encoded: String,
}
impl TryFrom<AddressFields> for Address {
type Error = Error;
fn try_from(v: AddressFields) -> Result<Self, Error> {
Self::parse(&v.encoded, v.namespace)
}
}
impl From<Address> for AddressFields {
fn from(v: Address) -> Self {
Self {
namespace: v.namespace,
encoded: v.encoded,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "CheckpointFields")]
pub struct ForkCheckpoint {
height: u32,
hash: BlockHash,
}
impl ForkCheckpoint {
pub fn new(height: u32, hash: BlockHash) -> Result<Self, Error> {
if height == 0 || hash.display_bytes() == [0; 32] {
return Err(super::invalid());
}
Ok(Self { height, hash })
}
#[must_use]
pub const fn height(self) -> u32 {
self.height
}
#[must_use]
pub const fn hash(self) -> BlockHash {
self.hash
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CheckpointFields {
height: u32,
hash: BlockHash,
}
impl TryFrom<CheckpointFields> for ForkCheckpoint {
type Error = Error;
fn try_from(v: CheckpointFields) -> Result<Self, Error> {
Self::new(v.height, v.hash)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "NetworkFields")]
pub struct NetworkIdentity {
namespace: AddressNamespace,
genesis_hash: BlockHash,
fork_checkpoint: ForkCheckpoint,
alias: String,
}
impl NetworkIdentity {
pub fn new(
namespace: AddressNamespace,
genesis_hash: BlockHash,
fork_checkpoint: ForkCheckpoint,
alias: impl Into<String>,
) -> Result<Self, Error> {
let alias = alias.into();
if genesis_hash.display_bytes() == [0; 32] || !valid_label(&alias, 128) {
return Err(super::invalid());
}
Ok(Self {
namespace,
genesis_hash,
fork_checkpoint,
alias,
})
}
pub fn mainnet(alias: impl Into<String>) -> Result<Self, Error> {
Self::new(
AddressNamespace::Mainnet,
BlockHash::parse("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f")?,
ForkCheckpoint::new(
661_648,
BlockHash::parse(
"0000000000000000029e471c41818d24b8b74c911071c4ef0b4a0509f9b5a8ce",
)?,
)?,
alias,
)
}
#[must_use]
pub const fn namespace(&self) -> AddressNamespace {
self.namespace
}
#[must_use]
pub const fn genesis_hash(&self) -> BlockHash {
self.genesis_hash
}
#[must_use]
pub const fn fork_checkpoint(&self) -> ForkCheckpoint {
self.fork_checkpoint
}
#[must_use]
pub fn alias(&self) -> &str {
&self.alias
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NetworkFields {
namespace: AddressNamespace,
genesis_hash: BlockHash,
fork_checkpoint: ForkCheckpoint,
alias: String,
}
impl TryFrom<NetworkFields> for NetworkIdentity {
type Error = Error;
fn try_from(v: NetworkFields) -> Result<Self, Error> {
Self::new(v.namespace, v.genesis_hash, v.fork_checkpoint, v.alias)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "HeaderFields")]
pub struct BlockHeader {
hex: String,
hash: BlockHash,
}
impl BlockHeader {
pub fn from_hex(hex: &str) -> Result<Self, Error> {
if hex.len() != 160 {
return Err(super::invalid());
}
let bytes: [u8; 80] = const_hex::decode_to_array(hex).map_err(|_| super::invalid())?;
Ok(Self {
hex: const_hex::encode(bytes),
hash: BlockHash::from_display_bytes(sha256d_display(&bytes)),
})
}
#[must_use]
pub fn hex(&self) -> &str {
&self.hex
}
#[must_use]
pub const fn hash(&self) -> BlockHash {
self.hash
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HeaderFields {
hex: String,
hash: BlockHash,
}
impl TryFrom<HeaderFields> for BlockHeader {
type Error = Error;
fn try_from(v: HeaderFields) -> Result<Self, Error> {
let header = Self::from_hex(&v.hex)?;
if header.hash != v.hash {
return Err(super::invalid());
}
Ok(header)
}
}