forked from freshgrlc/freshgrlc-indexer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexer.py
350 lines (268 loc) · 11.2 KB
/
indexer.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
import socket
from binascii import hexlify, unhexlify
from bitcoinrpc import authproxy
from cachetools import TTLCache
from datetime import datetime
from time import sleep, time
from traceback import print_exc
from sys import version_info, argv
from coindaemon import Daemon
from database import DatabaseIO
from models import Address, Block, CoinbaseInfo, Mutation, Transaction
from config import Configuration
from logger import log, log_event, log_block_event
if version_info[0] > 2:
import http.client as httplib
else:
import httplib
class Context(Configuration):
def __init__(self, db_timeout=30):
self._daemon = None
self.db = DatabaseIO(self.DATABASE_URL, timeout=db_timeout, utxo_cache=self.UTXO_CACHE, debug=self.DEBUG_SQL)
self.mempoolcache = TTLCache(ttl=600, maxsize=4096)
self.migration_type = 'init'
self.migration_last_id = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.db.flush()
def daemon(self):
if self._daemon is not None:
try:
self._daemon.uptime()
except (socket.timeout, socket.error, httplib.BadStatusLine):
self._daemon = None
if self._daemon is None:
self._daemon = Daemon(self.DAEMON_URL)
return self._daemon
def verify_state(self):
# Looks like we can end up in a state where we have blocks
# without coinbase info if we exit at the wrong point?
self.db.remove_blocks_without_coinbase()
# Verify transactions in on-chain blocks are confirmed
self.db.verify_confirmed_transactions_state()
# Verify confirmed transactions are on-chain
self.db.verify_unconfirmed_transactions_state()
self.db.session.commit()
def find_common_ancestor(self):
daemon = self.daemon()
chaintip_height = daemon.get_current_height()
indexer_tip = self.db.chaintip()
if indexer_tip == None:
return -1, -1, chaintip_height
ancestor_height = indexer_tip.height
chain_block_hash = daemon.getblockhash(ancestor_height)
if indexer_tip.hash != unhexlify(chain_block_hash):
ancestor_height -= 1
while ancestor_height > 0:
chain_block_hash = daemon.getblockhash(ancestor_height)
indexer_block = self.db.block(ancestor_height)
if indexer_block.hash == unhexlify(chain_block_hash):
break
ancestor_height -= 1
return ancestor_height, indexer_tip.height, chaintip_height
def sync_blocks(self, initial=False):
ancestor_height, indexer_height, chain_height = self.find_common_ancestor()
if initial:
log('Block heights:')
log(' Network: %7d' % chain_height)
log(' Indexer: %7d' % indexer_height)
log(' Last common: %7d' % ancestor_height)
log('')
if ancestor_height == chain_height and not initial:
return False
if ancestor_height < indexer_height:
self.db.orphan_blocks(ancestor_height + 1)
if initial and self.db.blockcount() != ancestor_height:
log('\nIndexer is missing %d blocks, doing full rescan...\n' % (ancestor_height - self.db.blockcount()))
for base in range(1, ancestor_height + 1, 1000):
if self.db.blockcount(range=(base, base + 1000)) != 1000:
for height in range(base, base + 1000 if base + 1000 < ancestor_height + 1 else ancestor_height + 1):
block = self.db.block(height)
if block == None:
self.import_blockheight(height)
newblock = None
next_commit = time() + 3
for height in range(ancestor_height + 1, chain_height + 1):
newblock = self.import_blockheight(height, commit=False)
if next_commit <= time():
log_block_event(hexlify(newblock.hash), 'Commit')
self.db.session.commit()
newblock = None
next_commit = time() + 3
if newblock is not None:
log_block_event(hexlify(newblock.hash), 'Commit')
self.db.session.commit()
return True
def import_blockheight(self, height, commit=True):
daemon = self.daemon()
blockhash = daemon.getblockhash(height)
blockinfo = daemon.getblock(blockhash)
last_blockhash = blockinfo['previousblockhash']
next_blockhash = blockinfo['nextblockhash'] if 'nextblockhash' in blockinfo else None
if height > 1:
lastblock = self.db.block(height - 1)
if unhexlify(last_blockhash) != lastblock.hash:
raise Exception('Chain error: blocks %d and %d not chaining' % (height - 1, height))
nextblock = self.db.block(height + 1)
if nextblock != None:
if next_blockhash is None or unhexlify(next_blockhash) != nextblock.hash:
self.db.orphan_blocks(height + 1)
return self.db.import_blockinfo(daemon.getblock(blockhash), tx_resolver=self.get_transaction, commit=commit)
def query_mempool(self):
new_txs = list(filter(lambda tx: tx not in self.mempoolcache, self.daemon().getrawmempool()))
if len(new_txs) == 0:
return False
for txid in new_txs:
self.db.check_need_import_transaction(txid, tx_resolver=self.get_transaction)
self.mempoolcache[txid] = True
return True
def update_single_balance(self):
dirty_address = self.db.next_dirty_address()
if dirty_address is None:
return False
self.db.update_address_balance(dirty_address)
return True
def update_single_balance_background(self):
self.db.reset_session()
dirty_address = self.db.next_dirty_address(check_for_id=2, random_address=True)
if dirty_address is None:
return False
self.db.update_address_balance_slow(dirty_address)
return True
def migrate_old_data(self):
if self.migration_type == 'init':
self.migration_type = 'mutations'
self.migration_last_id = 0
if self.migration_type == 'mutations':
if self.migration_update_tx_mutations():
return True
self.migration_type = 'address_script'
self.migration_last_id = 0
if self.migration_type == 'address_script':
if self.migration_update_add_address_script():
return True
self.migration_type = 'block_totalfee'
self.migration_last_id = 0
if self.migration_type == 'block_totalfee':
if self.migration_update_block_totalfee():
return True
self.migration_type = 'coinbase_newcoins'
self.migration_last_id = 0
if self.migration_type == 'coinbase_newcoins':
if self.migration_update_coinbase_newcoins():
return True
self.migration_type = None
self.migration_last_id = 0
return False
def migration_update_tx_mutations(self):
transaction = self.db.session.query(
Transaction
).join(
Transaction.address_mutations,
isouter=True
).filter(
Transaction.id > self.migration_last_id,
Mutation.id == None
).first()
if transaction == None:
return False
self.migration_last_id = transaction.id
self.db.add_tx_mutations_info(transaction)
self.db.session.flush()
return True
def migration_update_add_address_script(self):
address = self.db.session.query(
Address
).filter(
Address.id > self.migration_last_id,
Address.type_id.in_([ 0, 1 ]),
Address.raw == None
).first()
if address == None:
return False
self.migration_last_id = address.id
log_event('Import', 'scp', address.address)
daemon = self.daemon()
script = daemon.validateaddress(address.address)['scriptPubKey']
script = daemon.decodescript(script)['asm']
address.raw = script
self.db.session.add(address)
self.db.session.flush()
return True
def migration_update_block_totalfee(self):
block = self.db.session.query(Block).filter(Block.totalfee == None).filter(Block.id > self.migration_last_id).first()
if block == None:
return False
self.migration_last_id = block.id
log_block_event(hexlify(block.hash), 'Migrate')
block.totalfee = sum([ tx.fee for tx in block.transactions ])
self.db.session.add(block)
self.db.session.flush()
return True
def migration_update_coinbase_newcoins(self):
cb = self.db.session.query(CoinbaseInfo).filter(CoinbaseInfo.newcoins == None).filter(CoinbaseInfo.block_id > self.migration_last_id).first()
if cb == None:
return False
self.migration_last_id = cb.block_id
log_event('Migrate', 'cb', hexlify(cb.transaction.txid))
cb.newcoins = cb.transaction.totalvalue - cb.block.totalfee
self.db.session.add(cb)
self.db.session.flush()
return True
def get_transaction(self, txid):
return self.daemon().load_transaction(txid)
def do_until_timeout(operation, timeout):
if operation():
while time() < timeout:
if not operation():
break
return True
return False
def do_in_loop(operation, before_sleep=None, interval=1):
working = False
while True:
if working is None:
working = True
elif working == False:
working = None
if operation():
continue
if working:
before_sleep()
working = False
sleep(interval)
def indexer(context):
def main_loop():
context.db.reset_session()
context.query_mempool()
if context.sync_blocks():
return True
timeout = time() + 3
if do_until_timeout(context.update_single_balance, timeout):
return True
# Data migration is done in bulk (with large commits!)
if do_until_timeout(context.migrate_old_data, timeout):
context.db.session.commit()
return True
return False
log('\nChecking database state...\n')
context.verify_state()
log('\nPerforming initial sync...\n')
context.sync_blocks(initial=True)
log('\nSwitching to live tracking of mempool and chaintip.\n')
do_in_loop(operation=main_loop, before_sleep=lambda: log_event('Synced', 'chn', ''))
def background_task(context):
context.db.reset_slow_address_balance_updates()
do_in_loop(operation=context.update_single_balance_background, before_sleep=lambda: log_event('Synced', 'chn', ''), interval=30)
def main(func, db_timeout=30):
with Context(db_timeout) as c:
try:
func(c)
except KeyboardInterrupt:
return
if __name__ == '__main__':
if not '-B' in argv and not '--background-job' in argv:
main(indexer)
else:
main(background_task, db_timeout=300)