main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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: [u8; HASH_LEN],
  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().inner() + 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 cumulative
  152. /// difficulties, and a target block time in seconds.
  153. /// **NOTE**: `timestamps` get sorted in this function.
  154. ///
  155. /// Panics if:
  156. /// * `timestamps.len() != cumulative_difficulties.len()`
  157. /// * `timestamps.len() > DIFFICULTY_WINDOW`
  158. fn next_difficulty(
  159. timestamps: &mut Vec<u64>,
  160. cumulative_difficulties: &[BigUint],
  161. target_seconds: usize,
  162. ) -> BigUint {
  163. let length = timestamps.len();
  164. assert!(length == cumulative_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 = &cumulative_difficulties[cut_end - 1] - &cumulative_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 previous_hash = [0u8; HASH_LEN];
  191. previous_hash.copy_from_slice(GENESIS_HASH.as_bytes());
  192. let mut genesis_block = Block {
  193. header: BlockHeader {
  194. nonce: pallas::Base::ZERO,
  195. previous_hash,
  196. timestamp: Timestamp::current_time().inner(),
  197. txtree: MerkleTree::new(1),
  198. },
  199. txs: vec![],
  200. };
  201. let genesis_tx = Transaction(vec![1, 3, 3, 7]);
  202. genesis_block.append_tx(genesis_tx)?;
  203. // This represents the blocks in our blockchain
  204. let mut blockchain: Vec<Block> = vec![genesis_block.clone()];
  205. // The cumulative difficulties track difficulty through time.
  206. // The genesis block (block 0) is ignored. Blocks 1 and 2 must have difficulty 1.
  207. let mut difficulties = vec![];
  208. let mut cumulative_difficulty = BigUint::zero();
  209. // We also track block timestamps this way.
  210. let mut timestamps = vec![];
  211. // Melt the CPU
  212. loop {
  213. // Reference to our chain tip
  214. let n = blockchain.len(); // Block height
  215. let cur_block = &blockchain.last().unwrap();
  216. assert!(difficulties.len() == timestamps.len() && timestamps.len() == n - 1);
  217. // Calculate the next difficulty target: T = 2^256 / difficulty
  218. let begin: usize;
  219. let end: usize;
  220. if n - 1 < DIFFICULTY_WINDOW + DIFFICULTY_LAG {
  221. begin = 0;
  222. end = min(n - 1, DIFFICULTY_WINDOW);
  223. } else {
  224. end = n - 1 - DIFFICULTY_LAG;
  225. begin = end - DIFFICULTY_WINDOW;
  226. }
  227. let mut ts: Vec<u64> = timestamps[begin..end].to_vec();
  228. let difficulty = next_difficulty(&mut ts, &difficulties[begin..end], DIFFICULTY_TARGET);
  229. let target = BigUint::from_bytes_be(&[0xFF; 32]) / &difficulty;
  230. println!("[#{}] [MINER] Difficulty: 0x{:064x}", n, difficulty);
  231. println!("[#{}] [MINER] Mine target: 0x{:064x}", n, target);
  232. // Get the PoW input. The key changes with every mined block.
  233. let powinput = cur_block.hash()?;
  234. println!("[#{}] [MINER] PoW input: {}", n, powinput.to_hex());
  235. let miner_setup = Instant::now();
  236. let flags = RandomXFlags::default() | RandomXFlags::FULLMEM;
  237. println!("[#{}] [MINER] Initializing RandomX dataset...", n);
  238. let dataset = Arc::new(RandomXDataset::new(flags, powinput.as_bytes(), N_THREADS).unwrap());
  239. // The miner creates a block
  240. let mut previous_hash = [0u8; HASH_LEN];
  241. previous_hash.copy_from_slice(cur_block.hash()?.as_bytes());
  242. let mut miner_block = Block {
  243. header: BlockHeader {
  244. nonce: pallas::Base::ZERO,
  245. previous_hash,
  246. timestamp: Timestamp::current_time().inner(),
  247. txtree: MerkleTree::new(1),
  248. },
  249. txs: vec![],
  250. };
  251. // Insert some transactions from the mempool
  252. let tx0 = Transaction(OsRng.gen::<[u8; 32]>().to_vec());
  253. let tx1 = Transaction(OsRng.gen::<[u8; 32]>().to_vec());
  254. miner_block.append_tx(tx0)?;
  255. miner_block.append_tx(tx1)?;
  256. println!("[#{}] [MINER] Setup time: {:?}", n, miner_setup.elapsed());
  257. // Multithreaded mining setup
  258. let mining_time = Instant::now();
  259. let mut handles = vec![];
  260. let found_block = Arc::new(AtomicBool::new(false));
  261. let found_nonce = Arc::new(AtomicU32::new(0));
  262. for t in 0..N_THREADS {
  263. let target = target.clone();
  264. let mut block = miner_block.clone();
  265. let found_block = Arc::clone(&found_block);
  266. let found_nonce = Arc::clone(&found_nonce);
  267. let dataset = Arc::clone(&dataset);
  268. handles.push(thread::spawn(move || {
  269. println!("[#{}] [MINER] Initializing RandomX VM #{}...", n, t);
  270. let mut miner_nonce = t as u32;
  271. let vm = RandomXVM::new_fast(flags, &dataset).unwrap();
  272. loop {
  273. block.header.nonce = pallas::Base::from(miner_nonce as u64);
  274. if found_block.load(Ordering::SeqCst) {
  275. println!("[#{}] [MINER] Block found, thread #{} exiting", n, t);
  276. break;
  277. }
  278. let out_hash = vm.hash(block.hash().unwrap().as_bytes());
  279. let out_hash = BigUint::from_bytes_be(&out_hash);
  280. if out_hash <= target {
  281. found_block.store(true, Ordering::SeqCst);
  282. found_nonce.store(miner_nonce, Ordering::SeqCst);
  283. println!(
  284. "[#{}] [MINER] Thread #{} found block using nonce {}",
  285. n, t, miner_nonce
  286. );
  287. println!("[#{}] [MINER] Block hash {}", n, block.hash().unwrap().to_hex());
  288. println!("[#{}] [MINER] RandomX output: 0x{:064x}", n, out_hash);
  289. break;
  290. }
  291. // This means thread 0 will use nonces, 0, 4, 8, ...
  292. // and thread 1 will use nonces, 1, 5, 9, ...
  293. miner_nonce += N_THREADS as u32;
  294. }
  295. }));
  296. }
  297. for handle in handles {
  298. let _ = handle.join();
  299. }
  300. println!("[#{}] [MINER] Mining time: {:?}", n, mining_time.elapsed());
  301. // Set the valid mined nonce in the block that's being broadcasted
  302. miner_block.header.nonce = pallas::Base::from(found_nonce.load(Ordering::SeqCst) as u64);
  303. // Now the block is broadcasted to the network, and a node can verify it.
  304. // First we verify the block's timestamp. We take the last
  305. // `BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW` timestamps and perform the check:
  306. let mut v_ts =
  307. timestamps.iter().rev().take(BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW).copied().collect();
  308. assert!(check_block_timestamp(&miner_block, &mut v_ts));
  309. // Then we verify the proof of work:
  310. let verifier_setup = Instant::now();
  311. let flags = RandomXFlags::default();
  312. let cache = RandomXCache::new(flags, powinput.as_bytes()).unwrap();
  313. let vm = RandomXVM::new(flags, &cache).unwrap();
  314. println!("[#{}] [VERIFIER] Setup time: {:?}", n, verifier_setup.elapsed());
  315. let verification_time = Instant::now();
  316. let out_hash = vm.hash(miner_block.hash()?.as_bytes());
  317. let out_hash = BigUint::from_bytes_be(&out_hash);
  318. assert!(out_hash <= target);
  319. println!("[#{}] [VERIFIER] Verification time: {:?}", n, verification_time.elapsed());
  320. // The new block appends to the blockchain
  321. timestamps.push(miner_block.header.timestamp);
  322. blockchain.push(miner_block);
  323. cumulative_difficulty += difficulty;
  324. difficulties.push(cumulative_difficulty.clone());
  325. }
  326. }