Browse Source

blockchain: minor pointers cleanup

We don't want to introduce &BlockchainOverlayPtr in runtime, because we will end up with lifetime hells, and copying is cheap
aggstam 3 years ago
parent
commit
b122e4e19e

+ 4 - 4
src/blockchain/block_store.rs

@@ -269,9 +269,9 @@ impl BlockStore {
 pub struct BlockStoreOverlay(SledDbOverlayPtr);
 
 impl BlockStoreOverlay {
-    pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
+    pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
         overlay.lock().unwrap().open_tree(SLED_BLOCK_TREE)?;
-        Ok(Self(overlay))
+        Ok(Self(overlay.clone()))
     }
 
     /// Insert a slice of [`Block`] into the overlay.
@@ -466,9 +466,9 @@ impl BlockOrderStore {
 pub struct BlockOrderStoreOverlay(SledDbOverlayPtr);
 
 impl BlockOrderStoreOverlay {
-    pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
+    pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
         overlay.lock().unwrap().open_tree(SLED_BLOCK_ORDER_TREE)?;
-        Ok(Self(overlay))
+        Ok(Self(overlay.clone()))
     }
 
     /// Insert a slice of `u64` and block hashes into the store. With sled, the

+ 4 - 4
src/blockchain/contract_store.rs

@@ -66,9 +66,9 @@ impl WasmStore {
 pub struct WasmStoreOverlay(SledDbOverlayPtr);
 
 impl WasmStoreOverlay {
-    pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
+    pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
         overlay.lock().unwrap().open_tree(SLED_BINCODE_TREE)?;
-        Ok(Self(overlay))
+        Ok(Self(overlay.clone()))
     }
 
     /// Fetches the bincode for a given ContractId
@@ -222,9 +222,9 @@ impl ContractStateStore {
 pub struct ContractStateStoreOverlay(SledDbOverlayPtr);
 
 impl ContractStateStoreOverlay {
-    pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
+    pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
         overlay.lock().unwrap().open_tree(SLED_CONTRACTS_TREE)?;
-        Ok(Self(overlay))
+        Ok(Self(overlay.clone()))
     }
 
     /// Try to initialize a new contract state. Contracts can create a number

+ 2 - 2
src/blockchain/header_store.rs

@@ -160,9 +160,9 @@ impl HeaderStore {
 pub struct HeaderStoreOverlay(SledDbOverlayPtr);
 
 impl HeaderStoreOverlay {
-    pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
+    pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
         overlay.lock().unwrap().open_tree(SLED_HEADER_TREE)?;
-        Ok(Self(overlay))
+        Ok(Self(overlay.clone()))
     }
 
     /// Insert a slice of [`Header`] into the overlay.

+ 7 - 7
src/blockchain/mod.rs

@@ -400,13 +400,13 @@ impl BlockchainOverlay {
     /// Instantiate a new `BlockchainOverlay` over the given [`Blockchain`] instance.
     pub fn new(blockchain: &Blockchain) -> Result<BlockchainOverlayPtr> {
         let overlay = Arc::new(Mutex::new(sled_overlay::SledDbOverlay::new(&blockchain.sled_db)));
-        let headers = HeaderStoreOverlay::new(overlay.clone())?;
-        let blocks = BlockStoreOverlay::new(overlay.clone())?;
-        let order = BlockOrderStoreOverlay::new(overlay.clone())?;
-        let slots = SlotStoreOverlay::new(overlay.clone())?;
-        let transactions = TxStoreOverlay::new(overlay.clone())?;
-        let contracts = ContractStateStoreOverlay::new(overlay.clone())?;
-        let wasm_bincode = WasmStoreOverlay::new(overlay.clone())?;
+        let headers = HeaderStoreOverlay::new(&overlay)?;
+        let blocks = BlockStoreOverlay::new(&overlay)?;
+        let order = BlockOrderStoreOverlay::new(&overlay)?;
+        let slots = SlotStoreOverlay::new(&overlay)?;
+        let transactions = TxStoreOverlay::new(&overlay)?;
+        let contracts = ContractStateStoreOverlay::new(&overlay)?;
+        let wasm_bincode = WasmStoreOverlay::new(&overlay)?;
 
         Ok(Arc::new(Mutex::new(Self {
             overlay,

+ 2 - 2
src/blockchain/slot_store.rs

@@ -145,9 +145,9 @@ impl SlotStore {
 pub struct SlotStoreOverlay(SledDbOverlayPtr);
 
 impl SlotStoreOverlay {
-    pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
+    pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
         overlay.lock().unwrap().open_tree(SLED_SLOT_TREE)?;
-        Ok(Self(overlay))
+        Ok(Self(overlay.clone()))
     }
 
     /// Insert a slice of [`Slot`] into the overlay.

+ 2 - 2
src/blockchain/tx_store.rs

@@ -132,9 +132,9 @@ impl TxStore {
 pub struct TxStoreOverlay(SledDbOverlayPtr);
 
 impl TxStoreOverlay {
-    pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
+    pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
         overlay.lock().unwrap().open_tree(SLED_TX_TREE)?;
-        Ok(Self(overlay))
+        Ok(Self(overlay.clone()))
     }
 
     /// Insert a slice of [`Transaction`] into the overlay.

+ 6 - 12
src/consensus/validator.rs

@@ -993,7 +993,7 @@ impl ValidatorState {
     /// for the contract calls.
     async fn verify_transaction(
         &self,
-        blockchain_overlay: BlockchainOverlayPtr,
+        overlay: &BlockchainOverlayPtr,
         tx: &Transaction,
         verifying_slot: u64,
     ) -> Result<()> {
@@ -1036,12 +1036,8 @@ impl ValidatorState {
             let runtime_key = call.contract_id.to_string();
             if !runtimes.contains_key(&runtime_key) {
                 let wasm = self.blockchain.wasm_bincode.get(call.contract_id)?;
-                let r = Runtime::new(
-                    &wasm,
-                    blockchain_overlay.clone(),
-                    call.contract_id,
-                    time_keeper.clone(),
-                )?;
+                let r =
+                    Runtime::new(&wasm, overlay.clone(), call.contract_id, time_keeper.clone())?;
                 runtimes.insert(runtime_key.clone(), r);
             }
             let runtime = runtimes.get_mut(&runtime_key).unwrap();
@@ -1153,18 +1149,16 @@ impl ValidatorState {
         info!(target: "consensus::validator", "Verifying {} transaction(s)", txs.len());
 
         let mut erroneous_txs = vec![];
-        let blockchain_overlay = BlockchainOverlay::new(&self.blockchain)?;
+        let overlay = BlockchainOverlay::new(&self.blockchain)?;
 
         for tx in txs {
-            if let Err(e) =
-                self.verify_transaction(blockchain_overlay.clone(), tx, verifying_slot).await
-            {
+            if let Err(e) = self.verify_transaction(&overlay, tx, verifying_slot).await {
                 warn!(target: "consensus::validator", "Transaction verification failed: {}", e);
                 erroneous_txs.push(tx.clone());
             }
         }
 
-        let lock = blockchain_overlay.lock().unwrap();
+        let lock = overlay.lock().unwrap();
         let mut overlay = lock.overlay.lock().unwrap();
         if !erroneous_txs.is_empty() {
             warn!(target: "consensus::validator", "Erroneous transactions found in set");

+ 15 - 12
src/validator/mod.rs

@@ -79,23 +79,19 @@ impl Validator {
         let blockchain = Blockchain::new(db)?;
 
         // Create an overlay over whole blockchain so we can write stuff
-        let blockchain_overlay = BlockchainOverlay::new(&blockchain)?;
+        let overlay = BlockchainOverlay::new(&blockchain)?;
 
         // Add genesis block if blockchain is empty
         if blockchain.genesis().is_err() {
             info!(target: "validator", "Appending genesis block");
-            verify_block(blockchain_overlay.clone(), &config.genesis_block, &None)?;
+            verify_block(&overlay, &config.genesis_block, None)?;
         };
 
         // Deploy native wasm contracts
-        deploy_native_contracts(
-            blockchain_overlay.clone(),
-            &config.time_keeper,
-            &config.faucet_pubkeys,
-        )?;
+        deploy_native_contracts(&overlay, &config.time_keeper, &config.faucet_pubkeys)?;
 
         // Write the changes to the actual chain db
-        blockchain_overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
+        overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
 
         info!(target: "validator", "Initializing Consensus");
         let consensus = Consensus::new(blockchain.clone(), config.time_keeper);
@@ -126,17 +122,24 @@ impl Validator {
 
         // Retrieve last block
         let lock = overlay.lock().unwrap();
-        let mut previous = if !lock.is_empty()? { Some(lock.last_block()?) } else { None };
+        // If blockchain is empty it will error out here
+        let last_block = match lock.last_block() {
+            Ok(l) => l,
+            Err(_) => BlockInfo::default(),
+        };
+        // We only need the reference, thats why we do it like this
+        let mut previous = if !lock.is_empty()? { Some(&last_block) } else { None };
+
         // Validate and insert each block
         for block in blocks {
-            if verify_block(overlay.clone(), block, &previous).is_err() {
+            if verify_block(&overlay, block, previous).is_err() {
                 warn!(target: "validator", "Erroneous block found in set");
                 overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
                 return Err(Error::BlockIsInvalid(block.blockhash().to_string()))
             };
 
             // Use last inserted block as next iteration previous
-            previous = Some(block.clone());
+            previous = Some(block);
         }
 
         debug!(target: "validator", "Applying overlay changes");
@@ -166,7 +169,7 @@ impl Validator {
         );
 
         // Verify all transactions and get erroneous ones
-        let erroneous_txs = verify_transactions(overlay.clone(), &time_keeper, txs).await?;
+        let erroneous_txs = verify_transactions(&overlay, &time_keeper, txs).await?;
 
         let lock = overlay.lock().unwrap();
         let mut overlay = lock.overlay.lock().unwrap();

+ 2 - 3
src/validator/utils.rs

@@ -35,7 +35,7 @@ use crate::{
 /// is necessary. This logic should be handled in the init function of
 /// the actual contract, so make sure the native contracts handle this well.
 pub fn deploy_native_contracts(
-    blockchain_overlay: BlockchainOverlayPtr,
+    overlay: &BlockchainOverlayPtr,
     time_keeper: &TimeKeeper,
     faucet_pubkeys: &Vec<PublicKey>,
 ) -> Result<()> {
@@ -75,8 +75,7 @@ pub fn deploy_native_contracts(
     for nc in native_contracts {
         info!(target: "validator", "Deploying {} with ContractID {}", nc.0, nc.1);
 
-        let mut runtime =
-            Runtime::new(&nc.2[..], blockchain_overlay.clone(), nc.1, time_keeper.clone())?;
+        let mut runtime = Runtime::new(&nc.2[..], overlay.clone(), nc.1, time_keeper.clone())?;
 
         runtime.deploy(&nc.3)?;
 

+ 5 - 5
src/validator/verification.rs

@@ -34,9 +34,9 @@ use crate::{
 
 /// Validate given [`Transaction`], and apply it to the provided overlay
 pub fn verify_block(
-    overlay: BlockchainOverlayPtr,
+    overlay: &BlockchainOverlayPtr,
     block: &BlockInfo,
-    previous: &Option<BlockInfo>,
+    previous: Option<&BlockInfo>,
 ) -> Result<()> {
     let block_hash = block.blockhash();
     debug!(target: "validator", "Validating block {}", block_hash);
@@ -65,7 +65,7 @@ pub fn verify_block(
 /// Validate WASM execution, signatures, and ZK proofs for a given [`Transaction`],
 /// and apply them it to the provided overlay.
 pub async fn verify_transaction(
-    overlay: BlockchainOverlayPtr,
+    overlay: &BlockchainOverlayPtr,
     time_keeper: &TimeKeeper,
     tx: &Transaction,
     verifying_keys: &mut HashMap<[u8; 32], HashMap<String, VerifyingKey>>,
@@ -174,7 +174,7 @@ pub async fn verify_transaction(
 /// The function takes a boolean called `write` which tells it to actually write
 /// the state transitions to the database.
 pub async fn verify_transactions(
-    overlay: BlockchainOverlayPtr,
+    overlay: &BlockchainOverlayPtr,
     time_keeper: &TimeKeeper,
     txs: &[Transaction],
 ) -> Result<Vec<Transaction>> {
@@ -196,7 +196,7 @@ pub async fn verify_transactions(
     // Iterate over transactions and attempt to verify them
     for tx in txs {
         overlay.lock().unwrap().checkpoint();
-        if let Err(e) = verify_transaction(overlay.clone(), time_keeper, tx, &mut vks).await {
+        if let Err(e) = verify_transaction(overlay, time_keeper, tx, &mut vks).await {
             warn!(target: "validator", "Transaction verification failed: {}", e);
             erroneous_txs.push(tx.clone());
             // TODO: verify this works as expected