Skip to content

Added logging and changed .gitignore to ignore log gile #70

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

Open
wants to merge 1 commit 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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
*.pyc
*.pyc

miner_log.txt
30 changes: 30 additions & 0 deletions simpleCoin/miner.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,22 @@
from flask import Flask, request
from multiprocessing import Process, Pipe
import ecdsa
import logging

from miner_config import MINER_ADDRESS, MINER_NODE_URL, PEER_NODES

node = Flask(__name__)

# logging
log = logging.getLogger('miner')

fh = logging.FileHandler('miner_log.txt')
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', '', '%')
fh.setFormatter(formatter)
log.addHandler(fh)

log.setLevel(logging.DEBUG)


class Block:
def __init__(self, index, timestamp, data, previous_hash):
Expand Down Expand Up @@ -41,13 +52,15 @@ def hash_block(self):
"""Creates the unique hash for the block. It uses sha256."""
sha = hashlib.sha256()
sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)).encode('utf-8'))
log.info('sha256 hash block created')
return sha.hexdigest()


def create_genesis_block():
"""To create each block, it needs the hash of the previous one. First
block has no previous, so it must be created manually (with index zero
and arbitrary previous hash)"""
log.info('genesis block created')
return Block(0, time.time(), {
"proof-of-work": 9,
"transactions": None},
Expand Down Expand Up @@ -78,9 +91,11 @@ def proof_of_work(last_proof, blockchain):
# If any other node got the proof, stop searching
new_blockchain = consensus(blockchain)
if new_blockchain:
logging.info('Another node got proof, new blockchain')
# (False: another node got proof first, new blockchain)
return False, new_blockchain
# Once that number is found, we can return it as a proof of our work
log.info('found proof of work: %d', incrementer)
return incrementer, blockchain


Expand All @@ -101,6 +116,7 @@ def mine(a, blockchain, node_pending_transactions):
# If we didn't guess the proof, start mining again
if not proof[0]:
# Update blockchain and save it to file
logging.info('No proof found, continue mining')
BLOCKCHAIN = proof[1]
a.send(BLOCKCHAIN)
continue
Expand All @@ -127,6 +143,9 @@ def mine(a, blockchain, node_pending_transactions):
NODE_PENDING_TRANSACTIONS = []
# Now create the new block
mined_block = Block(new_block_index, new_block_timestamp, new_block_data, last_block_hash)
log.info('New block created:\n\tINDEX: %d\n\tDATA: %s\n\tHASH: %s',
new_block_index, new_block_data, last_block_hash
)
BLOCKCHAIN.append(mined_block)
# Let the client know this node mined a block
print(json.dumps({
Expand Down Expand Up @@ -169,6 +188,7 @@ def consensus(blockchain):
return False
else:
# Give up searching proof, update chain and start over again
log.info('Updating chain, restarting process')
BLOCKCHAIN = longest_chain
return BLOCKCHAIN

Expand Down Expand Up @@ -200,6 +220,7 @@ def get_blocks():

# Send our chain to whomever requested it
chain_to_send = json.dumps(chain_to_send_json)
log.info('Sending chain to requester')
return chain_to_send


Expand All @@ -222,14 +243,19 @@ def transaction():
print("TO: {0}".format(new_txion['to']))
print("AMOUNT: {0}\n".format(new_txion['amount']))
# Then we let the client know it worked out
log.info('Successful transaction\n\tFROM: %s\n\tTO: %s\n\tAMOUNT: %d',
new_txion['from'], new_txion['to'], new_txion['amount']
)
return "Transaction submission successful\n"
else:
log.info('Transation failed due to invalid signature.')
return "Transaction submission failed. Wrong signature\n"
# Send pending transactions to the mining process
elif request.method == 'GET' and request.args.get("update") == MINER_ADDRESS:
pending = json.dumps(NODE_PENDING_TRANSACTIONS)
# Empty transaction list
NODE_PENDING_TRANSACTIONS[:] = []
log.info('Sending pending transactions to the mining process')
return pending


Expand All @@ -243,8 +269,10 @@ def validate_signature(public_key, signature, message):
vk = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key), curve=ecdsa.SECP256k1)
# Try changing into an if/else statement as except is too broad.
try:
log.info('Validating signature')
return vk.verify(signature, message.encode())
except:
log.info('Invalid signature')
return False


Expand All @@ -260,9 +288,11 @@ def welcome_msg():
if __name__ == '__main__':
welcome_msg()
# Start mining
log.info('Starting mining')
a, b = Pipe()
p1 = Process(target=mine, args=(a, BLOCKCHAIN, NODE_PENDING_TRANSACTIONS))
p1.start()
# Start server to receive transactions
log.info('Starting server')
p2 = Process(target=node.run(), args=b)
p2.start()