Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import hashlib
- import json
- from textwrap import dedent
- 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 = []
- def proof_of_work(self, last_proof):
- """
- Simple proof of work algorithm:
- - Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous
- - p is the previus proof, and p' is the new proof
- :param last_proof:<int>
- :return:<int>
- """
- proof = 0
- while self.valid_proof(last_proof, proof) is False:
- proof += 1
- return proof
- # Instantiate our Node
- app = Flask(__name__)
- #Generate a globally unique address for this node
- node_identifier = str(uuid4()).replace('-', '')
- #instantate the blockchain
- blockchain = Blockchain()
- @app.route('/mine', methods=['GET'])
- def mine():
- return "We'll mine a new block"
- @app.route('/transactions/new', methods=['POST'])
- def new_transaction():
- return "We'll add a new transaction"
- @app.route('/chain', methods=['GET'])
- def full_chain():
- response = {
- 'chain': blockchain.chain,
- 'length': len(blockchain.chain),
- }
- return jsonify(response), 200
- if __name__ == '__main__':
- app.run(host='0.0.0.0', port=50000)
- def new_block(self, proof, previous_hash):
- """
- :param proof:<int> The proof given by the proof of the work algroithm
- :param previous_hash: (optional) <str> Hash of the prevoious 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.chain[-1])
- }
- self.current_transactions = []
- self.chain.append(block)
- return block
- def new_transactions(self, sender, recipient, amount):
- """
- Creates a new transaction to go into the next mined block
- :param sender: <str> Adress of the sender
- :param recipient:<str>Adress of the reciever
- :param amount:<int> The 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
- @property
- def last_block(self):
- return self.chain[-1]
- @staticmethod
- def valid_proof(last_proof, proof):
- """
- Validates the proof Does hash(last proof, proof) contain 4 leading zeroes?
- :param last_proof:<int> Previous proof
- :param proof:<int> Current proof
- :return:<bool> True if correct, False if not.
- """
- guess = f'{last_proof}{proof}'.encode()
- guess_hash = hashlib.sha256(guess).hexdiguest()
- return guess_hash[:4] == "0000"
- def hash(block):
- """
- Creates a SHA-256 hash of a block
- :param block:<dict> Block
- :return:<str>
- """
- #We must make sure that the directory is ordered, or we'll have inconsistent hashes
- block_string = json.dumps(block, sort_keys=True).encode()
- return hashlib.sha_256(block_string).hexdigest()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement