multithreaded_mining.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. //! randomx example that mines a dummy header using multiple threads
  2. use std::{
  3. sync::{
  4. atomic::{AtomicBool, AtomicU64, Ordering},
  5. Arc,
  6. },
  7. thread,
  8. time::Instant,
  9. };
  10. use num_bigint::BigUint;
  11. use randomx::*;
  12. #[derive(Clone, Debug)]
  13. struct Header {
  14. version: u8,
  15. previous: blake3::Hash,
  16. height: u32,
  17. nonce: u64,
  18. }
  19. impl Header {
  20. fn new(previous: blake3::Hash) -> Self {
  21. Self {
  22. version: 1,
  23. previous,
  24. height: 1,
  25. nonce: 0,
  26. }
  27. }
  28. fn hash(&self) -> blake3::Hash {
  29. let mut hasher = blake3::Hasher::new();
  30. hasher.update(&self.version.to_le_bytes());
  31. hasher.update(self.previous.as_bytes());
  32. hasher.update(&self.height.to_le_bytes());
  33. hasher.update(&self.nonce.to_le_bytes());
  34. hasher.finalize()
  35. }
  36. }
  37. fn get_mining_flags() -> RandomXFlags {
  38. // Try adding `| RandomXFlags::LARGEPAGES`.
  39. RandomXFlags::get_recommended_flags() | RandomXFlags::FULLMEM
  40. }
  41. fn init_dataset(flags: RandomXFlags, input: &[u8; 32]) -> RandomXDataset {
  42. // Allocate cache and dataset
  43. let cache = RandomXCache::new(flags, &input[..]).unwrap();
  44. let dataset_item_count = RandomXDataset::count().unwrap();
  45. let dataset = RandomXDataset::new(flags, cache, dataset_item_count).unwrap();
  46. // Multithreaded dataset init using all available threads
  47. let threads = thread::available_parallelism()
  48. .map(|n| n.get())
  49. .unwrap_or(1);
  50. println!("Initializing RandomX dataset using {threads} threads...");
  51. let mut handles = Vec::with_capacity(threads);
  52. let threads_u32 = threads as u32;
  53. let per_thread = dataset_item_count / threads_u32;
  54. let remainder = dataset_item_count % threads_u32;
  55. for t in 0..threads_u32 {
  56. let dataset = dataset.clone();
  57. let start_item = t * per_thread;
  58. let count = per_thread + if t == threads_u32 - 1 { remainder } else { 0 };
  59. handles.push(thread::spawn(move || {
  60. dataset.init(start_item, count);
  61. }));
  62. }
  63. // Wait for threads to finish setup
  64. for handle in handles {
  65. let _ = handle.join();
  66. }
  67. dataset
  68. }
  69. fn single_thread_mine(header: &mut Header, target: &BigUint, input: &[u8; 32]) {
  70. println!("Initializing RandomX cache and dataset...");
  71. let setup_start = Instant::now();
  72. let flags = get_mining_flags();
  73. let dataset = init_dataset(flags, input);
  74. println!("Setup time: {:?}", setup_start.elapsed());
  75. println!("Initializing RandomX VM...");
  76. let vm_start = Instant::now();
  77. let vm = RandomXVM::new(flags, None, Some(dataset)).unwrap();
  78. println!("Initialized RandomX VM in {:?}", vm_start.elapsed());
  79. println!("Mining started!");
  80. let mining_start = Instant::now();
  81. loop {
  82. let out_hash = vm.calculate_hash(header.hash().as_bytes()).unwrap();
  83. let out_hash = BigUint::from_bytes_le(&out_hash);
  84. if &out_hash <= target {
  85. println!("Found block header using nonce {}", header.nonce);
  86. println!("Block header hash {}", header.hash());
  87. println!("RandomX output: 0x{out_hash:064x}");
  88. break;
  89. }
  90. header.nonce += 1;
  91. }
  92. println!("Completed mining in {:?}", mining_start.elapsed());
  93. println!("Mined header: {header:?}");
  94. }
  95. fn multi_thread_mine(threads: usize, header: &mut Header, target: &BigUint, input: &[u8; 32]) {
  96. println!("Initializing RandomX cache and dataset...");
  97. let setup_start = Instant::now();
  98. let flags = get_mining_flags();
  99. let dataset = init_dataset(flags, input);
  100. println!("Setup time: {:?}", setup_start.elapsed());
  101. println!("Initializing mining threads...");
  102. let mut handles = Vec::with_capacity(threads);
  103. let found_header = Arc::new(AtomicBool::new(false));
  104. let found_nonce = Arc::new(AtomicU64::new(0));
  105. let threads_u64 = threads as u64;
  106. let mining_start = Instant::now();
  107. for t in 0..threads_u64 {
  108. if found_header.load(Ordering::SeqCst) {
  109. println!("Block header found, threads creation loop exiting");
  110. break;
  111. }
  112. let target = target.clone();
  113. let mut thread_header = header.clone();
  114. thread_header.nonce = t;
  115. let found_header = Arc::clone(&found_header);
  116. let found_nonce = Arc::clone(&found_nonce);
  117. let dataset = dataset.clone();
  118. handles.push(thread::spawn(move || {
  119. println!("Initializing RandomX VM #{t}...");
  120. let vm_start = Instant::now();
  121. let vm = RandomXVM::new(flags, None, Some(dataset)).unwrap();
  122. println!("Initialized RandomX VM #{t} in {:?}", vm_start.elapsed());
  123. loop {
  124. if found_header.load(Ordering::SeqCst) {
  125. println!("Block header found, thread #{t} exiting");
  126. break;
  127. }
  128. let out_hash = vm.calculate_hash(thread_header.hash().as_bytes()).unwrap();
  129. let out_hash = BigUint::from_bytes_le(&out_hash);
  130. if out_hash <= target {
  131. found_header.store(true, Ordering::SeqCst);
  132. found_nonce.store(thread_header.nonce, Ordering::SeqCst);
  133. println!(
  134. "Thread #{t} found block header using nonce {}",
  135. thread_header.nonce
  136. );
  137. println!("Block header hash {}", thread_header.hash());
  138. println!("RandomX output: 0x{out_hash:064x}");
  139. break;
  140. }
  141. // This means thread 0 will use nonces, 0, 4, 8, ...
  142. // and thread 1 will use nonces, 1, 5, 9, ...
  143. thread_header.nonce += threads_u64;
  144. }
  145. }));
  146. }
  147. // Wait for threads to finish mining
  148. for handle in handles {
  149. let _ = handle.join();
  150. }
  151. println!("Completed mining in {:?}", mining_start.elapsed());
  152. header.nonce = found_nonce.load(Ordering::SeqCst);
  153. println!("Mined header: {header:?}");
  154. }
  155. fn main() {
  156. const THREADS: usize = 8;
  157. let difficulty = BigUint::from(2500_u32);
  158. let target = BigUint::from_bytes_le(&[0xFF; 32]) / difficulty;
  159. let previous = blake3::hash(b"Let there be dark!");
  160. let input = previous.as_bytes();
  161. let mut header = Header::new(previous);
  162. println!("Mine target: 0x{target:064x}");
  163. println!("PoW input: {previous}");
  164. match THREADS {
  165. 0 => panic!("Can't use 0 threads!"),
  166. 1 => single_thread_mine(&mut header, &target, input),
  167. _ => multi_thread_mine(THREADS, &mut header, &target, input),
  168. }
  169. println!("Initializing verifier...");
  170. let verifier_setup = Instant::now();
  171. let flags = RandomXFlags::get_recommended_flags();
  172. let cache = RandomXCache::new(flags, input).unwrap();
  173. let vm = RandomXVM::new(flags, Some(cache), None).unwrap();
  174. println!("Setup time: {:?}", verifier_setup.elapsed());
  175. let hashing_time = Instant::now();
  176. let out_hash = vm.calculate_hash(header.hash().as_bytes()).unwrap();
  177. println!("Completed hashing in {:?}", hashing_time.elapsed());
  178. let out_hash = BigUint::from_bytes_le(&out_hash);
  179. println!("RandomX output: 0x{out_hash:064x}");
  180. assert!(out_hash <= target);
  181. }