main.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{process::exit, sync::mpsc::channel};
  19. use clap::Parser;
  20. use darkfi_sdk::crypto::{Address, Keypair, SecretKey};
  21. use indicatif::{ProgressBar, ProgressStyle};
  22. use rand::rngs::OsRng;
  23. use rayon::prelude::*;
  24. use darkfi::cli_desc;
  25. #[derive(Parser)]
  26. #[clap(name = "vanityaddr", about = cli_desc!(), version)]
  27. #[clap(arg_required_else_help(true))]
  28. struct Args {
  29. /// Prefixes to search (must start with 1)
  30. prefix: Vec<String>,
  31. /// Should the search be case-sensitive
  32. #[clap(short)]
  33. case_sensitive: bool,
  34. /// Number of threads to use (defaults to number of available CPUs)
  35. #[clap(short, parse(try_from_str))]
  36. threads: Option<usize>,
  37. }
  38. struct DrkAddr {
  39. pub address: String,
  40. pub secret: SecretKey,
  41. }
  42. impl DrkAddr {
  43. pub fn new() -> Self {
  44. let kp = Keypair::random(&mut OsRng);
  45. let addr = Address::from(kp.public);
  46. Self { secret: kp.secret, address: format!("{}", addr) }
  47. }
  48. pub fn starts_with(&self, prefix: &str, case_sensitive: bool) -> bool {
  49. if case_sensitive {
  50. self.address.starts_with(prefix)
  51. } else {
  52. self.address.to_lowercase().starts_with(prefix.to_lowercase().as_str())
  53. }
  54. }
  55. pub fn starts_with_any(&self, prefixes: &[String], case_sensitive: bool) -> bool {
  56. for prefix in prefixes {
  57. if self.starts_with(prefix, case_sensitive) {
  58. return true
  59. }
  60. }
  61. false
  62. }
  63. }
  64. fn main() {
  65. let args = Args::parse();
  66. if args.prefix.is_empty() {
  67. eprintln!("Error: No prefix given to search.");
  68. exit(1);
  69. }
  70. for (idx, prefix) in args.prefix.iter().enumerate() {
  71. if !prefix.starts_with('1') {
  72. eprintln!("Error: Address prefix at index {} must start with \"1\".", idx);
  73. exit(1);
  74. }
  75. }
  76. // Check if prefixes are valid base58
  77. for (idx, prefix) in args.prefix.iter().enumerate() {
  78. match bs58::decode(prefix).into_vec() {
  79. Ok(_) => {}
  80. Err(e) => {
  81. eprintln!("Error: Invalid base58 for prefix {}: {}", idx, e);
  82. exit(1);
  83. }
  84. };
  85. }
  86. // Threadpool
  87. let num_threads = if args.threads.is_some() { args.threads.unwrap() } else { num_cpus::get() };
  88. let rayon_pool = rayon::ThreadPoolBuilder::new().num_threads(num_threads).build().unwrap();
  89. // Handle SIGINT
  90. let (tx, rx) = channel();
  91. ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel"))
  92. .expect("Error setting SIGINT handler");
  93. // Something fancy
  94. let progress = ProgressBar::new_spinner();
  95. let template =
  96. ProgressStyle::default_bar().template("[{elapsed_precise}] {pos} attempts").unwrap();
  97. progress.set_style(template);
  98. // Fire off the threadpool
  99. rayon_pool.spawn(move || {
  100. let addr = rayon::iter::repeat(DrkAddr::new)
  101. .inspect(|_| progress.inc(1))
  102. .map(|create| create())
  103. .find_any(|address| address.starts_with_any(&args.prefix, args.case_sensitive))
  104. .expect("Failed to find an address match");
  105. // The above will keep running until it finds a match or until the
  106. // program terminates. Only if a match is found shall the following
  107. // code be executed and the program exit successfully:
  108. let attempts = progress.position();
  109. progress.finish_and_clear();
  110. println!(
  111. "{{\"address\":\"{}\",\"attempts\":{},\"secret\":\"{:?}\"}}",
  112. addr.address,
  113. attempts,
  114. addr.secret.inner()
  115. );
  116. exit(0);
  117. });
  118. // This now blocks and lets our threadpool execute in the background.
  119. rx.recv().expect("Could not receive from channel");
  120. eprintln!("\rCaught SIGINT, exiting...");
  121. exit(127);
  122. }