Guest User

Untitled

a guest
Jan 18th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import json
  2. import os
  3. import hashlib
  4.  
  5. blockchain_dir = os.curdir + '/blockchain/'
  6.  
  7.  
  8. def get_hash(filename):
  9. file = open(blockchain_dir + filename, 'rb').read()
  10. return hashlib.md5(file).hexdigest()
  11.  
  12. def get_files():
  13. files = os.listdir(blockchain_dir)
  14. return sorted([int(i) for i in files])
  15.  
  16. def check_integrity():
  17. files = get_files()
  18.  
  19. results = []
  20.  
  21. for file in files[1:]:
  22. f = open(blockchain_dir + str(file))
  23. h = json.load(f)['hash']
  24.  
  25. prev_file = str(file - 1)
  26. actual_hash = get_hash(prev_file)
  27.  
  28. if h == actual_hash:
  29. res = 'ok'
  30. else:
  31. res = 'Corrupted'
  32.  
  33. #print('block{} is: {}'.format(prev_file, res))
  34.  
  35. results.append({'block': prev_file, 'result': res})
  36.  
  37. return results
  38.  
  39. def write_block(name, amount, to_whom, prev_hash=''):
  40.  
  41. files = get_files()
  42. prev_file = files [-1]
  43.  
  44. filename = str(last_file + 1)
  45.  
  46. prev_hash = get_hash(str(prec_file))
  47.  
  48.  
  49. #print(filename)
  50.  
  51. data = {'name':name,
  52. 'amount': amount,
  53. 'to_whom': to_whom,
  54. 'hash': prev_hash}
  55.  
  56. with open(blockchain_dir + filename, 'w') as file:
  57. json.dump(data, file, indent=4, ensure_ascii=False)
  58.  
  59. def main ():
  60. #write_block(name='oleg2', amount=7, to_whom= 'ksu')
  61. print(check_integrity())
  62.  
  63.  
  64. if __name__ == '__main__':
  65. main()
Add Comment
Please, Sign In to add comment