utils.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 darkfi_sdk::{
  19. crypto::{DAO_CONTRACT_ID, DEPLOYOOOR_CONTRACT_ID, MONEY_CONTRACT_ID},
  20. tx::TransactionHash,
  21. };
  22. use log::info;
  23. use num_bigint::BigUint;
  24. use randomx::{RandomXCache, RandomXFlags, RandomXVM};
  25. use crate::{
  26. blockchain::{BlockInfo, BlockchainOverlayPtr, Header},
  27. runtime::vm_runtime::Runtime,
  28. validator::consensus::{Fork, Proposal},
  29. Error, Result,
  30. };
  31. /// Deploy DarkFi native wasm contracts to provided blockchain overlay.
  32. ///
  33. /// If overlay already contains the contracts, it will just open the
  34. /// necessary db and trees, and give back what it has. This means that
  35. /// on subsequent runs, our native contracts will already be in a deployed
  36. /// state, so what we actually do here is a redeployment. This kind of
  37. /// operation should only modify the contract's state in case it wasn't
  38. /// deployed before (meaning the initial run). Otherwise, it shouldn't
  39. /// touch anything, or just potentially update the db schemas or whatever
  40. /// is necessary. This logic should be handled in the init function of
  41. /// the actual contract, so make sure the native contracts handle this well.
  42. pub async fn deploy_native_contracts(
  43. overlay: &BlockchainOverlayPtr,
  44. block_target: u32,
  45. ) -> Result<()> {
  46. info!(target: "validator::utils::deploy_native_contracts", "Deploying native WASM contracts");
  47. // The Money contract uses an empty payload to deploy itself.
  48. let money_contract_deploy_payload = vec![];
  49. // The DAO contract uses an empty payload to deploy itself.
  50. let dao_contract_deploy_payload = vec![];
  51. // The Deployooor contract uses an empty payload to deploy itself.
  52. let deployooor_contract_deploy_payload = vec![];
  53. let native_contracts = vec![
  54. (
  55. "Money Contract",
  56. *MONEY_CONTRACT_ID,
  57. include_bytes!("../contract/money/darkfi_money_contract.wasm").to_vec(),
  58. money_contract_deploy_payload,
  59. ),
  60. (
  61. "DAO Contract",
  62. *DAO_CONTRACT_ID,
  63. include_bytes!("../contract/dao/darkfi_dao_contract.wasm").to_vec(),
  64. dao_contract_deploy_payload,
  65. ),
  66. (
  67. "Deployooor Contract",
  68. *DEPLOYOOOR_CONTRACT_ID,
  69. include_bytes!("../contract/deployooor/darkfi_deployooor_contract.wasm").to_vec(),
  70. deployooor_contract_deploy_payload,
  71. ),
  72. ];
  73. // Grab last known block height to verify against next one.
  74. // If no blocks exist, we verify against genesis block height (0).
  75. let verifying_block_height = match overlay.lock().unwrap().last() {
  76. Ok((last_block_height, _)) => last_block_height + 1,
  77. Err(_) => 0,
  78. };
  79. for (call_idx, nc) in native_contracts.into_iter().enumerate() {
  80. info!(target: "validator::utils::deploy_native_contracts", "Deploying {} with ContractID {}", nc.0, nc.1);
  81. let mut runtime = Runtime::new(
  82. &nc.2[..],
  83. overlay.clone(),
  84. nc.1,
  85. verifying_block_height,
  86. block_target,
  87. TransactionHash::none(),
  88. call_idx as u8,
  89. )?;
  90. runtime.deploy(&nc.3)?;
  91. info!(target: "validator::utils::deploy_native_contracts", "Successfully deployed {}", nc.0);
  92. }
  93. info!(target: "validator::utils::deploy_native_contracts", "Finished deployment of native WASM contracts");
  94. Ok(())
  95. }
  96. /// Verify provided header is valid for provided mining target and compute its rank.
  97. ///
  98. /// Header's rank is the tuple of its squared mining target distance from max 32 bytes int,
  99. /// along with its squared RandomX hash number distance from max 32 bytes int.
  100. /// Genesis block has rank (0, 0).
  101. pub fn header_rank(header: &Header, target: &BigUint) -> Result<(BigUint, BigUint)> {
  102. // Genesis header has rank 0
  103. if header.height == 0 {
  104. return Ok((0u64.into(), 0u64.into()))
  105. }
  106. // Setup RandomX verifier
  107. let flags = RandomXFlags::default();
  108. let cache = RandomXCache::new(flags, header.previous.inner()).unwrap();
  109. let vm = RandomXVM::new(flags, &cache).unwrap();
  110. // Compute the output hash
  111. let out_hash = vm.hash(header.hash().inner());
  112. let out_hash = BigUint::from_bytes_be(&out_hash);
  113. // Verify hash is less than the expected mine target
  114. if out_hash > *target {
  115. return Err(Error::PoWInvalidOutHash)
  116. }
  117. // Grab the max 32 bytes int
  118. let max = BigUint::from_bytes_be(&[0xFF; 32]);
  119. // Compute the squared mining target distance
  120. let target_distance = &max - target;
  121. let target_distance_sq = &target_distance * &target_distance;
  122. // Compute the output hash distance
  123. let hash_distance = max - out_hash;
  124. let hash_distance_sq = &hash_distance * &hash_distance;
  125. Ok((target_distance_sq, hash_distance_sq))
  126. }
  127. /// Compute a block's rank, assuming that its valid, based on provided mining target.
  128. ///
  129. /// Block's rank is the tuple of its squared mining target distance from max 32 bytes int,
  130. /// along with its squared RandomX hash number distance from max 32 bytes int.
  131. /// Genesis block has rank (0, 0).
  132. pub fn block_rank(block: &BlockInfo, target: &BigUint) -> (BigUint, BigUint) {
  133. // Genesis block has rank 0
  134. if block.header.height == 0 {
  135. return (0u64.into(), 0u64.into())
  136. }
  137. // Grab the max 32 bytes int
  138. let max = BigUint::from_bytes_be(&[0xFF; 32]);
  139. // Compute the squared mining target distance
  140. let target_distance = &max - target;
  141. let target_distance_sq = &target_distance * &target_distance;
  142. // Setup RandomX verifier
  143. let flags = RandomXFlags::default();
  144. let cache = RandomXCache::new(flags, block.header.previous.inner()).unwrap();
  145. let vm = RandomXVM::new(flags, &cache).unwrap();
  146. // Compute the output hash distance
  147. let out_hash = vm.hash(block.hash().inner());
  148. let out_hash = BigUint::from_bytes_be(&out_hash);
  149. let hash_distance = max - out_hash;
  150. let hash_distance_sq = &hash_distance * &hash_distance;
  151. (target_distance_sq, hash_distance_sq)
  152. }
  153. /// Auxiliary function to calculate the middle value between provided u64 numbers
  154. pub fn get_mid(a: u64, b: u64) -> u64 {
  155. (a / 2) + (b / 2) + ((a - 2 * (a / 2)) + (b - 2 * (b / 2))) / 2
  156. }
  157. /// Auxiliary function to calculate the median of a given `Vec<u64>`.
  158. /// The function sorts the vector internally.
  159. pub fn median(mut v: Vec<u64>) -> u64 {
  160. if v.len() == 1 {
  161. return v[0]
  162. }
  163. let n = v.len() / 2;
  164. v.sort_unstable();
  165. if v.len() % 2 == 0 {
  166. v[n]
  167. } else {
  168. get_mid(v[n - 1], v[n])
  169. }
  170. }
  171. /// Given a proposal, find the index of a fork chain it extends, along with the specific
  172. /// extended proposal index. Additionally, check that proposal doesn't already exists in any
  173. /// fork chain.
  174. pub fn find_extended_fork_index(forks: &[Fork], proposal: &Proposal) -> Result<(usize, usize)> {
  175. // Grab provided proposal hash
  176. let proposal_hash = proposal.hash;
  177. // Keep track of fork and proposal indexes
  178. let (mut fork_index, mut proposal_index) = (None, None);
  179. // Loop through all the forks
  180. for (f_index, fork) in forks.iter().enumerate() {
  181. // Traverse fork proposals sequence in reverse
  182. for (p_index, p_hash) in fork.proposals.iter().enumerate().rev() {
  183. // Check we haven't already seen that proposal
  184. if &proposal_hash == p_hash {
  185. return Err(Error::ProposalAlreadyExists)
  186. }
  187. // Check if proposal extends this fork
  188. if &proposal.block.header.previous == p_hash {
  189. (fork_index, proposal_index) = (Some(f_index), Some(p_index));
  190. }
  191. }
  192. }
  193. if let (Some(f_index), Some(p_index)) = (fork_index, proposal_index) {
  194. return Ok((f_index, p_index))
  195. }
  196. Err(Error::ExtendedChainIndexNotFound)
  197. }
  198. /// Auxiliary function to find best ranked fork.
  199. ///
  200. /// The best ranked fork is the one with the highest sum of
  201. /// its blocks squared mining target distances, from max 32
  202. /// bytes int. In case of a tie, the fork with the highest
  203. /// sum of its blocks squared RandomX hash number distances,
  204. /// from max 32 bytes int, wins.
  205. pub fn best_fork_index(forks: &[Fork]) -> Result<usize> {
  206. // Check if node has any forks
  207. if forks.is_empty() {
  208. return Err(Error::ForksNotFound)
  209. }
  210. // Find the best ranked forks
  211. let mut best = &BigUint::from(0u64);
  212. let mut indexes = vec![];
  213. for (f_index, fork) in forks.iter().enumerate() {
  214. let rank = &fork.targets_rank;
  215. // Fork ranks lower that current best
  216. if rank < best {
  217. continue
  218. }
  219. // Fork has same rank as current best
  220. if rank == best {
  221. indexes.push(f_index);
  222. continue
  223. }
  224. // Fork ranks higher that current best
  225. best = rank;
  226. indexes = vec![f_index];
  227. }
  228. // If a single best ranking fork exists, return it
  229. if indexes.len() == 1 {
  230. return Ok(indexes[0])
  231. }
  232. // Break tie using their hash distances rank
  233. let mut best_index = indexes[0];
  234. for index in &indexes[1..] {
  235. if forks[*index].hashes_rank > forks[best_index].hashes_rank {
  236. best_index = *index;
  237. }
  238. }
  239. Ok(best_index)
  240. }