use crate::{UnifiedAddress, sapling, transparent};
use bc_envelope::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub enum ProtocolAddress {
Transparent(transparent::Address),
Sapling(Box<sapling::Address>),
Unified(Box<UnifiedAddress>),
}
impl ProtocolAddress {
pub fn as_string(&self) -> String {
match self {
ProtocolAddress::Transparent(addr) => addr.address().to_string(),
ProtocolAddress::Sapling(addr) => addr.address().to_string(),
ProtocolAddress::Unified(addr) => addr.address().to_string(),
}
}
pub fn is_sapling(&self) -> bool {
matches!(self, ProtocolAddress::Sapling(_))
}
pub fn is_transparent(&self) -> bool {
matches!(self, ProtocolAddress::Transparent(_))
}
pub fn is_unified(&self) -> bool {
matches!(self, ProtocolAddress::Unified(_))
}
}
impl From<ProtocolAddress> for Envelope {
fn from(value: ProtocolAddress) -> Self {
match value {
ProtocolAddress::Transparent(addr) => addr.into(),
ProtocolAddress::Sapling(addr) => (*addr).into(),
ProtocolAddress::Unified(addr) => (*addr).into(),
}
}
}
impl TryFrom<Envelope> for ProtocolAddress {
type Error = anyhow::Error;
fn try_from(envelope: Envelope) -> Result<Self, Self::Error> {
if envelope.has_type_envelope("TransparentAddress") {
Ok(ProtocolAddress::Transparent(envelope.try_into()?))
} else if envelope.has_type_envelope("SaplingAddress") {
Ok(ProtocolAddress::Sapling(Box::new(envelope.try_into()?)))
} else if envelope.has_type_envelope("UnifiedAddress") {
Ok(ProtocolAddress::Unified(Box::new(envelope.try_into()?)))
} else {
Err(anyhow::anyhow!("Invalid ProtocolAddress type"))
}
}
}
#[cfg(test)]
mod tests {
use super::ProtocolAddress;
use crate::{UnifiedAddress, sapling, test_envelope_roundtrip, transparent};
impl crate::RandomInstance for ProtocolAddress {
fn random() -> Self {
let mut rng = rand::thread_rng();
let choice = rand::Rng::gen_range(&mut rng, 0..3);
match choice {
0 => ProtocolAddress::Transparent(transparent::Address::random()),
1 => ProtocolAddress::Sapling(Box::new(sapling::Address::random())),
_ => ProtocolAddress::Unified(Box::new(UnifiedAddress::random())),
}
}
}
test_envelope_roundtrip!(ProtocolAddress);
}