-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproofOfWork.py
More file actions
211 lines (159 loc) · 5.32 KB
/
proofOfWork.py
File metadata and controls
211 lines (159 loc) · 5.32 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import hashlib
import datetime
import json
import random
class Node:
def __init__(self):
self.address = 0
self.balance = 0
self.isMiner = False
self.chain = []
self.transactions = []
def proof(self, block):
difficulty = block['difficulty']
hash = hashlib.sha256(json.dumps(block).encode()).hexdigest()
if int(hash, 16) < int(difficulty, 16):
return True
return False
def recvBlock(self, block):
res = self.proof(block)
if res:
self.chain.append(block)
self.transactions = []
return res
def recvTransactions(self, transaction):
sender = transaction['from']
amount = transaction['amount']
to = transaction['to']
if sender == self.address:
if amount > self.balance:
return False
self.balance -= amount
if to == self.address:
self.balance += amount
self.transactions.append(transaction)
return True
def sendTo(self, to, amount):
transaction = {
'from': self.address,
'to': to,
'amount': amount
}
return transaction
class Miner(Node):
def __init__(self):
super().__init__()
self.isMiner = True
def getLeafs(self, transactions):
res = []
for i in range(0, len(transactions)):
hash = hashlib.sha256(json.dumps(transactions[i]).encode()).hexdigest()
res.append(hash)
return res
def getMrklRoot(self, transactions):
leafs = self.getLeafs(transactions)
if len(leafs) <= 0:
return ''
elif len(leafs) == 1:
return leafs[0]
while len(leafs) > 1:
hashA = leafs.pop(0)
hashB = leafs.pop(0)
hashC = hashlib.sha256(''.join([hashA, hashB]).encode()).hexdigest()
leafs.append(hashC)
return leafs[0]
def doMining(self):
time = self.chain[len(self.chain) - 1]['time'] + 600
block = {
'ver': 1,
'prev_hash': '',
'mrkl_root': self.getMrklRoot(self.transactions),
'time': time,
'difficulty': '0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'nonce': 0,
'transactions': []
}
prevHash = ''
if len(self.chain) > 0:
prevBlock = self.chain[len(self.chain) - 1]
prevHash = hashlib.sha256(json.dumps(prevBlock).encode()).hexdigest()
self.recvTransactions({
'from': 'None',
'to': self.address,
'amount': 50
})
block['transactions'] = self.transactions
block['prev_hash'] = prevHash
difficulty = block['difficulty']
while True:
hash = hashlib.sha256(json.dumps(block).encode()).hexdigest()
if int(hash, 16) < int(difficulty, 16):
break
block['nonce'] += 1
return block
nodes = []
nodeCount = 5
limit = 20
def getGenBlock():
block = {
'ver': 1,
'prev_hash': '',
'mrkl_root': '',
'time': datetime.datetime.now().timestamp(),
'difficulty': '0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'nonce': 0,
'transactions': []
}
difficulty = block['difficulty']
while True:
hash = hashlib.sha256(json.dumps(block).encode()).hexdigest()
if int(hash, 16) < int(difficulty, 16):
break
block['nonce'] += 1
return block
def init():
genBlock = getGenBlock()
miner = Miner()
miner.address = hashlib.sha256(str(0).encode()).hexdigest()
miner.recvBlock(genBlock)
nodes.append(miner)
for i in range(1, nodeCount):
node = Node()
node.address = hashlib.sha256(str(i).encode()).hexdigest()
node.recvBlock(genBlock)
nodes.append(node)
return True
def broadcastTransaction(transaction):
for i in range(0, nodeCount):
nodes[i].recvTransactions(transaction)
return True
def broadcastBlock(block):
for i in range(0, nodeCount):
nodes[i].recvBlock(block)
return True
init()
repeat = 0
while repeat < limit:
for i in range(0, nodeCount):
if random.randint(0, 1) > 0:
sender = nodes[i]
if sender.balance < 1:
continue
sel = i
while sel == i:
sel = random.randint(0, nodeCount - 1)
to = nodes[sel]
amount = random.randint(1, sender.balance)
transaction = sender.sendTo(to.address, amount)
broadcastTransaction(transaction)
miner = nodes[0]
candBlock = miner.doMining()
if broadcastBlock(candBlock):
print('+ Mining block ' + str(repeat + 1) + ' --------- ' + str(datetime.datetime.fromtimestamp(candBlock['time'])))
print('hash: ' + hashlib.sha256(json.dumps(candBlock).encode()).hexdigest())
print('nonce: ' + str(candBlock['nonce']))
repeat += 1
for c in nodes[0].chain:
print(c)
for node in nodes:
print(node.balance)