main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. * Copyright (C) 2014-2023 The Monero Project (Under MIT license)
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as
  8. * published by the Free Software Foundation, either version 3 of the
  9. * License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. use std::{
  20. cmp::min,
  21. sync::{
  22. atomic::{AtomicBool, AtomicU32, Ordering},
  23. Arc,
  24. },
  25. thread,
  26. time::Instant,
  27. };
  28. use darkfi::{util::time::Timestamp, Result};
  29. use darkfi_sdk::{
  30. crypto::{pasta_prelude::Field, MerkleTree},
  31. num_traits::{One, Zero},
  32. pasta::{group::ff::FromUniformBytes, pallas},
  33. };
  34. use darkfi_serial::{async_trait, Encodable, SerialEncodable};
  35. use lazy_static::lazy_static;
  36. use num_bigint::BigUint;
  37. use rand::{rngs::OsRng, Rng};
  38. use randomx::{RandomXCache, RandomXDataset, RandomXFlags, RandomXVM};
  39. #[cfg(test)]
  40. mod tests;
  41. /// Number of threads to use for hashing
  42. const N_THREADS: usize = 4;
  43. /// The output length of the BLAKE2b hash in bytes
  44. const HASH_LEN: usize = 32;
  45. /// Amount of blocks to take for next difficulty calculation.
  46. /// Must be >= 2
  47. const DIFFICULTY_WINDOW: usize = 720;
  48. /// Timestamps to cut after sorting for next difficulty calculation.
  49. /// (2*DIFFICULTY_CUT <= DIFFICULTY_WINDOW-2) must be true.
  50. const DIFFICULTY_CUT: usize = 60;
  51. /// !!!
  52. const DIFFICULTY_LAG: usize = 15;
  53. /// Target block time in seconds
  54. const DIFFICULTY_TARGET: usize = 20;
  55. /// How many most recent blocks to use to verify new blocks' timestamp
  56. const BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW: usize = 60;
  57. /// Time limit in the future of what blocks can be
  58. const BLOCK_FUTURE_TIME_LIMIT: u64 = 60 * 60 * 2;
  59. lazy_static! {
  60. /// The genesis block hash
  61. static ref GENESIS_HASH: blake2b_simd::Hash =
  62. blake2b_simd::Params::new().hash_length(HASH_LEN).to_state().update(b"genesis").finalize();
  63. }
  64. #[derive(Clone, SerialEncodable)]
  65. /// Dummy transaction definition
  66. struct Transaction(Vec<u8>);
  67. impl Transaction {
  68. /// Hash the transaction
  69. fn hash(&self) -> Result<blake2b_simd::Hash> {
  70. let mut hasher = blake2b_simd::Params::new().hash_length(HASH_LEN).to_state();
  71. self.encode(&mut hasher)?;
  72. Ok(hasher.finalize())
  73. }
  74. }
  75. #[derive(Clone, SerialEncodable)]
  76. /// A block's header
  77. struct BlockHeader {
  78. /// The block's nonce, represented as a pallas::Base.
  79. /// This value changes arbitrarily with mining.
  80. nonce: pallas::Base,
  81. /// The hash of the previous block in the blockchain
  82. previous_hash: blake2b_simd::Hash,
  83. /// The block timestamp
  84. timestamp: u64,
  85. /// Merkle tree of the transactions contained in this block
  86. txtree: MerkleTree,
  87. }
  88. #[derive(Clone, SerialEncodable)]
  89. /// Block definition
  90. struct Block {
  91. /// The block header
  92. header: BlockHeader,
  93. /// Transactions contained in the block
  94. txs: Vec<Transaction>,
  95. }
  96. impl Block {
  97. /// Compute the block's hash
  98. fn hash(&self) -> Result<blake2b_simd::Hash> {
  99. let mut hasher = blake2b_simd::Params::new().hash_length(HASH_LEN).to_state();
  100. self.header.nonce.encode(&mut hasher)?;
  101. self.header.previous_hash.encode(&mut hasher)?;
  102. self.header.timestamp.encode(&mut hasher)?;
  103. self.header.txtree.root(0).unwrap().encode(&mut hasher)?;
  104. Ok(hasher.finalize())
  105. }
  106. /// Append a transaction to the block. Also adds it to the Merkle tree.
  107. fn append_tx(&mut self, tx: Transaction) -> Result<()> {
  108. let mut buf = [0u8; 64];
  109. buf[..HASH_LEN].copy_from_slice(tx.hash()?.as_bytes());
  110. let leaf = pallas::Base::from_uniform_bytes(&buf);
  111. self.header.txtree.append(leaf.into());
  112. self.txs.push(tx);
  113. Ok(())
  114. }
  115. }
  116. fn get_mid(a: u64, b: u64) -> u64 {
  117. (a / 2) + (b / 2) + ((a - 2 * (a / 2)) + (b - 2 * (b / 2))) / 2
  118. }
  119. /// Aux function to calculate the median of a given `Vec<u64>`.
  120. /// The function sorts the vector internally.
  121. fn median(v: &mut Vec<u64>) -> u64 {
  122. assert!(v.is_empty());
  123. if v.len() == 1 {
  124. return v[0]
  125. }
  126. let n = v.len() / 2;
  127. v.sort_unstable();
  128. if v.len() % 2 == 0 {
  129. v[n]
  130. } else {
  131. get_mid(v[n - 1], v[n])
  132. }
  133. }
  134. /// Verify a block's timestamp is valid and matches certain criteria.
  135. fn check_block_timestamp(block: &Block, timestamps: &mut Vec<u64>) -> bool {
  136. if block.header.timestamp > Timestamp::current_time().0 + BLOCK_FUTURE_TIME_LIMIT {
  137. return false
  138. }
  139. // If not enough blocks, no proper median yet, return true
  140. if timestamps.len() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW {
  141. return true
  142. }
  143. // Make sure the timestamp is higher than the median
  144. if block.header.timestamp < median(timestamps) {
  145. return false
  146. }
  147. true
  148. }
  149. /// Calculate the next mining difficulty.
  150. ///
  151. /// Takes a `RingBuffer` of timestamps, a `RingBuffer` of cummulative
  152. /// difficulties, and a target block time in seconds.
  153. /// **NOTE**: `timestamps` get sorted in this function.
  154. ///
  155. /// Panics if:
  156. /// * `timestamps.len() != cummulative_difficulties.len()`
  157. /// * `timestamps.len() > DIFFICULTY_WINDOW`
  158. fn next_difficulty(
  159. timestamps: &mut Vec<u64>,
  160. cummulative_difficulties: &[BigUint],
  161. target_seconds: usize,
  162. ) -> BigUint {
  163. let length = timestamps.len();
  164. assert!(length == cummulative_difficulties.len() && length <= DIFFICULTY_WINDOW);
  165. if length <= 1 {
  166. return BigUint::one()
  167. }
  168. // Sort the timestamps vector
  169. timestamps.sort_unstable();
  170. let cut_begin: usize;
  171. let cut_end: usize;
  172. if length <= DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT {
  173. cut_begin = 0;
  174. cut_end = length;
  175. } else {
  176. cut_begin = (length - (DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT) + 1) / 2;
  177. cut_end = cut_begin + (DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT);
  178. }
  179. assert!(/* cut_begin >= 0 && */ cut_begin + 2 <= cut_end && cut_end <= length);
  180. let mut time_span = timestamps[cut_end - 1] - timestamps[cut_begin];
  181. if time_span == 0 {
  182. time_span = 1;
  183. }
  184. let total_work = &cummulative_difficulties[cut_end - 1] - &cummulative_difficulties[cut_begin];
  185. assert!(total_work > BigUint::zero());
  186. (total_work * target_seconds + time_span - BigUint::one()) / time_span
  187. }
  188. fn main() -> Result<()> {
  189. // Construct the genesis block
  190. let mut genesis_block = Block {
  191. header: BlockHeader {
  192. nonce: pallas::Base::ZERO,
  193. previous_hash: *GENESIS_HASH,
  194. timestamp: Timestamp::current_time().0,
  195. txtree: MerkleTree::new(1),
  196. },
  197. txs: vec![],
  198. };
  199. let genesis_tx = Transaction(vec![1, 3, 3, 7]);
  200. genesis_block.append_tx(genesis_tx)?;
  201. // This represents the blocks in our blockchain
  202. let mut blockchain: Vec<Block> = vec![genesis_block.clone()];
  203. // The cummulative difficulties track difficulty through time.
  204. // The genesis block (block 0) is ignored. Blocks 1 and 2 must have difficulty 1.
  205. let mut difficulties = vec![];
  206. let mut cummulative_difficulty = BigUint::zero();
  207. // We also track block timestamps this way.
  208. let mut timestamps = vec![];
  209. // Melt the CPU
  210. loop {
  211. // Reference to our chain tip
  212. let n = blockchain.len(); // Block height
  213. let cur_block = &blockchain.last().unwrap();
  214. assert!(difficulties.len() == timestamps.len() && timestamps.len() == n - 1);
  215. // Calculate the next difficulty target: T = 2^256 / difficulty
  216. let begin: usize;
  217. let end: usize;
  218. if n - 1 < DIFFICULTY_WINDOW + DIFFICULTY_LAG {
  219. begin = 0;
  220. end = min(n - 1, DIFFICULTY_WINDOW);
  221. } else {
  222. end = n - 1 - DIFFICULTY_LAG;
  223. begin = end - DIFFICULTY_WINDOW;
  224. }
  225. let mut ts: Vec<u64> = timestamps[begin..end].to_vec();
  226. let difficulty = next_difficulty(&mut ts, &difficulties[begin..end], DIFFICULTY_TARGET);
  227. let target = BigUint::from_bytes_be(&[0xFF; 32]) / &difficulty;
  228. println!("[#{}] [MINER] Difficulty: 0x{:064x}", n, difficulty);
  229. println!("[#{}] [MINER] Mine target: 0x{:064x}", n, target);
  230. // Get the PoW input. The key changes with every mined block.
  231. let powinput = cur_block.hash()?;
  232. println!("[#{}] [MINER] PoW input: {}", n, powinput.to_hex());
  233. let miner_setup = Instant::now();
  234. let flags = RandomXFlags::default() | RandomXFlags::FULLMEM;
  235. println!("[#{}] [MINER] Initializing RandomX dataset...", n);
  236. let dataset = Arc::new(RandomXDataset::new(flags, powinput.as_bytes(), N_THREADS).unwrap());
  237. // The miner creates a block
  238. let mut miner_block = Block {
  239. header: BlockHeader {
  240. nonce: pallas::Base::ZERO,
  241. previous_hash: cur_block.hash()?,
  242. timestamp: Timestamp::current_time().0,
  243. txtree: MerkleTree::new(1),
  244. },
  245. txs: vec![],
  246. };
  247. // Insert some transactions from the mempool
  248. let tx0 = Transaction(OsRng.gen::<[u8; 32]>().to_vec());
  249. let tx1 = Transaction(OsRng.gen::<[u8; 32]>().to_vec());
  250. miner_block.append_tx(tx0)?;
  251. miner_block.append_tx(tx1)?;
  252. println!("[#{}] [MINER] Setup time: {:?}", n, miner_setup.elapsed());
  253. // Multithreaded mining setup
  254. let mining_time = Instant::now();
  255. let mut handles = vec![];
  256. let found_block = Arc::new(AtomicBool::new(false));
  257. let found_nonce = Arc::new(AtomicU32::new(0));
  258. for t in 0..N_THREADS {
  259. let target = target.clone();
  260. let mut block = miner_block.clone();
  261. let found_block = Arc::clone(&found_block);
  262. let found_nonce = Arc::clone(&found_nonce);
  263. let dataset = Arc::clone(&dataset);
  264. handles.push(thread::spawn(move || {
  265. println!("[#{}] [MINER] Initializing RandomX VM #{}...", n, t);
  266. let mut miner_nonce = t as u32;
  267. let vm = RandomXVM::new_fast(flags, &dataset).unwrap();
  268. loop {
  269. block.header.nonce = pallas::Base::from(miner_nonce as u64);
  270. if found_block.load(Ordering::SeqCst) {
  271. println!("[#{}] [MINER] Block found, thread #{} exiting", n, t);
  272. break
  273. }
  274. let out_hash = vm.hash(block.hash().unwrap().as_bytes());
  275. let out_hash = BigUint::from_bytes_be(&out_hash);
  276. if out_hash <= target {
  277. found_block.store(true, Ordering::SeqCst);
  278. found_nonce.store(miner_nonce, Ordering::SeqCst);
  279. println!(
  280. "[#{}] [MINER] Thread #{} found block using nonce {}",
  281. n, t, miner_nonce
  282. );
  283. println!("[#{}] [MINER] Block hash {}", n, block.hash().unwrap().to_hex());
  284. println!("[#{}] [MINER] RandomX output: 0x{:064x}", n, out_hash);
  285. break
  286. }
  287. // This means thread 0 will use nonces, 0, 4, 8, ...
  288. // and thread 1 will use nonces, 1, 5, 9, ...
  289. miner_nonce += N_THREADS as u32;
  290. }
  291. }));
  292. }
  293. for handle in handles {
  294. let _ = handle.join();
  295. }
  296. println!("[#{}] [MINER] Mining time: {:?}", n, mining_time.elapsed());
  297. // Set the valid mined nonce in the block that's being broadcasted
  298. miner_block.header.nonce = pallas::Base::from(found_nonce.load(Ordering::SeqCst) as u64);
  299. // Now the block is broadcasted to the network, and a node can verify it.
  300. // First we verify the block's timestamp. We take the last
  301. // `BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW` timestamps and perform the check:
  302. let mut v_ts =
  303. timestamps.iter().rev().take(BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW).copied().collect();
  304. assert!(check_block_timestamp(&miner_block, &mut v_ts));
  305. // Then we verify the proof of work:
  306. let verifier_setup = Instant::now();
  307. let flags = RandomXFlags::default();
  308. let cache = RandomXCache::new(flags, powinput.as_bytes()).unwrap();
  309. let vm = RandomXVM::new(flags, &cache).unwrap();
  310. println!("[#{}] [VERIFIER] Setup time: {:?}", n, verifier_setup.elapsed());
  311. let verification_time = Instant::now();
  312. let out_hash = vm.hash(miner_block.hash()?.as_bytes());
  313. let out_hash = BigUint::from_bytes_be(&out_hash);
  314. assert!(out_hash <= target);
  315. println!("[#{}] [VERIFIER] Verification time: {:?}", n, verification_time.elapsed());
  316. // The new block appends to the blockchain
  317. timestamps.push(miner_block.header.timestamp);
  318. blockchain.push(miner_block);
  319. cummulative_difficulty += difficulty;
  320. difficulties.push(cummulative_difficulty.clone());
  321. }
  322. }