utils.rs 8.3 KB

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