Parcourir la source

darkfid2/utils: moved genesis_txs_total function to src/validator/utils

aggstam il y a 2 ans
Parent
commit
71b8d8d71c

+ 2 - 2
bin/darkfid2/src/main.rs

@@ -38,7 +38,7 @@ use darkfi::{
     },
     system::{StoppableTask, StoppableTaskPtr},
     util::time::TimeKeeper,
-    validator::{Validator, ValidatorConfig, ValidatorPtr},
+    validator::{utils::genesis_txs_total, Validator, ValidatorConfig, ValidatorPtr},
     Error, Result,
 };
 use darkfi_contract_test_harness::vks;
@@ -64,7 +64,7 @@ mod proto;
 
 /// Utility functions
 mod utils;
-use utils::{genesis_txs_total, spawn_consensus_p2p, spawn_sync_p2p};
+use utils::{spawn_consensus_p2p, spawn_sync_p2p};
 
 const CONFIG_FILE: &str = "darkfid_config.toml";
 const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");

+ 2 - 2
bin/darkfid2/src/tests/harness.rs

@@ -24,7 +24,7 @@ use darkfi::{
     rpc::jsonrpc::JsonSubscriber,
     tx::Transaction,
     util::time::TimeKeeper,
-    validator::{pid::slot_pid_output, Validator, ValidatorConfig},
+    validator::{pid::slot_pid_output, utils::genesis_txs_total, Validator, ValidatorConfig},
     Result,
 };
 use darkfi_contract_test_harness::{vks, Holder, TestHarness};
@@ -37,7 +37,7 @@ use url::Url;
 use crate::{
     proto::BlockInfoMessage,
     task::sync::sync_task,
-    utils::{genesis_txs_total, spawn_consensus_p2p, spawn_sync_p2p},
+    utils::{spawn_consensus_p2p, spawn_sync_p2p},
     Darkfid,
 };
 

+ 0 - 54
bin/darkfid2/src/utils.rs

@@ -22,67 +22,13 @@ use log::info;
 use smol::Executor;
 
 use darkfi::{
-    error::TxVerifyFailed,
     net::{P2p, P2pPtr, Settings, SESSION_ALL},
     rpc::jsonrpc::JsonSubscriber,
-    tx::Transaction,
     validator::ValidatorPtr,
-    Result,
 };
-use darkfi_consensus_contract::{
-    model::ConsensusGenesisStakeParamsV1, ConsensusFunction::GenesisStakeV1,
-};
-use darkfi_money_contract::{model::MoneyTokenMintParamsV1, MoneyFunction::GenesisMintV1};
-use darkfi_sdk::crypto::{CONSENSUS_CONTRACT_ID, MONEY_CONTRACT_ID};
-use darkfi_serial::deserialize;
 
 use crate::proto::{ProtocolBlock, ProtocolProposal, ProtocolSync, ProtocolTx};
 
-/// Auxiliary function to calculate the total amount of minted tokens in provided
-/// genesis transactions set. This includes both staked and normal tokens.
-/// If a non-genesis transaction is found, execution fails.
-/// Set must also include the genesis transaction(empty) at last position.
-pub fn genesis_txs_total(txs: &[Transaction]) -> Result<u64> {
-    let mut total = 0;
-
-    if txs.is_empty() {
-        return Ok(total)
-    }
-
-    // Iterate transactions, exluding producer(last) one
-    for tx in &txs[..txs.len() - 1] {
-        // Transaction must contain a single Consensus::GenesisStake or Money::GenesisMint call
-        if tx.calls.len() != 1 {
-            return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
-        }
-        let call = &tx.calls[0];
-        let function = call.data[0];
-        if !(call.contract_id == *CONSENSUS_CONTRACT_ID || call.contract_id == *MONEY_CONTRACT_ID) ||
-            (call.contract_id == *CONSENSUS_CONTRACT_ID && function != GenesisStakeV1 as u8) ||
-            (call.contract_id == *MONEY_CONTRACT_ID && function != GenesisMintV1 as u8)
-        {
-            return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
-        }
-
-        let value = if function == GenesisStakeV1 as u8 {
-            let params: ConsensusGenesisStakeParamsV1 = deserialize(&call.data[1..])?;
-            params.input.value
-        } else {
-            let params: MoneyTokenMintParamsV1 = deserialize(&call.data[1..])?;
-            params.input.value
-        };
-
-        total += value;
-    }
-
-    let tx = txs.last().unwrap();
-    if tx != &Transaction::default() {
-        return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
-    }
-
-    Ok(total)
-}
-
 /// Auxiliary function to generate the sync P2P network and register all its protocols.
 pub async fn spawn_sync_p2p(
     settings: &Settings,

+ 50 - 0
src/validator/utils.rs

@@ -30,7 +30,9 @@ use log::info;
 
 use crate::{
     blockchain::{BlockInfo, BlockchainOverlayPtr},
+    error::TxVerifyFailed,
     runtime::vm_runtime::Runtime,
+    tx::Transaction,
     util::time::TimeKeeper,
     Error, Result,
 };
@@ -171,3 +173,51 @@ pub fn median(mut v: Vec<u64>) -> u64 {
         get_mid(v[n - 1], v[n])
     }
 }
+
+/// Auxiliary function to calculate the total amount of minted tokens in provided
+/// genesis transactions set. This includes both staked and normal tokens.
+/// If a non-genesis transaction is found, execution fails.
+/// Set must also include the genesis transaction(empty) at last position.
+pub fn genesis_txs_total(txs: &[Transaction]) -> Result<u64> {
+    let mut total = 0;
+
+    if txs.is_empty() {
+        return Ok(total)
+    }
+
+    // Iterate transactions, exluding producer(last) one
+    for tx in &txs[..txs.len() - 1] {
+        // Transaction must contain a single Consensus::GenesisStake (0x00)
+        // or Money::GenesisMint (0x01) call
+        if tx.calls.len() != 1 {
+            return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
+        }
+        let call = &tx.calls[0];
+        let function = call.data[0];
+        if !(call.contract_id == *CONSENSUS_CONTRACT_ID || call.contract_id == *MONEY_CONTRACT_ID) ||
+            (call.contract_id == *CONSENSUS_CONTRACT_ID && function != 0x00_u8) ||
+            (call.contract_id == *MONEY_CONTRACT_ID && function != 0x01_u8)
+        {
+            return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
+        }
+
+        // Extract transaction input value.
+        // Consensus::GenesisStake uses ConsensusGenesisStakeParamsV1, while
+        // Money::GenesisMint uses MoneyGenesisMintParamsV1. Both params structs
+        // have the value at same position (1).
+        let data = &tx.calls[0].data;
+        let position = 1;
+        let mut decoder = Cursor::new(&data);
+        decoder.set_position(position);
+        let value: u64 = Decodable::decode(&mut decoder)?;
+
+        total += value;
+    }
+
+    let tx = txs.last().unwrap();
+    if tx != &Transaction::default() {
+        return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
+    }
+
+    Ok(total)
+}