Advertisement
Falexom

Untitled

Sep 20th, 2021
2,115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. import json
  2. import os
  3. from os import listdir
  4. import hashlib
  5.  
  6. block_dir = os.curdir + '/blockchain/'  # ./blockchain/
  7.  
  8.  
  9. def get_files():
  10.     files = os.listdir(block_dir)
  11.     return sorted([int(i) for i in files])
  12.  
  13.  
  14. def get_hash(filename):
  15.     file = open(block_dir + filename, 'rb').read()     # читаем бинарно
  16.     return hashlib.md5(file).hexdigest()
  17.  
  18.  
  19. def check_integrity():
  20.  
  21.     files = get_files()
  22.     result = []
  23.  
  24.     for file in files[1:]:  # минуем генезис блок
  25.         f = open(block_dir + str(file))
  26.         hash = json.load(f)['hash']   # читаем хеш
  27.  
  28.         prev_file = str(file - 1)
  29.         actual_hash = get_hash(prev_file)    # получаем новый блок и проверяем хеш
  30.  
  31.         if hash == actual_hash:
  32.             res = 'Ok'
  33.         else:
  34.             res = 'Corrupted'
  35.  
  36.         result.append({'block': prev_file, 'result': res})
  37.  
  38.     return result
  39.  
  40.  
  41. def write_block(name, amount, to_whom, prev_hash=''):
  42.  
  43.     files = get_files()
  44.     prev_file = files[-1]   # сортируем номерные файлы
  45.     file_name = str(prev_file + 1)
  46.  
  47.     prev_hash = get_hash(str(prev_file))
  48.  
  49.     data = {'name': name,
  50.             'amount': amount,
  51.             'to_whom': to_whom,
  52.             'hash': prev_hash
  53.             }
  54.  
  55.     with open(block_dir + file_name, 'w') as file:
  56.         json.dump(data, file, indent=4, ensure_ascii=False)
  57.  
  58.  
  59. def main():
  60.     write_block(name='name', amount=0, to_whom='name')
  61.     print(check_integrity())
  62.  
  63.  
  64. if __name__ == '__main__':
  65.     main()
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement