vanity_core/chains/
create2.rs1use crate::chain::{ChainGrinder, GrindAttempt, KeyExport, KeypairResult};
7use crate::pattern::Pattern;
8use rand::rngs::OsRng;
9use rand::RngCore;
10use sha3::{Digest, Keccak256};
11
12use super::util::{
13 build_hex_pattern, expected_from_pattern, hex_combinations, matches_pattern,
14 secret_from_attempt,
15};
16
17#[derive(Clone)]
18pub struct Create2Grinder {
19 pub deployer: [u8; 20],
20 pub init_code_hash: [u8; 32],
21}
22
23impl Create2Grinder {
24 pub fn new(deployer: [u8; 20], init_code_hash: [u8; 32]) -> Self {
25 Self {
26 deployer,
27 init_code_hash,
28 }
29 }
30
31 pub fn parse(deployer_hex: &str, init_code_hash_hex: &str) -> Result<Self, String> {
32 Ok(Self {
33 deployer: parse_hex_fixed::<20>(deployer_hex, "deployer")?,
34 init_code_hash: parse_hex_fixed::<32>(init_code_hash_hex, "init-code-hash")?,
35 })
36 }
37
38 fn derive_address(&self, salt: &[u8; 32]) -> String {
39 let mut buf = [0u8; 1 + 20 + 32 + 32];
40 buf[0] = 0xff;
41 buf[1..21].copy_from_slice(&self.deployer);
42 buf[21..53].copy_from_slice(salt);
43 buf[53..85].copy_from_slice(&self.init_code_hash);
44 let hash = Keccak256::digest(buf);
45 format!("0x{}", hex::encode(&hash[12..]))
46 }
47}
48
49impl ChainGrinder for Create2Grinder {
50 fn id(&self) -> &'static str {
51 "create2"
52 }
53
54 fn display_name(&self) -> &'static str {
55 "EVM CREATE2 (contract salt)"
56 }
57
58 fn grind_attempt(&self) -> (String, GrindAttempt) {
59 let mut salt = [0u8; 32];
60 OsRng.fill_bytes(&mut salt);
61 let address = self.derive_address(&salt);
62 (address, GrindAttempt::Secret32(salt))
63 }
64
65 fn finalize(&self, attempt: GrindAttempt) -> KeypairResult {
66 let salt = secret_from_attempt(attempt);
67 let address = self.derive_address(&salt);
68 KeypairResult {
69 address,
70 exports: vec![
71 KeyExport {
72 label: "CREATE2 Salt (hex)".into(),
73 value: hex::encode(salt),
74 hint: Some("Pass as salt to CREATE2 / factory deploy".into()),
75 },
76 KeyExport {
77 label: "CREATE2 Salt (0x hex)".into(),
78 value: format!("0x{}", hex::encode(salt)),
79 hint: Some("EVM tooling format".into()),
80 },
81 KeyExport {
82 label: "Deployer".into(),
83 value: format!("0x{}", hex::encode(self.deployer)),
84 hint: None,
85 },
86 KeyExport {
87 label: "Init Code Hash".into(),
88 value: format!("0x{}", hex::encode(self.init_code_hash)),
89 hint: None,
90 },
91 ],
92 }
93 }
94
95 fn build_pattern(
96 &self,
97 prefix: Option<&str>,
98 suffix: Option<&str>,
99 contains: Option<&str>,
100 _exact: bool,
101 ) -> Result<Pattern, String> {
102 build_hex_pattern(prefix, suffix, contains, true, 40)
103 }
104
105 fn expected_attempts(&self, pattern: &Pattern) -> f64 {
106 expected_from_pattern(pattern, hex_combinations)
107 }
108
109 fn matches(&self, address: &str, pattern: &Pattern) -> bool {
110 matches_pattern(address, pattern, true)
111 }
112
113 fn supports_exact_case(&self) -> bool {
114 false
115 }
116
117 fn pattern_hint(&self) -> &'static str {
118 "Hex pattern for the resulting contract address (same as EVM)."
119 }
120}
121
122fn parse_hex_fixed<const N: usize>(input: &str, label: &str) -> Result<[u8; N], String> {
123 let stripped = input.strip_prefix("0x").unwrap_or(input);
124 let bytes = hex::decode(stripped).map_err(|e| format!("invalid {label} hex: {e}"))?;
125 if bytes.len() != N {
126 return Err(format!(
127 "{label} must be {N} bytes ({} hex chars), got {}",
128 N * 2,
129 bytes.len()
130 ));
131 }
132 let mut out = [0u8; N];
133 out.copy_from_slice(&bytes);
134 Ok(out)
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140 use crate::chain::ChainGrinder;
141
142 #[test]
143 fn create2_address_is_0x_hex40() {
144 let g = Create2Grinder::new([0u8; 20], [0u8; 32]);
145 let (addr, _) = g.grind_attempt();
146 assert!(addr.starts_with("0x"));
147 assert_eq!(addr.len(), 42);
148 }
149
150 #[test]
151 fn create2_known_vector() {
152 let g = Create2Grinder::new([0u8; 20], [0u8; 32]);
154 let salt = [0u8; 32];
155 let addr = g.derive_address(&salt);
156 assert_eq!(addr.len(), 42);
157 assert_eq!(g.derive_address(&salt), addr);
159 }
160}