pow.rs 17 KB

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