Forráskód Böngészése

verify the height of blocks

Malte Kraus 8 éve
szülő
commit
7b7cd4e7cd
2 módosított fájl, 10 hozzáadás és 2 törlés
  1. 8 0
      src/block.py
  2. 2 2
      src/blockchain.py

+ 8 - 0
src/block.py

@@ -145,6 +145,14 @@ class Block:
         """ Verify the previous block pointer points to a valid block in the given block chain. """
         if self.hash == GENESIS_BLOCK_HASH:
             return True
+        prev = chain.get_block_by_hash(self.prev_block_hash)
+        if prev is None:
+            logging.warning("Previous block is missing in the block chain.")
+            return False
+        if prev.height + chain.compute_difficulty(prev) != self.height:
+            logging.warning("Block has wrong height.")
+            return False
+        return True
 
     def verify_transactions(self, chain):
         """ Verify all transaction in this block are valid in the given block chain. """

+ 2 - 2
src/blockchain.py

@@ -96,8 +96,8 @@ class Blockchain:
         """
         return self.blocks[-1]
 
-    def compute_difficulty(self) -> int:
-        """ Compute the desired difficulty for the next block. """
+    def compute_difficulty(self, prev_block: 'Block'=None) -> int:
+        """ Compute the desired difficulty for the block after `prev_block` (defaults to `head`). """
         # TODO: dynamic calculation
         # TODO: verify difficulty in new blocks
         return self.head.difficulty