Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. import hashlib
  2. import json
  3. from time import time
  4.  
  5.  
  6. class Blockchain(object):
  7. def __init__(self):
  8. self.current_transactions = []
  9. self.chain = []
  10.  
  11. # Create the genesis block
  12. genesis_block = self.new_block(previous_hash=1, proof=100)
  13. self.chain.append(genesis_block)
  14.  
  15. def new_block(self, proof, previous_hash=None):
  16. """
  17. Create a new Block in the Blockchain
  18.  
  19. :param proof: <int> The proof given by the Proof of Work algorithm
  20. :param previous_hash: (Optional) <str> Hash of previous Block
  21. :return: <dict> New Block
  22. """
  23.  
  24. block = {
  25. 'index': len(self.chain) + 1,
  26. 'timestamp': time(),
  27. 'transactions': self.current_transactions,
  28. 'proof': proof,
  29. 'previous_hash': previous_hash or self.chain[-1]['hash'],
  30. }
  31.  
  32. # Calculate the hash of this new Block
  33. block['hash'] = self.hash(block)
  34.  
  35. # Reset the current list of transactions
  36. self.current_transactions = []
  37.  
  38. self.chain.append(block)
  39. return block
  40.  
  41. def new_transaction(self, sender, recipient, amount):
  42. """
  43. Creates a new transaction to go into the next mined Block
  44.  
  45. :param sender: <str> Address of the Sender
  46. :param recipient: <str> Address of the Recipient
  47. :param amount: <int> Amount
  48. :return: <int> The index of the Block that will hold this transaction
  49. """
  50. self.current_transactions.append({
  51. 'sender': sender,
  52. 'recipient': recipient,
  53. 'amount': amount,
  54. })
  55.  
  56. return self.last_block['index'] + 1
  57.  
  58. @property
  59. def last_block(self):
  60. return self.chain[-1]
  61.  
  62. @staticmethod
  63. def hash(block):
  64. """
  65. Creates a SHA-256 hash of a Block
  66.  
  67. :param block: <dict> Block
  68. :return: <str>
  69. """
  70.  
  71. block_string = json.dumps(block).encode()
  72. return hashlib.sha256(block_string).hexdigest()
  73.  
  74. @staticmethod
  75. def proof_of_work(last_proof):
  76. # The algorithm used to mine new blocks
  77. pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement