-
Notifications
You must be signed in to change notification settings - Fork 2
/
month_builder.py
171 lines (146 loc) · 7.51 KB
/
month_builder.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
import candidate_builder as csb
import ancestor_builder as asb
import utils
import argparse
import datetime
import time
import logging
import os
import random
import sys
"""
The Monthbuilder class manages the global context across blocks.
The flow of this class is roughly:
1) Identify the starting height, set as current height
---
2) Load the diffpool for the current height
3) Merge txs from current mempool with the `globalMempool`, combining ancestry information
4) Remove confirmed transactions from the `globalMempool`
5) Instantiate a blockbuilder with a copy of the `globalMempool`
6) Build block, add selected transactions to the `confirmed_txs`
7) Increment height, repeat from 3)
"""
def main(argv):
parser = argparse.ArgumentParser(description='Build an alternative blockchain from a sequence of mempools and blocks.')
parser.add_argument('-a', '--asb', type=int, help='proportion of AncestorSetBlockbuilder being randomly chosen from sum of asb+csb', default=0, required=False)
parser.add_argument('-c', '--csb', type=int, help='proportion of CandidateSetBlockbuilder being randomly chosen from sum of asb+csb', default=0, required=False)
args = parser.parse_args()
asb_proportion = 0
csb_proportion = 0
if (args.asb == 0 and args.csb == 0):
print("Defaulting to ancestorset-based blockbuilding (`asb=1, csb=0`) since proportions were not specified")
asb_proportion = 1
csb_proportion = 0
else:
asb_proportion = args.asb
csb_proportion = args.csb
print("Blocks will be randomly drawn from (`asb= " + str(asb_proportion) + ", csb= " + str(csb_proportion) + "`)")
month_builder_start_time = datetime.datetime.now()
result_dir = 'results_' + utils.get_timestamp() + '_asb_' + str(asb_proportion) + '_csb_' + str(csb_proportion) + '/'
os.mkdir(result_dir)
logfile = result_dir + utils.get_timestamp() + '_monthbuilder.log'
logging.basicConfig(filename=logfile, level=logging.INFO)
logging.info("Starttime: " + month_builder_start_time.isoformat())
logging.info("Making " + str(asb_proportion) + " ancestorset blocks per " + str(csb_proportion) + " candidateset blocks.")
mb = Monthbuilder(".", result_dir)
mb.loadCoinbaseSizes()
while(True):
mb.getNextBlockHeight()
blockfileName = ''
files = os.listdir(mb.pathToMonth)
for f in files:
if f.startswith(str(mb.height)):
blockfileName = f.split('.')[0]
break
if blockfileName == '':
logging.info('Height ' + str(mb.height) + ' not found, done')
break
logging.info("Starting block: " + blockfileName)
block_start_time = time.time()
mb.loadBlockMempool(blockfileName)
mb.runBlockWithGlobalMempool(asb_proportion, csb_proportion)
block_end_time = time.time()
logging.info('building ' + blockfileName + ' elapsed time: ' + str(block_end_time - block_start_time))
month_builder_end_time = datetime.datetime.now()
logging.info("Endtime: " + str(month_builder_end_time) + ', total elapsed time: ' + str(month_builder_end_time - month_builder_start_time))
class Monthbuilder():
def __init__(self, monthPath, result_dir="results/"):
self.pathToMonth = monthPath
self.globalMempool = csb.Mempool()
self.confirmed_txs = set()
self.height = -1
self.coinbaseSizes = {}
self.result_dir = result_dir
def removeSetOfTxsFromMempool(self, txsSet, mempool):
try:
for k in txsSet:
mempool.dropTx(k)
except KeyError:
logging.error("tx to delete not found" + k)
return mempool
def loadBlockMempool(self, blockId):
fileFound = 0
for file in os.listdir(self.pathToMonth):
if file.endswith(blockId+'.diffpool'):
fileFound = 1
blockMempool = csb.Mempool()
blockMempool.fromTXT(os.path.join(self.pathToMonth, file), False) # Do not backfill relatives on loading diffpool, ancestors may not be present
blockTxsSet = set(blockMempool.txs.keys())
for k in blockMempool.txs.keys():
if (k in self.globalMempool.txs):
raise Exception(k + ' loaded from .diffpool, but already in globalMempool')
self.globalMempool.txs[k] = blockMempool.txs[k]
self.globalMempool.backfill_relatives(self.confirmed_txs) # Ensure that all ancestors, children and descendants are set after merging global and block mempool
for k in set(self.globalMempool.txs.keys()).intersection(self.confirmed_txs):
self.globalMempool.removeConfirmedTx(k)
logging.debug("Global Mempool after loading block: " + str(self.globalMempool.txs.keys()))
if fileFound == 0:
raise Exception("Diffpool for " + blockId + " not found")
def loadCoinbaseSizes(self):
for file in os.listdir(self.pathToMonth):
if file.endswith('.coinbases'):
with open(os.path.join(self.pathToMonth, file), 'r') as coinbaseSizes:
for line in coinbaseSizes:
lineItems = line.split(' ')
self.coinbaseSizes[int(lineItems[0])] = lineItems[1].rstrip('\n')
coinbaseSizes.close()
logging.debug("CoinbaseSizes: " + str(self.coinbaseSizes))
if len(self.coinbaseSizes) == 0:
raise Exception('Coinbase file not found, please run `preprocessing.py`')
def runBlockWithGlobalMempool(self, asb_proportion=0, csb_proportion=1):
start_time = time.time()
coinbaseSizeForCurrentBlock = self.coinbaseSizes[self.height]
logging.info("Current height: " + str(self.height))
weightAllowance = 4000000 - int(coinbaseSizeForCurrentBlock)
logging.debug("Current weightAllowance: " + str(weightAllowance))
logging.debug("Global Mempool before BB(): " + str(self.globalMempool.txs.keys()))
builder_type = ''
builder = None
if (random.randint(1, asb_proportion + csb_proportion) <= asb_proportion):
builder_type = 'ASB'
builder = asb.AncestorSetBlockbuilder(self.globalMempool, weightAllowance)
else:
builder_type = 'CSB'
builder = csb.CandidateSetBlockbuilder(self.globalMempool, weightAllowance)
logging.debug("Block Mempool after BB(): " + str(builder.mempool.txs.keys()))
selectedTxs = builder.buildBlockTemplate()
logging.debug("selectedTxs: " + str(selectedTxs))
self.confirmed_txs = set(selectedTxs).union(self.confirmed_txs)
builder.outputBlockTemplate(self.height, self.result_dir) # TODO: Height+blockhash?
endTime = time.time()
logging.info('runBlockWithGlobalMempool() [' + builder_type + '] elapsed time: ' + str(endTime - start_time))
def getNextBlockHeight(self):
## Assume that there are mempool files in folder and they are prefixed with a _seven_ digit block height
if self.height > 0:
self.height = int(self.height) + 1
return self.height
else:
dirContent = os.listdir(self.pathToMonth)
onlymempool = [f for f in dirContent if f.endswith('.mempool')]
onlymempool.sort()
if 0 == len(onlymempool):
raise Exception("No mempool files found")
self.height = int(onlymempool[0][0:6])
return self.height
if __name__ == '__main__':
main(sys.argv[1:])