Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #59 and some blockchain file save logic changes #68

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 36 additions & 16 deletions node_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from flask import Flask, request
import requests

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,13 +45,16 @@ 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):
"""
Expand All @@ -59,13 +64,21 @@ def add_block(self, block, proof):
* 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 @@ -170,12 +183,9 @@ def new_transaction():

chain_file_name = os.environ.get('DATA_FILE')


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
for idx, block_data in enumerate(chain_dump): # no longer need to skip genesis block
block = Block(block_data["index"],
block_data["transactions"],
block_data["timestamp"],
Expand Down Expand Up @@ -216,13 +226,18 @@ def exit_from_signal(signum, stack_frame):

if chain_file_name is None:
data = None
else:
elif os.path.exists(chain_file_name): # else if chain file exists
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: # else if chain file specfied but does not exists
blockchain = Blockchain()
data = None
with open(chain_file_name,"w") as chain_file:
chain_file.write(get_chain())

if data is None:
# the node's copy of blockchain
Expand All @@ -247,7 +262,7 @@ 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)
return "Block #{} is mined.".format(blockchain.last_block.index)


# endpoint to add new peers to the network.
Expand Down Expand Up @@ -322,6 +337,11 @@ def verify_and_add_block():
def get_pending_tx():
return json.dumps(blockchain.unconfirmed_transactions)

@app.route('/save', methods=['GET'])
def save():
save_chain()
return "Blockchain saved", 200


def consensus():
"""
Expand Down Expand Up @@ -362,4 +382,4 @@ 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)
#app.run(debug=True, port=8000)