|
| 1 | +//! A stake address. |
| 2 | +
|
| 3 | +// cspell: words Scripthash, Keyhash |
| 4 | + |
| 5 | +use std::fmt::{Display, Formatter}; |
| 6 | + |
| 7 | +use anyhow::{anyhow, Context}; |
| 8 | +use pallas::{ |
| 9 | + crypto::hash::Hash, |
| 10 | + ledger::{ |
| 11 | + addresses::{ |
| 12 | + ShelleyAddress, ShelleyDelegationPart, ShelleyPaymentPart, |
| 13 | + StakeAddress as PallasStakeAddress, |
| 14 | + }, |
| 15 | + primitives::conway, |
| 16 | + }, |
| 17 | +}; |
| 18 | + |
| 19 | +use crate::Network; |
| 20 | + |
| 21 | +/// A stake address. |
| 22 | +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] |
| 23 | +pub struct StakeAddress(PallasStakeAddress); |
| 24 | + |
| 25 | +impl StakeAddress { |
| 26 | + /// Creates a new instance from the given parameters. |
| 27 | + #[allow(clippy::expect_used, clippy::missing_panics_doc)] |
| 28 | + #[must_use] |
| 29 | + pub fn new(network: Network, is_script: bool, hash: Hash<28>) -> Self { |
| 30 | + let network = network.into(); |
| 31 | + // `pallas::StakeAddress` can only be constructed from `ShelleyAddress`, so we are forced |
| 32 | + // to create a dummy shelley address. The input hash parameter is used to construct both |
| 33 | + // payment and delegation parts, but the payment part isn't used in the stake address |
| 34 | + // construction, so it doesn't matter. |
| 35 | + let payment = ShelleyPaymentPart::Key(hash); |
| 36 | + let delegation = if is_script { |
| 37 | + ShelleyDelegationPart::Script(hash) |
| 38 | + } else { |
| 39 | + ShelleyDelegationPart::Key(hash) |
| 40 | + }; |
| 41 | + let address = ShelleyAddress::new(network, payment, delegation); |
| 42 | + // This conversion can only fail if the delegation part isn't key or script, but we know |
| 43 | + // it is valid because we construct it just above. |
| 44 | + let address = address.try_into().expect("Unexpected delegation part"); |
| 45 | + Self(address) |
| 46 | + } |
| 47 | + |
| 48 | + /// Creates `StakeAddress` from `StakeCredential`. |
| 49 | + #[must_use] |
| 50 | + pub fn from_stake_cred(network: Network, cred: &conway::StakeCredential) -> Self { |
| 51 | + match cred { |
| 52 | + conway::StakeCredential::Scripthash(h) => Self::new(network, true, *h), |
| 53 | + conway::StakeCredential::AddrKeyhash(h) => Self::new(network, false, *h), |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /// Returns true if it is a script address. |
| 58 | + #[must_use] |
| 59 | + pub fn is_script(&self) -> bool { |
| 60 | + self.0.is_script() |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +impl From<PallasStakeAddress> for StakeAddress { |
| 65 | + fn from(value: PallasStakeAddress) -> Self { |
| 66 | + Self(value) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +impl TryFrom<ShelleyAddress> for StakeAddress { |
| 71 | + type Error = anyhow::Error; |
| 72 | + |
| 73 | + fn try_from(value: ShelleyAddress) -> Result<Self, Self::Error> { |
| 74 | + let address = PallasStakeAddress::try_from(value.clone()) |
| 75 | + .with_context(|| format!("Unable to get stake address from {value:?}"))?; |
| 76 | + Ok(Self(address)) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +impl TryFrom<&[u8]> for StakeAddress { |
| 81 | + type Error = anyhow::Error; |
| 82 | + |
| 83 | + fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { |
| 84 | + /// A stake address length in bytes. |
| 85 | + const ADDRESS_LENGTH: usize = 29; |
| 86 | + /// A hash length in bytes. |
| 87 | + const HASH_LENGTH: usize = 28; |
| 88 | + |
| 89 | + let (header, hash) = match bytes { |
| 90 | + [header, hash @ ..] if hash.len() == HASH_LENGTH => (header, Hash::<28>::from(hash)), |
| 91 | + _ => { |
| 92 | + return Err(anyhow!( |
| 93 | + "Invalid bytes length: {}, expected {ADDRESS_LENGTH}", |
| 94 | + bytes.len() |
| 95 | + )); |
| 96 | + }, |
| 97 | + }; |
| 98 | + |
| 99 | + // The network part stored in the last four bits of the header. |
| 100 | + let network = match header & 0b0000_1111 { |
| 101 | + 0 => Network::Preprod, |
| 102 | + 1 => Network::Mainnet, |
| 103 | + v => return Err(anyhow!("Unexpected network value: {v}, header = {header}")), |
| 104 | + }; |
| 105 | + |
| 106 | + // The 'type' (stake or script) is stored in the first four bits of the header. |
| 107 | + let type_ = header >> 4; |
| 108 | + let is_script = match type_ { |
| 109 | + 0b1110 => false, |
| 110 | + 0b1111 => true, |
| 111 | + v => return Err(anyhow!("Unexpected type value: {v}, header = {header}")), |
| 112 | + }; |
| 113 | + |
| 114 | + Ok(Self::new(network, is_script, hash)) |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +/// This conversion returns a 29 bytes value that includes both header and hash. |
| 119 | +impl From<StakeAddress> for Vec<u8> { |
| 120 | + fn from(value: StakeAddress) -> Self { |
| 121 | + value.0.to_vec() |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +impl Display for StakeAddress { |
| 126 | + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 127 | + // The `to_bech32` implementation returns an error if the network isn't equal to testnet |
| 128 | + // or mainnet. We don't allow other networks, so it is safe to unwrap, but just in case |
| 129 | + // return a debug representation. |
| 130 | + let bech32 = self |
| 131 | + .0 |
| 132 | + .to_bech32() |
| 133 | + .unwrap_or_else(|_| format!("{:?}", self.0)); |
| 134 | + write!(f, "{bech32}") |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +#[cfg(test)] |
| 139 | +mod tests { |
| 140 | + use super::*; |
| 141 | + |
| 142 | + #[allow(clippy::indexing_slicing)] |
| 143 | + #[test] |
| 144 | + fn roundtrip() { |
| 145 | + let hash: Hash<28> = "276fd18711931e2c0e21430192dbeac0e458093cd9d1fcd7210f64b3" |
| 146 | + .parse() |
| 147 | + .unwrap(); |
| 148 | + let test_data = [ |
| 149 | + (Network::Mainnet, true, hash, 0b1111_0001), |
| 150 | + (Network::Mainnet, false, hash, 0b1110_0001), |
| 151 | + (Network::Preprod, true, hash, 0b1111_0000), |
| 152 | + (Network::Preprod, false, hash, 0b1110_0000), |
| 153 | + (Network::Preview, true, hash, 0b1111_0000), |
| 154 | + (Network::Preview, false, hash, 0b1110_0000), |
| 155 | + ]; |
| 156 | + |
| 157 | + for (network, is_script, hash, expected_header) in test_data { |
| 158 | + let stake_address = StakeAddress::new(network, is_script, hash); |
| 159 | + assert_eq!(stake_address.is_script(), is_script); |
| 160 | + |
| 161 | + // Check that conversion to bytes includes the expected header value. |
| 162 | + let bytes: Vec<_> = stake_address.clone().into(); |
| 163 | + assert_eq!(29, bytes.len(), "Invalid length for {network} {is_script}"); |
| 164 | + assert_eq!( |
| 165 | + &bytes[1..], |
| 166 | + hash.as_ref(), |
| 167 | + "Invalid hash for {network} {is_script}" |
| 168 | + ); |
| 169 | + assert_eq!( |
| 170 | + expected_header, |
| 171 | + *bytes.first().unwrap(), |
| 172 | + "Invalid header for {network} {is_script}" |
| 173 | + ); |
| 174 | + |
| 175 | + // Check that it is possible to create an address from the bytes. |
| 176 | + let from_bytes = StakeAddress::try_from(bytes.as_slice()).unwrap(); |
| 177 | + assert_eq!(from_bytes.is_script(), is_script); |
| 178 | + assert_eq!(from_bytes, stake_address); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + #[test] |
| 183 | + fn display() { |
| 184 | + let hash: Hash<28> = "276fd18711931e2c0e21430192dbeac0e458093cd9d1fcd7210f64b3" |
| 185 | + .parse() |
| 186 | + .unwrap(); |
| 187 | + |
| 188 | + // cSpell:disable |
| 189 | + let test_data = [ |
| 190 | + ( |
| 191 | + Network::Mainnet, |
| 192 | + true, |
| 193 | + hash, |
| 194 | + "stake17ynkl5v8zxf3utqwy9psrykmatqwgkqf8nvarlxhyy8kfvcpxcgqv", |
| 195 | + ), |
| 196 | + ( |
| 197 | + Network::Mainnet, |
| 198 | + false, |
| 199 | + hash, |
| 200 | + "stake1uynkl5v8zxf3utqwy9psrykmatqwgkqf8nvarlxhyy8kfvcgwyghv", |
| 201 | + ), |
| 202 | + ( |
| 203 | + Network::Preprod, |
| 204 | + true, |
| 205 | + hash, |
| 206 | + "stake_test17qnkl5v8zxf3utqwy9psrykmatqwgkqf8nvarlxhyy8kfvcxvj2y3", |
| 207 | + ), |
| 208 | + ( |
| 209 | + Network::Preprod, |
| 210 | + false, |
| 211 | + hash, |
| 212 | + "stake_test1uqnkl5v8zxf3utqwy9psrykmatqwgkqf8nvarlxhyy8kfvc0yw2n3", |
| 213 | + ), |
| 214 | + ( |
| 215 | + Network::Preview, |
| 216 | + true, |
| 217 | + hash, |
| 218 | + "stake_test17qnkl5v8zxf3utqwy9psrykmatqwgkqf8nvarlxhyy8kfvcxvj2y3", |
| 219 | + ), |
| 220 | + ( |
| 221 | + Network::Preview, |
| 222 | + false, |
| 223 | + hash, |
| 224 | + "stake_test1uqnkl5v8zxf3utqwy9psrykmatqwgkqf8nvarlxhyy8kfvc0yw2n3", |
| 225 | + ), |
| 226 | + ]; |
| 227 | + // cSpell:enable |
| 228 | + |
| 229 | + for (network, is_script, hash, expected) in test_data { |
| 230 | + let address = StakeAddress::new(network, is_script, hash); |
| 231 | + assert_eq!(expected, format!("{address}")); |
| 232 | + } |
| 233 | + } |
| 234 | +} |
0 commit comments