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