main.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::{ContractId, PublicKey, SecretKey, TokenId};
  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
  30. prefix: Vec<String>,
  31. /// Should the search be case-sensitive
  32. #[clap(short)]
  33. case_sensitive: bool,
  34. /// Search for an Address
  35. #[clap(long)]
  36. address: bool,
  37. /// Search for a Token ID
  38. #[clap(long)]
  39. token_id: bool,
  40. /// Search for a Contract ID
  41. #[clap(long)]
  42. contract_id: bool,
  43. /// Number of threads to use (defaults to number of available CPUs)
  44. #[clap(short)]
  45. threads: Option<usize>,
  46. }
  47. struct DrkAddr {
  48. pub public: PublicKey,
  49. pub secret: SecretKey,
  50. }
  51. struct DrkToken {
  52. pub token_id: TokenId,
  53. pub secret: SecretKey,
  54. }
  55. struct DrkContract {
  56. pub contract_id: ContractId,
  57. pub secret: SecretKey,
  58. }
  59. trait Prefixable {
  60. fn new() -> Self;
  61. fn to_string(&self) -> String;
  62. fn get_secret(&self) -> SecretKey;
  63. fn starts_with(&self, prefix: &str, case_sensitive: bool) -> bool {
  64. if case_sensitive {
  65. self.to_string().starts_with(prefix)
  66. } else {
  67. self.to_string().to_lowercase().starts_with(prefix.to_lowercase().as_str())
  68. }
  69. }
  70. fn starts_with_any(&self, prefixes: &[String], case_sensitive: bool) -> bool {
  71. prefixes.iter().any(|prefix| self.starts_with(prefix, case_sensitive))
  72. }
  73. }
  74. impl Prefixable for DrkAddr {
  75. fn new() -> Self {
  76. let secret = SecretKey::random(&mut OsRng);
  77. let public = PublicKey::from_secret(secret);
  78. Self { public, secret }
  79. }
  80. fn to_string(&self) -> String {
  81. self.public.to_string()
  82. }
  83. fn get_secret(&self) -> SecretKey {
  84. self.secret
  85. }
  86. }
  87. impl Prefixable for DrkToken {
  88. fn new() -> Self {
  89. let secret = SecretKey::random(&mut OsRng);
  90. let token_id = TokenId::derive(secret);
  91. Self { token_id, secret }
  92. }
  93. fn to_string(&self) -> String {
  94. self.token_id.to_string()
  95. }
  96. fn get_secret(&self) -> SecretKey {
  97. self.secret
  98. }
  99. }
  100. impl Prefixable for DrkContract {
  101. fn new() -> Self {
  102. let secret = SecretKey::random(&mut OsRng);
  103. let contract_id = ContractId::derive(secret);
  104. Self { contract_id, secret }
  105. }
  106. fn to_string(&self) -> String {
  107. self.contract_id.to_string()
  108. }
  109. fn get_secret(&self) -> SecretKey {
  110. self.secret
  111. }
  112. }
  113. fn main() {
  114. let args = Args::parse();
  115. if !((args.address ^ args.contract_id ^ args.token_id) &&
  116. !(args.address && args.contract_id && args.token_id))
  117. {
  118. eprintln!("Error: Can only search for one of Address/ContractId/TokenId");
  119. exit(1);
  120. }
  121. if args.prefix.is_empty() {
  122. eprintln!("Error: No prefix given to search.");
  123. exit(1);
  124. }
  125. // Check if prefixes are valid base58
  126. for (idx, prefix) in args.prefix.iter().enumerate() {
  127. match bs58::decode(prefix).into_vec() {
  128. Ok(_) => {}
  129. Err(e) => {
  130. eprintln!("Error: Invalid base58 for prefix {}: {}", idx, e);
  131. exit(1);
  132. }
  133. };
  134. }
  135. // Threadpool
  136. let num_threads = if args.threads.is_some() {
  137. args.threads.unwrap()
  138. } else {
  139. std::thread::available_parallelism().unwrap().get()
  140. };
  141. let rayon_pool = rayon::ThreadPoolBuilder::new().num_threads(num_threads).build().unwrap();
  142. // Handle SIGINT
  143. let (tx, rx) = channel();
  144. ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel"))
  145. .expect("Error setting SIGINT handler");
  146. // Something fancy
  147. let progress = ProgressBar::new_spinner();
  148. let template =
  149. ProgressStyle::default_bar().template("[{elapsed_precise}] {pos} attempts").unwrap();
  150. progress.set_style(template);
  151. // Fire off the threadpool
  152. rayon_pool.spawn(move || {
  153. if args.token_id {
  154. let tid = rayon::iter::repeat(DrkToken::new)
  155. .inspect(|_| progress.inc(1))
  156. .map(|create| create())
  157. .find_any(|token_id| token_id.starts_with_any(&args.prefix, args.case_sensitive))
  158. .expect("Failed to find a token ID match");
  159. // The above will keep running until it finds a match or until the
  160. // program terminates. Only if a match is found shall the following
  161. // code be executed and the program exit successfully:
  162. let attempts = progress.position();
  163. progress.finish_and_clear();
  164. println!(
  165. "{{\"token_id\":\"{}\",\"attempts\":{},\"secret\":\"{}\"}}",
  166. tid.token_id, attempts, tid.secret,
  167. );
  168. } else if args.address {
  169. let addr = rayon::iter::repeat(DrkAddr::new)
  170. .inspect(|_| progress.inc(1))
  171. .map(|create| create())
  172. .find_any(|address| address.starts_with_any(&args.prefix, args.case_sensitive))
  173. .expect("Failed to find an address match");
  174. let attempts = progress.position();
  175. progress.finish_and_clear();
  176. println!(
  177. "{{\"address\":\"{}\",\"attempts\":{},\"secret\":\"{}\"}}",
  178. addr.public, attempts, addr.secret,
  179. );
  180. } else if args.contract_id {
  181. let cid = rayon::iter::repeat(DrkContract::new)
  182. .inspect(|_| progress.inc(1))
  183. .map(|create| create())
  184. .find_any(|contract_id| {
  185. contract_id.starts_with_any(&args.prefix, args.case_sensitive)
  186. })
  187. .expect("Failed to find a contract ID match");
  188. let attempts = progress.position();
  189. progress.finish_and_clear();
  190. println!(
  191. "{{\"contract_id\":\"{}\",\"attempts\":{},\"secret\":\"{}\"}}",
  192. cid.contract_id, attempts, cid.secret,
  193. );
  194. }
  195. exit(0);
  196. });
  197. // This now blocks and lets our threadpool execute in the background.
  198. rx.recv().expect("Could not receive from channel");
  199. eprintln!("\rCaught SIGINT, exiting...");
  200. exit(127);
  201. }