-
Notifications
You must be signed in to change notification settings - Fork 17
/
pos.py
313 lines (272 loc) · 10.5 KB
/
pos.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
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
"""
Python implementation of POW
Credit: https://github.com/mycoralhealth/blockchain-tutorial
"""
from datetime import datetime
import time
from hashlib import sha256
import json, requests
from random import randint
DATE = datetime.now()
GENESIS_BLOCK = {
"Index": 0,
"Timestamp": str(DATE),
"BPM": 0, #instead of transactions
"PrevHash": "",
"Validator": "" #address to receive the reward {validator, weight, age}
}
GENESIS_BLOCK2 = {
"Index": 0,
"Timestamp": str(DATE),
"BPM": 0, #instead of transactions
"PrevHash": "",
"Validator": "" #address to receive the reward {validator, weight, age}
}
GENESIS_BLOCK3 = {
"Index": 0,
"Timestamp": str(DATE),
"BPM": 0, #instead of transactions
"PrevHash": "",
"Validator": "" #address to receive the reward {validator, weight, age}
}
GENESIS_BLOCK4 = {
"Index": 0,
"Timestamp": str(DATE),
"BPM": 0, #instead of transactions
"PrevHash": "",
"Validator": "" #address to receive the reward {validator, weight, age}
}
class Blockchain(object):
def __init__(self, _genesisBlock, account):
"""
If the genesis block is valid, create chain
"""
self.blockChain = []
self.tempBlocks = []
#self.candidateBlocks = [] #constains block
self.myCurrBlock = {}
#self.announcements = []
self.validators = set() # stakers and balance
#self.unconfirmed_txns = []
self.nodes = set()
self.myAccount = {'Address': '', 'Weight': 0, 'Age': 0}
self.myAccount['Address'] = account['Address']
self.myAccount['Weight'] = account['Weight']
try:
genesisBlock = self.generate_genesis_block(_genesisBlock)
if self.is_block_valid(genesisBlock):
self.blockChain.append(genesisBlock)
else:
raise Exception('Unable to verify block')
except Exception as e:
print('Invalid genesis block.\nOR\n' + str(e))
def is_block_valid(self, block, prevBlock={}):
try:
_hash = block.pop('Hash')
except KeyError as e:
return False
try:
hash2 = self.hasher(block)
assert _hash == hash2
except AssertionError as e:
return False
prevHash = prevBlock['Hash'] if prevBlock else ''
block['Hash'] = _hash
if self.blockChain:
prevHash = self.blockChain[-1]['Hash'] if not prevHash else prevHash
try:
assert prevHash == block["PrevHash"]
except AssertionError as e:
if prevHash == self.blockChain[0]['Hash']:
block['Hash'] = _hash
return True
block['Hash'] = _hash
return False
block['Hash'] = _hash
return True
def generate_new_block(self, bpm=randint(53, 63), oldBlock='', address=''):
if self.myCurrBlock:
return self.myCurrBlock
prevHash = self.blockChain[-1]['Hash']
index = len(self.blockChain) if not oldBlock else oldBlock['Index'] + 1
address = self.get_validator(self.myAccount) if not address else address
newBlock = {
"Index": index,
"Timestamp": str(datetime.now()),
"BPM": bpm, #instead of transactions
"PrevHash": prevHash,
"Validator": address
}
newBlock["Hash"] = self.hasher(newBlock)
assert self.is_block_valid(newBlock)
self.myCurrBlock = newBlock
return newBlock
def get_blocks_from_nodes(self):
if self.nodes:
for node in self.nodes:
#resp = requests.get('http://{}/newblock'.format(node))
node.add_another_block(self.myCurrBlock)
resp = node.generate_new_block()
if self.is_block_valid(resp): #resp.json()
#self.tempBlocks.append(resp.json())
if not resp['Validator'] in self.validators:
self.tempBlocks.append(resp)
self.validators.add(resp['Validator'])
def add_another_block(self, another_block):
if self.is_block_valid(another_block):
if not another_block['Validator'] in self.validators:
self.tempBlocks.append(another_block)
self.validators.add(another_block['Validator'])
def pick_winner(self):
"""Creates a lottery pool of validators and choose the validator
who gets to forge the next block. Random selection weighted by amount of token staked
Do this every 30 seconds
"""
winner = []
self.tempBlocks.append(self.myCurrBlock)
self.validators.add(self.myCurrBlock['Validator'])
for validator in self.validators:
acct = (validator.rsplit(sep=', '))
acct.append(int(acct[1]) * int(acct[2]))
if winner and acct[-1]:
winner = acct if winner[-1] < acct[-1] else winner
else:
winner = acct if acct[-1] else winner
if winner:
return winner
for validator in self.validators:
acct = (validator.rsplit(sep=', '))
acct.append((int(acct[1]) + int(acct[2]))/len(acct[0]))
if winner:
winner = acct if winner[-1] < acct[-1] else winner
else:
winner = acct
return winner
def pos(self):
"""
#get other's stakes
#add owns claim
#pick winner
"""
print(str(self.myAccount) + ' =======================> Getting Valid chain\n')
self.resolve_conflict()
time.sleep(1)
self._pos()
print('***Calling other nodes to announce theirs***' + "\n")
time.sleep(1)
for node in self.nodes:
node._pos()
time.sleep(1)
for block in self.tempBlocks:
validator = block['Validator'].rsplit(', ')
if validator[0] == self.pick_winner()[0]:
new_block = block
break
else:
pass
print('New Block ====> ' + str(new_block) + "\n")
time.sleep(1)
self.add_new_block(new_block)
for node in self.nodes:
node.add_new_block(new_block)
print('Process ends' + "\n")
def announce_winner(self):
self.blockChain.append(self.myCurrBlock)
def add_new_block(self, block):
if self.is_block_valid(block):
#check index too
self.blockChain.append(block)
acct = block['Validator'].rsplit(', ')
if self.myAccount['Address'] != acct[0]:
self.myAccount['Age'] += 1
else:
self.myAccount['Weight'] += (randint(1, 10) * self.myAccount['Age'])
self.myAccount['Age'] = 0
self.tempBlocks = []
self.myCurrBlock = {}
self.validators = set()
def _pos(self):
print("Coming from ==========================> " + str(self.myAccount) + "\n")
time.sleep(1)
print('***Generating new stake block***' + "\n")
time.sleep(1)
self.generate_new_block()
print('***Exchanging temporary blocks with other nodes***' + "\n")
time.sleep(1)
self.get_blocks_from_nodes()
print('***Picking a winner***' + "\n")
time.sleep(1)
print("Winner is =======================> " + str(self.pick_winner()) + "\n")
def resolve_conflict(self):
for node in self.nodes:
if len(node.blockChain) > len(self.blockChain):
if self.is_chain_valid(node.blockChain):
print('***Replacing node***' + "\n")
self.blockChain = node.blockChain
return
print('***My chain is authoritative***' + "\n")
return
def is_chain_valid(self, chain):
_prevBlock = ''
for block in chain:
if self.is_block_valid(block, prevBlock=_prevBlock):
_prevBlock = block
else:
return False
return True
def add_new_node(self, new_node):
self.nodes.add(new_node)
new_node.add_another_node(self)
def add_another_node(self, another_node):
self.nodes.add(another_node)
@staticmethod
def hasher(block):
block_string = json.dumps(block, sort_keys=True).encode()
return sha256(block_string).hexdigest()
@staticmethod
def get_validator(address):
return ', '.join([address['Address'], str(address['Weight']), str(address['Age'])])
def generate_genesis_block(self, genesisblock):
address = {'Address': 'eltneg', 'Weight': 50, 'Age': 0}
address = self.get_validator(address)
genesisblock['Index'] = 0 if not genesisblock['Index'] else genesisblock['Index']
genesisblock['Timestamp'] = str(datetime.now()) if not genesisblock['Timestamp'] else genesisblock['Timestamp']
genesisblock['BPM'] = 0 if not genesisblock['BPM'] else genesisblock['BPM']
genesisblock['PrevHash'] = '0000000000000000'
genesisblock['Validator'] = address if not genesisblock['Validator'] else genesisblock['Validator']
genesisblock['Hash'] = self.hasher(genesisblock)
return genesisblock
def main():
"""Run test"""
account = {'Address': 'eltneg', 'Weight': 50}
account2 = {'Address': 'account2', 'Weight': 55}
account3 = {'Address': 'account3', 'Weight': 43}
account4 = {'Address': 'account4', 'Weight': 16}
blockchain = Blockchain(GENESIS_BLOCK, account)
blockchain.generate_new_block(52)
blockchain2 = Blockchain(GENESIS_BLOCK2, account2)
blockchain3 = Blockchain(GENESIS_BLOCK3, account3)
clients = [blockchain, blockchain2, blockchain3]
blockchain.add_new_node(blockchain2)
blockchain.add_new_node(blockchain3)
blockchain2.add_new_node(blockchain)
blockchain2.add_new_node(blockchain3)
blockchain.get_blocks_from_nodes()
blockchain2.get_blocks_from_nodes()
blockchain.pick_winner()
#check if temp blocks are same
blockchain.pos()
blockchain2.pos()
blockchain3.pos()
blockchain4 = Blockchain(GENESIS_BLOCK4, account4)
blockchain4.add_new_node(blockchain)
blockchain4.add_new_node(blockchain2)
blockchain4.add_new_node(blockchain3)
blockchain4.pos()
clients.append(blockchain4)
while True:
print('============================================ \n\n')
client = clients[randint(0, 3)]
client.pos()
if __name__ == '__main__':
main()