/
chain.py
446 lines (348 loc) · 11.6 KB
/
chain.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# -*- coding: utf-8 -*-
"""
Classes to handle Chain and acceess to .dat files. Also includes examples and
quick tests
"""
# %% Imports
import mmap
import pickle
import numpy as np
import pandas as pd
from pybit.py3.block import Block
from pybit.py3.common import Export
from pybit.pyx.utils import tqdm_off
# Optional import for pretty waitbars
try:
from tqdm import tqdm
print("Imported tqdm")
except ImportError:
tqdm = tqdm_off
# %% High level classes
class Dat(Export):
"""
Class to represent .dat file on disk.
Opens and maps .dat ready for reading
"""
_index = -1
def __init__(self, path: str, f: str,
verb: int=2,
defer_printing: int=0,
**kwargs) -> None:
"""Initialise Dat.
Preallocate attributes.
Args:
path: Path to folder containing .dats eg. "Blocks/"
fn: File name of .dat eg. "blk0000.dat"
verb: Control verbosity of printing. Level 2 (default)
prints Dat level updates (ie. not detailed block
or trans info.)
defer_printing: Don't print anything until block
n then print at level specified by verb.
**kwargs: Args to pass on to Block and Trans classes when used.
"""
# Increment Dat counter and remember which one this is
Dat._index += 1
self.index = Dat._index
self.f = f
self.path = path
self.mmap = None
self.length = 0
self.prepare_mem()
self.cursor = 0
self.blocks = {}
self.nBlock = -1
self.verb = verb
self.defer_printing = defer_printing
self.block_kwargs = kwargs
self.validateBlocks = kwargs.get('validateBlocks', True)
def __repr__(self) -> str:
"""
Overload __repr__.
Identify as filename and cursor location.
"""
s = f"dat: {self.f} @ {self.cursor}"
return s
def __str__(self) -> str:
"""
Overload __str__.
Return __repr__ and number of blocks loaded.
"""
s = f"{self.__repr__()}"\
f"Loaded: {self.nBlock}"
return s
def _print(self):
"""Print after checking verbosity level."""
if self.verb >= 2:
print(self)
def prepare_mem(self) -> None:
"""Open file, map, reset cursor.
TODO:
- Test this function, might need updating
"""
with open(self.path + self.f, 'rb') as fo:
self.mmap = mmap.mmap(fo.fileno(), 0,
access=mmap.ACCESS_READ)
# Reset cursor and block count
self.cursor = 0
self.length = len(self.mmap)
Block._index = -1
def read_next_block(self,
n: int=1,
tqdm_on=True) -> None:
"""
Read and return the next block.
Args:
n: NUmber of blocks to read. Default 1.
tqdm_on: Use tqdm waitbar (if available). Default True.
Track cursor position.
"""
# If verb is low,
# tqdm is not specifically turned off,
# and available.
if tqdm_on:
# Note if tqdm isn't available, it'll use the placeholder
# function which does nothing
tqdm_runner = tqdm
else:
tqdm_runner = tqdm_off
for _ in tqdm_runner(range(n)):
# Check progress to control printing
# If verb is >0 tqdm will already have been turned off in Chain
if Block._index+1 >= self.defer_printing:
# Allow printing
verb = self.verb
else:
# Keep off for now
verb = 0
# Create Block object
b = Block(self.mmap, self.cursor,
f=self.path+self.f,
verb=verb,
**self.block_kwargs)
# Read it
b.read_block()
# Validate, if on
if self.validateBlocks:
b.api_verify()
self.cursor = b.end
self.nBlock += 1
# Save block dat object - unordered at this point
# self.blocks[self.nBlock] = b
self.blocks[b.index] = b
if self.verb == 2:
print(f"{self.verb*' '*2}Read block {self.nBlock}")
def read_all(self) -> None:
"""
Read all blocks in .dat.
Reads one by one until end is found.
"""
nBlock = 0
pbar = tqdm(total=int(self.length),
unit_divisor=1024)
while self.cursor < self.length:
# Read next block without waitbars
self.read_next_block(tqdm_on=False)
# And update this one manually
pbar.update(np.around(
(self.blocks[nBlock].end - self.blocks[nBlock].start),
4).astype(np.int))
nBlock += 1
if self.verb >= 2:
print(f"\nRead {nBlock} blocks")
def blocks_to_pandas(self) -> pd.DataFrame:
"""
Output all loaded blocks to pandas df.
Not particularly efficient.
"""
df = pd.DataFrame()
# For each loaded block
for v in self.blocks.values():
# Get pandas row for block
b = v.to_pandas()
# Concat to data frame
df = pd.concat((df, b),
axis=0)
return df
def trans_to_pandas_(self) -> pd.DataFrame:
"""
Output all loaded trans to pandas df (abridged version).
Loops over loaded (or mapped) blocks and calls
trans_to_pandas_() private method.
Not particularly efficient.
"""
df = pd.DataFrame()
# For each block
for v in self.blocks.values():
# Get pandas rows for block transactions
ts = v.trans_to_pandas_()
# Concat to data frame
df = pd.concat((df, ts),
axis=0)
return df
def trans_to_pandas(self) -> None:
"""
Output all loaded trans to pandas df.
Loops over loaded (or mapped) blocks and calls
trans_to_pandas() method.
Not particularly efficient.
"""
df = pd.DataFrame()
for v in self.blocks.values():
# Get pandas rows for block transactions
b = v.trans_to_pandas()
# Concat to data frame
df = pd.concat((df, b),
axis=0)
return df
def to_pic(self,
fn: str='test.pic') -> None:
"""
Serialize Dat to pickle object.
Need to run through children objects recursively to
remove the (redundant) mmaps, which can't be serialized.
(Not working?)
"""
# Can't pickle .mmap objects
out = self
out.mmap = []
for bk in out.blocks.keys():
# From block
out.blocks[bk].mmap = []
for tk in out.blocks[bk].trans.keys():
# From transaction
out.blocks[bk].trans[tk].mmap = []
for ti in range(len(out.blocks[bk].trans[tk].txIn)):
# From TxIns
out.blocks[bk].trans[tk].txIn[ti].mmap = []
for to in range(len(out.blocks[bk].trans[tk].txIn)):
# From TxOuts
out.blocks[bk].trans[tk].txOut[to].mmap = []
p = open(fn, 'wb')
pickle.dump(out, p)
class Chain():
"""Class to handle chain and loading from .dat files."""
def __init__(self,
path: str='Blocks/',
datStart: int=0,
datn: int=10,
verb: int=1,
outputPath: str=None,
**kwargs) -> None:
"""
Initialise Chain object.
Args:
path: Path to folder containing .dats eg. "Blocks/"
fn: File name of .dat eg. "blk0000.dat"
verb: Control verbosity of printing. Level 1 (default)
prints Chain level updates (ie. not detailed Dat, Block
or Trans info.)
**kwargs: Args to pass on to Dat, Block, and Trans
classes when used.
"""
self.datStart = datStart
self.datn = datn
self.datEnd = datStart+datn
self.datPath = path
self.verb = verb
self.datni = -1
self.dats = {}
self.on = datStart
self.outputPath = outputPath
self.dat_kwargs = kwargs
def __repr__(self) -> str:
"""
Overload __str__.
Return __repr__ path and range.
"""
s = f"Chain over {self.datPath} {self.datStart} - {self.datEnd}"
return s
def read_next_Dat(self) -> None:
"""
Read next .dat, track progress.
Can move past specified end.
"""
d = self.readDat(datn=self.on)
d.read_all()
self.dats[self.on] = d
self.on += 1
def readDat(self, datn: int) -> Dat:
"""
Read block specified by file number.
Args:
datn: Integer identifier for file. Used to generate name.
eg. 1 -> "blk0001.dat".
"""
fn = "blk{0:05d}.dat".format(datn)
if self.verb >= 1:
print(fn)
d = Dat(path=self.datPath,
f=fn,
verb=self.verb,
**self.dat_kwargs)
self.datni += 1
return d
def read_all(self) -> None:
"""
Read all (or specified range of) blocks in .dat.
Limited range specified by datStart -> datStart+datn
when initializing Chain object.
"""
# Read requested range
for fi in range(self.datStart,
self.datStart+self.datn):
d = self.readDat(datn=fi)
d.read_all()
if self.outputPath is not None:
# Save dat and transactions to csv
print(f"Saving blocks to {self.outputPath}")
d.blocks_to_pandas().to_csv(
self.outputPath + d.f + "_blocks.csv",
index=False)
print(f"Saving trans to {self.outputPath}")
d.trans_to_pandas().to_csv(
self.outputPath + d.f + "_trans.csv",
index=False)
# For now:
# Save dat contents to Chain (dats ordered, blocks not)
print(d)
self.dats[d.index] = d
if __name__ == "__main__":
"""
Examples and tests.
"""
# %% Load .dat
path = 'Blocks/'
f = 'blk00001.dat'
dat = Dat(path, f,
verb=6)
# Read first block
dat.read_next_block()
# Verify it's correct (this may already have been done on import)
dat.blocks[0].api_verify()
# Output block data as dict
dat.blocks[0].to_dict()
# %% Read another 10 blocks and export
# Read block
dat.read_next_block(10)
# Export to pandas df
blockTable = dat.blocks_to_pandas()
blockTable.head()
# %% Print example transaction
print(dat.blocks[0].trans[0])
# %% Verify it's correct
dat.blocks[0].trans[0].api_verify()
# %% Convert block transaction to pandas df
transTable = dat.trans_to_pandas()
transTable.head()
# %% Read chain - 1 step
"""
c = Chain(verb=4)
c.read_next_Dat()
"""
# %% Read chain - all (in range)
c = Chain(verb=1,
datStart=1,
datn=1)
c.read_all()
# %% Print example transaction
print(c.dats[1].blocks[2].trans[0])