Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. from datetime import datetime
  2. import hashlib as hasher
  3.  
  4.  
  5. class Block:
  6. def __init__(self, index, timestamp, data, previous_hash):
  7. self.index = index
  8. self.timestamp = timestamp
  9. self.data = data
  10. self.previous_hash = previous_hash
  11. self.hash = self.hash_block()
  12.  
  13. def __str__(self):
  14. return 'Block #{}'.format(self.index)
  15.  
  16. def hash_block(self):
  17. sha = hasher.sha256()
  18. seq = (str(x) for x in (
  19. self.index, self.timestamp, self.data, self.previous_hash))
  20. sha.update(''.join(seq).encode('utf-8'))
  21. return sha.hexdigest()
  22.  
  23.  
  24. def make_genesis_block():
  25. """Make the first block in a block-chain."""
  26. block = Block(index=0,
  27. timestamp=datetime.now(),
  28. data="Genesis Block",
  29. previous_hash="0")
  30. return block
  31.  
  32.  
  33. def next_block(last_block, data=''):
  34. """Return next block in a block chain."""
  35. idx = last_block.index + 1
  36. block = Block(index=idx,
  37. timestamp=datetime.now(),
  38. data='{}{}'.format(data, idx),
  39. previous_hash=last_block.hash)
  40. return block
  41.  
  42.  
  43. def test_code():
  44. """Test creating chain of 20 blocks."""
  45. blockchain = [make_genesis_block()]
  46. prev_block = blockchain[0]
  47. for _ in range(0, 20):
  48. block = next_block(prev_block, data='some data here')
  49. blockchain.append(block)
  50. prev_block = block
  51. print('{} added to blockchain'.format(block))
  52. print('Hash: {}\n'.format(block.hash))
  53.  
  54.  
  55. # run the test code
  56. test_code()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement