Skip to content

Commit

Permalink
Changed blockchain saving logic
Browse files Browse the repository at this point in the history
Fix: timestamp is not included when calculate genesis block (satwikkansal#59)
  • Loading branch information
SALTWOOD committed Nov 11, 2023
1 parent ac0d1be commit 19b3c80
Showing 1 changed file with 45 additions and 24 deletions.
69 changes: 45 additions & 24 deletions node_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
from hashlib import sha256
import json
import time

from flask import Flask, request
import requests
from multiprocessing import Process

directory = os.path.dirname(os.path.abspath(__file__))
os.chdir(directory)

class Block:
def __init__(self, index, transactions, timestamp, previous_hash, nonce=0):
Expand Down Expand Up @@ -43,29 +45,40 @@ def create_genesis_block(self):
the chain. The block has index 0, previous_hash as 0, and
a valid hash.
"""
genesis_block = Block(0, [], 0, "0")
genesis_block = Block(0, [], time.time(), "0")
genesis_block.hash = genesis_block.compute_hash()
self.chain.append(genesis_block)

@property
def last_block(self):
return self.chain[-1]
if len(self.chain) <= 0:
return None
else:
return self.chain[-1]

def add_block(self, block, proof):
def add_block(self, block : Block, proof):
"""
A function that adds the block to the chain after verification.
Verification includes:
* Checking if the proof is valid.
* The previous_hash referred in the block and the hash of latest block
in the chain match.
"""
previous_hash = self.last_block.hash

if previous_hash != block.previous_hash:
raise ValueError("Previous hash incorrect")

if not Blockchain.is_valid_proof(block, proof):
raise ValueError("Block proof invalid")
last_block = self.last_block

if block.index == 0: # if the block is a genesis block
self.chain.clear() # then give up all the blocks in the chain
block.hash = proof
self.chain.append(block)
return

if last_block is not None:
previous_hash = last_block.hash
if previous_hash != block.previous_hash:
raise ValueError("Previous hash incorrect")

if not Blockchain.is_valid_proof(block, proof):
raise ValueError("Block proof invalid")

block.hash = proof
self.chain.append(block)
Expand Down Expand Up @@ -174,8 +187,8 @@ def new_transaction():
def create_chain_from_dump(chain_dump):
generated_blockchain = Blockchain()
for idx, block_data in enumerate(chain_dump):
if idx == 0:
continue # skip genesis block
#if idx == 0:
#continue # skip genesis block
block = Block(block_data["index"],
block_data["transactions"],
block_data["timestamp"],
Expand Down Expand Up @@ -213,16 +226,23 @@ def exit_from_signal(signum, stack_frame):
signal.signal(signal.SIGTERM, exit_from_signal)
signal.signal(signal.SIGINT, exit_from_signal)


if chain_file_name is None:
data = None
else:
with open(chain_file_name, 'r') as chain_file:
raw_data = chain_file.read()
if raw_data is None or len(raw_data) == 0:
default_template = {"length":0,"chain":[],"peers":[]}
data = None
if chain_file_name is not None:
if os.path.exists(chain_file_name):
if chain_file_name is None:
data = None
else:
data = json.loads(raw_data)
with open(chain_file_name, 'r') as chain_file:
raw_data = chain_file.read()
if raw_data is None or len(raw_data) == 0:
data = None
else:
data = json.loads(raw_data)
else:
with open(chain_file_name,"w") as f:
f.write(json.dumps(default_template))
data = default_template

if data is None:
# the node's copy of blockchain
Expand All @@ -231,7 +251,6 @@ def exit_from_signal(signum, stack_frame):
blockchain = create_chain_from_dump(data['chain'])
peers.update(data['peers'])


# endpoint to request the node to mine the unconfirmed
# transactions (if any). We'll be using it to initiate
# a command to mine from our application itself.
Expand All @@ -247,7 +266,8 @@ def mine_unconfirmed_transactions():
if chain_length == len(blockchain.chain):
# announce the recently mined block to the network
announce_new_block(blockchain.last_block)
return "Block #{} is mined.".format(blockchain.last_block.index)
save_chain()
return "Block #{} is mined.".format(blockchain.last_block.index)


# endpoint to add new peers to the network.
Expand Down Expand Up @@ -362,4 +382,5 @@ def announce_new_block(block):
headers=headers)

# Uncomment this line if you want to specify the port number in the code
#app.run(debug=True, port=8000)
if __name__ == "__main__":
app.run(debug=True, port=8000,use_reloader=False)

0 comments on commit 19b3c80

Please sign in to comment.