Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ requests = ">=2.20.0"
flask = ">=1.0.0"

[requires]
python_version = "3.7"
python_version = "3"
65 changes: 35 additions & 30 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 34 additions & 17 deletions basic_block_gp/blockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from flask import Flask, jsonify, request


class Blockchain(object):
def __init__(self):
self.chain = []
Expand All @@ -17,40 +16,48 @@ def __init__(self):
def new_block(self, proof, previous_hash=None):
"""
Create a new Block in the Blockchain

A block should have:
* Index
* Timestamp
* List of current transactions
* The proof used to mine this block
* The hash of the previous block

:param proof: <int> The proof given by the Proof of Work algorithm
:param previous_hash: (Optional) <str> Hash of previous Block
:return: <dict> New Block
"""

block = {
# TODO
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.last_block)
}

# Reset the current list of transactions
self.current_transactions = []
# Append the chain to the block
self.chain.append(block)
# Return the new block
pass
return block

def hash(self, block):
"""
Creates a SHA-256 hash of a Block

:param block": <dict> Block
"return": <str>
"""

# Use json.dumps to convert json into a string
string_block = json.dumps(block, sort_keys=True)
# Use hashlib.sha256 to create a hash
# It requires a `bytes-like` object, which is what
# .encode() does.
raw_hash = hashlib.sha256(string_block.encode())
# It converts the Python string into a byte string.
# We must make sure that the Dictionary is Ordered,
# or we'll have inconsistent hashes
Expand All @@ -64,9 +71,10 @@ def hash(self, block):
# This can be hard to read, but .hexdigest() converts the
# hash to a string of hexadecimal characters, which is
# easier to work with and understand
hex_hash = raw_hash.hexdigest()

# TODO: Return the hashed block string in hexadecimal format
pass
return hex_hash

@property
def last_block(self):
Expand All @@ -80,14 +88,18 @@ def proof_of_work(self, block):
in an effort to find a number that is a valid proof
:return: A valid proof for the provided block
"""
# TODO
pass
# return proof
block_string = json.dumps(block, sort_keys=True)

proof = 0
while self.valid_proof(block_string, proof) is False:
proof += 1

return proof

@staticmethod
def valid_proof(block_string, proof):
"""
Validates the Proof: Does hash(block_string, proof) contain 3
Validates the Proof: Does hash(block_string + proof) contain 3
leading zeroes? Return true if the proof is valid
:param block_string: <string> The stringified block to use to
check in combination with `proof`
Expand All @@ -96,14 +108,14 @@ def valid_proof(block_string, proof):
correct number of leading zeroes.
:return: True if the resulting hash is a valid proof, False otherwise
"""
# TODO
pass
# return True or False

guess = f'{block_string}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()

return guess_hash[:6] == "000000"

# Instantiate our Node
app = Flask(__name__)

# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')

Expand All @@ -114,11 +126,14 @@ def valid_proof(block_string, proof):
@app.route('/mine', methods=['GET'])
def mine():
# Run the proof of work algorithm to get the next proof
proof = blockchain.proof_of_work(blockchain.last_block)

# Forge the new Block by adding it to the chain with the proof
previous_hash = blockchain.hash(blockchain.last_block)
block = blockchain.new_block(proof, previous_hash)

response = {
# TODO: Send a JSON response with the new block
'new_block': block
}

return jsonify(response), 200
Expand All @@ -128,10 +143,12 @@ def mine():
def full_chain():
response = {
# TODO: Return the chain and its current length
'chain': blockchain.chain,
'length': len(blockchain.chain)
}
return jsonify(response), 200


# Run the program on port 5000
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
app.run(host='0.0.0.0', port=5000)
28 changes: 14 additions & 14 deletions client_mining_p/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@ Furthermore, the amount of work needed to actually mine a block is a bit low. W

*Server*
Modify the server we created to:
* Remove the `proof_of_work` function from the server.
* Change `valid_proof` to require *6* leading zeroes.
* Add an endpoint called `last_block` that returns the last block in the chain
* Modify the `mine` endpoint to instead receive and validate or reject a new proof sent by a client.
* It should accept a POST
* Use `data = request.get_json()` to pull the data out of the POST
* Note that `request` and `requests` both exist in this project
* Check that 'proof', and 'id' are present
* return a 400 error using `jsonify(response)` with a 'message'
* Return a message indicating success or failure. Remember, a valid proof should fail for all senders except the first.
d* Remove the `proof_of_work` function from the server.
d* Change `valid_proof` to require *6* leading zeroes.
d* Add an endpoint called `last_block` that returns the last block in the chain
d* Modify the `mine` endpoint to instead receive and validate or reject a new proof sent by a client.
d* It should accept a POST
d* Use `data = request.get_json()` to pull the data out of the POST
d* Note that `request` and `requests` both exist in this project
d* Check that 'proof', and 'id' are present
d* return a 400 error using `jsonify(response)` with a 'message'
d* Return a message indicating success or failure. Remember, a valid proof should fail for all senders except the first.

*Client Mining*
Create a client application that will:
* Get the last block from the server
* Run the `proof_of_work` function until a valid proof is found, validating or rejecting each attempt. Use a copy of `valid_proof` to assist.
* Print messages indicating that this has started and finished.
* Modify it to generate proofs with *6* leading zeroes.
d* Get the last block from the server
d* Run the `proof_of_work` function until a valid proof is found, validating or rejecting each attempt. Use a copy of `valid_proof` to assist.
d* Print messages indicating that this has started and finished.
d* Modify it to generate proofs with *6* leading zeroes.
* Print a message indicating the success or failure response from the server
* Add any coins granted to a simple integer total, and print the amount of coins the client has earned
* Continue mining until the app is interrupted.
Expand Down
Loading