-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulator.py
370 lines (255 loc) · 12 KB
/
simulator.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 18 15:27:36 2018
@author: aviasayag
"""
import node
import epool
import block
import utils
import numpy as np
import time
import math
def print1(isPrint ,strToPrint):
if(isPrint):
print(strToPrint)
class EblockSimulator:
"""
Initial setup of the simulation.
1) create nodes each with the same epoolSample
2) create global epool by epoolSize
3) each node chooses its txs from the global epool (by its sample)
"""
def __init__(self, nodesNum, epoolSample, epoolSize, isPrint=1):
start = time.process_time()
self.isPrint = isPrint
self.nodesNum = nodesNum
self.nodesList = node.createNodes(nodesNum, epoolSample)
end = time.process_time()
print1(isPrint, "Time elapsed (createNodes): %s" % (end-start))
self.globalEpool = epool.createGlobalEpool(self.nodesList, epoolSize)
end = time.process_time()
print1(isPrint, "Time elapsed (createGlobalEpool): %s" % (end-start))
epool.chooseTXs(self.nodesList, self.globalEpool)
end = time.process_time()
print1(isPrint, "Time elapsed (chooseTXs): %s" % (end-start))
# print initial setup statisitics
print1(isPrint, "Total nodes: %s || Global epool size: %s" \
% (len(self.nodesList), len(self.globalEpool)))
print1(isPrint, "-----------------")
for nd in self.nodesList:
print1(isPrint, "Node %s: (epool size: %s), (epool sample: %s), (global epool portion: %s)" % \
(nd.index, nd.epoolSize, nd.sample, nd.portion))
print1(isPrint, "-----------------")
epoolCompareMat = utils.compareEpools(self.nodesList, isPrint)
avg = utils.meanMatrixWithoutDiagonal(epoolCompareMat)
np.fill_diagonal(epoolCompareMat, avg) # so min won't return 0
print1(isPrint, "avg epool diff: %s || max diff: %s || min diff: %s" % \
(avg, epoolCompareMat.max(), epoolCompareMat.min()))
print1(isPrint, "-----------------")
end = time.process_time()
print1(isPrint, "Time elapsed (initial setup): %s" % (end-start))
print1(isPrint, "-----------------")
print1(isPrint, "-----------------")
"""
Simulate the b txs with minimum hash
"""
def sim1(self, numTxInBlock):
print1(self.isPrint, "")
print1(self.isPrint, "==== Simulation 1 =====")
return genericSim(self.nodesList, self.isPrint, 0,
block.buildGoodEblock, numTxInBlock)
"""
Simulate the b txs with constant threshold
"""
def sim2(self, numTxInBlock, threshold):
print1(self.isPrint, "")
print1(self.isPrint, "==== Simulation 2A =====")
return genericSim(self.nodesList, self.isPrint, 0,
block.buildGoodEblockConstThreshold, numTxInBlock, threshold)
"""
Simulate the b txs with constant threshold .
Here, we check how many txs we could have insert
"""
def sim2B(self, threshold):
print1(self.isPrint, "")
print1(self.isPrint, "==== Simulation 2B =====")
return genericSim(self.nodesList, self.isPrint, 1,
epool.sliceEpoolByThreshold, threshold)
"""
Generic simulation
"""
def genericSim(nodesList, isPrint, isCount, func, *args):
start = time.process_time()
blocks = []
totalTxs = 0
# build block for each node
for nd in nodesList:
blockToAppend = func(nd, *args)
blocks.append(blockToAppend)
if isCount:
blockSize = len(blockToAppend)
totalTxs += blockSize
print1(isPrint, "Node %s txs under threshold: %s" % (nd.index, blockSize))
if isCount:
print1(isPrint, "under threshold (avg: %s)" % (totalTxs/len(blocks)))
blockCompMat = utils.compareBlocks(blocks, isPrint)
avg = utils.meanMatrixWithoutDiagonal(blockCompMat)
np.fill_diagonal(blockCompMat, avg) # so min won't return 0
mini = blockCompMat.min()
maxi = blockCompMat.max()
print1(isPrint, "avg block diff: %s || max diff: %s || min diff: %s" % \
(avg, maxi, mini))
print1(isPrint, "-----------------")
end = time.process_time()
print1(isPrint, "Time elapsed (sim): %s" % (end-start))
return (avg, mini, maxi)
class FairnessSimulator:
"""
Initial setup of the fairness simulation.
1) create nodes each with the same epoolSample.
2) the first node is byzantine, make its epool sample to be 100%, i.e., the byzantine knows all the
transactions.
3) create global epool by epoolSize. The byzantine node has more etx in the global epool by factor
of (byznatineNum/nodesNum)
4) each node chooses its txs from the global epool (by its sample)
"""
def __init__(self, nodesNum, byzantineNum, epoolSample, epoolSize, isPrint=1):
start = time.process_time()
self.globalEpoolSize = epoolSize
self.isPrint = isPrint
self.nodesNum = nodesNum
self.byzantineNum = byzantineNum
self.nodesList = node.createNodesWithSingleByzantine(nodesNum, byzantineNum, epoolSample)
end = time.process_time()
print1(isPrint, "Time elapsed (createNodes): %s" % (end-start))
self.globalEpool = epool.createGlobalEpool(self.nodesList, epoolSize)
end = time.process_time()
print1(isPrint, "Time elapsed (createGlobalEpool): %s" % (end-start))
epool.chooseTXs(self.nodesList, self.globalEpool)
end = time.process_time()
print1(isPrint, "Time elapsed (chooseTXs): %s" % (end-start))
# print initial setup statisitics
if(isPrint):
self.printInitialSetup(start)
def printInitialSetup(self, start):
isPrint = self.isPrint
print1(isPrint, "Total nodes: %s || Global epool size: %s" \
% (len(self.nodesList), len(self.globalEpool)))
print1(isPrint, "-----------------")
for nd in self.nodesList:
print1(isPrint, "Node %s: (epool size: %s), (epool sample: %s), (global epool portion: %s)" % \
(nd.index, nd.epoolSize, nd.sample, nd.portion))
print1(isPrint, "-----------------")
epoolCompareMat = utils.compareEpools(self.nodesList, isPrint)
avg = utils.meanMatrixWithoutDiagonal(epoolCompareMat)
np.fill_diagonal(epoolCompareMat, avg) # so min won't return 0
print1(isPrint, "avg epool diff: %s || max diff: %s || min diff: %s" % \
(avg, epoolCompareMat.max(), epoolCompareMat.min()))
print1(isPrint, "-----------------")
end = time.process_time()
print1(isPrint, "Time elapsed (initial setup): %s" % (end-start))
print1(isPrint, "-----------------")
print1(isPrint, "-----------------")
"""
All nodes construct valid Eblocks
"""
def allConstructValidEblocks(self, numTxInBlock, termNum=0):
print1(self.isPrint, "")
print1(self.isPrint, "==== Valid Eblock Construction =====")
start = time.process_time()
blocks = []
# build block for each node
for nd in self.nodesList:
blockToAppend = block.buildGoodEblock(nd, numTxInBlock, termNum)
nd.block = blockToAppend
blocks.append(blockToAppend)
blockCompList = utils.compareBlocksWithByzantine(blocks, self.isPrint)
avg = np.average(blockCompList[1:])
mini = np.min(blockCompList[1:])
maxi = np.max(blockCompList[1:])
print1(self.isPrint, "avg block diff: %s || max diff: %s || min diff: %s" % \
(avg, maxi, mini))
print1(self.isPrint, "-----------------")
end = time.process_time()
print1(self.isPrint, "Time elapsed (sim): %s" % (end-start))
return (avg, mini, maxi)
"""
After a Byzantine nodes constructed a valid Eblock it manipulates a
(1-beta)-fraction of its Eblock by removing all the etxs (that he is not the owner)
that have maximal hash value in its block and replacing it with it own.
"""
def byzantineManipulateItsBlock(self, beta, termNum=0):
byzantine = self.nodesList[0]
block = byzantine.block
blockSize = len(block)
# update epool without the blocks selected transactions
byzantineEpool = set(byzantine.epool).difference(block)
byzantineEpool = [i for i in byzantineEpool if i.source == 0]
sortedEpool = sorted(byzantineEpool, \
key=lambda tx: tx.sha256ToInt("%s" % (termNum)))
epoolSize = len(sortedEpool)
numOfTxsToReplace = math.ceil(blockSize * (1 - beta))
print1(self.isPrint, "replace %s txs" % (numOfTxsToReplace))
countReplaced = 0
blockIndex = blockSize-1
epoolIndex = 0
while (countReplaced < numOfTxsToReplace and blockIndex > -1
and epoolIndex < epoolSize):
# Replace only non-Byzantine txs
if block[blockIndex].source != 0:
block[blockIndex] = sortedEpool[epoolIndex]
epoolIndex += 1
countReplaced += 1
blockIndex -= 1
print1(self.isPrint, "%s txs replaced" % (countReplaced))
return block
"""
Each node validates the proposed Byzantine's Eblock by the beta parameter
(i.e., each of the nodes looks for at least beta-fraction intersection
between its Eblock to the Byzantine's Eblock).
Returns the number of nodes that negative validated the Eblock.
"""
def validateEblocks(self, beta):
txsDiffThreshold = math.ceil(len(self.nodesList[0].block) * (1 - beta))
print1(self.isPrint, "Validation threshold %s:" %(txsDiffThreshold))
blocks = []
# build block for each node
for nd in self.nodesList:
blocks.append(nd.block)
blockCompList = utils.compareBlocksWithByzantine(blocks, self.isPrint)
avg = np.average(blockCompList[1:])
mini = np.min(blockCompList[1:])
maxi = np.max(blockCompList[1:])
print1(self.isPrint, "avg block diff: %s || max diff: %s || min diff: %s" % \
(avg, maxi, mini))
notPassedValidation = list(map(lambda diff: 0 if diff <= txsDiffThreshold else 1, blockCompList))
print1(self.isPrint, notPassedValidation)
numOfNotPassed = sum(notPassedValidation)
print1(self.isPrint, "Number nodes that did not passed the block is %s " % (numOfNotPassed))
print1(self.isPrint, "-----------------")
return numOfNotPassed
"""
This function takes a block and extract it from each node's Epool
as well as the global Epool. Later, the global Epool and the nodes'
epools are being filled with new txs by each node's initial portion.
"""
def inputNewTxs(self, blockToExtract):
start = time.process_time()
# update all Epools without the extracted block
self.globalEpool = list(set(self.globalEpool).difference(blockToExtract))
for nd in self.nodesList:
nd.epool = list(set(nd.epool).difference(blockToExtract))
# Fill global Epool by each node portion
addToGlobalEpool = epool.createGlobalEpool(self.nodesList, len(blockToExtract))
self.globalEpool += addToGlobalEpool
# Add the new txs to each node epool by it sampling
epool.chooseTXs(self.nodesList, addToGlobalEpool)
if self.isPrint:
self.printInitialSetup(start)
"""
Returns nodes' distribution in the global Epool
"""
def getGlobalEpoolDist(self):
return epool.getNodesDistribution(self.globalEpool, self.nodesNum)