use crate::DerivationInfo;
use super::TransparentSpendAuthority;
use anyhow::Context;
use bc_envelope::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub struct Address {
address: String,
spend_authority: Option<TransparentSpendAuthority>,
derivation_info: Option<DerivationInfo>,
}
impl Address {
pub fn new(address: impl Into<String>) -> Self {
Address {
address: address.into(),
spend_authority: None,
derivation_info: None,
}
}
pub fn address(&self) -> &str {
&self.address
}
pub fn spend_authority(&self) -> Option<&TransparentSpendAuthority> {
self.spend_authority.as_ref()
}
pub fn set_spend_authority(&mut self, spend_authority: TransparentSpendAuthority) {
self.spend_authority = Some(spend_authority);
}
pub fn derivation_info(&self) -> Option<&DerivationInfo> {
self.derivation_info.as_ref()
}
pub fn set_derivation_info(&mut self, derivation_info: DerivationInfo) {
self.derivation_info = Some(derivation_info);
}
}
impl From<Address> for Envelope {
fn from(value: Address) -> Self {
Envelope::new(value.address)
.add_type("TransparentAddress")
.add_optional_assertion("spend_authority", value.spend_authority)
.add_optional_assertion("derivation_info", value.derivation_info)
}
}
impl TryFrom<Envelope> for Address {
type Error = anyhow::Error;
fn try_from(envelope: Envelope) -> Result<Self, Self::Error> {
envelope
.check_type_envelope("TransparentAddress")
.context("TransparentAddress")?;
let address = envelope.extract_subject().context("address")?;
let spend_authority = envelope
.try_optional_object_for_predicate("spend_authority")
.context("spend_authority")?;
let derivation_info = envelope
.try_optional_object_for_predicate("derivation_info")
.context("derivation_info")?;
Ok(Address {
address,
spend_authority,
derivation_info,
})
}
}
#[cfg(test)]
impl crate::RandomInstance for Address {
fn random() -> Self {
Self {
address: String::random(),
spend_authority: TransparentSpendAuthority::opt_random(),
derivation_info: DerivationInfo::opt_random(),
}
}
}
#[cfg(test)]
mod tests {
use super::Address;
use crate::test_envelope_roundtrip;
test_envelope_roundtrip!(Address);
}