pow.rs 16 KB

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