pow.rs 17 KB

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