-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.py
50 lines (40 loc) · 1.42 KB
/
blockchain.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import json
import hashlib
import collections
import pickle
import random
import string
import hashlib
import socket
import threading
import time
import sys
import os
from serverConstants import *
genesisString ="Genesis"
genesisHash = hashlib.sha256(genesisString.encode()).hexdigest()
def createNonce():
nonce = ''.join(random.choice(string.ascii_letters) for i in range(10))
return nonce
def newBlock(op_info):
global DEPTH
global genesisHash
nonce = createNonce()
hashable = op_info["op"] + op_info["key"] + op_info["value"] + nonce
curr_hash = hashlib.sha256(hashable.encode()).hexdigest()
while (curr_hash[-1] != "0" and curr_hash[-1] != "1" and curr_hash[-1] != "2"):
nonce = createNonce()
hashable = op_info["op"] + op_info["key"] + op_info["value"] + nonce
curr_hash = hashlib.sha256(hashable.encode()).hexdigest()
print(f"Found nonce: {nonce} for hash value: {curr_hash}")
hash_ptr = None
if len(BLOCKCHAIN) != 0:
hashable = BLOCKCHAIN[-1]["operation"]["key"] + BLOCKCHAIN[-1]["operation"]["value"] + BLOCKCHAIN[-1]["header"]["nonce"] + BLOCKCHAIN[-1]["header"]["hash"]
hash_ptr = hashlib.sha256(hashable.encode()).hexdigest()
else:
hash_ptr = genesisHash
block = {
"header": {"nonce": nonce, "hash": hash_ptr},
"operation": {"op": op_info["op"], "key": op_info["key"], "value": op_info["value"]}
}
return block