vanity-core 0.8.1

Multi-chain vanity address grinding core library
Documentation
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use crate::chain::GrindAttempt;
use crate::pattern::Pattern;
use ed25519_dalek::{PublicKey, SecretKey as Ed25519SecretKey};
use rand::rngs::OsRng;
use rand::RngCore;
use ripemd::Ripemd160;
use secp256k1::{Secp256k1, SecretKey};
use sha2::{Digest, Sha256};

/// Local ed25519 keypair wrapper — same call surface as the
/// `solana_sdk::signature::Keypair` this replaces (`.new()`, `.from_seed()`,
/// `.pubkey()`, `.secret()`), so the ~13 chain files that construct/read
/// keys through it don't need to change beyond their import line.
pub struct Keypair {
    secret: Ed25519SecretKey,
    public: PublicKey,
}

impl Keypair {
    pub fn new() -> Self {
        let mut seed = [0u8; 32];
        OsRng.fill_bytes(&mut seed);
        Self::from_seed(&seed).expect("random 32-byte seed is always a valid ed25519 secret key")
    }

    pub fn from_seed(seed: &[u8]) -> Result<Self, ed25519_dalek::SignatureError> {
        let secret = Ed25519SecretKey::from_bytes(seed)?;
        let public = PublicKey::from(&secret);
        Ok(Self { secret, public })
    }

    pub fn pubkey(&self) -> PublicKey {
        self.public
    }

    pub fn secret(&self) -> &Ed25519SecretKey {
        &self.secret
    }
}

pub const BASE58_ALPHABET: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

pub const RIPPLE_ALPHABET: &str = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz";

/// Bech32 data charset (cosmos1… addresses).
pub const BECH32_CHARSET: &str = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";

pub fn hash160(data: &[u8]) -> [u8; 20] {
    let sha = Sha256::digest(data);
    let rip = Ripemd160::digest(sha);
    let mut out = [0u8; 20];
    out.copy_from_slice(&rip);
    out
}

pub fn random_secp256k1_secret() -> SecretKey {
    SecretKey::new(&mut OsRng)
}

pub fn grind_secp256k1<F>(derive: F) -> (String, GrindAttempt)
where
    F: Fn(&SecretKey) -> String,
{
    let secret = random_secp256k1_secret();
    let address = derive(&secret);
    (address, GrindAttempt::Secret32(secret.secret_bytes()))
}

pub fn base58_check_encode(version: u8, payload: &[u8]) -> String {
    let mut data = Vec::with_capacity(1 + payload.len() + 4);
    data.push(version);
    data.extend_from_slice(payload);
    let checksum = &Sha256::digest(Sha256::digest(&data))[..4];
    data.extend_from_slice(checksum);
    bs58::encode(data).into_string()
}

pub fn base58_check_encode_raw(payload: &[u8]) -> String {
    let checksum = &Sha256::digest(Sha256::digest(payload))[..4];
    let mut data = payload.to_vec();
    data.extend_from_slice(checksum);
    bs58::encode(data).into_string()
}

pub fn encode_base58_with_alphabet(data: &[u8], alphabet: &str) -> String {
    if data.is_empty() {
        return String::new();
    }

    let mut digits = vec![0u8];
    for &byte in data {
        let mut carry = byte as u32;
        for digit in &mut digits {
            carry += (*digit as u32) * 256;
            *digit = (carry % 58) as u8;
            carry /= 58;
        }
        while carry > 0 {
            digits.push((carry % 58) as u8);
            carry /= 58;
        }
    }

    let mut encoded = String::new();
    for &byte in data {
        if byte == 0 {
            encoded.push(alphabet.chars().next().unwrap());
        } else {
            break;
        }
    }
    for &digit in digits.iter().rev() {
        let ch = alphabet.chars().nth(digit as usize).unwrap_or_else(|| {
            panic!(
                "base58 digit {digit} out of range for alphabet len {}",
                alphabet.len()
            )
        });
        encoded.push(ch);
    }
    encoded
}

pub fn p2pkh_address(secret: &SecretKey, version: u8) -> String {
    let secp = Secp256k1::new();
    p2pkh_address_from_pubkey(&secret.public_key(&secp), version)
}

/// P2PKH from an already-known compressed/uncompressed secp256k1 public key.
pub fn p2pkh_address_from_pubkey(pubkey: &secp256k1::PublicKey, version: u8) -> String {
    let hash = hash160(&pubkey.serialize());
    base58_check_encode(version, &hash)
}

pub fn validate_chars(label: &str, pattern: &str, allowed: &str) -> Result<String, String> {
    if pattern.is_empty() {
        return Err(format!("'{label}' cannot be empty"));
    }
    for c in pattern.chars() {
        if c == '*' {
            continue; // wildcard
        }
        if !allowed.contains(c) {
            return Err(format!(
                "'{label}' contains '{c}' — allowed: {allowed} (and *)"
            ));
        }
    }
    Ok(pattern.to_string())
}

fn literal_char_count(s: &str) -> usize {
    s.chars().filter(|c| *c != '*').count()
}

pub fn build_base58_pattern(
    prefix: Option<&str>,
    suffix: Option<&str>,
    contains: Option<&str>,
    exact: bool,
    allowed: &str,
    max_len: usize,
) -> Result<Pattern, String> {
    let prefix_raw = prefix.unwrap_or("").to_string();
    let suffix_raw = suffix.unwrap_or("").to_string();
    let contains_raw = contains.unwrap_or("").to_string();

    if prefix_raw.is_empty() && suffix_raw.is_empty() && contains_raw.is_empty() {
        return Err("Provide at least one of --prefix, --suffix, or --contains".into());
    }

    let prefix = if prefix_raw.is_empty() {
        String::new()
    } else {
        let validated = validate_chars("prefix", &prefix_raw, allowed)?;
        if literal_char_count(&validated) > max_len {
            return Err(format!("prefix is too long (max {max_len} characters)"));
        }
        validated
    };

    let suffix = if suffix_raw.is_empty() {
        String::new()
    } else {
        let validated = validate_chars("suffix", &suffix_raw, allowed)?;
        if literal_char_count(&validated) > max_len {
            return Err(format!("suffix is too long (max {max_len} characters)"));
        }
        validated
    };

    let contains = if contains_raw.is_empty() {
        String::new()
    } else {
        let validated = validate_chars("contains", &contains_raw, allowed)?;
        if literal_char_count(&validated) > max_len {
            return Err(format!("contains is too long (max {max_len} characters)"));
        }
        validated
    };

    if !prefix.is_empty()
        && !suffix.is_empty()
        && literal_char_count(&prefix) + literal_char_count(&suffix) > max_len
    {
        return Err(format!(
            "prefix + suffix length ({}) exceeds {max_len} characters",
            literal_char_count(&prefix) + literal_char_count(&suffix)
        ));
    }

    let (prefix_match, suffix_match, contains_match) = if exact {
        (prefix.clone(), suffix.clone(), contains.clone())
    } else {
        (
            prefix.to_ascii_lowercase(),
            suffix.to_ascii_lowercase(),
            contains.to_ascii_lowercase(),
        )
    };

    Ok(Pattern {
        prefix,
        suffix,
        contains,
        prefix_match,
        suffix_match,
        contains_match,
        ignore_case: !exact,
        fixed_prefix_len: 0,
    })
}

pub fn build_hex_pattern(
    prefix: Option<&str>,
    suffix: Option<&str>,
    contains: Option<&str>,
    with_0x_prefix: bool,
    max_hex_len: usize,
) -> Result<Pattern, String> {
    let prefix_raw = prefix.unwrap_or("").to_string();
    let suffix_raw = suffix.unwrap_or("").to_string();
    let contains_raw = contains.unwrap_or("").to_string();

    if prefix_raw.is_empty() && suffix_raw.is_empty() && contains_raw.is_empty() {
        return Err("Provide at least one of --prefix, --suffix, or --contains".into());
    }

    let normalize = |label: &str, input: &str| -> Result<String, String> {
        let stripped = input.strip_prefix("0x").unwrap_or(input);
        let normalized = stripped.to_ascii_lowercase();
        if normalized.is_empty() {
            return Err(format!("'{label}' cannot be empty"));
        }
        for c in normalized.chars() {
            if c == '*' {
                continue;
            }
            if !c.is_ascii_hexdigit() {
                return Err(format!(
                    "'{label}' contains '{c}' — must be hex (0-9, a-f) or *"
                ));
            }
        }
        Ok(normalized)
    };

    let prefix = if prefix_raw.is_empty() {
        String::new()
    } else {
        let normalized = normalize("prefix", &prefix_raw)?;
        if literal_char_count(&normalized) > max_hex_len {
            return Err(format!("prefix is too long (max {max_hex_len} hex chars)"));
        }
        if with_0x_prefix {
            format!("0x{normalized}")
        } else {
            normalized
        }
    };

    let suffix = if suffix_raw.is_empty() {
        String::new()
    } else {
        let normalized = normalize("suffix", &suffix_raw)?;
        if literal_char_count(&normalized) > max_hex_len {
            return Err(format!("suffix is too long (max {max_hex_len} hex chars)"));
        }
        normalized
    };

    let contains = if contains_raw.is_empty() {
        String::new()
    } else {
        let normalized = normalize("contains", &contains_raw)?;
        if literal_char_count(&normalized) > max_hex_len {
            return Err(format!(
                "contains is too long (max {max_hex_len} hex chars)"
            ));
        }
        normalized
    };

    let prefix_hex_len = literal_char_count(prefix.strip_prefix("0x").unwrap_or(&prefix));
    if !prefix.is_empty()
        && !suffix.is_empty()
        && prefix_hex_len + literal_char_count(&suffix) > max_hex_len
    {
        return Err(format!(
            "prefix + suffix length ({}) exceeds {max_hex_len} hex characters",
            prefix_hex_len + literal_char_count(&suffix)
        ));
    }

    let fixed_prefix_len = if with_0x_prefix && !prefix.is_empty() {
        2
    } else {
        0
    };
    Ok(Pattern {
        prefix: prefix.clone(),
        suffix: suffix.clone(),
        contains: contains.clone(),
        prefix_match: prefix,
        suffix_match: suffix,
        contains_match: contains,
        ignore_case: true,
        fixed_prefix_len,
    })
}

/// Expected attempts for one pattern character against a concrete alphabet.
///
/// When `ignore_case` is set, a letter counts as two matches only if **both**
/// cases appear in `alphabet` (Base58 omits `O`/`I`/`l`, so `o`/`i`/`L` stay 1×).
pub fn alphabet_char_expected(c: char, ignore_case: bool, alphabet: &str) -> f64 {
    let size = alphabet.len() as f64;
    let mut matches: f64 = 0.0;
    if alphabet.contains(c) {
        matches += 1.0;
    }
    if ignore_case && c.is_ascii_alphabetic() {
        let other = if c.is_ascii_lowercase() {
            c.to_ascii_uppercase()
        } else {
            c.to_ascii_lowercase()
        };
        if other != c && alphabet.contains(other) {
            matches += 1.0;
        }
    }
    size / matches.max(1.0)
}

/// Product of [`alphabet_char_expected`] over literal (non-`*`) pattern chars.
pub fn alphabet_combinations(pattern: &str, ignore_case: bool, alphabet: &str) -> f64 {
    pattern
        .chars()
        .filter(|c| *c != '*')
        .map(|c| alphabet_char_expected(c, ignore_case, alphabet))
        .product()
}

#[allow(dead_code)] // exact-case helper; layouts use alphabet_combinations with ignore_case
pub fn base58_combinations(pattern: &str) -> f64 {
    alphabet_combinations(pattern, false, BASE58_ALPHABET)
}

pub fn hex_combinations(pattern: &str) -> f64 {
    let hex = pattern.strip_prefix("0x").unwrap_or(pattern);
    16f64.powi(literal_char_count(hex) as i32)
}

pub fn bech32_combinations(pattern: &str) -> f64 {
    32f64.powi(literal_char_count(pattern) as i32)
}

pub fn base32_combinations(pattern: &str) -> f64 {
    32f64.powi(literal_char_count(pattern) as i32)
}

/// RFC 4648 base32 alphabet (Algorand / Filecoin / ICP).
pub const BASE32_ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
pub const BASE32_ALPHABET_LOWER: &str = "abcdefghijklmnopqrstuvwxyz234567";

/// TON user-friendly address alphabet (base64url).
pub const BASE64URL_ALPHABET: &str =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

#[allow(dead_code)] // exact-case helper; TON uses alphabet_combinations with ignore_case
pub fn base64url_combinations(pattern: &str) -> f64 {
    alphabet_combinations(pattern, false, BASE64URL_ALPHABET)
}

/// DER-encodes a raw 32-byte Ed25519 public key as a SubjectPublicKeyInfo
/// (RFC 8410), used by both ICP principals and Hedera's public key export.
pub fn der_ed25519_spki(pubkey: &[u8; 32]) -> Vec<u8> {
    let mut der = vec![
        0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
    ];
    der.extend_from_slice(pubkey);
    der
}

pub fn blake2b_var(data: &[u8], out_len: usize) -> Vec<u8> {
    use blake2::digest::{Update, VariableOutput};
    use blake2::Blake2bVar;
    let mut hasher = Blake2bVar::new(out_len).expect("valid blake2b length");
    hasher.update(data);
    let mut out = vec![0u8; out_len];
    hasher
        .finalize_variable(&mut out)
        .expect("blake2b finalize");
    out
}

/// Kaspa's address checksum (a CashAddr-style BCH code over GF(2^5)) — NOT
/// standard BIP-173 bech32, despite using the same 32-symbol charset. Ported
/// from kaspa-addresses (rusty-kaspa) and verified against its own test
/// vectors in `kaspa::tests::kaspa_matches_known_vector`.
fn cashaddr_polymod(values: impl Iterator<Item = u8>) -> u64 {
    let mut c: u64 = 1;
    for d in values {
        let c0 = c >> 35;
        c = ((c & 0x0007_ffff_ffff) << 5) ^ (d as u64);
        if c0 & 0x01 != 0 {
            c ^= 0x98f2bc8e61;
        }
        if c0 & 0x02 != 0 {
            c ^= 0x79b76d99e2;
        }
        if c0 & 0x04 != 0 {
            c ^= 0xf33e5fb3c4;
        }
        if c0 & 0x08 != 0 {
            c ^= 0xae2eabe2a8;
        }
        if c0 & 0x10 != 0 {
            c ^= 0x1e4f43e470;
        }
    }
    c ^ 1
}

/// Regroups 8-bit bytes into 5-bit words, right-padding the final word with
/// zero bits (matches kaspa-addresses' `conv8to5`).
fn conv8to5(payload: &[u8]) -> Vec<u8> {
    let padding = usize::from(!payload.len().is_multiple_of(5));
    let mut out = vec![0u8; payload.len() * 8 / 5 + padding];
    let mut idx = 0;
    let mut buf: u16 = 0;
    let mut bits = 0u32;
    for &byte in payload {
        buf = (buf << 8) | u16::from(byte);
        bits += 8;
        while bits >= 5 {
            bits -= 5;
            out[idx] = (buf >> bits) as u8;
            buf &= (1 << bits) - 1;
            idx += 1;
        }
    }
    if bits > 0 {
        out[idx] = (buf << (5 - bits)) as u8;
    }
    out
}

/// Encodes a Kaspa address body (`version` byte + raw payload, e.g. a
/// 32-byte Schnorr x-only pubkey) for the given prefix ("kaspa" / "kaspatest"),
/// returning just the data+checksum part (caller adds `prefix:`).
pub fn kaspa_address_data(prefix: &str, version: u8, payload: &[u8]) -> String {
    let mut versioned = Vec::with_capacity(1 + payload.len());
    versioned.push(version);
    versioned.extend_from_slice(payload);
    let fivebit_payload = conv8to5(&versioned);

    let fivebit_prefix = prefix.as_bytes().iter().copied().map(|c| c & 0x1f);
    let checksum = cashaddr_polymod(
        fivebit_prefix
            .chain([0u8])
            .chain(fivebit_payload.iter().copied())
            .chain([0u8; 8]),
    );
    let checksum5 = conv8to5(&checksum.to_be_bytes()[3..]);

    let chars: Vec<char> = BECH32_CHARSET.chars().collect();
    fivebit_payload
        .iter()
        .chain(checksum5.iter())
        .map(|&i| chars[i as usize])
        .collect()
}

pub fn crc16_xmodem(data: &[u8]) -> u16 {
    let mut crc: u16 = 0;
    for &b in data {
        crc ^= u16::from(b) << 8;
        for _ in 0..8 {
            if crc & 0x8000 != 0 {
                crc = (crc << 1) ^ 0x1021;
            } else {
                crc <<= 1;
            }
        }
    }
    crc
}

/// Every address of a chain starts with `fixed`, and the characters right after it
/// can only be `next[0]`, `next[1]`, …. Adds `fixed` and any leading single-option
/// `next` characters when the user left them out (they aren't counted as
/// difficulty) and rejects prefixes that can never occur.
pub fn apply_address_start(
    pattern: &mut Pattern,
    chain_name: &str,
    fixed: &str,
    next: &[&str],
) -> Result<(), String> {
    if !pattern.has_prefix() {
        return Ok(());
    }
    let ignore_case = pattern.ignore_case;
    let same = |a: char, b: char| a == b || (ignore_case && a.eq_ignore_ascii_case(&b));
    let starts_with = |s: &str, head: &str, wildcard: bool| {
        s.chars().count() >= head.chars().count()
            && s.chars()
                .zip(head.chars())
                .all(|(c, h)| same(c, h) || (wildcard && c == '*'))
    };

    let after_fixed = if starts_with(&pattern.prefix, fixed, false) {
        pattern.prefix[fixed.len()..].to_string()
    } else {
        pattern.prefix.clone()
    };
    let forced: String = next.iter().take_while(|s| s.len() == 1).copied().collect();
    let head = format!("{fixed}{forced}");
    let rest = &next[forced.len()..];
    let check = |user: &str| -> Result<(), String> {
        for (i, (c, allowed)) in user.chars().zip(rest).enumerate() {
            if c == '*' || allowed.chars().any(|a| same(c, a)) {
                continue;
            }
            let before = format!("{head}{}", &user[..i]);
            let options: Vec<String> = allowed.chars().map(|a| a.to_string()).collect();
            return Err(format!(
                "{chain_name} addresses can never have '{c}' after '{before}'. The next character is always {}. Try a prefix like '{}…'.",
                options.join(" / "),
                rest.iter().map(|s| &s[..1]).collect::<String>()
            ));
        }
        Ok(())
    };

    // Typed the forced characters, or is that the start of their own text (Kaspa `q0` = `qq0…`)?
    let mut user = after_fixed.as_str();
    let mut result = check(user);
    if starts_with(&after_fixed, &forced, true) {
        let stripped = &after_fixed[forced.len()..];
        let stripped_result = check(stripped);
        if stripped_result.is_ok() || result.is_err() {
            user = stripped;
            result = stripped_result;
        }
    }
    result?;

    pattern.prefix = format!("{head}{user}");
    pattern.prefix_match = if pattern.ignore_case {
        pattern.prefix.to_ascii_lowercase()
    } else {
        pattern.prefix.clone()
    };
    pattern.set_fixed_prefix(&head);
    Ok(())
}

/// Odds correction for the `next` positions of [`apply_address_start`]: they only
/// have `allowed.len()` possible characters, not the whole `alphabet`.
pub fn address_start_factor(pattern: &Pattern, next: &[&str], alphabet: f64) -> f64 {
    let rest = next.iter().skip_while(|s| s.len() == 1);
    pattern
        .user_prefix()
        .chars()
        .zip(rest)
        .filter(|(c, _)| *c != '*')
        .map(|(_, allowed)| allowed.len() as f64 / alphabet)
        .product()
}

pub fn expected_from_pattern(pattern: &Pattern, per_char: impl Fn(&str) -> f64) -> f64 {
    let mut combos = 1.0_f64;
    if pattern.has_prefix() {
        combos *= per_char(pattern.user_prefix());
    }
    if pattern.has_suffix() {
        combos *= per_char(&pattern.suffix);
    }
    if pattern.has_contains() {
        // Contains is harder to estimate; treat literals like a free-floating suffix.
        combos *= per_char(&pattern.contains);
    }
    combos
}

pub fn matches_pattern(address: &str, pattern: &Pattern, force_lower: bool) -> bool {
    let addr = if force_lower || pattern.ignore_case {
        address.to_ascii_lowercase()
    } else {
        address.to_string()
    };
    crate::pattern::matches_full(
        &addr,
        &pattern.prefix_match,
        &pattern.suffix_match,
        &pattern.contains_match,
        pattern.ignore_case || force_lower,
    )
}

pub fn grind_ed25519<F>(derive: F) -> (String, GrindAttempt)
where
    F: Fn(&Keypair) -> String,
{
    let keypair = Keypair::new();
    let address = derive(&keypair);
    (
        address,
        GrindAttempt::Secret32(secret32_from_keypair(&keypair)),
    )
}

pub fn keypair_from_secret(secret: [u8; 32]) -> Keypair {
    Keypair::from_seed(&secret).expect("valid ed25519 seed")
}

pub fn secret32_from_keypair(keypair: &Keypair) -> [u8; 32] {
    let seed = keypair.secret().to_bytes();
    let mut secret = [0u8; 32];
    secret.copy_from_slice(&seed);
    secret
}

pub fn secret_from_attempt(attempt: GrindAttempt) -> [u8; 32] {
    attempt.secret_bytes()
}