utils.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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::{
  19. ecvrf::VrfProof, DAO_CONTRACT_ID, DEPLOYOOOR_CONTRACT_ID, MONEY_CONTRACT_ID,
  20. };
  21. use darkfi_serial::AsyncDecodable;
  22. use log::info;
  23. use num_bigint::BigUint;
  24. use smol::io::Cursor;
  25. use crate::{
  26. blockchain::{BlockInfo, BlockchainOverlayPtr},
  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. /// If overlay already contains the contracts, it will just open the
  33. /// necessary db and trees, and give back what it has. This means that
  34. /// on subsequent runs, our native contracts will already be in a deployed
  35. /// state, so what we actually do here is a redeployment. This kind of
  36. /// operation should only modify the contract's state in case it wasn't
  37. /// deployed before (meaning the initial run). Otherwise, it shouldn't
  38. /// touch anything, or just potentially update the db schemas or whatever
  39. /// is necessary. This logic should be handled in the init function of
  40. /// the actual contract, so make sure the native contracts handle this well.
  41. pub async fn deploy_native_contracts(overlay: &BlockchainOverlayPtr) -> Result<()> {
  42. info!(target: "validator::utils::deploy_native_contracts", "Deploying native WASM contracts");
  43. // The Money contract uses an empty payload to deploy itself.
  44. let money_contract_deploy_payload = vec![];
  45. // The DAO contract uses an empty payload to deploy itself.
  46. let dao_contract_deploy_payload = vec![];
  47. // The Deployooor contract uses an empty payload to deploy itself.
  48. let deployooor_contract_deploy_payload = vec![];
  49. let native_contracts = vec![
  50. (
  51. "Money Contract",
  52. *MONEY_CONTRACT_ID,
  53. include_bytes!("../contract/money/darkfi_money_contract.wasm").to_vec(),
  54. money_contract_deploy_payload,
  55. ),
  56. (
  57. "DAO Contract",
  58. *DAO_CONTRACT_ID,
  59. include_bytes!("../contract/dao/darkfi_dao_contract.wasm").to_vec(),
  60. dao_contract_deploy_payload,
  61. ),
  62. (
  63. "Deployooor Contract",
  64. *DEPLOYOOOR_CONTRACT_ID,
  65. include_bytes!("../contract/deployooor/darkfi_deployooor_contract.wasm").to_vec(),
  66. deployooor_contract_deploy_payload,
  67. ),
  68. ];
  69. // Grab last known block height to verify against next one.
  70. // If no blocks exist, we verify against genesis block height (0).
  71. let verifying_block_height = match overlay.lock().unwrap().last() {
  72. Ok((last_block_height, _)) => last_block_height + 1,
  73. Err(_) => 0,
  74. };
  75. for nc in native_contracts {
  76. info!(target: "validator::utils::deploy_native_contracts", "Deploying {} with ContractID {}", nc.0, nc.1);
  77. let mut runtime = Runtime::new(&nc.2[..], overlay.clone(), nc.1, verifying_block_height)?;
  78. runtime.deploy(&nc.3)?;
  79. info!(target: "validator::utils::deploy_native_contracts", "Successfully deployed {}", nc.0);
  80. }
  81. info!(target: "validator::utils::deploy_native_contracts", "Finished deployment of native WASM contracts");
  82. Ok(())
  83. }
  84. /// Compute a block's rank, assuming that its valid.
  85. /// Genesis block has rank 0.
  86. /// First 2 blocks rank is equal to their hash number, since their previous
  87. /// previous block producer doesn't exist or have a VRF.
  88. pub async fn block_rank(block: &BlockInfo, previous_previous: &BlockInfo) -> Result<BigUint> {
  89. // Genesis block has rank 0
  90. if block.header.height == 0 {
  91. return Ok(0u64.into())
  92. }
  93. // Grab block hash number
  94. let hash_number = BigUint::from_bytes_be(block.hash()?.as_bytes());
  95. // First 2 blocks have rank equal to their block hash number
  96. if block.header.height < 3 {
  97. return Ok(hash_number)
  98. }
  99. // Extract VRF proof from the previous previous producer transaction
  100. let tx = previous_previous.txs.last().unwrap();
  101. let data = &tx.calls[0].data.data;
  102. let mut decoder = Cursor::new(&data);
  103. // PoW uses MoneyPoWRewardParamsV1
  104. decoder.set_position(499); // FIXME: This should not be done like this
  105. // Get the VRF output as big-endian
  106. let vrf_proof: VrfProof = AsyncDecodable::decode_async(&mut decoder).await?;
  107. let vrf_output = BigUint::from_bytes_be(vrf_proof.hash_output().as_bytes());
  108. // Finally, compute the rank
  109. let rank = if hash_number != 0u8.into() { vrf_output % hash_number } else { vrf_output };
  110. Ok(rank)
  111. }
  112. /// Auxiliary function to calculate the middle value between provided u64 numbers
  113. pub fn get_mid(a: u64, b: u64) -> u64 {
  114. (a / 2) + (b / 2) + ((a - 2 * (a / 2)) + (b - 2 * (b / 2))) / 2
  115. }
  116. /// Auxiliary function to calculate the median of a given `Vec<u64>`.
  117. /// The function sorts the vector internally.
  118. pub fn median(mut v: Vec<u64>) -> u64 {
  119. if v.len() == 1 {
  120. return v[0]
  121. }
  122. let n = v.len() / 2;
  123. v.sort_unstable();
  124. if v.len() % 2 == 0 {
  125. v[n]
  126. } else {
  127. get_mid(v[n - 1], v[n])
  128. }
  129. }
  130. /// Given a proposal, find the index of the fork chain it extends, along with the specific
  131. /// extended proposal index. Additionally, check that proposal doesn't already exists in any
  132. /// fork chain.
  133. pub fn find_extended_fork_index(forks: &[Fork], proposal: &Proposal) -> Result<(usize, usize)> {
  134. // Grab provided proposal hash
  135. let proposal_hash = proposal.block.hash()?;
  136. // Keep track of fork and proposal indexes
  137. let (mut fork_index, mut proposal_index) = (None, None);
  138. // Loop through all the forks
  139. for (f_index, fork) in forks.iter().enumerate() {
  140. // Traverse fork proposals sequence in reverse
  141. for (p_index, p_hash) in fork.proposals.iter().enumerate().rev() {
  142. // Check we haven't already seen that proposal
  143. if &proposal_hash == p_hash {
  144. return Err(Error::ProposalAlreadyExists)
  145. }
  146. // Check if proposal extends this fork
  147. if &proposal.block.header.previous == p_hash {
  148. // Proposal must only extend a single fork
  149. if fork_index.is_some() {
  150. return Err(Error::ProposalAlreadyExists)
  151. }
  152. (fork_index, proposal_index) = (Some(f_index), Some(p_index));
  153. }
  154. }
  155. }
  156. if let (Some(f_index), Some(p_index)) = (fork_index, proposal_index) {
  157. return Ok((f_index, p_index))
  158. }
  159. Err(Error::ExtendedChainIndexNotFound)
  160. }
  161. /// Auxiliary function to find best ranked forks indexes.
  162. pub fn best_forks_indexes(forks: &[Fork]) -> Result<Vec<usize>> {
  163. // Check if node has any forks
  164. if forks.is_empty() {
  165. return Err(Error::ForksNotFound)
  166. }
  167. // Find the best ranked forks
  168. let mut best = BigUint::from(0u64);
  169. let mut indexes = vec![];
  170. for (f_index, fork) in forks.iter().enumerate() {
  171. let rank = &fork.rank;
  172. // Fork ranks lower that current best
  173. if rank < &best {
  174. continue
  175. }
  176. // Fork has same rank as current best
  177. if rank == &best {
  178. indexes.push(f_index);
  179. continue
  180. }
  181. // Fork ranks higher that current best
  182. best = rank.clone();
  183. indexes = vec![f_index];
  184. }
  185. Ok(indexes)
  186. }