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
122 changes: 96 additions & 26 deletions basic_block_gp/blockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,24 @@ def __init__(self):
# Create the genesis block
self.new_block(previous_hash=1, proof=100)

def new_transaction(self, sender, recipient, amount):
"""
Creates a new transaction to go into the next mined Block

:param sender: <str> Address of the Recipient
:param recipient: <str> Address of the Recipient
:param amount: <int> Amount
:return: <int> The index of the BLock that will hold this transaction
"""
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
Expand All @@ -31,13 +49,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 +70,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,34 +79,25 @@ 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):
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
"""
# TODO
pass
# return proof

@staticmethod
def valid_proof(block_string, proof):
"""
Expand All @@ -97,8 +111,13 @@ def valid_proof(block_string, proof):
:return: True if the resulting hash is a valid proof, False otherwise
"""
# TODO
pass
# return True or False
# print(f"i will now check if {proof} is valid")
guess = block_string + str(proof)
guess = guess.encode()

hash_value = hashlib.sha256(guess).hexdigest()

return hash_value[:3] == '000'


# Instantiate our Node
Expand All @@ -111,27 +130,78 @@ def valid_proof(block_string, proof):
blockchain = Blockchain()


@app.route('/mine', methods=['GET'])
@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' not in data or 'proof' not in data:
response = {'message': 'missing values'}
return jsonify(response), 400
# Run the proof of work algorithm to get the next proof
# print("We shall now mine a block!")
proof = data['proof']
last_block = blockchain.last_block
block_string = json.dumps(last_block, sort_keys=True)

if blockchain.valid_proof(block_string, proof):
# lets mine a new block, and return a success!
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:
# respond with an error message
response = {
'message': 'Proof is invalid'
}
return jsonify(response), 200

# Forge the new Block by adding it to the chain with the proof

@app.route('/last_block', methods=['GET'])
def return_last_block():
response = {
# TODO: Send a JSON response with the new block
'last_block': blockchain.last_block
}

return jsonify(response), 200


@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('/transactions/new', methods=['POST'])
def new_transaction():
data = request.get_json()

# check that required fields are present
if 'recipient' not in data or 'amount' not in data or 'sender' not in data:
response = {'message' : 'Error: missing values'}
return jsonify(response), 400

# in the real world, we would probably want to verify that this transaction is legit
# for now, we can allow anyone to add whatever they want

# create the new transaction
index = blockchain.new_transaction(data['sender'], data['recipient'], data['amount'])
response = {'message': f'Transaction will be posted in block with index {index}'}
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=8000)
81 changes: 81 additions & 0 deletions basic_wallet_p/wallet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import requests
from argparse import ArgumentParser

def make_argparser() -> ArgumentParser:
"""
Parse command line arguments.
"""
parser = ArgumentParser(description='Find All Blockchain Transactions by ID')
parser.add_argument('id', type=str, help='Please enter a blockchain ID.')
# parser.add_argument('node', type=int, help='Please enter node address or press ENTER for default address of localhost:5000.')

return parser

def search_blockchain(id, chain) -> dict():
"""
Search the blockchain for an id and return all matching ids
"""


key_list = ['sent', 'received', 'all']
txt = {key : [] for key in key_list}
txt['balance'] = 0

for block in chain:
transactions = block['transactions']

for trans in transactions:

# print(trans)

flag = False

if trans['sender'] == id:
txt['sent'].append(trans)
flag = True
txt['balance'] -= trans['amount']

if trans['recipient'] == id:
txt['received'].append(trans)
flag = True
txt['balance'] += trans['amount']

if flag == True:
txt['all'].append(trans)


return txt




host = 'localhost:5000'

if __name__ == "__main__":
args = make_argparser().parse_args()



node = "http://localhost:8000"


r = requests.get(url=node + "/chain")
# Handle non-json response
try:
data = r.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(r)

blockchain = data['chain']

texts = search_blockchain(args.id, blockchain)

sent = texts['sent']
received = texts['received']
all_texts = texts['all']
balance = texts['balance']

print(f'''{args.id} has {len(all_texts)} total transactions on the blockchain with a balance of {balance}. \n
{len(sent)} send transactions: \n {sent} \n {len(received)} recieve transactions. \n {received}''')
29 changes: 21 additions & 8 deletions client_mining_p/miner.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ def proof_of_work(block):
in an effort to find a number that is a valid proof
:return: A valid proof for the provided block
"""
pass
block_string = json.dumps(block, sort_keys=True)
proof = 0
while valid_proof(block_string, proof) is False:
proof += 1

return proof


def valid_proof(block_string, proof):
Expand All @@ -27,7 +32,12 @@ def valid_proof(block_string, proof):
correct number of leading zeroes.
:return: True if the resulting hash is a valid proof, False otherwise
"""
pass
guess = block_string + str(proof)
guess = guess.encode()

hash_value = hashlib.sha256(guess).hexdigest()

return hash_value[:3] == '000'


if __name__ == '__main__':
Expand All @@ -37,6 +47,7 @@ def valid_proof(block_string, proof):
else:
node = "http://localhost:5000"

coins_mined = 0
# Load ID
f = open("my_id.txt", "r")
id = f.read()
Expand All @@ -56,15 +67,17 @@ def valid_proof(block_string, proof):
break

# TODO: Get the block from `data` and use it to look for a new proof
# new_proof = ???
new_proof = proof_of_work(data['last_block'])

# When found, POST it to the server {"proof": new_proof, "id": id}
post_data = {"proof": new_proof, "id": id}

r = requests.post(url=node + "/mine", json=post_data)
data = r.json()

# TODO: If the server responds with a 'message' 'New Block Forged'
# add 1 to the number of coins mined and print it. Otherwise,
# print the message from the server.
pass
print(data)
if 'block' in data:
# we have succeeded!
coins_mined += 1
print(f"Total coins mined: {coins_mined}")
else:
print(data['message'])
Loading