-
Notifications
You must be signed in to change notification settings - Fork 27
/
block_store.py
70 lines (53 loc) · 2.19 KB
/
block_store.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
import gevent.lock
class Block(object):
def __init__(self, raw_block):
assert isinstance(raw_block, dict)
self.blockhash = raw_block["hash"]
self.blockheight = raw_block["height"]
self.chainwork = int(raw_block["chainwork"], 16)
self.merkleroot = raw_block["merkleroot"]
self.size = raw_block["size"]
self.difficulty = raw_block["difficulty"]
self.time = raw_block["time"]
self.version = raw_block["version"]
self.raw_block = raw_block
self.tx = raw_block["tx"]
def __str__(self):
return "Block(height={}, hash={})".format(
self.blockheight, self.blockhash)
class BlockStore(object):
def __init__(self):
self._on_block = None # callback on any block
self._on_best_block = None # callback on block at front of chain
self._lock = gevent.lock.RLock()
self._best_block = (None, 0) # (hash, chainwork) of best block
self._blockhashes = {} # height -> blockhash
self._blocks = {} # hash -> block
self._rpcc = None # RPCClient
def get_hash(self, blockheight):
with self._lock:
return self._blockhashes[blockheight]
def get_block(self, blockhash):
with self._lock:
return self._blocks[blockhash]
def request_blockheight(self, blockheight):
self._rpcc.request("getblockhash", blockheight)
def put_raw_block(self, raw_block):
block = Block(raw_block)
with self._lock:
assert block.blockhash not in self._blocks
self._blocks[block.blockhash] = block
self._blockhashes[block.blockheight] = block.blockhash
best_block = block.chainwork >= self._best_block[1]
if best_block:
self._best_block = (block.blockhash, block.chainwork)
# Callbacks. TODO: should these be async?
if best_block and self._on_best_block:
self._on_best_block(block)
if self._on_block:
self._on_block(block)
with open("block.log", "a") as f:
f.write(str(block) + "\n")
def get_best_block_hash(self):
with self._lock:
return self._best_block[0]