Python Proof of Work


SUBMITTED BY: Guest

DATE: May 30, 2013, 6:56 a.m.

FORMAT: Python

SIZE: 1.6 kB

HITS: 1057

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import hashlib
  4. import time
  5. import json
  6. block = {
  7. 'block_id': 1,
  8. 'difficulty': '00000'
  9. }
  10. def proof_of_work(block):
  11. start_time = time.time()
  12. sha_block = hashlib.sha256(block).digest()
  13. json_block = json.loads(block)
  14. diffu = json_block['difficulty']
  15. proof = 0
  16. while True:
  17. work = hashlib.sha256(sha_block + str(proof)).hexdigest()
  18. if work.startswith(diffu):
  19. finished_time = time.time()
  20. done_time = finished_time - start_time
  21. print '-------------------'
  22. print 'Difficulty:', diffu
  23. print 'Proof Number:', proof
  24. print 'Time:', done_time
  25. print '-------------------'
  26. break
  27. else:
  28. proof += 1
  29. return (block, proof)
  30. def verify_work(data):
  31. block, proof = data
  32. sha_block = hashlib.sha256(block).digest()
  33. json_block = json.loads(block)
  34. work = hashlib.sha256(sha_block + str(proof)).hexdigest()
  35. if work.startswith(str(json_block['difficulty'])):
  36. return True # Accepted
  37. else:
  38. return False # Rejected
  39. working = proof_of_work(json.dumps(block))
  40. verified = verify_work(working)
  41. if verified:
  42. print 'Block has been accepted!'
  43. else:
  44. print 'Block has been rejected!'

comments powered by Disqus