浏览代码

move difficulty interval constants to proof of work

Malte Kraus 8 年之前
父节点
当前提交
94520a392d
共有 2 个文件被更改,包括 15 次插入7 次删除
  1. 9 7
      src/blockchain.py
  2. 6 0
      src/proof_of_work.py

+ 9 - 7
src/blockchain.py

@@ -2,10 +2,11 @@
 
 __all__ = ['Blockchain']
 import logging
-from datetime import timedelta
 from fractions import Fraction
 from typing import List, Dict, Optional
 
+from .proof_of_work import DIFFICULTY_BLOCK_INTERVAL, DIFFICULTY_TARGET_TIMEDELTA
+
 class Blockchain:
     """
     A block chain: a ordrered list of blocks.
@@ -110,24 +111,25 @@ class Blockchain:
 
     def compute_difficulty(self, prev_block: 'Block'=None) -> int:
         """ Compute the desired difficulty for the block after `prev_block` (defaults to `head`). """
-        BLOCK_INTERVAL = 120
-        BLOCK_TARGET_TIMEDELTA = Fraction(int(timedelta(minutes=1).total_seconds() * 1000 * 1000))
+        target_timedelta = Fraction(int(DIFFICULTY_TARGET_TIMEDELTA.total_seconds() * 1000 * 1000))
 
         if prev_block is None:
             prev_block = self.head
 
         block_idx = self.block_indices[prev_block.hash] + 1
-        if block_idx % BLOCK_INTERVAL != 0:
+        if block_idx % DIFFICULTY_BLOCK_INTERVAL != 0:
             return prev_block.difficulty
 
-        duration = prev_block.time - self.blocks[block_idx - BLOCK_INTERVAL].time
+        duration = prev_block.time - self.blocks[block_idx - DIFFICULTY_BLOCK_INTERVAL].time
         duration = Fraction(int(duration.total_seconds() * 1000 * 1000))
 
         prev_difficulty = Fraction(prev_block.difficulty)
-        hash_rate = prev_difficulty * BLOCK_INTERVAL / duration
+        hash_rate = prev_difficulty * DIFFICULTY_BLOCK_INTERVAL / duration
 
-        new_difficulty = hash_rate * BLOCK_TARGET_TIMEDELTA / BLOCK_INTERVAL
+        new_difficulty = hash_rate * target_timedelta / DIFFICULTY_BLOCK_INTERVAL
 
+        # the genesis difficulty was very easy, dropping below it means there was a pause
+        # in mining, so let's start with a new difficulty!
         if new_difficulty < self.blocks[0].difficulty:
             new_difficulty = self.blocks[0].difficulty
 

+ 6 - 0
src/proof_of_work.py

@@ -1,5 +1,6 @@
 """ Implementation and verification of the proof of work. """
 
+from datetime import timedelta
 from typing import Optional
 
 from .crypto import MAX_HASH
@@ -17,6 +18,11 @@ The difficulty of the genesis block.
 Right now this is the average required number of hashes to compute one valid block.
 """
 
+DIFFICULTY_BLOCK_INTERVAL = 30
+""" The number of blocks between difficulty changes. """
+DIFFICULTY_TARGET_TIMEDELTA = timedelta(minutes=1)
+""" The time span that it should approximately take to mine `DIFFICULTY_BLOCK_INTERVAL` blocks.  """
+
 class ProofOfWork:
     """
     Allows performing (and aborting) a proof of work.