Procházet zdrojové kódy

validator: removed genesis tx total calculation | darkfid: use next block height for contracts deployment

skoupidi před 2 roky
rodič
revize
2dc6832656

+ 1 - 1
bin/darkfid/genesis_block_localnet

@@ -1 +1 @@
-3N337zZEeEFfZFBPotybXsdtKNjrAUx56QLqcr4izXLvyTVCY6E4MgUvUpEj57f6RNbkqMtZ4vqxFzWKGEnhvoMuaj1QK1fs7nRA4bY3JNrbvfzvP5UBCL9F7uTT3vpDbUiNEWwwr1UnvrzFkj7jryLLGkFDo7VMYXgovrnxMfQQczSiPVSQWGm8yXXMp9SaWeDW96r6GLbJWVc5roofVyGYYw4Cdd4vrbRMGnP7n78xWRGcmmHRebBHru2TqDSFnxYRKN3vtu1s42TkyxbbWVLrJft8ta1sq6PPPvk4idJsboEaxX9gj1DCMdvkq5gKFp5WohfhfMz7jXJod6do4xdPfutedLK3fUVYvTkRRqoSVogbzr2jdjiRPzf9WuvJyULZY7KT6Knby6aenGLdPPd3TcndiqXyWscU1LcWFX59Z7Nkp63no6rmps
+9mbVkHECpef5uSqiQKKzj7Z5HjypYEL63oSDQdb54RkSXbZ8MafuPQ4F8P4auRoQLKAQWEX2nETDDPvnNbKHT38szyiCqwXArSo5eVcXsXEbbji4HSpTDxPFUy6jU5t4PoCn9LASqBWtef99XdWjwnoEs8JzxmBFPexctCeSncnNe2QCYErDtfEU84fecSkZNhUfMAvSZ6KK9BPjKpNoBj16ywrLX69yRGRwMq

+ 1 - 1
bin/darkfid/genesis_block_mainnet

@@ -1 +1 @@
-3N337zZEeEFfZFBPotybXsdtKNjrAUx56QLqcr4izXLvyTVCY6E4MgUvUpEj57f6RNbkqMtZ4vqxFzWKGEnhvoMuaj1QK1fs7nRA4bY3JNrbvfzvP5UBCL9F7uTT3vpDbUiNEWwwr1UnvrzFkj7jryLLGkFDo7VMYXgovrnxMfQQczSiPVSQWGm8yXXMp9SaWeDW96r6GLbJWVc5roofVyGYYw4Cdd4vrbRMGnP7n78xWRGcmmHRebBHru2TqDSFnxYRK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NoBj16ywrLX69yRGRwMq

+ 1 - 4
bin/darkfid/src/main.rs

@@ -39,7 +39,7 @@ use darkfi::{
     },
     system::{StoppableTask, StoppableTaskPtr},
     util::path::expand_path,
-    validator::{utils::genesis_txs_total, Validator, ValidatorConfig, ValidatorPtr},
+    validator::{Validator, ValidatorConfig, ValidatorPtr},
     Error, Result,
 };
 use darkfi_sdk::crypto::PublicKey;
@@ -216,8 +216,6 @@ async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
     let sled_db = sled::open(&db_path)?;
 
     // Initialize validator configuration
-    let genesis_txs_total = genesis_txs_total(&genesis_block.txs).await?;
-
     let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
         info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {}", diff);
         Some(diff.into())
@@ -230,7 +228,6 @@ async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
         blockchain_config.pow_target,
         pow_fixed_difficulty,
         genesis_block,
-        genesis_txs_total,
         vec![],
         false, // TODO: Make configurable
     );

+ 2 - 4
bin/darkfid/src/tests/harness.rs

@@ -22,7 +22,7 @@ use darkfi::{
     blockchain::BlockInfo,
     net::Settings,
     rpc::jsonrpc::JsonSubscriber,
-    validator::{utils::genesis_txs_total, Validator, ValidatorConfig},
+    validator::{Validator, ValidatorConfig},
     Result,
 };
 use darkfi_contract_test_harness::{vks, Holder, TestHarness};
@@ -64,9 +64,8 @@ impl Harness {
         // Generate default genesis block
         let mut genesis_block = BlockInfo::default();
 
-        // Append genesis transactions and calculate their total
+        // Append genesis transactions
         genesis_block.txs.push(genesis_mint_tx);
-        let genesis_txs_total = genesis_txs_total(&genesis_block.txs).await?;
 
         // Generate validators configuration
         // NOTE: we are not using consensus constants here so we
@@ -76,7 +75,6 @@ impl Harness {
             config.pow_target,
             config.pow_fixed_difficulty.clone(),
             genesis_block,
-            genesis_txs_total,
             vec![],
             verify_fees,
         );

+ 4 - 20
script/research/gg/src/main.rs

@@ -27,11 +27,8 @@ use darkfi::{
     blockchain::{BlockInfo, Blockchain, BlockchainOverlay},
     cli_desc,
     tx::Transaction,
-    util::{
-        path::expand_path,
-        time::{TimeKeeper, Timestamp},
-    },
-    validator::{utils::genesis_txs_total, verification::verify_genesis_block},
+    util::{path::expand_path, time::Timestamp},
+    validator::verification::verify_genesis_block,
 };
 use darkfi_contract_test_harness::vks;
 use darkfi_serial::{deserialize, serialize};
@@ -106,19 +103,12 @@ async fn main() -> Result<()> {
 
             // Append genesis transactions
             if !genesis_txs.is_empty() {
-                // Retrieve genesis producer transaction
-                let producer_tx = genesis_block.txs.pop().unwrap();
-
-                // Append genesis transactions and calculate their total
                 genesis_block.txs.append(&mut genesis_txs);
-                genesis_block.txs.push(producer_tx);
-                let genesis_txs_total = genesis_txs_total(&genesis_block.txs)?;
-                genesis_block.slots[0].total_tokens = genesis_txs_total;
             }
 
             // Write generated genesis block to stdin
             let encoded = bs58::encode(&serialize(&genesis_block)).into_string();
-            println!("{}", encoded);
+            println!("{encoded}");
 
             Ok(())
         }
@@ -138,13 +128,7 @@ async fn main() -> Result<()> {
             let blockchain = Blockchain::new(&sled_db)?;
             let overlay = BlockchainOverlay::new(&blockchain)?;
 
-            // Generate a dummy time keeper
-            let time_keeper = TimeKeeper::new(genesis_block.header.timestamp, 10, 90, 0);
-
-            // Grab block txs total
-            let genesis_txs_total = genesis_txs_total(&genesis_block.txs)?;
-
-            verify_genesis_block(&overlay, &time_keeper, &genesis_block, genesis_txs_total).await?;
+            verify_genesis_block(&overlay, &genesis_block).await?;
 
             println!("Genesis block {hash} verified successfully!");
 

+ 4 - 1
src/blockchain/block_store.rs

@@ -480,7 +480,10 @@ impl BlockOrderStoreOverlay {
     /// Fetch the last block hash in the overlay, based on the `Ord`
     /// implementation for `Vec<u8>`.
     pub fn get_last(&self) -> Result<(u64, blake3::Hash)> {
-        let found = self.0.lock().unwrap().last(SLED_BLOCK_ORDER_TREE)?.unwrap();
+        let found = match self.0.lock().unwrap().last(SLED_BLOCK_ORDER_TREE)? {
+            Some(b) => b,
+            None => return Err(Error::BlockNumberNotFound(0)),
+        };
         let (number, hash) = parse_u64_key_record(found)?;
 
         Ok((number, hash))

+ 0 - 1
src/contract/test-harness/src/lib.rs

@@ -146,7 +146,6 @@ impl Wallet {
             90,
             Some(BigUint::from(1_u8)),
             genesis_block.clone(),
-            0,
             faucet_pubkeys.to_vec(),
             verify_fees,
         );

+ 0 - 4
src/validator/mod.rs

@@ -67,8 +67,6 @@ pub struct ValidatorConfig {
     pub pow_fixed_difficulty: Option<BigUint>,
     /// Genesis block
     pub genesis_block: BlockInfo,
-    /// Total amount of minted tokens in genesis block
-    pub genesis_txs_total: u64,
     /// Whitelisted faucet pubkeys (testnet stuff)
     pub faucet_pubkeys: Vec<PublicKey>,
     /// Flag to enable tx fee verification
@@ -81,7 +79,6 @@ impl ValidatorConfig {
         pow_target: usize,
         pow_fixed_difficulty: Option<BigUint>,
         genesis_block: BlockInfo,
-        genesis_txs_total: u64,
         faucet_pubkeys: Vec<PublicKey>,
         verify_fees: bool,
     ) -> Self {
@@ -90,7 +87,6 @@ impl ValidatorConfig {
             pow_target,
             pow_fixed_difficulty,
             genesis_block,
-            genesis_txs_total,
             faucet_pubkeys,
             verify_fees,
         }

+ 8 - 48
src/validator/utils.rs

@@ -29,9 +29,7 @@ use smol::io::Cursor;
 
 use crate::{
     blockchain::{BlockInfo, BlockchainOverlayPtr},
-    error::TxVerifyFailed,
     runtime::vm_runtime::Runtime,
-    tx::Transaction,
     validator::consensus::{Fork, Proposal},
     Error, Result,
 };
@@ -83,11 +81,17 @@ pub async fn deploy_native_contracts(
         ),
     ];
 
+    // Grab last known block height to verify against next one.
+    // If no blocks exist, we verify against genesis block height (0).
+    let verifying_block_height = match overlay.lock().unwrap().last() {
+        Ok((last_block_height, _)) => last_block_height + 1,
+        Err(_) => 0,
+    };
+
     for nc in native_contracts {
         info!(target: "validator::utils::deploy_native_contracts", "Deploying {} with ContractID {}", nc.0, nc.1);
 
-        // Note: Native contracts are always verifying against genesis block height(0)
-        let mut runtime = Runtime::new(&nc.2[..], overlay.clone(), nc.1, 0)?;
+        let mut runtime = Runtime::new(&nc.2[..], overlay.clone(), nc.1, verifying_block_height)?;
 
         runtime.deploy(&nc.3)?;
 
@@ -163,50 +167,6 @@ pub fn median(mut v: Vec<u64>) -> u64 {
     }
 }
 
-/// 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 first position.
-pub async fn genesis_txs_total(txs: &[Transaction]) -> Result<u64> {
-    let mut total = 0;
-
-    if txs.is_empty() {
-        return Ok(total)
-    }
-
-    if txs[0] != Transaction::default() {
-        return Err(TxVerifyFailed::ErroneousTxs(vec![txs[0].clone()]).into())
-    }
-
-    // Iterate transactions, exluding producer(first) one
-    for tx in &txs[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 data = &call.data.data;
-        let function = data[0];
-        if call.data.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 position = 1;
-        let mut decoder = Cursor::new(&data);
-        decoder.set_position(position);
-        let value: u64 = AsyncDecodable::decode_async(&mut decoder).await?;
-
-        total += value;
-    }
-
-    Ok(total)
-}
-
 /// Given a proposal, find the index of the fork chain it extends, along with the specific
 /// extended proposal index. Additionally, check that proposal doesn't already exists in any
 /// fork chain.