pow.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. /// Target block time, in seconds
  73. pub target: usize,
  74. /// Optional fixed difficulty
  75. pub fixed_difficulty: Option<BigUint>,
  76. /// Latest block timestamps ringbuffer
  77. pub timestamps: RingBuffer<Timestamp, BUF_SIZE>,
  78. /// Latest block cummulative difficulties ringbuffer
  79. pub difficulties: RingBuffer<BigUint, BUF_SIZE>,
  80. /// Total blocks cummulative difficulty
  81. /// Note: we keep this as a struct field for faster
  82. /// access(optimization), since its always same as
  83. /// difficulties buffer last.
  84. pub cummulative_difficulty: BigUint,
  85. }
  86. impl PoWModule {
  87. pub fn new(
  88. blockchain: Blockchain,
  89. target: usize,
  90. fixed_difficulty: Option<BigUint>,
  91. ) -> Result<Self> {
  92. // Retrieving last BUF_SIZE difficulties from blockchain to build the buffers
  93. let mut timestamps = RingBuffer::<Timestamp, BUF_SIZE>::new();
  94. let mut difficulties = RingBuffer::<BigUint, BUF_SIZE>::new();
  95. let mut cummulative_difficulty = BigUint::zero();
  96. let last_n = blockchain.blocks.get_last_n_difficulties(BUF_SIZE)?;
  97. for difficulty in last_n {
  98. timestamps.push(difficulty.timestamp);
  99. difficulties.push(difficulty.cummulative_difficulty.clone());
  100. cummulative_difficulty = difficulty.cummulative_difficulty;
  101. }
  102. // If a fixed difficulty has been set, assert its greater than zero
  103. if let Some(diff) = &fixed_difficulty {
  104. assert!(diff > &BigUint::zero());
  105. }
  106. Ok(Self { target, fixed_difficulty, timestamps, difficulties, cummulative_difficulty })
  107. }
  108. /// Compute the next mining difficulty, based on current ring buffers.
  109. /// If ring buffers contain 2 or less items, difficulty 1 is returned.
  110. /// If a fixed difficulty has been set, this function will always
  111. /// return that after first 2 difficulties.
  112. pub fn next_difficulty(&self) -> Result<BigUint> {
  113. // Retrieve first DIFFICULTY_WINDOW timestamps from the ring buffer
  114. let mut timestamps: Vec<Timestamp> =
  115. self.timestamps.iter().take(DIFFICULTY_WINDOW).cloned().collect();
  116. // Check we have enough timestamps
  117. let length = timestamps.len();
  118. if length < 2 {
  119. return Ok(BigUint::one())
  120. }
  121. // If a fixed difficulty has been set, return that
  122. if let Some(diff) = &self.fixed_difficulty {
  123. return Ok(diff.clone())
  124. }
  125. // Sort the timestamps vector
  126. timestamps.sort_unstable();
  127. // Grab cutoff indexes
  128. let (cut_begin, cut_end) = self.cutoff(length)?;
  129. // Calculate total time span
  130. let cut_end = cut_end - 1;
  131. let mut time_span = timestamps[cut_end].checked_sub(timestamps[cut_begin])?;
  132. if time_span.inner() == 0 {
  133. time_span = 1.into();
  134. }
  135. // Calculate total work done during this time span
  136. let total_work = &self.difficulties[cut_end] - &self.difficulties[cut_begin];
  137. if total_work <= BigUint::zero() {
  138. return Err(Error::PoWTotalWorkIsZero)
  139. }
  140. // Compute next difficulty
  141. let next_difficulty =
  142. (total_work * self.target + time_span.inner() - BigUint::one()) / time_span.inner();
  143. Ok(next_difficulty)
  144. }
  145. /// Calculate cutoff indexes.
  146. /// If buffers have been filled, we return the
  147. /// already known indexes, for performance.
  148. fn cutoff(&self, length: usize) -> Result<(usize, usize)> {
  149. if length >= DIFFICULTY_WINDOW {
  150. return Ok((CUT_BEGIN, CUT_END))
  151. }
  152. let (cut_begin, cut_end) = if length <= RETAINED {
  153. (0, length)
  154. } else {
  155. let cut_begin = (length - RETAINED + 1) / 2;
  156. (cut_begin, cut_begin + RETAINED)
  157. };
  158. // Sanity check
  159. if
  160. /* cut_begin < 0 || */
  161. cut_begin + 2 > cut_end || cut_end > length {
  162. return Err(Error::PoWCuttofCalculationError)
  163. }
  164. Ok((cut_begin, cut_end))
  165. }
  166. /// Compute the next mine target
  167. pub fn next_mine_target(&self) -> Result<BigUint> {
  168. Ok(BigUint::from_bytes_be(&[0xFF; 32]) / &self.next_difficulty()?)
  169. }
  170. /// Compute the next mine target and difficulty
  171. pub fn next_mine_target_and_difficulty(&self) -> Result<(BigUint, BigUint)> {
  172. let difficulty = self.next_difficulty()?;
  173. let mine_target = BigUint::from_bytes_be(&[0xFF; 32]) / &difficulty;
  174. Ok((mine_target, difficulty))
  175. }
  176. /// Verify provided difficulty corresponds to the next one
  177. pub fn verify_difficulty(&self, difficulty: &BigUint) -> Result<bool> {
  178. Ok(difficulty == &self.next_difficulty()?)
  179. }
  180. /// Verify provided block timestamp is not far in the future and
  181. /// check its valid acorrding to current timestamps median
  182. pub fn verify_current_timestamp(&self, timestamp: Timestamp) -> Result<bool> {
  183. if timestamp > Timestamp::current_time().checked_add(BLOCK_FUTURE_TIME_LIMIT)? {
  184. return Ok(false)
  185. }
  186. Ok(self.verify_timestamp_by_median(timestamp))
  187. }
  188. /// Verify provided block timestamp is valid and matches certain criteria
  189. pub fn verify_timestamp_by_median(&self, timestamp: Timestamp) -> bool {
  190. // If not enough blocks, no proper median yet, return true
  191. if self.timestamps.len() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW {
  192. return true
  193. }
  194. // Make sure the timestamp is higher or equal to the median
  195. let timestamps = self
  196. .timestamps
  197. .iter()
  198. .rev()
  199. .take(BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
  200. .map(|x| x.inner())
  201. .collect();
  202. timestamp >= median(timestamps).into()
  203. }
  204. /// Verify provided block timestamp and hash
  205. pub fn verify_current_block(&self, block: &BlockInfo) -> Result<()> {
  206. // First we verify the block's timestamp
  207. if !self.verify_current_timestamp(block.header.timestamp)? {
  208. return Err(Error::PoWInvalidTimestamp)
  209. }
  210. // Then we verify the block's hash
  211. self.verify_block_hash(block)
  212. }
  213. /// Verify provided block corresponds to next mine target
  214. pub fn verify_block_hash(&self, block: &BlockInfo) -> Result<()> {
  215. // Then we verify the proof of work:
  216. let verifier_setup = Instant::now();
  217. // Grab the next mine target
  218. let target = self.next_mine_target()?;
  219. // Setup verifier
  220. let flags = RandomXFlags::default();
  221. let cache = RandomXCache::new(flags, block.header.previous.inner()).unwrap();
  222. let vm = RandomXVM::new(flags, &cache).unwrap();
  223. debug!(target: "validator::pow::verify_block", "[VERIFIER] Setup time: {:?}", verifier_setup.elapsed());
  224. // Compute the output hash
  225. let verification_time = Instant::now();
  226. let out_hash = vm.hash(block.hash().inner());
  227. let out_hash = BigUint::from_bytes_be(&out_hash);
  228. // Verify hash is less than the expected mine target
  229. if out_hash > target {
  230. return Err(Error::PoWInvalidOutHash)
  231. }
  232. debug!(target: "validator::pow::verify_block", "[VERIFIER] Verification time: {:?}", verification_time.elapsed());
  233. Ok(())
  234. }
  235. /// Append provided timestamp and difficulty to the ring buffers
  236. pub fn append(&mut self, timestamp: Timestamp, difficulty: &BigUint) {
  237. self.timestamps.push(timestamp);
  238. self.cummulative_difficulty += difficulty;
  239. self.difficulties.push(self.cummulative_difficulty.clone());
  240. }
  241. /// Append provided block difficulty to the ring buffers and insert
  242. /// it to provided overlay
  243. pub fn append_difficulty(
  244. &mut self,
  245. overlay: &BlockchainOverlayPtr,
  246. difficulty: BlockDifficulty,
  247. ) -> Result<()> {
  248. self.append(difficulty.timestamp, &difficulty.difficulty);
  249. overlay.lock().unwrap().blocks.insert_difficulty(&[difficulty])
  250. }
  251. /// Mine provided block, based on next mine target
  252. pub fn mine_block(
  253. &self,
  254. miner_block: &mut BlockInfo,
  255. threads: usize,
  256. stop_signal: &Receiver<()>,
  257. ) -> Result<()> {
  258. // Grab the next mine target
  259. let target = self.next_mine_target()?;
  260. mine_block(&target, miner_block, threads, stop_signal)
  261. }
  262. }
  263. impl std::fmt::Display for PoWModule {
  264. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  265. write!(f, "PoWModule:")?;
  266. write!(f, "\ttarget: {}", self.target)?;
  267. write!(f, "\ttimestamps: {:?}", self.timestamps)?;
  268. write!(f, "\tdifficulties: {:?}", self.difficulties)?;
  269. write!(f, "\tcummulative_difficulty: {}", self.cummulative_difficulty)
  270. }
  271. }
  272. /// Mine provided block, based on provided PoW module next mine target
  273. pub fn mine_block(
  274. target: &BigUint,
  275. miner_block: &mut BlockInfo,
  276. threads: usize,
  277. stop_signal: &Receiver<()>,
  278. ) -> Result<()> {
  279. let miner_setup = Instant::now();
  280. debug!(target: "validator::pow::mine_block", "[MINER] Mine target: 0x{:064x}", target);
  281. // Get the PoW input. The key changes with every mined block.
  282. let input = miner_block.header.previous;
  283. debug!(target: "validator::pow::mine_block", "[MINER] PoW input: {}", input);
  284. let flags = RandomXFlags::default() | RandomXFlags::FULLMEM;
  285. debug!(target: "validator::pow::mine_block", "[MINER] Initializing RandomX dataset...");
  286. let dataset = Arc::new(RandomXDataset::new(flags, input.inner(), threads).unwrap());
  287. debug!(target: "validator::pow::mine_block", "[MINER] Setup time: {:?}", miner_setup.elapsed());
  288. // Multithreaded mining setup
  289. let mining_time = Instant::now();
  290. let mut handles = vec![];
  291. let found_block = Arc::new(AtomicBool::new(false));
  292. let found_nonce = Arc::new(AtomicU64::new(0));
  293. let threads = threads as u64;
  294. for t in 0..threads {
  295. let target = target.clone();
  296. let mut block = miner_block.clone();
  297. let found_block = Arc::clone(&found_block);
  298. let found_nonce = Arc::clone(&found_nonce);
  299. let dataset = Arc::clone(&dataset);
  300. let stop_signal = stop_signal.clone();
  301. handles.push(thread::spawn(move || {
  302. debug!(target: "validator::pow::mine_block", "[MINER] Initializing RandomX VM #{}...", t);
  303. let mut miner_nonce = t;
  304. let vm = RandomXVM::new_fast(flags, &dataset).unwrap();
  305. loop {
  306. // Check if stop signal was received
  307. if stop_signal.is_full() {
  308. debug!(target: "validator::pow::mine_block", "[MINER] Stop signal received, thread #{} exiting", t);
  309. break
  310. }
  311. block.header.nonce = miner_nonce;
  312. if found_block.load(Ordering::SeqCst) {
  313. debug!(target: "validator::pow::mine_block", "[MINER] Block found, thread #{} exiting", t);
  314. break
  315. }
  316. let out_hash = vm.hash(block.hash().inner());
  317. let out_hash = BigUint::from_bytes_be(&out_hash);
  318. if out_hash <= target {
  319. found_block.store(true, Ordering::SeqCst);
  320. found_nonce.store(miner_nonce, Ordering::SeqCst);
  321. debug!(target: "validator::pow::mine_block", "[MINER] Thread #{} found block using nonce {}",
  322. t, miner_nonce
  323. );
  324. debug!(target: "validator::pow::mine_block", "[MINER] Block hash {}", block.hash());
  325. debug!(target: "validator::pow::mine_block", "[MINER] RandomX output: 0x{:064x}", out_hash);
  326. break
  327. }
  328. // This means thread 0 will use nonces, 0, 4, 8, ...
  329. // and thread 1 will use nonces, 1, 5, 9, ...
  330. miner_nonce += threads;
  331. }
  332. }));
  333. }
  334. for handle in handles {
  335. let _ = handle.join();
  336. }
  337. // Check if stop signal was received
  338. if stop_signal.is_full() {
  339. return Err(Error::MinerTaskStopped)
  340. }
  341. debug!(target: "validator::pow::mine_block", "[MINER] Mining time: {:?}", mining_time.elapsed());
  342. // Set the valid mined nonce in the block
  343. miner_block.header.nonce = found_nonce.load(Ordering::SeqCst);
  344. Ok(())
  345. }
  346. #[cfg(test)]
  347. mod tests {
  348. use std::{
  349. io::{BufRead, Cursor},
  350. process::Command,
  351. };
  352. use darkfi_sdk::num_traits::Num;
  353. use num_bigint::BigUint;
  354. use crate::{
  355. blockchain::{BlockInfo, Blockchain},
  356. Result,
  357. };
  358. use super::PoWModule;
  359. const DEFAULT_TEST_THREADS: usize = 2;
  360. const DEFAULT_TEST_DIFFICULTY_TARGET: usize = 120;
  361. #[test]
  362. fn test_wide_difficulty() -> Result<()> {
  363. let sled_db = sled::Config::new().temporary(true).open()?;
  364. let blockchain = Blockchain::new(&sled_db)?;
  365. let mut module = PoWModule::new(blockchain, DEFAULT_TEST_DIFFICULTY_TARGET, None)?;
  366. let output = Command::new("./script/research/pow/gen_wide_data.py").output().unwrap();
  367. let reader = Cursor::new(output.stdout);
  368. for (n, line) in reader.lines().enumerate() {
  369. let line = line.unwrap();
  370. let parts: Vec<String> = line.split(' ').map(|x| x.to_string()).collect();
  371. assert!(parts.len() == 2);
  372. let timestamp = parts[0].parse::<u64>().unwrap().into();
  373. let difficulty = BigUint::from_str_radix(&parts[1], 10).unwrap();
  374. let res = module.next_difficulty()?;
  375. if res != difficulty {
  376. eprintln!("Wrong wide difficulty for block {}", n);
  377. eprintln!("Expected: {}", difficulty);
  378. eprintln!("Found: {}", res);
  379. assert!(res == difficulty);
  380. }
  381. module.append(timestamp, &difficulty);
  382. }
  383. Ok(())
  384. }
  385. #[test]
  386. fn test_miner_correctness() -> Result<()> {
  387. // Default setup
  388. let sled_db = sled::Config::new().temporary(true).open()?;
  389. let blockchain = Blockchain::new(&sled_db)?;
  390. let module = PoWModule::new(blockchain, DEFAULT_TEST_DIFFICULTY_TARGET, None)?;
  391. let (_, recvr) = smol::channel::bounded(1);
  392. let genesis_block = BlockInfo::default();
  393. // Mine next block
  394. let mut next_block = BlockInfo::default();
  395. next_block.header.previous = genesis_block.hash();
  396. module.mine_block(&mut next_block, DEFAULT_TEST_THREADS, &recvr)?;
  397. // Verify it
  398. module.verify_current_block(&next_block)?;
  399. Ok(())
  400. }
  401. }