Skip to main content

zebra_chain/transparent/
address.rs

1//! Transparent Address types.
2
3use std::{fmt, io};
4
5use crate::{
6    parameters::NetworkKind,
7    serialization::{SerializationError, ZcashDeserialize, ZcashSerialize},
8    transparent::{opcodes::OpCode, Script},
9};
10
11#[cfg(test)]
12use proptest::prelude::*;
13use zcash_address::{ToAddress, ZcashAddress};
14use zcash_transparent::address::TransparentAddress;
15
16/// Transparent Zcash Addresses
17///
18/// In Bitcoin a single byte is used for the version field identifying
19/// the address type. In Zcash two bytes are used. For addresses on
20/// the production network, this and the encoded length cause the first
21/// two characters of the Base58Check encoding to be fixed as "t3" for
22/// P2SH addresses, and as "t1" for P2PKH addresses. (This does not
23/// imply that a transparent Zcash address can be parsed identically
24/// to a Bitcoin address just by removing the "t".)
25///
26/// <https://zips.z.cash/protocol/protocol.pdf#transparentaddrencoding>
27// TODO Remove this type and move to `TransparentAddress` in `zcash-transparent`.
28#[derive(
29    Clone, Copy, Eq, PartialEq, Hash, serde_with::SerializeDisplay, serde_with::DeserializeFromStr,
30)]
31pub enum Address {
32    /// P2SH (Pay to Script Hash) addresses
33    PayToScriptHash {
34        /// Production, test, or other network
35        network_kind: NetworkKind,
36        /// 20 bytes specifying a script hash.
37        script_hash: [u8; 20],
38    },
39
40    /// P2PKH (Pay to Public Key Hash) addresses
41    PayToPublicKeyHash {
42        /// Production, test, or other network
43        network_kind: NetworkKind,
44        /// 20 bytes specifying a public key hash, which is a RIPEMD-160
45        /// hash of a SHA-256 hash of a compressed ECDSA key encoding.
46        pub_key_hash: [u8; 20],
47    },
48
49    /// Transparent-Source-Only Address.
50    ///
51    /// <https://zips.z.cash/zip-0320.html>
52    Tex {
53        /// Production, test, or other network
54        network_kind: NetworkKind,
55        /// 20 bytes specifying the validating key hash.
56        validating_key_hash: [u8; 20],
57    },
58}
59
60impl From<Address> for ZcashAddress {
61    fn from(taddr: Address) -> Self {
62        match taddr {
63            Address::PayToScriptHash {
64                network_kind,
65                script_hash,
66            } => ZcashAddress::from_transparent_p2sh(network_kind.into(), script_hash),
67            Address::PayToPublicKeyHash {
68                network_kind,
69                pub_key_hash,
70            } => ZcashAddress::from_transparent_p2pkh(network_kind.into(), pub_key_hash),
71            Address::Tex {
72                network_kind,
73                validating_key_hash,
74            } => ZcashAddress::from_tex(network_kind.into(), validating_key_hash),
75        }
76    }
77}
78
79impl TryFrom<Address> for TransparentAddress {
80    type Error = &'static str;
81
82    fn try_from(taddr: Address) -> Result<Self, Self::Error> {
83        match taddr {
84            Address::PayToScriptHash { script_hash, .. } => Ok(Self::ScriptHash(script_hash)),
85            Address::PayToPublicKeyHash { pub_key_hash, .. } => {
86                Ok(Self::PublicKeyHash(pub_key_hash))
87            }
88            Address::Tex { .. } => Err("TransparentAddress can't be a Tex address"),
89        }
90    }
91}
92
93impl fmt::Debug for Address {
94    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95        let mut debug_struct = f.debug_struct("TransparentAddress");
96
97        match self {
98            Address::PayToScriptHash {
99                network_kind,
100                script_hash,
101            } => debug_struct
102                .field("network_kind", network_kind)
103                .field("script_hash", &hex::encode(script_hash))
104                .finish(),
105            Address::PayToPublicKeyHash {
106                network_kind,
107                pub_key_hash,
108            } => debug_struct
109                .field("network_kind", network_kind)
110                .field("pub_key_hash", &hex::encode(pub_key_hash))
111                .finish(),
112            Address::Tex {
113                network_kind,
114                validating_key_hash,
115            } => debug_struct
116                .field("network_kind", network_kind)
117                .field("validating_key_hash", &hex::encode(validating_key_hash))
118                .finish(),
119        }
120    }
121}
122
123impl fmt::Display for Address {
124    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125        match self {
126            // TEX addresses are Bech32m-encoded (ZIP 320), the inverse of the
127            // Bech32 branch of `FromStr`.
128            Address::Tex { .. } => f.write_str(&ZcashAddress::from(*self).encode()),
129
130            Address::PayToScriptHash { .. } | Address::PayToPublicKeyHash { .. } => {
131                let mut bytes = io::Cursor::new(Vec::new());
132                let _ = self.zcash_serialize(&mut bytes);
133
134                f.write_str(&bs58::encode(bytes.get_ref()).with_check().into_string())
135            }
136        }
137    }
138}
139
140impl std::str::FromStr for Address {
141    type Err = SerializationError;
142
143    fn from_str(s: &str) -> Result<Self, Self::Err> {
144        // Try Base58Check (prefixes: t1, t3, tm, t2)
145        if let Ok(data) = bs58::decode(s).with_check(None).into_vec() {
146            return Address::zcash_deserialize(&data[..]);
147        }
148
149        // Try Bech32 (prefixes: tex, textest)
150        let (hrp, payload) =
151            bech32::decode(s).map_err(|_| SerializationError::Parse("invalid Bech32 encoding"))?;
152
153        // We can’t meaningfully call `Address::zcash_deserialize` for Bech32 addresses, because
154        // that method is explicitly reading two binary prefix bytes (the Base58Check version) + 20 hash bytes.
155        // Bech32 textual addresses carry no such binary "version" on the wire, so there’s nothing in the
156        // reader for zcash_deserialize to match.
157
158        // Instead, we deserialize the Bech32 address here:
159
160        if payload.len() != 20 {
161            return Err(SerializationError::Parse("unexpected payload length"));
162        }
163
164        let mut hash_bytes = [0u8; 20];
165        hash_bytes.copy_from_slice(&payload);
166
167        match hrp.as_str() {
168            zcash_address::constants::mainnet::HRP_TEX_ADDRESS => Ok(Address::Tex {
169                network_kind: NetworkKind::Mainnet,
170                validating_key_hash: hash_bytes,
171            }),
172
173            zcash_address::constants::testnet::HRP_TEX_ADDRESS => Ok(Address::Tex {
174                network_kind: NetworkKind::Testnet,
175                validating_key_hash: hash_bytes,
176            }),
177
178            zcash_address::constants::regtest::HRP_TEX_ADDRESS => Ok(Address::Tex {
179                network_kind: NetworkKind::Regtest,
180                validating_key_hash: hash_bytes,
181            }),
182
183            _ => Err(SerializationError::Parse("unknown Bech32 HRP")),
184        }
185    }
186}
187
188impl ZcashSerialize for Address {
189    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
190        match self {
191            Address::PayToScriptHash {
192                network_kind,
193                script_hash,
194            } => {
195                writer.write_all(&network_kind.b58_script_address_prefix())?;
196                writer.write_all(script_hash)?
197            }
198            Address::PayToPublicKeyHash {
199                network_kind,
200                pub_key_hash,
201            } => {
202                writer.write_all(&network_kind.b58_pubkey_address_prefix())?;
203                writer.write_all(pub_key_hash)?
204            }
205            Address::Tex {
206                network_kind,
207                validating_key_hash,
208            } => {
209                writer.write_all(&network_kind.tex_address_prefix())?;
210                writer.write_all(validating_key_hash)?
211            }
212        }
213
214        Ok(())
215    }
216}
217
218impl ZcashDeserialize for Address {
219    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
220        let mut version_bytes = [0; 2];
221        reader.read_exact(&mut version_bytes)?;
222
223        let mut hash_bytes = [0; 20];
224        reader.read_exact(&mut hash_bytes)?;
225
226        match version_bytes {
227            zcash_address::constants::mainnet::B58_SCRIPT_ADDRESS_PREFIX => {
228                Ok(Address::PayToScriptHash {
229                    network_kind: NetworkKind::Mainnet,
230                    script_hash: hash_bytes,
231                })
232            }
233            zcash_address::constants::testnet::B58_SCRIPT_ADDRESS_PREFIX => {
234                Ok(Address::PayToScriptHash {
235                    network_kind: NetworkKind::Testnet,
236                    script_hash: hash_bytes,
237                })
238            }
239            zcash_address::constants::mainnet::B58_PUBKEY_ADDRESS_PREFIX => {
240                Ok(Address::PayToPublicKeyHash {
241                    network_kind: NetworkKind::Mainnet,
242                    pub_key_hash: hash_bytes,
243                })
244            }
245            zcash_address::constants::testnet::B58_PUBKEY_ADDRESS_PREFIX => {
246                Ok(Address::PayToPublicKeyHash {
247                    network_kind: NetworkKind::Testnet,
248                    pub_key_hash: hash_bytes,
249                })
250            }
251            _ => Err(SerializationError::Parse("bad t-addr version/type")),
252        }
253    }
254}
255
256impl Address {
257    /// Create an address for the given public key hash and network.
258    pub fn from_pub_key_hash(network_kind: NetworkKind, pub_key_hash: [u8; 20]) -> Self {
259        Self::PayToPublicKeyHash {
260            network_kind,
261            pub_key_hash,
262        }
263    }
264
265    /// Create an address for the given script hash and network.
266    pub fn from_script_hash(network_kind: NetworkKind, script_hash: [u8; 20]) -> Self {
267        Self::PayToScriptHash {
268            network_kind,
269            script_hash,
270        }
271    }
272
273    /// Returns the network kind for this address.
274    pub fn network_kind(&self) -> NetworkKind {
275        match self {
276            Address::PayToScriptHash { network_kind, .. } => *network_kind,
277            Address::PayToPublicKeyHash { network_kind, .. } => *network_kind,
278            Address::Tex { network_kind, .. } => *network_kind,
279        }
280    }
281
282    /// Returns `true` if the address is `PayToScriptHash`, and `false` if it is `PayToPublicKeyHash`.
283    pub fn is_script_hash(&self) -> bool {
284        matches!(self, Address::PayToScriptHash { .. })
285    }
286
287    /// Returns the hash bytes for this address, regardless of the address type.
288    ///
289    /// # Correctness
290    ///
291    /// Use [`ZcashSerialize`] and [`ZcashDeserialize`] for consensus-critical serialization.
292    pub fn hash_bytes(&self) -> [u8; 20] {
293        match *self {
294            Address::PayToScriptHash { script_hash, .. } => script_hash,
295            Address::PayToPublicKeyHash { pub_key_hash, .. } => pub_key_hash,
296            Address::Tex {
297                validating_key_hash,
298                ..
299            } => validating_key_hash,
300        }
301    }
302
303    /// Turns the address into the `scriptPubKey` script that can be used in a coinbase output.
304    ///
305    /// TEX addresses are not supported and return an empty script.
306    pub fn script(&self) -> Script {
307        let mut script_bytes = Vec::new();
308
309        match self {
310            // https://developer.bitcoin.org/devguide/transactions.html#pay-to-script-hash-p2sh
311            Address::PayToScriptHash { .. } => {
312                script_bytes.push(OpCode::Hash160 as u8);
313                script_bytes.push(OpCode::Push20Bytes as u8);
314                script_bytes.extend(self.hash_bytes());
315                script_bytes.push(OpCode::Equal as u8);
316            }
317            // https://developer.bitcoin.org/devguide/transactions.html#pay-to-public-key-hash-p2pkh
318            Address::PayToPublicKeyHash { .. } => {
319                script_bytes.push(OpCode::Dup as u8);
320                script_bytes.push(OpCode::Hash160 as u8);
321                script_bytes.push(OpCode::Push20Bytes as u8);
322                script_bytes.extend(self.hash_bytes());
323                script_bytes.push(OpCode::EqualVerify as u8);
324                script_bytes.push(OpCode::CheckSig as u8);
325            }
326            Address::Tex { .. } => {}
327        };
328
329        Script::new(&script_bytes)
330    }
331
332    /// Create a TEX address from the given network kind and validating key hash.
333    pub fn from_tex(network_kind: NetworkKind, validating_key_hash: [u8; 20]) -> Self {
334        Self::Tex {
335            network_kind,
336            validating_key_hash,
337        }
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use ripemd::{Digest, Ripemd160};
344    use secp256k1::PublicKey;
345    use sha2::Sha256;
346
347    use super::*;
348
349    trait ToAddressWithNetwork {
350        /// Convert `self` to an `Address`, given the current `network`.
351        fn to_address(&self, network: NetworkKind) -> Address;
352    }
353
354    impl ToAddressWithNetwork for Script {
355        fn to_address(&self, network_kind: NetworkKind) -> Address {
356            Address::PayToScriptHash {
357                network_kind,
358                script_hash: Address::hash_payload(self.as_raw_bytes()),
359            }
360        }
361    }
362
363    impl ToAddressWithNetwork for PublicKey {
364        fn to_address(&self, network_kind: NetworkKind) -> Address {
365            Address::PayToPublicKeyHash {
366                network_kind,
367                pub_key_hash: Address::hash_payload(&self.serialize()[..]),
368            }
369        }
370    }
371
372    impl Address {
373        /// A hash of a transparent address payload, as used in
374        /// transparent pay-to-script-hash and pay-to-publickey-hash
375        /// addresses.
376        ///
377        /// The resulting hash in both of these cases is always exactly 20
378        /// bytes.
379        /// <https://en.bitcoin.it/Base58Check_encoding#Encoding_a_Bitcoin_address>
380        #[allow(dead_code)]
381        fn hash_payload(bytes: &[u8]) -> [u8; 20] {
382            let sha_hash = Sha256::digest(bytes);
383            let ripe_hash = Ripemd160::digest(sha_hash);
384            let mut payload = [0u8; 20];
385            payload[..].copy_from_slice(&ripe_hash[..]);
386            payload
387        }
388    }
389
390    #[test]
391    fn pubkey_mainnet() {
392        let _init_guard = zebra_test::init();
393
394        let pub_key = PublicKey::from_slice(&[
395            3, 23, 183, 225, 206, 31, 159, 148, 195, 42, 67, 115, 146, 41, 248, 140, 11, 3, 51, 41,
396            111, 180, 110, 143, 114, 134, 88, 73, 198, 174, 52, 184, 78,
397        ])
398        .expect("A PublicKey from slice");
399
400        let t_addr = pub_key.to_address(NetworkKind::Mainnet);
401
402        assert_eq!(format!("{t_addr}"), "t1bmMa1wJDFdbc2TiURQP5BbBz6jHjUBuHq");
403    }
404
405    #[test]
406    fn pubkey_testnet() {
407        let _init_guard = zebra_test::init();
408
409        let pub_key = PublicKey::from_slice(&[
410            3, 23, 183, 225, 206, 31, 159, 148, 195, 42, 67, 115, 146, 41, 248, 140, 11, 3, 51, 41,
411            111, 180, 110, 143, 114, 134, 88, 73, 198, 174, 52, 184, 78,
412        ])
413        .expect("A PublicKey from slice");
414
415        let t_addr = pub_key.to_address(NetworkKind::Testnet);
416
417        assert_eq!(format!("{t_addr}"), "tmTc6trRhbv96kGfA99i7vrFwb5p7BVFwc3");
418    }
419
420    #[test]
421    fn empty_script_mainnet() {
422        let _init_guard = zebra_test::init();
423
424        let script = Script::new(&[0u8; 20]);
425
426        let t_addr = script.to_address(NetworkKind::Mainnet);
427
428        assert_eq!(format!("{t_addr}"), "t3Y5pHwfgHbS6pDjj1HLuMFxhFFip1fcJ6g");
429    }
430
431    #[test]
432    fn empty_script_testnet() {
433        let _init_guard = zebra_test::init();
434
435        let script = Script::new(&[0; 20]);
436
437        let t_addr = script.to_address(NetworkKind::Testnet);
438
439        assert_eq!(format!("{t_addr}"), "t2L51LcmpA43UMvKTw2Lwtt9LMjwyqU2V1P");
440    }
441
442    #[test]
443    fn from_string() {
444        let _init_guard = zebra_test::init();
445
446        let t_addr: Address = "t3Vz22vK5z2LcKEdg16Yv4FFneEL1zg9ojd".parse().unwrap();
447
448        assert_eq!(format!("{t_addr}"), "t3Vz22vK5z2LcKEdg16Yv4FFneEL1zg9ojd");
449    }
450
451    /// The validating key hash of the ZIP 320 test vector, whose TEX address
452    /// is [`TEX_MAINNET`] and whose P2PKH address is
453    /// `t1VmmGiyjVNeCjxDZzg7vZmd99WyzVby9yC`.
454    const TEX_KEY_HASH: &str = "8286bf790866805397e3a947640b77a43f0b43a5";
455
456    /// The ZIP 320 test vector: [`TEX_KEY_HASH`] with the Mainnet HRP.
457    const TEX_MAINNET: &str = "tex1s2rt77ggv6q989lr49rkgzmh5slsksa9khdgte";
458
459    /// [`TEX_KEY_HASH`] with the Testnet HRP.
460    const TEX_TESTNET: &str = "textest1s2rt77ggv6q989lr49rkgzmh5slsksa90ej7wz";
461
462    /// [`TEX_KEY_HASH`] with the Regtest HRP.
463    const TEX_REGTEST: &str = "texregtest1s2rt77ggv6q989lr49rkgzmh5slsksa990zqpk";
464
465    /// Parses a TEX address, checks its network kind and validating key hash,
466    /// and checks that `Display` gives the parsed string back.
467    fn check_tex_roundtrip(encoded: &str, network_kind: NetworkKind) {
468        let t_addr: Address = encoded.parse().expect("a valid TEX address");
469
470        let validating_key_hash: [u8; 20] = hex::decode(TEX_KEY_HASH)
471            .expect("valid hex")
472            .try_into()
473            .expect("20 bytes");
474        assert_eq!(t_addr, Address::from_tex(network_kind, validating_key_hash));
475
476        assert_eq!(format!("{t_addr}"), encoded);
477    }
478
479    #[test]
480    fn tex_mainnet() {
481        let _init_guard = zebra_test::init();
482
483        check_tex_roundtrip(TEX_MAINNET, NetworkKind::Mainnet);
484    }
485
486    #[test]
487    fn tex_testnet() {
488        let _init_guard = zebra_test::init();
489
490        check_tex_roundtrip(TEX_TESTNET, NetworkKind::Testnet);
491    }
492
493    #[test]
494    fn tex_regtest() {
495        let _init_guard = zebra_test::init();
496
497        check_tex_roundtrip(TEX_REGTEST, NetworkKind::Regtest);
498    }
499
500    /// A TEX address and the P2PKH address with the same key hash must not
501    /// display the same, and the P2PKH encoding is unchanged.
502    #[test]
503    fn tex_and_p2pkh_display_differently() {
504        let _init_guard = zebra_test::init();
505
506        let tex: Address = TEX_MAINNET.parse().expect("a valid TEX address");
507        let p2pkh = Address::from_pub_key_hash(NetworkKind::Mainnet, tex.hash_bytes());
508
509        assert_eq!(format!("{p2pkh}"), "t1VmmGiyjVNeCjxDZzg7vZmd99WyzVby9yC");
510        assert_ne!(format!("{tex}"), format!("{p2pkh}"));
511    }
512
513    #[test]
514    fn debug() {
515        let _init_guard = zebra_test::init();
516
517        let t_addr: Address = "t3Vz22vK5z2LcKEdg16Yv4FFneEL1zg9ojd".parse().unwrap();
518
519        assert_eq!(
520            format!("{t_addr:?}"),
521            "TransparentAddress { network_kind: Mainnet, script_hash: \"7d46a730d31f97b1930d3368a967c309bd4d136a\" }"
522        );
523    }
524}
525
526#[cfg(test)]
527proptest! {
528
529    #[test]
530    fn transparent_address_roundtrip(taddr in any::<Address>()) {
531        let _init_guard = zebra_test::init();
532
533        let mut data = Vec::new();
534
535        taddr.zcash_serialize(&mut data).expect("t-addr should serialize");
536
537        let taddr2 = Address::zcash_deserialize(&data[..]).expect("randomized t-addr should deserialize");
538
539        prop_assert_eq![taddr, taddr2];
540    }
541}