Browse Source

add a factory method for creating new blocks

Malte Kraus 8 năm trước cách đây
mục cha
commit
a7021158dd
2 tập tin đã thay đổi với 13 bổ sung5 xóa
  1. 12 0
      src/block.py
  2. 1 5
      src/mining_strategy.py

+ 12 - 0
src/block.py

@@ -47,6 +47,18 @@ class Block:
                    [Transaction.from_json_compatible(t) for t in list(val['transactions'])],
                    unhexlify(val['merkle_root_hash']))
 
+    @classmethod
+    def create(cls, blockchain: 'Blockchain', transactions: list, ts=None):
+        """
+        Create a new block for a certain blockchain, containing certain transactions.
+        """
+        tree = merkle_tree(transactions)
+        difficulty = blockchain.compute_difficulty()
+        if ts is None:
+            ts = datetime.now()
+        return Block(None, blockchain.head.hash, ts, 0, blockchain.head.height + difficulty,
+                     None, difficulty, transactions, tree.get_hash())
+
     def __str__(self):
         return json.dumps(self.to_json_compatible(), indent=4)
 

+ 1 - 5
src/mining_strategy.py

@@ -25,8 +25,4 @@ def create_block(blockchain, unconfirmed_transactions, reward_pubkey):
     trans = Transaction([], [TransactionTarget(reward_pubkey, reward)], [], iv=head.hash)
     transactions.add(trans)
 
-    transactions = list(transactions)
-    tree = merkle_tree(transactions)
-    difficulty = blockchain.compute_difficulty()
-    return Block(None, head.hash, datetime.now(), 0, head.height + difficulty,
-                 None, difficulty, transactions, tree.get_hash())
+    return Block.create(blockchain, list(transactions))