pow.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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. sync::{
  20. atomic::{AtomicBool, AtomicU64, Ordering},
  21. Arc,
  22. },
  23. thread,
  24. time::Instant,
  25. };
  26. use darkfi_sdk::num_traits::{One, Zero};
  27. use num_bigint::BigUint;
  28. use randomx::{RandomXCache, RandomXDataset, RandomXFlags, RandomXVM};
  29. use smol::channel::Receiver;
  30. use tracing::debug;
  31. use crate::{
  32. blockchain::{
  33. block_store::{BlockDifficulty, BlockInfo},
  34. Blockchain, BlockchainOverlayPtr,
  35. },
  36. util::{ringbuffer::RingBuffer, time::Timestamp},
  37. validator::{randomx_factory::init_dataset_wrapper, utils::median},
  38. Error, Result,
  39. };
  40. // Note: We have combined some constants for better performance.
  41. /// Amount of max items(blocks) to use for next difficulty calculation.
  42. /// Must be >= 2 and == BUF_SIZE - DIFFICULTY_LAG.
  43. const DIFFICULTY_WINDOW: usize = 720;
  44. /// Amount of latest blocks to exlude from the calculation.
  45. /// Our ring buffer has length: DIFFICULTY_WINDOW + DIFFICULTY_LAG,
  46. /// but we only use DIFFICULTY_WINDOW items in calculations.
  47. /// Must be == BUF_SIZE - DIFFICULTY_WINDOW.
  48. const _DIFFICULTY_LAG: usize = 15;
  49. /// Ring buffer length.
  50. /// Must be == DIFFICULTY_WINDOW + DIFFICULTY_LAG
  51. const BUF_SIZE: usize = 735;
  52. /// Used to calculate how many items to retain for next difficulty
  53. /// calculation. We are keeping the middle items, meaning cutting
  54. /// both from frond and back of the ring buffer, ending up with max
  55. /// DIFFICULTY_WINDOW - 2*DIFFICULTY_CUT items.
  56. /// (2*DIFFICULTY_CUT <= DIFFICULTY_WINDOW-2) must be true.
  57. const _DIFFICULTY_CUT: usize = 60;
  58. /// Max items to use for next difficulty calculation.
  59. /// Must be DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT
  60. const RETAINED: usize = 600;
  61. /// Already known cutoff start index for this config
  62. const CUT_BEGIN: usize = 60;
  63. /// Already known cutoff end index for this config
  64. const CUT_END: usize = 660;
  65. /// How many most recent blocks to use to verify new blocks' timestamp
  66. const BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW: usize = 60;
  67. /// Time limit in the future of what blocks can be
  68. const BLOCK_FUTURE_TIME_LIMIT: Timestamp = Timestamp::from_u64(60 * 60 * 2);
  69. /// This struct represents the information required by the PoW algorithm
  70. #[derive(Clone)]
  71. pub struct PoWModule {
  72. /// Genesis block timestamp
  73. pub genesis: Timestamp,
  74. /// Target block time, in seconds
  75. pub target: u32,
  76. /// Optional fixed difficulty
  77. pub fixed_difficulty: Option<BigUint>,
  78. /// Latest block timestamps ringbuffer
  79. pub timestamps: RingBuffer<Timestamp, BUF_SIZE>,
  80. /// Latest block cumulative difficulties ringbuffer
  81. pub difficulties: RingBuffer<BigUint, BUF_SIZE>,
  82. /// Total blocks cumulative difficulty
  83. /// Note: we keep this as a struct field for faster
  84. /// access(optimization), since its always same as
  85. /// difficulties buffer last.
  86. pub cumulative_difficulty: BigUint,
  87. }
  88. impl PoWModule {
  89. // Initialize a new `PowModule` for provided target over provided `Blockchain`.
  90. // Optionally, a fixed difficulty can be set and/or initialize before some height.
  91. pub fn new(
  92. blockchain: Blockchain,
  93. target: u32,
  94. fixed_difficulty: Option<BigUint>,
  95. height: Option<u32>,
  96. ) -> Result<Self> {
  97. // Retrieve genesis block timestamp
  98. let genesis = blockchain.genesis_block()?.header.timestamp;
  99. // Retrieving last BUF_SIZE difficulties from blockchain to build the buffers
  100. let mut timestamps = RingBuffer::<Timestamp, BUF_SIZE>::new();
  101. let mut difficulties = RingBuffer::<BigUint, BUF_SIZE>::new();
  102. let mut cumulative_difficulty = BigUint::zero();
  103. let last_n = match height {
  104. Some(h) => blockchain.blocks.get_difficulties_before(h, BUF_SIZE)?,
  105. None => blockchain.blocks.get_last_n_difficulties(BUF_SIZE)?,
  106. };
  107. for difficulty in last_n {
  108. timestamps.push(difficulty.timestamp);
  109. difficulties.push(difficulty.cumulative_difficulty.clone());
  110. cumulative_difficulty = difficulty.cumulative_difficulty;
  111. }
  112. // If a fixed difficulty has been set, assert its greater than zero
  113. if let Some(diff) = &fixed_difficulty {
  114. assert!(diff > &BigUint::zero());
  115. }
  116. Ok(Self {
  117. genesis,
  118. target,
  119. fixed_difficulty,
  120. timestamps,
  121. difficulties,
  122. cumulative_difficulty,
  123. })
  124. }
  125. /// Compute the next mining difficulty, based on current ring buffers.
  126. /// If ring buffers contain 2 or less items, difficulty 1 is returned.
  127. /// If a fixed difficulty has been set, this function will always
  128. /// return that after first 2 difficulties.
  129. pub fn next_difficulty(&self) -> Result<BigUint> {
  130. // Retrieve first DIFFICULTY_WINDOW timestamps from the ring buffer
  131. let mut timestamps: Vec<Timestamp> =
  132. self.timestamps.iter().take(DIFFICULTY_WINDOW).cloned().collect();
  133. // Check we have enough timestamps
  134. let length = timestamps.len();
  135. if length < 2 {
  136. return Ok(BigUint::one())
  137. }
  138. // If a fixed difficulty has been set, return that
  139. if let Some(diff) = &self.fixed_difficulty {
  140. return Ok(diff.clone())
  141. }
  142. // Sort the timestamps vector
  143. timestamps.sort_unstable();
  144. // Grab cutoff indexes
  145. let (cut_begin, cut_end) = self.cutoff(length)?;
  146. // Calculate total time span
  147. let cut_end = cut_end - 1;
  148. let mut time_span = timestamps[cut_end].checked_sub(timestamps[cut_begin])?;
  149. if time_span.inner() == 0 {
  150. time_span = 1.into();
  151. }
  152. // Calculate total work done during this time span
  153. let total_work = &self.difficulties[cut_end] - &self.difficulties[cut_begin];
  154. if total_work <= BigUint::zero() {
  155. return Err(Error::PoWTotalWorkIsZero)
  156. }
  157. // Compute next difficulty
  158. let next_difficulty =
  159. (total_work * self.target + time_span.inner() - BigUint::one()) / time_span.inner();
  160. Ok(next_difficulty)
  161. }
  162. /// Calculate cutoff indexes.
  163. /// If buffers have been filled, we return the
  164. /// already known indexes, for performance.
  165. fn cutoff(&self, length: usize) -> Result<(usize, usize)> {
  166. if length >= DIFFICULTY_WINDOW {
  167. return Ok((CUT_BEGIN, CUT_END))
  168. }
  169. let (cut_begin, cut_end) = if length <= RETAINED {
  170. (0, length)
  171. } else {
  172. let cut_begin = (length - RETAINED).div_ceil(2);
  173. (cut_begin, cut_begin + RETAINED)
  174. };
  175. // Sanity check
  176. if
  177. /* cut_begin < 0 || */
  178. cut_begin + 2 > cut_end || cut_end > length {
  179. return Err(Error::PoWCuttofCalculationError)
  180. }
  181. Ok((cut_begin, cut_end))
  182. }
  183. /// Compute the next mine target.
  184. pub fn next_mine_target(&self) -> Result<BigUint> {
  185. Ok(BigUint::from_bytes_be(&[0xFF; 32]) / &self.next_difficulty()?)
  186. }
  187. /// Compute the next mine target and difficulty.
  188. pub fn next_mine_target_and_difficulty(&self) -> Result<(BigUint, BigUint)> {
  189. let difficulty = self.next_difficulty()?;
  190. let mine_target = BigUint::from_bytes_be(&[0xFF; 32]) / &difficulty;
  191. Ok((mine_target, difficulty))
  192. }
  193. /// Verify provided difficulty corresponds to the next one.
  194. pub fn verify_difficulty(&self, difficulty: &BigUint) -> Result<bool> {
  195. Ok(difficulty == &self.next_difficulty()?)
  196. }
  197. /// Verify provided block timestamp is not far in the future and
  198. /// check its valid acorrding to current timestamps median.
  199. pub fn verify_current_timestamp(&self, timestamp: Timestamp) -> Result<bool> {
  200. if timestamp > Timestamp::current_time().checked_add(BLOCK_FUTURE_TIME_LIMIT)? {
  201. return Ok(false)
  202. }
  203. Ok(self.verify_timestamp_by_median(timestamp))
  204. }
  205. /// Verify provided block timestamp is valid and matches certain criteria.
  206. pub fn verify_timestamp_by_median(&self, timestamp: Timestamp) -> bool {
  207. // Check timestamp is after genesis one
  208. if timestamp <= self.genesis {
  209. return false
  210. }
  211. // If not enough blocks, no proper median yet, return true
  212. if self.timestamps.len() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW {
  213. return true
  214. }
  215. // Make sure the timestamp is higher or equal to the median
  216. let timestamps = self
  217. .timestamps
  218. .iter()
  219. .rev()
  220. .take(BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
  221. .map(|x| x.inner())
  222. .collect();
  223. timestamp >= median(timestamps).into()
  224. }
  225. /// Verify provided block timestamp and hash.
  226. pub fn verify_current_block(&self, block: &BlockInfo) -> Result<()> {
  227. // First we verify the block's timestamp
  228. if !self.verify_current_timestamp(block.header.timestamp)? {
  229. return Err(Error::PoWInvalidTimestamp)
  230. }
  231. // Then we verify the block's hash
  232. self.verify_block_hash(block)
  233. }
  234. /// Verify provided block corresponds to next mine target.
  235. // TODO: Verify depending on block Proof of Work data
  236. pub fn verify_block_hash(&self, block: &BlockInfo) -> Result<()> {
  237. let verifier_setup = Instant::now();
  238. // Grab the next mine target
  239. let target = self.next_mine_target()?;
  240. // Setup verifier
  241. let flags = RandomXFlags::get_recommended_flags();
  242. let cache = RandomXCache::new(flags, block.header.previous.inner())?;
  243. let vm = RandomXVM::new(flags, Some(cache), None)?;
  244. debug!(target: "validator::pow::verify_block", "[VERIFIER] Setup time: {:?}", verifier_setup.elapsed());
  245. // Compute the output hash
  246. let verification_time = Instant::now();
  247. let out_hash = vm.calculate_hash(block.header.hash().inner())?;
  248. let out_hash = BigUint::from_bytes_be(&out_hash);
  249. // Verify hash is less than the expected mine target
  250. if out_hash > target {
  251. return Err(Error::PoWInvalidOutHash)
  252. }
  253. debug!(target: "validator::pow::verify_block", "[VERIFIER] Verification time: {:?}", verification_time.elapsed());
  254. Ok(())
  255. }
  256. /// Append provided timestamp and difficulty to the ring buffers.
  257. pub fn append(&mut self, timestamp: Timestamp, difficulty: &BigUint) {
  258. self.timestamps.push(timestamp);
  259. self.cumulative_difficulty += difficulty;
  260. self.difficulties.push(self.cumulative_difficulty.clone());
  261. }
  262. /// Append provided block difficulty to the ring buffers and insert
  263. /// it to provided overlay.
  264. pub fn append_difficulty(
  265. &mut self,
  266. overlay: &BlockchainOverlayPtr,
  267. difficulty: BlockDifficulty,
  268. ) -> Result<()> {
  269. self.append(difficulty.timestamp, &difficulty.difficulty);
  270. overlay.lock().unwrap().blocks.insert_difficulty(&[difficulty])
  271. }
  272. /// Mine provided block, based on next mine target.
  273. pub fn mine_block(
  274. &self,
  275. miner_block: &mut BlockInfo,
  276. threads: usize,
  277. stop_signal: &Receiver<()>,
  278. ) -> Result<()> {
  279. // Grab the next mine target
  280. let target = self.next_mine_target()?;
  281. mine_block(&target, miner_block, threads, stop_signal)
  282. }
  283. }
  284. impl std::fmt::Display for PoWModule {
  285. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  286. write!(f, "PoWModule:")?;
  287. write!(f, "\ttarget: {}", self.target)?;
  288. write!(f, "\ttimestamps: {:?}", self.timestamps)?;
  289. write!(f, "\tdifficulties: {:?}", self.difficulties)?;
  290. write!(f, "\tcumulative_difficulty: {}", self.cumulative_difficulty)
  291. }
  292. }
  293. /// Mine provided block, based on provided PoW module next mine target.
  294. pub fn mine_block(
  295. target: &BigUint,
  296. miner_block: &mut BlockInfo,
  297. threads: usize,
  298. stop_signal: &Receiver<()>,
  299. ) -> Result<()> {
  300. let miner_setup = Instant::now();
  301. debug!(target: "validator::pow::mine_block", "[MINER] Mine target: 0x{:064x}", target);
  302. // Get the PoW input. The key changes with every mined block.
  303. let input = miner_block.header.previous;
  304. debug!(target: "validator::pow::mine_block", "[MINER] PoW input: {}", input);
  305. let mut flags = RandomXFlags::get_recommended_flags() | RandomXFlags::FULLMEM;
  306. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
  307. if is_x86_feature_detected!("avx2") {
  308. flags |= RandomXFlags::ARGON2_AVX2;
  309. } else if is_x86_feature_detected!("ssse3") {
  310. flags |= RandomXFlags::ARGON2_SSSE3;
  311. }
  312. debug!(target: "validator::pow::mine_block", "[MINER] Initializing RandomX cache...");
  313. let cache = RandomXCache::new(flags, input.inner())?;
  314. debug!(target: "validator::pow::mine_block", "[MINER] Setup time: {:?}", miner_setup.elapsed());
  315. // Multithreaded mining setup
  316. let mining_time = Instant::now();
  317. let mut handles = vec![];
  318. let found_block = Arc::new(AtomicBool::new(false));
  319. let found_nonce = Arc::new(AtomicU64::new(0));
  320. let threads = threads as u64;
  321. let dataset_item_count = RandomXDataset::count()?;
  322. for t in 0..threads {
  323. let target = target.clone();
  324. let mut block = miner_block.clone();
  325. let found_block = Arc::clone(&found_block);
  326. let found_nonce = Arc::clone(&found_nonce);
  327. // TODO: Clean up using RandomXFactory and add wrapper for AVX2
  328. let dataset = if threads > 1 {
  329. let a = (dataset_item_count * (t as u32)) / (threads as u32);
  330. let b = (dataset_item_count * (t as u32 + 1)) / (threads as u32);
  331. init_dataset_wrapper(flags, cache.clone(), a, b - a)?
  332. } else {
  333. init_dataset_wrapper(flags, cache.clone(), 0, dataset_item_count)?
  334. };
  335. let stop_signal = stop_signal.clone();
  336. handles.push(thread::spawn(move || {
  337. debug!(target: "validator::pow::mine_block", "[MINER] Initializing RandomX VM #{t}...");
  338. let mut miner_nonce = t;
  339. let vm = RandomXVM::new(flags, None, Some(dataset)).unwrap();
  340. loop {
  341. // Check if stop signal was received
  342. if stop_signal.is_full() {
  343. debug!(target: "validator::pow::mine_block", "[MINER] Stop signal received, thread #{t} exiting");
  344. break
  345. }
  346. block.header.nonce = miner_nonce;
  347. if found_block.load(Ordering::SeqCst) {
  348. debug!(target: "validator::pow::mine_block", "[MINER] Block found, thread #{t} exiting");
  349. break
  350. }
  351. let out_hash = vm.calculate_hash(block.hash().inner()).unwrap();
  352. let out_hash = BigUint::from_bytes_be(&out_hash);
  353. if out_hash <= target {
  354. found_block.store(true, Ordering::SeqCst);
  355. found_nonce.store(miner_nonce, Ordering::SeqCst);
  356. debug!(target: "validator::pow::mine_block", "[MINER] Thread #{t} found block using nonce {miner_nonce}");
  357. debug!(target: "validator::pow::mine_block", "[MINER] Block hash {}", block.hash());
  358. debug!(target: "validator::pow::mine_block", "[MINER] RandomX output: 0x{out_hash:064x}");
  359. break
  360. }
  361. // This means thread 0 will use nonces, 0, 4, 8, ...
  362. // and thread 1 will use nonces, 1, 5, 9, ...
  363. miner_nonce += threads;
  364. }
  365. }));
  366. }
  367. for handle in handles {
  368. let _ = handle.join();
  369. }
  370. // Check if stop signal was received
  371. if stop_signal.is_full() {
  372. return Err(Error::MinerTaskStopped)
  373. }
  374. debug!(target: "validator::pow::mine_block", "[MINER] Mining time: {:?}", mining_time.elapsed());
  375. // Set the valid mined nonce in the block
  376. miner_block.header.nonce = found_nonce.load(Ordering::SeqCst);
  377. Ok(())
  378. }
  379. #[cfg(test)]
  380. mod tests {
  381. use std::{
  382. io::{BufRead, Cursor},
  383. process::Command,
  384. };
  385. use darkfi_sdk::num_traits::Num;
  386. use num_bigint::BigUint;
  387. use sled_overlay::sled;
  388. use crate::{
  389. blockchain::{BlockInfo, Blockchain},
  390. Result,
  391. };
  392. use super::PoWModule;
  393. const DEFAULT_TEST_THREADS: usize = 2;
  394. const DEFAULT_TEST_DIFFICULTY_TARGET: u32 = 120;
  395. #[test]
  396. fn test_wide_difficulty() -> Result<()> {
  397. let sled_db = sled::Config::new().temporary(true).open()?;
  398. let blockchain = Blockchain::new(&sled_db)?;
  399. let genesis_block = BlockInfo::default();
  400. blockchain.add_block(&genesis_block)?;
  401. let mut module = PoWModule::new(blockchain, DEFAULT_TEST_DIFFICULTY_TARGET, None, None)?;
  402. let output = Command::new("./script/research/pow/gen_wide_data.py").output().unwrap();
  403. let reader = Cursor::new(output.stdout);
  404. for (n, line) in reader.lines().enumerate() {
  405. let line = line.unwrap();
  406. let parts: Vec<String> = line.split(' ').map(|x| x.to_string()).collect();
  407. assert!(parts.len() == 2);
  408. let timestamp = parts[0].parse::<u64>().unwrap().into();
  409. let difficulty = BigUint::from_str_radix(&parts[1], 10).unwrap();
  410. let res = module.next_difficulty()?;
  411. if res != difficulty {
  412. eprintln!("Wrong wide difficulty for block {n}");
  413. eprintln!("Expected: {difficulty}");
  414. eprintln!("Found: {res}");
  415. assert!(res == difficulty);
  416. }
  417. module.append(timestamp, &difficulty);
  418. }
  419. Ok(())
  420. }
  421. #[test]
  422. fn test_miner_correctness() -> Result<()> {
  423. // Default setup
  424. let sled_db = sled::Config::new().temporary(true).open()?;
  425. let blockchain = Blockchain::new(&sled_db)?;
  426. let mut genesis_block = BlockInfo::default();
  427. genesis_block.header.timestamp = 0.into();
  428. blockchain.add_block(&genesis_block)?;
  429. let module = PoWModule::new(blockchain, DEFAULT_TEST_DIFFICULTY_TARGET, None, None)?;
  430. let (_, recvr) = smol::channel::bounded(1);
  431. // Mine next block
  432. let mut next_block = BlockInfo::default();
  433. next_block.header.previous = genesis_block.hash();
  434. module.mine_block(&mut next_block, DEFAULT_TEST_THREADS, &recvr)?;
  435. // Verify it
  436. module.verify_current_block(&next_block)?;
  437. Ok(())
  438. }
  439. }