Created
September 24, 2022 17:44
-
-
Save EgorBron/379d90d58ecbd51c4ddb13428e7bf56e to your computer and use it in GitHub Desktop.
"Blockchain" on Python. Created using lessons by Oleg Molchanov (but code here is slightly improved and minified).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json as j, hashlib, os | |
def chinteg(): | |
res = [] | |
for f in [str(i) for i in sorted([int(ii) for ii in os.listdir('./blocks/')])][1:]: | |
h = j.load(fi:=open('./blocks/'+f, 'r'))['hash']; fi.close() | |
with open('./blocks/'+str(int(f)-1), 'rb') as fp: h2 = hashlib.md5(fp.read()).hexdigest() | |
res.append((int(f)-1, h2 == h)) | |
return res | |
def wbl(data: dict): | |
fp = sorted([int(ii) for ii in os.listdir('./blocks/')])[-1] | |
with open('./blocks/'+str(fp), 'rb') as f: data['hash'] = hashlib.md5(f.read()).hexdigest() | |
with open('./blocks/'+str(fp+1), 'w') as f: j.dump(data, f, ensure_ascii=False, indent=4) | |
def main(): | |
if not os.path.exists('./blocks/1'): | |
if not os.path.exists('./blocks'): os.mkdir('./blocks') | |
with open('1', 'w') as w: j.dump({}, w) | |
# chech integrity of blockchain | |
print(chinteg()) | |
# write block | |
wbl({'name': 'aaa', 'id': 'bbb'}) | |
if __name__ == "__main__": main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment