Skip to main content

vanity_core/chains/
tezos.rs

1use super::util::Keypair;
2use crate::chain::{ChainGrinder, GrindAttempt, KeyExport, KeypairResult};
3use crate::pattern::Pattern;
4
5use super::base58_odds::Base58Layout;
6use super::util::{
7    base58_check_encode_raw, blake2b_var, build_base58_pattern, grind_ed25519, keypair_from_secret,
8    matches_pattern, secret_from_attempt, BASE58_ALPHABET,
9};
10
11/// tz1 = ed25519 public key hash (Blake2b-160) with Tezos prefix.
12const TZ1_PREFIX: [u8; 3] = [6, 161, 159];
13
14/// tz1 prefix + 20-byte hash + 4-byte checksum.
15const LAYOUT: Base58Layout = Base58Layout {
16    version: &TZ1_PREFIX,
17    random_len: 24,
18    alphabet: BASE58_ALPHABET,
19};
20/// edsk = ed25519 32-byte seed prefix. (Not to be confused with the
21/// same-looking "edsk" prefix `[43, 246, 78, 7]` used for the 64-byte
22/// *expanded* secret key — a different, longer format. Using that prefix
23/// on a 32-byte seed produces a string wallets won't recognize as a valid
24/// key. Verified against pytezos's own test vector below.)
25const EDSK_PREFIX: [u8; 4] = [13, 15, 58, 7];
26
27#[derive(Clone, Default)]
28pub struct TezosGrinder;
29
30impl TezosGrinder {
31    fn derive_address(keypair: &Keypair) -> String {
32        let pubkey = keypair.pubkey().to_bytes();
33        let pkh = blake2b_var(&pubkey, 20);
34        let mut payload = Vec::with_capacity(23);
35        payload.extend_from_slice(&TZ1_PREFIX);
36        payload.extend_from_slice(&pkh);
37        base58_check_encode_raw(&payload)
38    }
39
40    fn encode_edsk(secret: [u8; 32]) -> String {
41        let mut payload = Vec::with_capacity(36);
42        payload.extend_from_slice(&EDSK_PREFIX);
43        payload.extend_from_slice(&secret);
44        base58_check_encode_raw(&payload)
45    }
46}
47
48impl ChainGrinder for TezosGrinder {
49    fn id(&self) -> &'static str {
50        "xtz"
51    }
52
53    fn display_name(&self) -> &'static str {
54        "Tezos (tz1)"
55    }
56
57    fn grind_attempt(&self) -> (String, GrindAttempt) {
58        grind_ed25519(Self::derive_address)
59    }
60
61    fn finalize(&self, attempt: GrindAttempt) -> KeypairResult {
62        let secret_bytes = secret_from_attempt(attempt);
63        let keypair = keypair_from_secret(secret_bytes);
64        let address = Self::derive_address(&keypair);
65
66        KeypairResult {
67            address,
68            exports: vec![
69                KeyExport {
70                    label: "Secret Key (edsk…)".into(),
71                    value: Self::encode_edsk(secret_bytes),
72                    hint: Some("Temple / Kukai wallet import".into()),
73                },
74                KeyExport {
75                    label: "Private Key (hex)".into(),
76                    value: hex::encode(secret_bytes),
77                    hint: None,
78                },
79            ],
80        }
81    }
82
83    fn build_pattern(
84        &self,
85        prefix: Option<&str>,
86        suffix: Option<&str>,
87        contains: Option<&str>,
88        exact: bool,
89    ) -> Result<Pattern, String> {
90        let mut pattern =
91            build_base58_pattern(prefix, suffix, contains, exact, BASE58_ALPHABET, 36)?;
92        LAYOUT.apply_lead("Tezos", &mut pattern, "tz1")?;
93        Ok(pattern)
94    }
95
96    fn expected_attempts(&self, pattern: &Pattern) -> f64 {
97        LAYOUT.expected_attempts(pattern)
98    }
99
100    fn matches(&self, address: &str, pattern: &Pattern) -> bool {
101        matches_pattern(address, pattern, false)
102    }
103
104    fn supports_exact_case(&self) -> bool {
105        true
106    }
107
108    fn pattern_hint(&self) -> &'static str {
109        "Base58 — tz1 (ed25519). After tz1 comes one of K–Z or a–i (tz1 is added for you)."
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::{TezosGrinder, EDSK_PREFIX};
116    use crate::chain::ChainGrinder;
117    use crate::chains::util::Keypair;
118
119    #[test]
120    fn tezos_address_starts_with_tz1() {
121        let g = TezosGrinder;
122        let (addr, _) = g.grind_attempt();
123        assert!(addr.starts_with("tz1"));
124    }
125
126    /// Known-answer test from pytezos: the seed encoded by
127    /// `edsk3nM41ygNfSxVU4w1uAW3G9EnTQEB5rjojeZedLTGmiGRcierVv` must derive
128    /// public key `edpku976gpuAD2bXyx1XGraeKuCo1gUZ3LAJcHM12W1ecxZwoiu22R` and
129    /// address `tz1eKkWU5hGtfLUiqNpucHrXymm83z3DG9Sq`. This also confirms
130    /// `EDSK_PREFIX` round-trips through an independent implementation.
131    #[test]
132    fn tezos_matches_pytezos_known_vector() {
133        let seed: [u8; 32] =
134            hex::decode("92542d866a5263115aa416fd3e1dce4ced35f5545417d1f73763f7093552a72b")
135                .unwrap()[..32]
136                .try_into()
137                .unwrap();
138        let keypair = Keypair::from_seed(&seed).unwrap();
139        let address = TezosGrinder::derive_address(&keypair);
140        assert_eq!(address, "tz1eKkWU5hGtfLUiqNpucHrXymm83z3DG9Sq");
141
142        let edsk = TezosGrinder::encode_edsk(seed);
143        assert_eq!(
144            edsk,
145            "edsk3nM41ygNfSxVU4w1uAW3G9EnTQEB5rjojeZedLTGmiGRcierVv"
146        );
147        assert_eq!(EDSK_PREFIX, [13, 15, 58, 7]);
148    }
149}