1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use crate::{
error, utils, with_crypto_scheme, CryptoSchemeFlag, NetworkSchemeFlag, OutputTypeFlag,
};
use rand::{rngs::OsRng, RngCore};
use sp_core::crypto::{Ss58AddressFormat, Ss58Codec};
use sp_runtime::traits::IdentifyAccount;
use structopt::StructOpt;
use utils::print_from_uri;
#[derive(Debug, StructOpt, Clone)]
#[structopt(name = "vanity", about = "Generate a seed that provides a vanity address")]
pub struct VanityCmd {
#[structopt(long, parse(try_from_str = assert_non_empty_string))]
pattern: String,
#[allow(missing_docs)]
#[structopt(flatten)]
network_scheme: NetworkSchemeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
output_scheme: OutputTypeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
crypto_scheme: CryptoSchemeFlag,
}
impl VanityCmd {
pub fn run(&self) -> error::Result<()> {
let formated_seed = with_crypto_scheme!(
self.crypto_scheme.scheme,
generate_key(&self.pattern, self.network_scheme.network.clone().unwrap_or_default()),
)?;
with_crypto_scheme!(
self.crypto_scheme.scheme,
print_from_uri(
&formated_seed,
None,
self.network_scheme.network.clone(),
self.output_scheme.output_type.clone(),
),
);
Ok(())
}
}
fn generate_key<Pair>(
desired: &str,
network_override: Ss58AddressFormat,
) -> Result<String, &'static str>
where
Pair: sp_core::Pair,
Pair::Public: IdentifyAccount,
<Pair::Public as IdentifyAccount>::AccountId: Ss58Codec,
{
println!("Generating key containing pattern '{}'", desired);
let top = 45 + (desired.len() * 48);
let mut best = 0;
let mut seed = Pair::Seed::default();
let mut done = 0;
loop {
if done % 100000 == 0 {
OsRng.fill_bytes(seed.as_mut());
} else {
next_seed(seed.as_mut());
}
let p = Pair::from_seed(&seed);
let ss58 = p.public().into_account().to_ss58check_with_version(network_override);
let score = calculate_score(&desired, &ss58);
if score > best || desired.len() < 2 {
best = score;
if best >= top {
println!("best: {} == top: {}", best, top);
return Ok(utils::format_seed::<Pair>(seed.clone()))
}
}
done += 1;
if done % good_waypoint(done) == 0 {
println!("{} keys searched; best is {}/{} complete", done, best, top);
}
}
}
fn good_waypoint(done: u64) -> u64 {
match done {
0..=1_000_000 => 100_000,
0..=10_000_000 => 1_000_000,
0..=100_000_000 => 10_000_000,
_ => 100_000_000,
}
}
fn next_seed(seed: &mut [u8]) {
for i in 0..seed.len() {
match seed[i] {
255 => {
seed[i] = 0;
},
_ => {
seed[i] += 1;
break
},
}
}
}
fn calculate_score(_desired: &str, key: &str) -> usize {
for truncate in 0.._desired.len() {
let snip_size = _desired.len() - truncate;
let truncated = &_desired[0..snip_size];
if let Some(pos) = key.find(truncated) {
return (47 - pos) + (snip_size * 48)
}
}
0
}
fn assert_non_empty_string(pattern: &str) -> Result<String, &'static str> {
if pattern.is_empty() {
Err("Pattern must not be empty")
} else {
Ok(pattern.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_core::{crypto::Ss58Codec, sr25519, Pair};
use structopt::StructOpt;
#[cfg(feature = "bench")]
use test::Bencher;
#[test]
fn vanity() {
let vanity = VanityCmd::from_iter(&["vanity", "--pattern", "j"]);
assert!(vanity.run().is_ok());
}
#[test]
fn test_generation_with_single_char() {
let seed = generate_key::<sr25519::Pair>("ab", Default::default()).unwrap();
assert!(sr25519::Pair::from_seed_slice(&hex::decode(&seed[2..]).unwrap())
.unwrap()
.public()
.to_ss58check()
.contains("ab"));
}
#[test]
fn generate_key_respects_network_override() {
let seed = generate_key::<sr25519::Pair>("ab", Ss58AddressFormat::PolkadotAccount).unwrap();
assert!(sr25519::Pair::from_seed_slice(&hex::decode(&seed[2..]).unwrap())
.unwrap()
.public()
.to_ss58check_with_version(Ss58AddressFormat::PolkadotAccount)
.contains("ab"));
}
#[test]
fn test_score_1_char_100() {
let score = calculate_score("j", "5jolkadotwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim");
assert_eq!(score, 94);
}
#[test]
fn test_score_100() {
let score = calculate_score("Polkadot", "5PolkadotwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim");
assert_eq!(score, 430);
}
#[test]
fn test_score_50_2() {
assert_eq!(
calculate_score("Polkadot", "5PolkXXXXwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim"),
238
);
}
#[test]
fn test_score_0() {
assert_eq!(
calculate_score("Polkadot", "5GUWv4bLCchGUHJrzULXnh4JgXsMpTKRnjuXTY7Qo1Kh9uYK"),
0
);
}
#[cfg(feature = "bench")]
#[bench]
fn bench_paranoiac(b: &mut Bencher) {
b.iter(|| generate_key("polk"));
}
#[cfg(feature = "bench")]
#[bench]
fn bench_not_paranoiac(b: &mut Bencher) {
b.iter(|| generate_key("polk"));
}
}