Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.46 KB | None | 0 0
  1. import hashlib
  2. import json
  3. from textwrap import dedent
  4. from time import time
  5. from uuid import uuid4
  6.  
  7. from flask import Flask, jsonify, request
  8.  
  9. class Blockchain(object):
  10.     def __init__(self):
  11.         self.chain = []
  12.         self.current_transactions = []
  13.  
  14.     def proof_of_work(self, last_proof):
  15.         """
  16.        Simple proof of work algorithm:
  17.        - Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous
  18.        - p is the previus proof, and p' is the new proof
  19.  
  20.        :param last_proof:<int>
  21.        :return:<int>
  22.        """
  23.  
  24.         proof = 0
  25.         while self.valid_proof(last_proof, proof) is False:
  26.             proof += 1
  27.  
  28.         return proof
  29.  
  30. # Instantiate our Node
  31. app = Flask(__name__)
  32.  
  33. #Generate a globally unique address for this node
  34. node_identifier = str(uuid4()).replace('-', '')
  35.  
  36. #instantate the blockchain
  37. blockchain = Blockchain()
  38.  
  39. @app.route('/mine', methods=['GET'])
  40. def mine():
  41.     return "We'll mine a new block"
  42.  
  43. @app.route('/transactions/new', methods=['POST'])
  44. def new_transaction():
  45.     return "We'll add a new transaction"
  46.  
  47. @app.route('/chain', methods=['GET'])
  48. def full_chain():
  49.     response = {
  50.         'chain': blockchain.chain,
  51.         'length': len(blockchain.chain),
  52.     }
  53.     return jsonify(response), 200
  54.  
  55. if __name__ == '__main__':
  56.     app.run(host='0.0.0.0', port=50000)
  57.  
  58.  
  59.     def new_block(self, proof, previous_hash):
  60.         """
  61.  
  62.        :param proof:<int> The proof given by the proof of the work algroithm
  63.        :param previous_hash: (optional) <str> Hash of the prevoious block
  64.        :return:<dict> New block
  65.        """
  66.         block = {
  67.             'index': len(self.chain) + 1,
  68.             'timestamp': time(),
  69.             'transactions': self.current_transactions,
  70.             'proof': proof,
  71.             'previous_hash': previous_hash or self.hash(self.chain[-1])
  72.         }
  73.  
  74.         self.current_transactions = []
  75.  
  76.         self.chain.append(block)
  77.         return block
  78.  
  79.     def new_transactions(self, sender, recipient, amount):
  80.         """
  81.        Creates a new transaction to go into the next mined block
  82.  
  83.        :param sender: <str> Adress of the sender
  84.        :param recipient:<str>Adress of the reciever
  85.        :param amount:<int> The amount
  86.        :return:<int> The index of the Block that will hold this transaction
  87.        """
  88.  
  89.         self.current_transactions.append({
  90.             'sender': sender,
  91.             'recipient': recipient,
  92.             'amount': amount,
  93.         })
  94.  
  95.         return self.last_block['index'] + 1
  96.  
  97.     @property
  98.     def last_block(self):
  99.         return self.chain[-1]
  100.  
  101.     @staticmethod
  102.     def valid_proof(last_proof, proof):
  103.         """
  104.        Validates the proof Does hash(last proof, proof) contain 4 leading zeroes?
  105.  
  106.        :param last_proof:<int> Previous proof
  107.        :param proof:<int> Current proof
  108.        :return:<bool> True if correct, False if not.
  109.        """
  110.  
  111.         guess = f'{last_proof}{proof}'.encode()
  112.         guess_hash = hashlib.sha256(guess).hexdiguest()
  113.         return guess_hash[:4] == "0000"
  114.  
  115.     def hash(block):
  116.         """
  117.        Creates a SHA-256 hash of a block
  118.  
  119.        :param block:<dict> Block
  120.        :return:<str>
  121.        """
  122.  
  123.         #We must make sure that the directory is ordered, or we'll have inconsistent hashes
  124.         block_string = json.dumps(block, sort_keys=True).encode()
  125.         return hashlib.sha_256(block_string).hexdigest()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement