Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. import hashlib as hasher
  2. import datetime as date
  3.  
  4. class Block:
  5. def __init__(self, index, timestamp, data, previous_hash):
  6. self.index = index
  7. self.timestamp = timestamp
  8. self.data = data
  9. self.previous_hash = previous_hash
  10. self.hash = self.hash_block()
  11.  
  12. def hash_block(self):
  13. sha = hasher.sha256()
  14. sha.update((str(self.index) +
  15. str(self.timestamp) +
  16. str(self.data) +
  17. str(self.previous_hash)).encode()) #change here
  18. return sha.hexdigest()
  19.  
  20. def create_genesis_block():
  21. # Manually construct a block with
  22. # index zero and arbitrary previous hash
  23. return Block(0, date.datetime.now(), "Genesis Block", "0")
  24.  
  25. def next_block(last_block):
  26. this_index = last_block.index + 1
  27. this_timestamp = date.datetime.now()
  28. this_data = "Hey! I'm block " + str(this_index)
  29. this_hash = last_block.hash
  30. return Block(this_index, this_timestamp, this_data, this_hash)
  31.  
  32. # Create the blockchain and add the genesis block
  33. blockchain = [create_genesis_block()]
  34. previous_block = blockchain[0]
  35.  
  36. # How many blocks should we add to the chain
  37. # after the genesis block
  38. num_of_blocks_to_add = 20
  39.  
  40. # Add blocks to the chain
  41. for i in range(0, num_of_blocks_to_add):
  42. block_to_add = next_block(previous_block)
  43. blockchain.append(block_to_add)
  44. previous_block = block_to_add
  45. # Tell everyone about it!
  46. print ("Block #{} has been added to the blockchain!".format(block_to_add.index))
  47. print ("Hash: {}\n".format(block_to_add.hash))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement