main.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{
  19. process::{exit, ExitCode},
  20. sync::{mpsc::channel, Arc},
  21. thread::available_parallelism,
  22. };
  23. use arg::Args;
  24. use darkfi::{util::cli::ProgressInc, ANSI_LOGO};
  25. use darkfi_sdk::crypto::{ContractId, PublicKey, SecretKey, TokenId};
  26. use rand::rngs::OsRng;
  27. use rayon::iter::ParallelIterator;
  28. const ABOUT: &str =
  29. concat!("vanityaddr ", env!("CARGO_PKG_VERSION"), '\n', env!("CARGO_PKG_DESCRIPTION"));
  30. const USAGE: &str = r#"
  31. Usage: vanityaddr [OPTIONS] <PREFIX> <PREFIX> ...
  32. Arguments:
  33. <PREFIX> Prefixes to search
  34. Options:
  35. -c Make the search case-sensitive
  36. -t Number of threads to use (defaults to number of available CPUs)
  37. -A Search for an address
  38. -C Search for a Contract ID
  39. -T Search for a Token ID
  40. "#;
  41. fn usage() {
  42. print!("{}{}\n{}", ANSI_LOGO, ABOUT, USAGE);
  43. }
  44. struct DrkAddr {
  45. pub public: PublicKey,
  46. pub secret: SecretKey,
  47. }
  48. struct DrkToken {
  49. pub token_id: TokenId,
  50. pub secret: SecretKey,
  51. }
  52. struct DrkContract {
  53. pub contract_id: ContractId,
  54. pub secret: SecretKey,
  55. }
  56. trait Prefixable {
  57. fn new() -> Self;
  58. fn to_string(&self) -> String;
  59. fn get_secret(&self) -> SecretKey;
  60. fn starts_with(&self, prefix: &str, case_sensitive: bool) -> bool {
  61. if case_sensitive {
  62. self.to_string().starts_with(prefix)
  63. } else {
  64. self.to_string().to_lowercase().starts_with(prefix.to_lowercase().as_str())
  65. }
  66. }
  67. fn starts_with_any(&self, prefixes: &[String], case_sensitive: bool) -> bool {
  68. prefixes.iter().any(|prefix| self.starts_with(prefix, case_sensitive))
  69. }
  70. }
  71. impl Prefixable for DrkAddr {
  72. fn new() -> Self {
  73. let secret = SecretKey::random(&mut OsRng);
  74. let public = PublicKey::from_secret(secret);
  75. Self { public, secret }
  76. }
  77. fn to_string(&self) -> String {
  78. self.public.to_string()
  79. }
  80. fn get_secret(&self) -> SecretKey {
  81. self.secret
  82. }
  83. }
  84. impl Prefixable for DrkToken {
  85. fn new() -> Self {
  86. let secret = SecretKey::random(&mut OsRng);
  87. let token_id = TokenId::derive(secret);
  88. Self { token_id, secret }
  89. }
  90. fn to_string(&self) -> String {
  91. self.token_id.to_string()
  92. }
  93. fn get_secret(&self) -> SecretKey {
  94. self.secret
  95. }
  96. }
  97. impl Prefixable for DrkContract {
  98. fn new() -> Self {
  99. let secret = SecretKey::random(&mut OsRng);
  100. let contract_id = ContractId::derive(secret);
  101. Self { contract_id, secret }
  102. }
  103. fn to_string(&self) -> String {
  104. self.contract_id.to_string()
  105. }
  106. fn get_secret(&self) -> SecretKey {
  107. self.secret
  108. }
  109. }
  110. fn main() -> ExitCode {
  111. let argv;
  112. let mut hflag = false;
  113. let mut cflag = false;
  114. let mut addrflag = false;
  115. let mut toknflag = false;
  116. let mut ctrcflag = false;
  117. let mut n_threads = available_parallelism().unwrap().get();
  118. {
  119. let mut args = Args::new().with_cb(|args, flag| match flag {
  120. 'c' => cflag = true,
  121. 'A' => addrflag = true,
  122. 'T' => toknflag = true,
  123. 'C' => ctrcflag = true,
  124. 't' => n_threads = args.eargf().parse::<usize>().unwrap(),
  125. _ => hflag = true,
  126. });
  127. argv = args.parse();
  128. }
  129. if hflag || argv.is_empty() {
  130. usage();
  131. return ExitCode::FAILURE
  132. }
  133. if (addrflag as u8 + toknflag as u8 + ctrcflag as u8) != 1 {
  134. eprintln!("The search flags are mutually exclusive. Use only one of -A/-C/-T.");
  135. return ExitCode::FAILURE
  136. }
  137. // Validate search prefixes
  138. for (idx, prefix) in argv.iter().enumerate() {
  139. match bs58::decode(prefix).into_vec() {
  140. Ok(_) => {}
  141. Err(e) => {
  142. eprintln!("Error: Invalid base58 for prefix #{}: {}", idx, e);
  143. return ExitCode::FAILURE
  144. }
  145. }
  146. }
  147. // Handle SIGINT
  148. let (tx, rx) = channel();
  149. ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel"))
  150. .expect("Error setting SIGINT handler");
  151. // Something fancy
  152. let progress = Arc::new(ProgressInc::new());
  153. // Threadpool
  154. let progress_ = progress.clone();
  155. let rayon_pool = rayon::ThreadPoolBuilder::new().num_threads(n_threads).build().unwrap();
  156. rayon_pool.spawn(move || {
  157. if addrflag {
  158. let addr = rayon::iter::repeat(DrkAddr::new)
  159. .inspect(|_| progress_.inc(1))
  160. .map(|create| create())
  161. .find_any(|address| address.starts_with_any(&argv, cflag))
  162. .expect("Failed to find an address match");
  163. // The above will keep running until it finds a match or until
  164. // the program terminates. Only if a match is found shall the
  165. // following code be executed and the program exit successfully:
  166. let attempts = progress_.position();
  167. progress_.finish_and_clear();
  168. println!(
  169. "{{\"address\":\"{}\",\"attempts\":{},\"secret\":\"{}\"}}",
  170. addr.public, attempts, addr.secret,
  171. );
  172. }
  173. if toknflag {
  174. let tid = rayon::iter::repeat(DrkToken::new)
  175. .inspect(|_| progress_.inc(1))
  176. .map(|create| create())
  177. .find_any(|token_id| token_id.starts_with_any(&argv, cflag))
  178. .expect("Failed to find a token ID match");
  179. let attempts = progress_.position();
  180. progress_.finish_and_clear();
  181. println!(
  182. "{{\"token_id\":\"{}\",\"attempts\":{},\"secret\":\"{}\"}}",
  183. tid.token_id, attempts, tid.secret,
  184. );
  185. }
  186. if ctrcflag {
  187. let cid = rayon::iter::repeat(DrkContract::new)
  188. .inspect(|_| progress_.inc(1))
  189. .map(|create| create())
  190. .find_any(|contract_id| contract_id.starts_with_any(&argv, cflag))
  191. .expect("Failed to find a contract ID match");
  192. let attempts = progress_.position();
  193. progress_.finish_and_clear();
  194. println!(
  195. "{{\"contract_id\":\"{}\",\"attempts\":{},\"secret\":\"{}\"}}",
  196. cid.contract_id, attempts, cid.secret,
  197. );
  198. }
  199. exit(0);
  200. });
  201. // This now blocks and lets our threadpool execute in the background.
  202. rx.recv().expect("Could not receive from channel");
  203. progress.finish_and_clear();
  204. eprintln!("\r\x1b[2KCaught SIGINT, exiting...");
  205. ExitCode::FAILURE
  206. }