Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import os
- from os import listdir
- import hashlib
- block_dir = os.curdir + '/blockchain/' # ./blockchain/
- def get_files():
- files = os.listdir(block_dir)
- return sorted([int(i) for i in files])
- def get_hash(filename):
- file = open(block_dir + filename, 'rb').read() # читаем бинарно
- return hashlib.md5(file).hexdigest()
- def check_integrity():
- files = get_files()
- result = []
- for file in files[1:]: # минуем генезис блок
- f = open(block_dir + str(file))
- hash = json.load(f)['hash'] # читаем хеш
- prev_file = str(file - 1)
- actual_hash = get_hash(prev_file) # получаем новый блок и проверяем хеш
- if hash == actual_hash:
- res = 'Ok'
- else:
- res = 'Corrupted'
- result.append({'block': prev_file, 'result': res})
- return result
- def write_block(name, amount, to_whom, prev_hash=''):
- files = get_files()
- prev_file = files[-1] # сортируем номерные файлы
- file_name = str(prev_file + 1)
- prev_hash = get_hash(str(prev_file))
- data = {'name': name,
- 'amount': amount,
- 'to_whom': to_whom,
- 'hash': prev_hash
- }
- with open(block_dir + file_name, 'w') as file:
- json.dump(data, file, indent=4, ensure_ascii=False)
- def main():
- write_block(name='name', amount=0, to_whom='name')
- print(check_integrity())
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement