pow.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. 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 log::debug;
  28. use num_bigint::BigUint;
  29. use randomx::{RandomXCache, RandomXDataset, RandomXFlags, RandomXVM};
  30. use smol::channel::Receiver;
  31. use crate::{
  32. blockchain::{
  33. block_store::{BlockDifficulty, BlockInfo},
  34. Blockchain, BlockchainOverlayPtr,
  35. },
  36. util::{ringbuffer::RingBuffer, time::Timestamp},
  37. validator::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 cummulative difficulties ringbuffer
  81. pub difficulties: RingBuffer<BigUint, BUF_SIZE>,
  82. /// Total blocks cummulative 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 cummulative_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 cummulative_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.cummulative_difficulty.clone());
  110. cummulative_difficulty = difficulty.cummulative_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. cummulative_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 + 1) / 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. pub fn verify_block_hash(&self, block: &BlockInfo) -> Result<()> {
  236. let verifier_setup = Instant::now();
  237. // Grab the next mine target
  238. let target = self.next_mine_target()?;
  239. // Setup verifier
  240. let flags = RandomXFlags::default();
  241. let cache = RandomXCache::new(flags, block.header.previous.inner()).unwrap();
  242. let vm = RandomXVM::new(flags, &cache).unwrap();
  243. debug!(target: "validator::pow::verify_block", "[VERIFIER] Setup time: {:?}", verifier_setup.elapsed());
  244. // Compute the output hash
  245. let verification_time = Instant::now();
  246. let out_hash = vm.hash(block.header.hash().inner());
  247. let out_hash = BigUint::from_bytes_be(&out_hash);
  248. // Verify hash is less than the expected mine target
  249. if out_hash > target {
  250. return Err(Error::PoWInvalidOutHash)
  251. }
  252. debug!(target: "validator::pow::verify_block", "[VERIFIER] Verification time: {:?}", verification_time.elapsed());
  253. Ok(())
  254. }
  255. /// Append provided timestamp and difficulty to the ring buffers.
  256. pub fn append(&mut self, timestamp: Timestamp, difficulty: &BigUint) {
  257. self.timestamps.push(timestamp);
  258. self.cummulative_difficulty += difficulty;
  259. self.difficulties.push(self.cummulative_difficulty.clone());
  260. }
  261. /// Append provided block difficulty to the ring buffers and insert
  262. /// it to provided overlay.
  263. pub fn append_difficulty(
  264. &mut self,
  265. overlay: &BlockchainOverlayPtr,
  266. difficulty: BlockDifficulty,
  267. ) -> Result<()> {
  268. self.append(difficulty.timestamp, &difficulty.difficulty);
  269. overlay.lock().unwrap().blocks.insert_difficulty(&[difficulty])
  270. }
  271. /// Mine provided block, based on next mine target.
  272. pub fn mine_block(
  273. &self,
  274. miner_block: &mut BlockInfo,
  275. threads: usize,
  276. stop_signal: &Receiver<()>,
  277. ) -> Result<()> {
  278. // Grab the next mine target
  279. let target = self.next_mine_target()?;
  280. mine_block(&target, miner_block, threads, stop_signal)
  281. }
  282. }
  283. impl std::fmt::Display for PoWModule {
  284. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  285. write!(f, "PoWModule:")?;
  286. write!(f, "\ttarget: {}", self.target)?;
  287. write!(f, "\ttimestamps: {:?}", self.timestamps)?;
  288. write!(f, "\tdifficulties: {:?}", self.difficulties)?;
  289. write!(f, "\tcummulative_difficulty: {}", self.cummulative_difficulty)
  290. }
  291. }
  292. /// Mine provided block, based on provided PoW module next mine target.
  293. pub fn mine_block(
  294. target: &BigUint,
  295. miner_block: &mut BlockInfo,
  296. threads: usize,
  297. stop_signal: &Receiver<()>,
  298. ) -> Result<()> {
  299. let miner_setup = Instant::now();
  300. debug!(target: "validator::pow::mine_block", "[MINER] Mine target: 0x{:064x}", target);
  301. // Get the PoW input. The key changes with every mined block.
  302. let input = miner_block.header.previous;
  303. debug!(target: "validator::pow::mine_block", "[MINER] PoW input: {}", input);
  304. let flags = RandomXFlags::default() | RandomXFlags::FULLMEM;
  305. debug!(target: "validator::pow::mine_block", "[MINER] Initializing RandomX dataset...");
  306. let dataset = Arc::new(RandomXDataset::new(flags, input.inner(), threads).unwrap());
  307. debug!(target: "validator::pow::mine_block", "[MINER] Setup time: {:?}", miner_setup.elapsed());
  308. // Multithreaded mining setup
  309. let mining_time = Instant::now();
  310. let mut handles = vec![];
  311. let found_block = Arc::new(AtomicBool::new(false));
  312. let found_nonce = Arc::new(AtomicU64::new(0));
  313. let threads = threads as u64;
  314. for t in 0..threads {
  315. let target = target.clone();
  316. let mut block = miner_block.clone();
  317. let found_block = Arc::clone(&found_block);
  318. let found_nonce = Arc::clone(&found_nonce);
  319. let dataset = Arc::clone(&dataset);
  320. let stop_signal = stop_signal.clone();
  321. handles.push(thread::spawn(move || {
  322. debug!(target: "validator::pow::mine_block", "[MINER] Initializing RandomX VM #{}...", t);
  323. let mut miner_nonce = t;
  324. let vm = RandomXVM::new_fast(flags, &dataset).unwrap();
  325. loop {
  326. // Check if stop signal was received
  327. if stop_signal.is_full() {
  328. debug!(target: "validator::pow::mine_block", "[MINER] Stop signal received, thread #{} exiting", t);
  329. break
  330. }
  331. block.header.nonce = miner_nonce;
  332. if found_block.load(Ordering::SeqCst) {
  333. debug!(target: "validator::pow::mine_block", "[MINER] Block found, thread #{} exiting", t);
  334. break
  335. }
  336. let out_hash = vm.hash(block.hash().inner());
  337. let out_hash = BigUint::from_bytes_be(&out_hash);
  338. if out_hash <= target {
  339. found_block.store(true, Ordering::SeqCst);
  340. found_nonce.store(miner_nonce, Ordering::SeqCst);
  341. debug!(target: "validator::pow::mine_block", "[MINER] Thread #{} found block using nonce {}",
  342. t, miner_nonce
  343. );
  344. debug!(target: "validator::pow::mine_block", "[MINER] Block hash {}", block.hash());
  345. debug!(target: "validator::pow::mine_block", "[MINER] RandomX output: 0x{:064x}", out_hash);
  346. break
  347. }
  348. // This means thread 0 will use nonces, 0, 4, 8, ...
  349. // and thread 1 will use nonces, 1, 5, 9, ...
  350. miner_nonce += threads;
  351. }
  352. }));
  353. }
  354. for handle in handles {
  355. let _ = handle.join();
  356. }
  357. // Check if stop signal was received
  358. if stop_signal.is_full() {
  359. return Err(Error::MinerTaskStopped)
  360. }
  361. debug!(target: "validator::pow::mine_block", "[MINER] Mining time: {:?}", mining_time.elapsed());
  362. // Set the valid mined nonce in the block
  363. miner_block.header.nonce = found_nonce.load(Ordering::SeqCst);
  364. Ok(())
  365. }
  366. #[cfg(test)]
  367. mod tests {
  368. use std::{
  369. io::{BufRead, Cursor},
  370. process::Command,
  371. };
  372. use darkfi_sdk::num_traits::Num;
  373. use num_bigint::BigUint;
  374. use sled_overlay::sled;
  375. use crate::{
  376. blockchain::{BlockInfo, Blockchain},
  377. Result,
  378. };
  379. use super::PoWModule;
  380. const DEFAULT_TEST_THREADS: usize = 2;
  381. const DEFAULT_TEST_DIFFICULTY_TARGET: u32 = 120;
  382. #[test]
  383. fn test_wide_difficulty() -> Result<()> {
  384. let sled_db = sled::Config::new().temporary(true).open()?;
  385. let blockchain = Blockchain::new(&sled_db)?;
  386. let genesis_block = BlockInfo::default();
  387. blockchain.add_block(&genesis_block)?;
  388. let mut module = PoWModule::new(blockchain, DEFAULT_TEST_DIFFICULTY_TARGET, None, None)?;
  389. let output = Command::new("./script/research/pow/gen_wide_data.py").output().unwrap();
  390. let reader = Cursor::new(output.stdout);
  391. for (n, line) in reader.lines().enumerate() {
  392. let line = line.unwrap();
  393. let parts: Vec<String> = line.split(' ').map(|x| x.to_string()).collect();
  394. assert!(parts.len() == 2);
  395. let timestamp = parts[0].parse::<u64>().unwrap().into();
  396. let difficulty = BigUint::from_str_radix(&parts[1], 10).unwrap();
  397. let res = module.next_difficulty()?;
  398. if res != difficulty {
  399. eprintln!("Wrong wide difficulty for block {}", n);
  400. eprintln!("Expected: {}", difficulty);
  401. eprintln!("Found: {}", res);
  402. assert!(res == difficulty);
  403. }
  404. module.append(timestamp, &difficulty);
  405. }
  406. Ok(())
  407. }
  408. #[test]
  409. fn test_miner_correctness() -> Result<()> {
  410. // Default setup
  411. let sled_db = sled::Config::new().temporary(true).open()?;
  412. let blockchain = Blockchain::new(&sled_db)?;
  413. let mut genesis_block = BlockInfo::default();
  414. genesis_block.header.timestamp = 0.into();
  415. blockchain.add_block(&genesis_block)?;
  416. let module = PoWModule::new(blockchain, DEFAULT_TEST_DIFFICULTY_TARGET, None, None)?;
  417. let (_, recvr) = smol::channel::bounded(1);
  418. // Mine next block
  419. let mut next_block = BlockInfo::default();
  420. next_block.header.previous = genesis_block.hash();
  421. module.mine_block(&mut next_block, DEFAULT_TEST_THREADS, &recvr)?;
  422. // Verify it
  423. module.verify_current_block(&next_block)?;
  424. Ok(())
  425. }
  426. }