multithreaded_mining.rs 6.9 KB

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