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

day 1 working #91

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
Binary file added .DS_Store
Binary file not shown.
93 changes: 78 additions & 15 deletions basic_block_gp/blockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,19 @@ def new_block(self, proof, previous_hash=None):
"""

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):
"""
Expand All @@ -46,7 +52,6 @@ def hash(self, block):
:param block": <dict> Block
"return": <str>
"""

# Use json.dumps to convert json into a string
# Use hashlib.sha256 to create a hash
# It requires a `bytes-like` object, which is what
Expand All @@ -56,17 +61,18 @@ def hash(self, block):
# or we'll have inconsistent hashes

# TODO: Create the block_string

string_object = json.dumps(block, sort_keys=True)
block_string = string_object.encode()
# TODO: Hash this string using sha256

raw_hash = hashlib.sha256(block_string)
# By itself, the sha256 function returns the hash in a raw string
# that will likely include escaped characters.
# 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

hash_string = raw_hash.hexdigest()
# TODO: Return the hashed block string in hexadecimal format
pass
return hash_string

@property
def last_block(self):
Expand All @@ -80,9 +86,12 @@ 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
black_string = json.dumps(block, sort_keys=True)
proof = 0

while self.valid_proof(black_string, proof) is False:
proof += 1
return proof

@staticmethod
def valid_proof(block_string, proof):
Expand All @@ -96,8 +105,13 @@ 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
print(f'i will now check if {proof} is valid')
guess = block_string + str(proof)
guess = guess.encode()
hash_value = hashlib.sha256(guess).hexdigest()
print(hash_value)
return hash_value[:4] == '0000'

# return True or False


Expand All @@ -111,23 +125,72 @@ def valid_proof(block_string, proof):
blockchain = Blockchain()


@app.route('/', methods=['GET'])
def hello_world():
response = {
'text': 'hello world'
}
return jsonify(response), 200


@app.route('/mine', methods=['GET'])
def mine():
# Run the proof of work algorithm to get the next proof

print('we shall now mine a block!')
proof = blockchain.proof_of_work(blockchain.last_block)
print(f'after a long process, we got a value {proof}')
# Forge the new Block by adding it to the chain with the proof
new_block = blockchain.new_block(proof)

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

return jsonify(response), 200


# @app.route('/mine', methods=['POST'])
# def mine():
# data = request.get_json()

# if 'proof' not in data or 'id' not in data:
# response = {
# 'message': 'you are missing some values'
# }
# return jsonify(response), 400
# new_proof = data.get('proof')

# block_string = json.dumps(blockchain.last_block, sort_keys=True)
# if blockchain.valid_proof(block_string, new_proof):

# previous_hash = blockchain.hash(blockchain.last_block)
# block = blockchain.new_block(new_proof, previous_hash)

# response = {
# 'message': 'Success'
# }
# return jsonify(response), 200

# else:
# response = {
# 'message': 'Proof was missing, incorrect, or too late'
# }
# return jsonify(response), 400


@app.route('/chain', methods=['GET'])
def full_chain():
response = {
# TODO: Return the chain and its current length
'len': len(blockchain.chain),
'chain': blockchain.chain
}
return jsonify(response), 200


@app.route('/last_block', methods=['GET'])
def last_block():
response = {
'last_block': blockchain.chain[-1]
}
return jsonify(response), 200

Expand Down
235 changes: 235 additions & 0 deletions client_mining_p/blockchain.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,237 @@
# Paste your version of blockchain.py from the basic_block_gp
# folder here
import hashlib
import json
from time import time
from uuid import uuid4

from flask import Flask, jsonify, request


class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []

# Create the genesis block
self.new_block(previous_hash=1, proof=100)

'''
:param sender: <str>
:param recipient: <str>
:param amount: <int>

:returns <int> the index of the block that will hold the new transaction
'''

def new_transaction(self, sender, recipient, amount):
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount
})

return self.last_block['index'] + 1

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 = {
'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
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
# Use hashlib.sha256 to create a hash
# It requires a `bytes-like` object, which is what
# .encode() does.
# It converts the Python string into a byte string.
# We must make sure that the Dictionary is Ordered,
# or we'll have inconsistent hashes

# TODO: Create the block_string
string_object = json.dumps(block, sort_keys=True)
block_string = string_object.encode()
# TODO: Hash this string using sha256
raw_hash = hashlib.sha256(block_string)
# By itself, the sha256 function returns the hash in a raw string
# that will likely include escaped characters.
# 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
hash_string = raw_hash.hexdigest()
# TODO: Return the hashed block string in hexadecimal format
return hash_string

@property
def last_block(self):
return self.chain[-1]

# def proof_of_work(self, block):
# """
# Simple Proof of Work Algorithm
# Stringify the block and look for a proof.
# Loop through possibilities, checking each one against `valid_proof`
# in an effort to find a number that is a valid proof
# :return: A valid proof for the provided block
# """
# black_string = json.dumps(block, sort_keys=True)
# proof = 0

# while self.valid_proof(black_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
leading zeroes? Return true if the proof is valid
:param block_string: <string> The stringified block to use to
check in combination with `proof`
:param proof: <int?> The value that when combined with the
stringified previous block results in a hash that has the
correct number of leading zeroes.
:return: True if the resulting hash is a valid proof, False otherwise
"""

guess = block_string + str(proof)
guess = guess.encode()
hash_value = hashlib.sha256(guess).hexdigest()
return hash_value[:3] == '000'

# return True or False


# Instantiate our Node
app = Flask(__name__)

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

# Instantiate the Blockchain
blockchain = Blockchain()


@app.route('/', methods=['GET'])
def hello_world():
response = {
'text': 'hello world'
}
return jsonify(response), 200


@app.route('/mine', methods=['POST'])
def mine():
data = request.get_json()
if 'id' and 'proof' not in data:
response = {
'message': 'you have missing values'
}
return jsonify(response), 400
proof = data['proof']
last_block = blockchain.last_block
block_string = json.dumps(last_block, sort_keys=True)

if blockchain.valid_proof(block_string, proof):
blockchain.new_transaction(
sender='0',
recipient=data['id'],
amount=1
)
new_block = blockchain.new_block(proof)
response = {
'block': new_block
}
return jsonify(response), 200
else:
response = {
'message': 'Proof is invalid'
}
return jsonify(response), 200
# block_string = json.dumps(blockchain.last_block, sort_keys=True)
# if blockchain.valid_proof(block_string, new_proof):

# previous_hash = blockchain.hash(blockchain.last_block)
# block = blockchain.new_block(new_proof, previous_hash)

# response = {
# 'message': 'Success'
# }
# return jsonify(response), 200

# else:
# response = {
# 'message': 'Proof was missing, incorrect, or too late'
# }
# return jsonify(response), 400


@app.route('/chain', methods=['GET'])
def full_chain():
response = {
'len': len(blockchain.chain),
'chain': blockchain.chain
}
return jsonify(response), 200


@app.route('/last_block', methods=['GET'])
def last_block():
response = {
'last_block': blockchain.chain[-1]
}
return jsonify(response), 200


@app.route('/new_transaction', methods=['POST'])
def new_transaction():
data = request.get_json()

if 'recipient' and 'amount' and 'sender' not in data:
response = {
'message': 'try again, you missed something'
}
return jsonify(response), 400

index = blockchain.new_transaction(
data['sender'], data['recipient'], data['amount'])
response = {
'message': f'you can view this transaction on block {index}'
}
return jsonify(response), 200


# Run the program on port 5000
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Loading