Skip to content

Commit

Permalink
zcash_address: Add support for ZIP 320, TEX addresses.
Browse files Browse the repository at this point in the history
  • Loading branch information
nuttycom authored and str4d committed Mar 6, 2024
1 parent 16e3d1b commit a6bac34
Show file tree
Hide file tree
Showing 8 changed files with 191 additions and 23 deletions.
6 changes: 6 additions & 0 deletions components/zcash_address/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ and this library adheres to Rust's notion of

## [Unreleased]

### Added
- `zcash_address::convert`:
- `TryFromRawAddress::try_from_raw_tex`
- `TryFromAddress::try_from_tex`
- `ToAddress::from_tex`

## [0.3.1] - 2024-01-12
### Fixed
- Stubs for `zcash_address::convert` traits that are created by `rust-analyzer`
Expand Down
27 changes: 27 additions & 0 deletions components/zcash_address/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ pub trait TryFromRawAddress: Sized {
"transparent P2SH",
)))
}

fn try_from_raw_tex(data: [u8; 20]) -> Result<Self, ConversionError<Self::Error>> {
let _ = data;
Err(ConversionError::Unsupported(UnsupportedAddress(
"transparent-source restricted P2PKH",
)))
}
}

/// A helper trait for converting a [`ZcashAddress`] into another type.
Expand Down Expand Up @@ -225,6 +232,13 @@ pub trait TryFromAddress: Sized {
"transparent P2SH",
)))
}

fn try_from_tex(net: Network, data: [u8; 20]) -> Result<Self, ConversionError<Self::Error>> {
let _ = (net, data);
Err(ConversionError::Unsupported(UnsupportedAddress(
"transparent-source restricted P2PKH",
)))
}
}

impl<T: TryFromRawAddress> TryFromAddress for (Network, T) {
Expand Down Expand Up @@ -261,6 +275,10 @@ impl<T: TryFromRawAddress> TryFromAddress for (Network, T) {
) -> Result<Self, ConversionError<Self::Error>> {
T::try_from_raw_transparent_p2sh(data).map(|addr| (net, addr))
}

fn try_from_tex(net: Network, data: [u8; 20]) -> Result<Self, ConversionError<Self::Error>> {
T::try_from_raw_tex(data).map(|addr| (net, addr))
}
}

/// A helper trait for converting another type into a [`ZcashAddress`].
Expand Down Expand Up @@ -304,6 +322,8 @@ pub trait ToAddress: private::Sealed {
fn from_transparent_p2pkh(net: Network, data: [u8; 20]) -> Self;

fn from_transparent_p2sh(net: Network, data: [u8; 20]) -> Self;

fn from_tex(net: Network, data: [u8; 20]) -> Self;
}

impl ToAddress for ZcashAddress {
Expand Down Expand Up @@ -353,6 +373,13 @@ impl ToAddress for ZcashAddress {
kind: AddressKind::P2sh(data),
}
}

fn from_tex(net: Network, data: [u8; 20]) -> Self {
ZcashAddress {
net,
kind: AddressKind::Tex(data),
}
}
}

mod private {
Expand Down
143 changes: 120 additions & 23 deletions components/zcash_address/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,34 +56,56 @@ impl FromStr for ZcashAddress {
kind: AddressKind::Unified(data),
});
}
Err(unified::ParseError::NotUnified) => {
// allow decoding to fall through to Sapling/Transparent
Err(unified::ParseError::NotUnified | unified::ParseError::UnknownPrefix(_)) => {
// allow decoding to fall through to Sapling/TEX/Transparent
}
Err(e) => {
return Err(ParseError::from(e));
}
}

// Try decoding as a Sapling address (Bech32)
if let Ok((hrp, data, Variant::Bech32)) = bech32::decode(s) {
// If we reached this point, the encoding is supposed to be valid Bech32.
// Try decoding as a Sapling or TEX address (Bech32/Bech32m)
if let Ok((hrp, data, variant)) = bech32::decode(s) {
// If we reached this point, the encoding is found to be valid Bech32 or Bech32m.
let data = Vec::<u8>::from_base32(&data).map_err(|_| ParseError::InvalidEncoding)?;

let net = match hrp.as_str() {
mainnet::HRP_SAPLING_PAYMENT_ADDRESS => NetworkType::Main,
testnet::HRP_SAPLING_PAYMENT_ADDRESS => NetworkType::Test,
regtest::HRP_SAPLING_PAYMENT_ADDRESS => NetworkType::Regtest,
// We will not define new Bech32 address encodings.
_ => {
return Err(ParseError::NotZcash);
match variant {
Variant::Bech32 => {
let net = match hrp.as_str() {
mainnet::HRP_SAPLING_PAYMENT_ADDRESS => NetworkType::Main,
testnet::HRP_SAPLING_PAYMENT_ADDRESS => NetworkType::Test,
regtest::HRP_SAPLING_PAYMENT_ADDRESS => NetworkType::Regtest,
// We will not define new Bech32 address encodings.
_ => {
return Err(ParseError::NotZcash);
}
};

return data[..]
.try_into()
.map(AddressKind::Sapling)
.map_err(|_| ParseError::InvalidEncoding)
.map(|kind| ZcashAddress { net, kind });
}
};
Variant::Bech32m => {
// Try decoding as a TEX address (Bech32m)
let net = match hrp.as_str() {
mainnet::HRP_TEX_ADDRESS => NetworkType::Main,
testnet::HRP_TEX_ADDRESS => NetworkType::Test,
regtest::HRP_TEX_ADDRESS => NetworkType::Regtest,
// Not recognized as a Zcash address type
_ => {
return Err(ParseError::NotZcash);
}
};

return data[..]
.try_into()
.map(AddressKind::Sapling)
.map_err(|_| ParseError::InvalidEncoding)
.map(|kind| ZcashAddress { net, kind });
return data[..]
.try_into()
.map(AddressKind::Tex)
.map_err(|_| ParseError::InvalidEncoding)
.map(|kind| ZcashAddress { net, kind });
}
}
}

// The rest use Base58Check.
Expand Down Expand Up @@ -122,8 +144,8 @@ impl FromStr for ZcashAddress {
}
}

fn encode_bech32(hrp: &str, data: &[u8]) -> String {
bech32::encode(hrp, data.to_base32(), Variant::Bech32).expect("hrp is invalid")
fn encode_bech32(hrp: &str, data: &[u8], variant: Variant) -> String {
bech32::encode(hrp, data.to_base32(), variant).expect("hrp is invalid")
}

fn encode_b58(prefix: [u8; 2], data: &[u8]) -> String {
Expand All @@ -137,19 +159,26 @@ impl fmt::Display for ZcashAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let encoded = match &self.kind {
AddressKind::Sprout(data) => encode_b58(self.net.b58_sprout_address_prefix(), data),
AddressKind::Sapling(data) => {
encode_bech32(self.net.hrp_sapling_payment_address(), data)
}
AddressKind::Sapling(data) => encode_bech32(
self.net.hrp_sapling_payment_address(),
data,
Variant::Bech32,
),
AddressKind::Unified(addr) => addr.encode(&self.net),
AddressKind::P2pkh(data) => encode_b58(self.net.b58_pubkey_address_prefix(), data),
AddressKind::P2sh(data) => encode_b58(self.net.b58_script_address_prefix(), data),
AddressKind::Tex(data) => {
encode_bech32(self.net.hrp_tex_address(), data, Variant::Bech32m)
}
};
write!(f, "{}", encoded)
}
}

#[cfg(test)]
mod tests {
use assert_matches::assert_matches;

use super::*;
use crate::{kind::unified, Network};

Expand Down Expand Up @@ -258,6 +287,74 @@ mod tests {
);
}

#[test]
fn tex() {
let p2pkh_str = "t1VmmGiyjVNeCjxDZzg7vZmd99WyzVby9yC";
let tex_str = "tex1s2rt77ggv6q989lr49rkgzmh5slsksa9khdgte";

// Transcode P2PKH to TEX
let p2pkh_zaddr: ZcashAddress = p2pkh_str.parse().unwrap();
assert_matches!(p2pkh_zaddr.net, Network::Main);
if let AddressKind::P2pkh(zaddr_data) = p2pkh_zaddr.kind {
let tex_zaddr = ZcashAddress {
net: p2pkh_zaddr.net,
kind: AddressKind::Tex(zaddr_data),
};

assert_eq!(tex_zaddr.to_string(), tex_str);
} else {
panic!("Decoded address should have been a P2PKH address.");
}

// Transcode TEX to P2PKH
let tex_zaddr: ZcashAddress = tex_str.parse().unwrap();
assert_matches!(tex_zaddr.net, Network::Main);
if let AddressKind::Tex(zaddr_data) = tex_zaddr.kind {
let p2pkh_zaddr = ZcashAddress {
net: tex_zaddr.net,
kind: AddressKind::P2pkh(zaddr_data),
};

assert_eq!(p2pkh_zaddr.to_string(), p2pkh_str);
} else {
panic!("Decoded address should have been a TEX address.");
}
}

#[test]
fn tex_testnet() {
let p2pkh_str = "tm9ofD7kHR7AF8MsJomEzLqGcrLCBkD9gDj";
let tex_str = "textest1qyqszqgpqyqszqgpqyqszqgpqyqszqgpfcjgfy";

// Transcode P2PKH to TEX
let p2pkh_zaddr: ZcashAddress = p2pkh_str.parse().unwrap();
assert_matches!(p2pkh_zaddr.net, Network::Test);
if let AddressKind::P2pkh(zaddr_data) = p2pkh_zaddr.kind {
let tex_zaddr = ZcashAddress {
net: p2pkh_zaddr.net,
kind: AddressKind::Tex(zaddr_data),
};

assert_eq!(tex_zaddr.to_string(), tex_str);
} else {
panic!("Decoded address should have been a P2PKH address.");
}

// Transcode TEX to P2PKH
let tex_zaddr: ZcashAddress = tex_str.parse().unwrap();
assert_matches!(tex_zaddr.net, Network::Test);
if let AddressKind::Tex(zaddr_data) = tex_zaddr.kind {
let p2pkh_zaddr = ZcashAddress {
net: tex_zaddr.net,
kind: AddressKind::P2pkh(zaddr_data),
};

assert_eq!(p2pkh_zaddr.to_string(), p2pkh_str);
} else {
panic!("Decoded address should have been a TEX address.");
}
}

#[test]
fn whitespace() {
assert_eq!(
Expand Down
3 changes: 3 additions & 0 deletions components/zcash_address/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ enum AddressKind {
Unified(unified::Address),
P2pkh([u8; 20]),
P2sh([u8; 20]),
Tex([u8; 20]),
}

impl ZcashAddress {
Expand Down Expand Up @@ -222,6 +223,7 @@ impl ZcashAddress {
AddressKind::Unified(data) => T::try_from_unified(self.net, data),
AddressKind::P2pkh(data) => T::try_from_transparent_p2pkh(self.net, data),
AddressKind::P2sh(data) => T::try_from_transparent_p2sh(self.net, data),
AddressKind::Tex(data) => T::try_from_tex(self.net, data),
}
}

Expand Down Expand Up @@ -257,6 +259,7 @@ impl ZcashAddress {
T::try_from_raw_transparent_p2pkh(data)
}
AddressKind::P2sh(data) if regtest_exception => T::try_from_raw_transparent_p2sh(data),
AddressKind::Tex(data) if network_matches => T::try_from_raw_tex(data),
_ => Err(ConversionError::IncorrectNetwork {
expected: net,
actual: self.net,
Expand Down
20 changes: 20 additions & 0 deletions components/zcash_protocol/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,14 @@ pub trait NetworkConstants: Clone {
///
/// [`TransparentAddress::Script`]: zcash_primitives::legacy::TransparentAddress::Script
fn b58_script_address_prefix(&self) -> [u8; 2];

/// Returns the Bech32-encoded human-readable prefix for TEX addresses, for the
/// network to which this `NetworkConstants` value applies.
///
/// Defined in [ZIP 320].
///
/// [ZIP 320]: https://zips.z.cash/zip-0320
fn hrp_tex_address(&self) -> &'static str;
}

/// The enumeration of known Zcash network types.
Expand Down Expand Up @@ -264,6 +272,14 @@ impl NetworkConstants for NetworkType {
NetworkType::Regtest => regtest::B58_SCRIPT_ADDRESS_PREFIX,
}
}

fn hrp_tex_address(&self) -> &'static str {
match self {
NetworkType::Main => mainnet::HRP_TEX_ADDRESS,
NetworkType::Test => testnet::HRP_TEX_ADDRESS,
NetworkType::Regtest => regtest::HRP_TEX_ADDRESS,
}
}
}

/// Zcash consensus parameters.
Expand Down Expand Up @@ -310,6 +326,10 @@ impl<P: Parameters> NetworkConstants for P {
fn b58_script_address_prefix(&self) -> [u8; 2] {
self.network_type().b58_script_address_prefix()
}

fn hrp_tex_address(&self) -> &'static str {
self.network_type().hrp_tex_address()
}
}

/// Marker struct for the production network.
Expand Down
5 changes: 5 additions & 0 deletions components/zcash_protocol/src/constants/mainnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,8 @@ pub const B58_PUBKEY_ADDRESS_PREFIX: [u8; 2] = [0x1c, 0xb8];
///
/// [`ScriptHash`]: https://docs.rs/zcash_primitives/latest/zcash_primitives/legacy/enum.TransparentAddress.html
pub const B58_SCRIPT_ADDRESS_PREFIX: [u8; 2] = [0x1c, 0xbd];

/// The HRP for a Bech32m-encoded mainnet [ZIP 320] TEX address.
///
/// [ZIP 320]: https://zips.z.cash/zip-0320
pub const HRP_TEX_ADDRESS: &str = "tex";
5 changes: 5 additions & 0 deletions components/zcash_protocol/src/constants/regtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,8 @@ pub const B58_PUBKEY_ADDRESS_PREFIX: [u8; 2] = [0x1d, 0x25];
///
/// [`ScriptHash`]: https://docs.rs/zcash_primitives/latest/zcash_primitives/legacy/enum.TransparentAddress.html
pub const B58_SCRIPT_ADDRESS_PREFIX: [u8; 2] = [0x1c, 0xba];

/// The HRP for a Bech32m-encoded regtest [ZIP 320] TEX address.
///
/// [ZIP 320]: https://zips.z.cash/zip-0320
pub const HRP_TEX_ADDRESS: &str = "texregtest";
5 changes: 5 additions & 0 deletions components/zcash_protocol/src/constants/testnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,8 @@ pub const B58_PUBKEY_ADDRESS_PREFIX: [u8; 2] = [0x1d, 0x25];
///
/// [`ScriptHash`]: https://docs.rs/zcash_primitives/latest/zcash_primitives/legacy/enum.TransparentAddress.html
pub const B58_SCRIPT_ADDRESS_PREFIX: [u8; 2] = [0x1c, 0xba];

/// The HRP for a Bech32m-encoded testnet [ZIP 320] TEX address.
///
/// [ZIP 320]: https://zips.z.cash/zip-0320
pub const HRP_TEX_ADDRESS: &str = "textest";

0 comments on commit a6bac34

Please sign in to comment.