Skip to main content

vanity_core/chains/
filecoin.rs

1use crate::chain::{ChainGrinder, GrindAttempt, KeyExport, KeypairResult};
2use crate::pattern::Pattern;
3use data_encoding::BASE32_NOPAD;
4use secp256k1::{PublicKey, Secp256k1, SecretKey};
5
6use super::util::{
7    base32_combinations, blake2b_var, build_base58_pattern, expected_from_pattern, grind_secp256k1,
8    matches_pattern, secret_from_attempt, BASE32_ALPHABET_LOWER,
9};
10
11#[derive(Clone, Default)]
12pub struct FilecoinGrinder;
13
14impl FilecoinGrinder {
15    /// Protocol 1 (secp256k1) address: f1 + base32(payload || checksum).
16    fn address_from_uncompressed_pubkey(uncompressed: &[u8]) -> String {
17        let payload = blake2b_var(uncompressed, 20);
18        let mut checksum_input = Vec::with_capacity(21);
19        checksum_input.push(1u8); // protocol
20        checksum_input.extend_from_slice(&payload);
21        let checksum = blake2b_var(&checksum_input, 4);
22        let mut encoded = Vec::with_capacity(24);
23        encoded.extend_from_slice(&payload);
24        encoded.extend_from_slice(&checksum);
25        format!("f1{}", BASE32_NOPAD.encode(&encoded).to_ascii_lowercase())
26    }
27
28    fn derive(secret: &SecretKey) -> String {
29        let secp = Secp256k1::new();
30        let pubkey: PublicKey = secret.public_key(&secp);
31        Self::address_from_uncompressed_pubkey(&pubkey.serialize_uncompressed())
32    }
33}
34
35impl ChainGrinder for FilecoinGrinder {
36    fn id(&self) -> &'static str {
37        "fil"
38    }
39
40    fn display_name(&self) -> &'static str {
41        "Filecoin (f1)"
42    }
43
44    fn grind_attempt(&self) -> (String, GrindAttempt) {
45        grind_secp256k1(Self::derive)
46    }
47
48    fn finalize(&self, attempt: GrindAttempt) -> KeypairResult {
49        let secret_bytes = secret_from_attempt(attempt);
50        let secret_key = SecretKey::from_slice(&secret_bytes).expect("valid secp256k1 secret");
51        let address = Self::derive(&secret_key);
52
53        KeypairResult {
54            address,
55            exports: vec![KeyExport {
56                label: "Private Key (hex)".into(),
57                value: hex::encode(secret_bytes),
58                hint: Some("Lotus / Glif secp256k1 (f1) import".into()),
59            }],
60        }
61    }
62
63    fn build_pattern(
64        &self,
65        prefix: Option<&str>,
66        suffix: Option<&str>,
67        contains: Option<&str>,
68        exact: bool,
69    ) -> Result<Pattern, String> {
70        let lower = |s: Option<&str>| s.map(|v| v.to_ascii_lowercase());
71        let mut pattern = build_base58_pattern(
72            lower(prefix).as_deref(),
73            lower(suffix).as_deref(),
74            lower(contains).as_deref(),
75            exact,
76            BASE32_ALPHABET_LOWER,
77            64,
78        )?;
79        if pattern.has_prefix() && !pattern.prefix.starts_with("f1") {
80            let rest = pattern.prefix.strip_prefix('f').unwrap_or(&pattern.prefix);
81            pattern.prefix = format!("f1{rest}");
82            pattern.prefix_match = pattern.prefix.clone();
83        }
84        pattern.set_fixed_prefix("f1");
85        Ok(pattern)
86    }
87
88    fn expected_attempts(&self, pattern: &Pattern) -> f64 {
89        expected_from_pattern(pattern, |p| {
90            let data = p.strip_prefix("f1").unwrap_or(p);
91            base32_combinations(data)
92        })
93    }
94
95    fn matches(&self, address: &str, pattern: &Pattern) -> bool {
96        matches_pattern(address, pattern, true)
97    }
98
99    fn supports_exact_case(&self) -> bool {
100        false
101    }
102
103    fn pattern_hint(&self) -> &'static str {
104        "Base32 after f1 (secp256k1 protocol-1 addresses)."
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::FilecoinGrinder;
111    use crate::chain::ChainGrinder;
112
113    #[test]
114    fn filecoin_address_starts_with_f1() {
115        let g = FilecoinGrinder;
116        let (addr, _) = g.grind_attempt();
117        assert!(addr.starts_with("f1"));
118    }
119
120    /// Known-answer test from filecoin-project/go-address's own
121    /// TestVectorSecp256k1Address: this exact uncompressed pubkey must
122    /// produce this exact mainnet f1 address.
123    #[test]
124    fn filecoin_matches_go_address_known_vector() {
125        let uncompressed: [u8; 65] = [
126            4, 148, 2, 250, 195, 126, 100, 50, 164, 22, 163, 160, 202, 84, 38, 181, 24, 90, 179,
127            178, 79, 97, 52, 239, 162, 92, 228, 135, 200, 45, 46, 78, 19, 191, 69, 37, 17, 224,
128            210, 36, 84, 33, 248, 97, 59, 193, 13, 114, 250, 33, 102, 102, 169, 108, 59, 193, 57,
129            32, 211, 255, 35, 63, 208, 188, 5,
130        ];
131        let addr = FilecoinGrinder::address_from_uncompressed_pubkey(&uncompressed);
132        assert_eq!(addr, "f15ihq5ibzwki2b4ep2f46avlkrqzhpqgtga7pdrq");
133    }
134}