rather get hashes in a better way
This commit is contained in:
parent
fd7cf5e2f9
commit
d3298af019
|
@ -1,10 +1,8 @@
|
|||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
|
||||
from database import Block, db, DateTimeEncoder
|
||||
from helpers import json_serializer
|
||||
from database import Block, db
|
||||
|
||||
|
||||
logger = logging.getLogger('root.blockchain')
|
||||
|
@ -72,9 +70,11 @@ class Blockchain:
|
|||
last_block = self.last_block
|
||||
|
||||
return {
|
||||
'height': last_block.height + 1 if last_block else 0,
|
||||
'timestamp': datetime.utcnow(),
|
||||
'transactions': self.current_transactions,
|
||||
'previous_hash': last_block.hash if last_block else 0,
|
||||
'timestamp': datetime.now()
|
||||
'proof': -1,
|
||||
}
|
||||
|
||||
def save_block(self, block_dict):
|
||||
|
@ -118,9 +118,14 @@ class Blockchain:
|
|||
return db.query(Block).order_by(Block.height.desc()).first()
|
||||
|
||||
@staticmethod
|
||||
def hash(block):
|
||||
def hash(b):
|
||||
"""
|
||||
Creates a SHA-256 hash of the fields for a Block
|
||||
"""
|
||||
json_string = json.dumps(block, sort_keys=True, cls=DateTimeEncoder)
|
||||
return sha256(json_string.encode()).hexdigest()
|
||||
byte_array = f"{b['height']}" \
|
||||
f"{b['timestamp']}" \
|
||||
f"{b['transactions']}" \
|
||||
f"{b['previous_hash']}" \
|
||||
f"{b['proof']}".encode()
|
||||
|
||||
return sha256(byte_array).hexdigest()
|
||||
|
|
|
@ -53,7 +53,7 @@ class Peer(BaseModel):
|
|||
|
||||
|
||||
class Block(BaseModel):
|
||||
height = Column(Integer, primary_key=True, autoincrement=True)
|
||||
height = Column(Integer, primary_key=True)
|
||||
timestamp = Column(DateTime, index=True)
|
||||
transactions = Column(PickleType)
|
||||
previous_hash = Column(String(64))
|
||||
|
|
|
@ -20,7 +20,7 @@ def proof_of_work(current_block, difficulty, event):
|
|||
# String of 64 f's replaced with 3 leading zeros (if the difficulty is 3): 000fff...f
|
||||
target = str.ljust("0" * difficulty, 64, "f")
|
||||
|
||||
current_block['timestamp'] = datetime.now()
|
||||
current_block['timestamp'] = datetime.utcnow()
|
||||
current_block['proof'] = 0
|
||||
guess_hash = Blockchain.hash(current_block)
|
||||
|
||||
|
@ -28,7 +28,7 @@ def proof_of_work(current_block, difficulty, event):
|
|||
# Check if we should still be mining
|
||||
# if not event.is_set():
|
||||
# raise Exception("STOP MINING")
|
||||
current_block['timestamp'] = datetime.now()
|
||||
current_block['timestamp'] = datetime.utcnow()
|
||||
current_block['proof'] += 1
|
||||
guess_hash = Blockchain.hash(current_block)
|
||||
|
||||
|
|
Loading…
Reference in New Issue