wait until bitcoind is ready on startup
[electrum-server.git] / backends / bitcoind / blockchain_processor.py
1 import ast
2 import hashlib
3 from json import dumps, loads
4 import leveldb
5 import os
6 from Queue import Queue
7 import random
8 import sys
9 import time
10 import threading
11 import traceback
12 import urllib
13
14 from backends.bitcoind import deserialize
15 from processor import Processor, print_log
16 from utils import *
17
18
19 class BlockchainProcessor(Processor):
20
21     def __init__(self, config, shared):
22         Processor.__init__(self)
23
24         self.shared = shared
25         self.config = config
26         self.up_to_date = False
27         self.watched_addresses = []
28         self.history_cache = {}
29         self.chunk_cache = {}
30         self.cache_lock = threading.Lock()
31         self.headers_data = ''
32
33         self.mempool_addresses = {}
34         self.mempool_hist = {}
35         self.mempool_hashes = []
36         self.mempool_lock = threading.Lock()
37
38         self.address_queue = Queue()
39         self.dbpath = config.get('leveldb', 'path')
40         self.pruning_limit = config.getint('leveldb', 'pruning_limit')
41         self.db_version = 1 # increase this when database needs to be updated
42
43         self.dblock = threading.Lock()
44         try:
45             self.db = leveldb.LevelDB(self.dbpath)
46         except:
47             traceback.print_exc(file=sys.stdout)
48             self.shared.stop()
49
50         self.bitcoind_url = 'http://%s:%s@%s:%s/' % (
51             config.get('bitcoind', 'user'),
52             config.get('bitcoind', 'password'),
53             config.get('bitcoind', 'host'),
54             config.get('bitcoind', 'port'))
55
56         while True:
57             try:
58                 self.bitcoind('getinfo')
59                 break
60             except:
61                 print_log('cannot contact bitcoind...')
62                 time.sleep(5)
63                 continue
64
65         self.height = 0
66         self.is_test = False
67         self.sent_height = 0
68         self.sent_header = None
69
70         try:
71             hist = self.deserialize(self.db.Get('height'))
72             self.last_hash, self.height, db_version = hist[0]
73             print_log("Database version", self.db_version)
74             print_log("Blockchain height", self.height)
75         except:
76             traceback.print_exc(file=sys.stdout)
77             print_log('initializing database')
78             self.height = 0
79             self.last_hash = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
80             db_version = self.db_version
81
82         # check version
83         if self.db_version != db_version:
84             print_log("Your database '%s' is deprecated. Please create a new database"%self.dbpath)
85             self.shared.stop()
86             return
87
88         # catch_up headers
89         self.init_headers(self.height)
90
91         threading.Timer(0, lambda: self.catch_up(sync=False)).start()
92         while not shared.stopped() and not self.up_to_date:
93             try:
94                 time.sleep(1)
95             except:
96                 print "keyboard interrupt: stopping threads"
97                 shared.stop()
98                 sys.exit(0)
99
100         print_log("Blockchain is up to date.")
101         self.memorypool_update()
102         print_log("Memory pool initialized.")
103
104         threading.Timer(10, self.main_iteration).start()
105
106     def bitcoind(self, method, params=[]):
107         postdata = dumps({"method": method, 'params': params, 'id': 'jsonrpc'})
108         try:
109             respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
110         except:
111             traceback.print_exc(file=sys.stdout)
112             self.shared.stop()
113
114         r = loads(respdata)
115         if r['error'] is not None:
116             raise BaseException(r['error'])
117         return r.get('result')
118
119     def serialize(self, h):
120         s = ''
121         for txid, txpos, height in h:
122             s += self.serialize_item(txid, txpos, height)
123         return s
124
125     def serialize_item(self, txid, txpos, height, spent=chr(0)):
126         s = (txid + int_to_hex(txpos, 4) + int_to_hex(height, 3)).decode('hex') + spent 
127         return s
128
129     def deserialize_item(self,s):
130         txid = s[0:32].encode('hex')
131         txpos = int(rev_hex(s[32:36].encode('hex')), 16)
132         height = int(rev_hex(s[36:39].encode('hex')), 16)
133         spent = s[39:40]
134         return (txid, txpos, height, spent)
135
136     def deserialize(self, s):
137         h = []
138         while s:
139             txid, txpos, height, spent = self.deserialize_item(s[0:40])
140             h.append((txid, txpos, height))
141             if spent == chr(1):
142                 txid, txpos, height, spent = self.deserialize_item(s[40:80])
143                 h.append((txid, txpos, height))
144             s = s[80:]
145         return h
146
147     def block2header(self, b):
148         return {
149             "block_height": b.get('height'),
150             "version": b.get('version'),
151             "prev_block_hash": b.get('previousblockhash'),
152             "merkle_root": b.get('merkleroot'),
153             "timestamp": b.get('time'),
154             "bits": int(b.get('bits'), 16),
155             "nonce": b.get('nonce'),
156         }
157
158     def get_header(self, height):
159         block_hash = self.bitcoind('getblockhash', [height])
160         b = self.bitcoind('getblock', [block_hash])
161         return self.block2header(b)
162
163     def init_headers(self, db_height):
164         self.chunk_cache = {}
165         self.headers_filename = os.path.join(self.dbpath, 'blockchain_headers')
166
167         if os.path.exists(self.headers_filename):
168             height = os.path.getsize(self.headers_filename)/80 - 1   # the current height
169             if height > 0:
170                 prev_hash = self.hash_header(self.read_header(height))
171             else:
172                 prev_hash = None
173         else:
174             open(self.headers_filename, 'wb').close()
175             prev_hash = None
176             height = -1
177
178         if height < db_height:
179             print_log("catching up missing headers:", height, db_height)
180
181         try:
182             while height < db_height:
183                 height = height + 1
184                 header = self.get_header(height)
185                 if height > 1:
186                     assert prev_hash == header.get('prev_block_hash')
187                 self.write_header(header, sync=False)
188                 prev_hash = self.hash_header(header)
189                 if (height % 1000) == 0:
190                     print_log("headers file:", height)
191         except KeyboardInterrupt:
192             self.flush_headers()
193             sys.exit()
194
195         self.flush_headers()
196
197     def hash_header(self, header):
198         return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
199
200     def read_header(self, block_height):
201         if os.path.exists(self.headers_filename):
202             with open(self.headers_filename, 'rb') as f:
203                 f.seek(block_height * 80)
204                 h = f.read(80)
205             if len(h) == 80:
206                 h = header_from_string(h)
207                 return h
208
209     def read_chunk(self, index):
210         with open(self.headers_filename, 'rb') as f:
211             f.seek(index*2016*80)
212             chunk = f.read(2016*80)
213         return chunk.encode('hex')
214
215     def write_header(self, header, sync=True):
216         if not self.headers_data:
217             self.headers_offset = header.get('block_height')
218
219         self.headers_data += header_to_string(header).decode('hex')
220         if sync or len(self.headers_data) > 40*100:
221             self.flush_headers()
222
223         with self.cache_lock:
224             chunk_index = header.get('block_height')/2016
225             if self.chunk_cache.get(chunk_index):
226                 self.chunk_cache.pop(chunk_index)
227
228     def pop_header(self):
229         # we need to do this only if we have not flushed
230         if self.headers_data:
231             self.headers_data = self.headers_data[:-40]
232
233     def flush_headers(self):
234         if not self.headers_data:
235             return
236         with open(self.headers_filename, 'rb+') as f:
237             f.seek(self.headers_offset*80)
238             f.write(self.headers_data)
239         self.headers_data = ''
240
241     def get_chunk(self, i):
242         # store them on disk; store the current chunk in memory
243         with self.cache_lock:
244             chunk = self.chunk_cache.get(i)
245             if not chunk:
246                 chunk = self.read_chunk(i)
247                 self.chunk_cache[i] = chunk
248
249         return chunk
250
251     def get_mempool_transaction(self, txid):
252         try:
253             raw_tx = self.bitcoind('getrawtransaction', [txid, 0, -1])
254         except:
255             return None
256
257         vds = deserialize.BCDataStream()
258         vds.write(raw_tx.decode('hex'))
259
260         return deserialize.parse_Transaction(vds, is_coinbase=False)
261
262     def get_history(self, addr, cache_only=False):
263         with self.cache_lock:
264             hist = self.history_cache.get(addr)
265         if hist is not None:
266             return hist
267         if cache_only:
268             return -1
269
270         with self.dblock:
271             try:
272                 hist = self.deserialize(self.db.Get(addr))
273                 is_known = True
274             except:
275                 hist = []
276                 is_known = False
277
278         # sort history, because redeeming transactions are next to the corresponding txout
279         hist.sort(key=lambda tup: tup[2])
280
281         # add memory pool
282         with self.mempool_lock:
283             for txid in self.mempool_hist.get(addr, []):
284                 hist.append((txid, 0, 0))
285
286         # uniqueness
287         hist = set(map(lambda x: (x[0], x[2]), hist))
288
289         # convert to dict
290         hist = map(lambda x: {'tx_hash': x[0], 'height': x[1]}, hist)
291
292         # add something to distinguish between unused and empty addresses
293         if hist == [] and is_known:
294             hist = ['*']
295
296         with self.cache_lock:
297             self.history_cache[addr] = hist
298         return hist
299
300     def get_status(self, addr, cache_only=False):
301         tx_points = self.get_history(addr, cache_only)
302         if cache_only and tx_points == -1:
303             return -1
304
305         if not tx_points:
306             return None
307         if tx_points == ['*']:
308             return '*'
309         status = ''
310         for tx in tx_points:
311             status += tx.get('tx_hash') + ':%d:' % tx.get('height')
312         return hashlib.sha256(status).digest().encode('hex')
313
314     def get_merkle(self, tx_hash, height):
315
316         block_hash = self.bitcoind('getblockhash', [height])
317         b = self.bitcoind('getblock', [block_hash])
318         tx_list = b.get('tx')
319         tx_pos = tx_list.index(tx_hash)
320
321         merkle = map(hash_decode, tx_list)
322         target_hash = hash_decode(tx_hash)
323         s = []
324         while len(merkle) != 1:
325             if len(merkle) % 2:
326                 merkle.append(merkle[-1])
327             n = []
328             while merkle:
329                 new_hash = Hash(merkle[0] + merkle[1])
330                 if merkle[0] == target_hash:
331                     s.append(hash_encode(merkle[1]))
332                     target_hash = new_hash
333                 elif merkle[1] == target_hash:
334                     s.append(hash_encode(merkle[0]))
335                     target_hash = new_hash
336                 n.append(new_hash)
337                 merkle = merkle[2:]
338             merkle = n
339
340         return {"block_height": height, "merkle": s, "pos": tx_pos}
341
342
343     def add_to_history(self, addr, tx_hash, tx_pos, tx_height):
344         # keep it sorted
345         s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
346         assert len(s) == 80
347
348         serialized_hist = self.batch_list[addr]
349
350         l = len(serialized_hist)/80
351         for i in range(l-1, -1, -1):
352             item = serialized_hist[80*i:80*(i+1)]
353             item_height = int(rev_hex(item[36:39].encode('hex')), 16)
354             if item_height <= tx_height:
355                 serialized_hist = serialized_hist[0:80*(i+1)] + s + serialized_hist[80*(i+1):]
356                 break
357         else:
358             serialized_hist = s + serialized_hist
359
360         self.batch_list[addr] = serialized_hist
361
362         # backlink
363         txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
364         self.batch_txio[txo] = addr
365
366
367
368     def revert_add_to_history(self, addr, tx_hash, tx_pos, tx_height):
369
370         serialized_hist = self.batch_list[addr]
371         s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
372         if serialized_hist.find(s) == -1: raise
373         serialized_hist = serialized_hist.replace(s, '')
374         self.batch_list[addr] = serialized_hist
375
376
377
378     def prune_history(self, addr, undo):
379         # remove items that have bit set to one
380         if undo.get(addr) is None: undo[addr] = []
381
382         serialized_hist = self.batch_list[addr]
383         l = len(serialized_hist)/80
384         for i in range(l):
385             if len(serialized_hist)/80 < self.pruning_limit: break
386             item = serialized_hist[80*i:80*(i+1)] 
387             if item[39:40] == chr(1):
388                 assert item[79:80] == chr(2)
389                 serialized_hist = serialized_hist[0:80*i] + serialized_hist[80*(i+1):]
390                 undo[addr].append(item)  # items are ordered
391         self.batch_list[addr] = serialized_hist
392
393
394     def revert_prune_history(self, addr, undo):
395         # restore removed items
396         serialized_hist = self.batch_list[addr]
397
398         if undo.get(addr) is not None: 
399             itemlist = undo.pop(addr)
400         else:
401             return 
402
403         if not itemlist: return
404
405         l = len(serialized_hist)/80
406         tx_item = ''
407         for i in range(l-1, -1, -1):
408             if tx_item == '':
409                 if not itemlist: 
410                     break
411                 else:
412                     tx_item = itemlist.pop(-1) # get the last element
413                     tx_height = int(rev_hex(tx_item[36:39].encode('hex')), 16)
414             
415             item = serialized_hist[80*i:80*(i+1)]
416             item_height = int(rev_hex(item[36:39].encode('hex')), 16)
417
418             if item_height < tx_height:
419                 serialized_hist = serialized_hist[0:80*(i+1)] + tx_item + serialized_hist[80*(i+1):]
420                 tx_item = ''
421
422         else:
423             serialized_hist = ''.join(itemlist) + tx_item + serialized_hist
424
425         self.batch_list[addr] = serialized_hist
426
427
428     def set_spent_bit(self, addr, txi, is_spent, txid=None, index=None, height=None):
429         serialized_hist = self.batch_list[addr]
430         l = len(serialized_hist)/80
431         for i in range(l):
432             item = serialized_hist[80*i:80*(i+1)]
433             if item[0:36] == txi:
434                 if is_spent:
435                     new_item = item[0:39] + chr(1) + self.serialize_item(txid, index, height, chr(2))
436                 else:
437                     new_item = item[0:39] + chr(0) + chr(0)*40 
438                 serialized_hist = serialized_hist[0:80*i] + new_item + serialized_hist[80*(i+1):]
439                 break
440         else:
441             self.shared.stop()
442             hist = self.deserialize(serialized_hist)
443             raise BaseException("prevout not found", addr, hist, txi.encode('hex'))
444
445         self.batch_list[addr] = serialized_hist
446
447
448     def unset_spent_bit(self, addr, txi):
449         self.set_spent_bit(addr, txi, False)
450         self.batch_txio[txi] = addr
451
452
453     def deserialize_block(self, block):
454         txlist = block.get('tx')
455         tx_hashes = []  # ordered txids
456         txdict = {}     # deserialized tx
457         is_coinbase = True
458         for raw_tx in txlist:
459             tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
460             tx_hashes.append(tx_hash)
461             vds = deserialize.BCDataStream()
462             vds.write(raw_tx.decode('hex'))
463             tx = deserialize.parse_Transaction(vds, is_coinbase)
464             txdict[tx_hash] = tx
465             is_coinbase = False
466         return tx_hashes, txdict
467
468     def get_undo_info(self, height):
469         s = self.db.Get("undo%d" % (height % 100))
470         return eval(s)
471
472     def write_undo_info(self, batch, height, undo_info):
473         if self.is_test or height > self.bitcoind_height - 100:
474             batch.Put("undo%d" % (height % 100), repr(undo_info))
475
476     def import_block(self, block, block_hash, block_height, sync, revert=False):
477
478         self.batch_list = {}  # address -> history
479         self.batch_txio = {}  # transaction i/o -> address
480
481         block_inputs = []
482         block_outputs = []
483         addr_to_read = []
484
485         # deserialize transactions
486         t0 = time.time()
487         tx_hashes, txdict = self.deserialize_block(block)
488
489         t00 = time.time()
490
491         # undo info
492         if revert:
493             undo_info = self.get_undo_info(block_height)
494         else:
495             undo_info = {}
496
497
498         if not revert:
499             # read addresses of tx inputs
500             for tx in txdict.values():
501                 for x in tx.get('inputs'):
502                     txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
503                     block_inputs.append(txi)
504
505             block_inputs.sort()
506             for txi in block_inputs:
507                 try:
508                     addr = self.db.Get(txi)
509                 except KeyError:
510                     # the input could come from the same block
511                     continue
512                 except:
513                     traceback.print_exc(file=sys.stdout)
514                     self.shared.stop()
515                     raise
516
517                 self.batch_txio[txi] = addr
518                 addr_to_read.append(addr)
519
520         else:
521             for txid, tx in txdict.items():
522                 for x in tx.get('outputs'):
523                     txo = (txid + int_to_hex(x.get('index'), 4)).decode('hex')
524                     block_outputs.append(txo)
525                     addr_to_read.append( x.get('address') )
526
527                 undo = undo_info.get(txid)
528                 for i, x in enumerate(tx.get('inputs')):
529                     addr = undo['prev_addr'][i]
530                     addr_to_read.append(addr)
531
532
533
534
535
536         # read histories of addresses
537         for txid, tx in txdict.items():
538             for x in tx.get('outputs'):
539                 addr_to_read.append(x.get('address'))
540
541         addr_to_read.sort()
542         for addr in addr_to_read:
543             try:
544                 self.batch_list[addr] = self.db.Get(addr)
545             except KeyError:
546                 self.batch_list[addr] = ''
547             except:
548                 traceback.print_exc(file=sys.stdout)
549                 self.shared.stop()
550                 raise
551
552
553         # process
554         t1 = time.time()
555
556         if revert:
557             tx_hashes = tx_hashes[::-1]
558
559
560         for txid in tx_hashes:  # must be ordered
561             tx = txdict[txid]
562             if not revert:
563
564                 undo = { 'prev_addr':[] } # contains the list of pruned items for each address in the tx; also, 'prev_addr' is a list of prev addresses
565                 
566                 prev_addr = []
567                 for i, x in enumerate(tx.get('inputs')):
568                     txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
569                     addr = self.batch_txio[txi]
570
571                     # add redeem item to the history.
572                     # add it right next to the input txi? this will break history sorting, but it's ok if I neglect tx inputs during search
573                     self.set_spent_bit(addr, txi, True, txid, i, block_height)
574
575                     # when I prune, prune a pair
576                     self.prune_history(addr, undo)
577                     prev_addr.append(addr)
578
579                 undo['prev_addr'] = prev_addr 
580
581                 # here I add only the outputs to history; maybe I want to add inputs too (that's in the other loop)
582                 for x in tx.get('outputs'):
583                     addr = x.get('address')
584                     self.add_to_history(addr, txid, x.get('index'), block_height)
585                     self.prune_history(addr, undo)  # prune here because we increased the length of the history
586
587                 undo_info[txid] = undo
588
589             else:
590
591                 undo = undo_info.pop(txid)
592
593                 for x in tx.get('outputs'):
594                     addr = x.get('address')
595                     self.revert_prune_history(addr, undo)
596                     self.revert_add_to_history(addr, txid, x.get('index'), block_height)
597
598                 prev_addr = undo.pop('prev_addr')
599                 for i, x in enumerate(tx.get('inputs')):
600                     addr = prev_addr[i]
601                     self.revert_prune_history(addr, undo)
602                     txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
603                     self.unset_spent_bit(addr, txi)
604
605                 assert undo == {}
606
607         if revert: 
608             assert undo_info == {}
609
610
611         # write
612         max_len = 0
613         max_addr = ''
614         t2 = time.time()
615
616         batch = leveldb.WriteBatch()
617         for addr, serialized_hist in self.batch_list.items():
618             batch.Put(addr, serialized_hist)
619             l = len(serialized_hist)/80
620             if l > max_len:
621                 max_len = l
622                 max_addr = addr
623
624         if not revert:
625             # add new created outputs
626             for txio, addr in self.batch_txio.items():
627                 batch.Put(txio, addr)
628             # delete spent inputs
629             for txi in block_inputs:
630                 batch.Delete(txi)
631             # add undo info
632             self.write_undo_info(batch, block_height, undo_info)
633         else:
634             # restore spent inputs
635             for txio, addr in self.batch_txio.items():
636                 # print "restoring spent input", repr(txio)
637                 batch.Put(txio, addr)
638             # delete spent outputs
639             for txo in block_outputs:
640                 batch.Delete(txo)
641
642         # add the max
643         batch.Put('height', self.serialize([(block_hash, block_height, self.db_version)]))
644
645         # actual write
646         self.db.Write(batch, sync=sync)
647
648         t3 = time.time()
649         if t3 - t0 > 10 and not sync:
650             print_log("block", block_height,
651                       "parse:%0.2f " % (t00 - t0),
652                       "read:%0.2f " % (t1 - t00),
653                       "proc:%.2f " % (t2-t1),
654                       "write:%.2f " % (t3-t2),
655                       "max:", max_len, max_addr)
656
657         for addr in self.batch_list.keys():
658             self.invalidate_cache(addr)
659
660     def add_request(self, request):
661         # see if we can get if from cache. if not, add to queue
662         if self.process(request, cache_only=True) == -1:
663             self.queue.put(request)
664
665     def process(self, request, cache_only=False):
666         #print "abe process", request
667
668         message_id = request['id']
669         method = request['method']
670         params = request.get('params', [])
671         result = None
672         error = None
673
674         if method == 'blockchain.numblocks.subscribe':
675             result = self.height
676
677         elif method == 'blockchain.headers.subscribe':
678             result = self.header
679
680         elif method == 'blockchain.address.subscribe':
681             try:
682                 address = params[0]
683                 result = self.get_status(address, cache_only)
684                 self.watch_address(address)
685             except BaseException, e:
686                 error = str(e) + ': ' + address
687                 print_log("error:", error)
688
689         elif method == 'blockchain.address.unsubscribe':
690             try:
691                 password = params[0]
692                 address = params[1]
693                 if password == self.config.get('server', 'password'):
694                     self.watched_addresses.remove(address)
695                     # print_log('unsubscribed', address)
696                     result = "ok"
697                 else:
698                     print_log('incorrect password')
699                     result = "authentication error"
700             except BaseException, e:
701                 error = str(e) + ': ' + address
702                 print_log("error:", error)
703
704         elif method == 'blockchain.address.get_history':
705             try:
706                 address = params[0]
707                 result = self.get_history(address, cache_only)
708             except BaseException, e:
709                 error = str(e) + ': ' + address
710                 print_log("error:", error)
711
712         elif method == 'blockchain.block.get_header':
713             if cache_only:
714                 result = -1
715             else:
716                 try:
717                     height = params[0]
718                     result = self.get_header(height)
719                 except BaseException, e:
720                     error = str(e) + ': %d' % height
721                     print_log("error:", error)
722
723         elif method == 'blockchain.block.get_chunk':
724             if cache_only:
725                 result = -1
726             else:
727                 try:
728                     index = params[0]
729                     result = self.get_chunk(index)
730                 except BaseException, e:
731                     error = str(e) + ': %d' % index
732                     print_log("error:", error)
733
734         elif method == 'blockchain.transaction.broadcast':
735             try:
736                 txo = self.bitcoind('sendrawtransaction', params)
737                 print_log("sent tx:", txo)
738                 result = txo
739             except BaseException, e:
740                 result = str(e)  # do not send an error
741                 print_log("error:", result, params)
742
743         elif method == 'blockchain.transaction.get_merkle':
744             if cache_only:
745                 result = -1
746             else:
747                 try:
748                     tx_hash = params[0]
749                     tx_height = params[1]
750                     result = self.get_merkle(tx_hash, tx_height)
751                 except BaseException, e:
752                     error = str(e) + ': ' + repr(params)
753                     print_log("get_merkle error:", error)
754
755         elif method == 'blockchain.transaction.get':
756             try:
757                 tx_hash = params[0]
758                 height = params[1]
759                 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height])
760             except BaseException, e:
761                 error = str(e) + ': ' + repr(params)
762                 print_log("tx get error:", error)
763
764         else:
765             error = "unknown method:%s" % method
766
767         if cache_only and result == -1:
768             return -1
769
770         if error:
771             self.push_response({'id': message_id, 'error': error})
772         elif result != '':
773             self.push_response({'id': message_id, 'result': result})
774
775     def watch_address(self, addr):
776         if addr not in self.watched_addresses:
777             self.watched_addresses.append(addr)
778
779     def catch_up(self, sync=True):
780         t1 = time.time()
781
782         while not self.shared.stopped():
783             # are we done yet?
784             info = self.bitcoind('getinfo')
785             self.bitcoind_height = info.get('blocks')
786             bitcoind_block_hash = self.bitcoind('getblockhash', [self.bitcoind_height])
787             if self.last_hash == bitcoind_block_hash:
788                 self.up_to_date = True
789                 break
790
791             # not done..
792             self.up_to_date = False
793             next_block_hash = self.bitcoind('getblockhash', [self.height + 1])
794             next_block = self.bitcoind('getblock', [next_block_hash, 1])
795
796             # fixme: this is unsafe, if we revert when the undo info is not yet written
797             revert = (random.randint(1, 100) == 1) if self.is_test else False
798
799             if (next_block.get('previousblockhash') == self.last_hash) and not revert:
800
801                 self.import_block(next_block, next_block_hash, self.height+1, sync)
802                 self.height = self.height + 1
803                 self.write_header(self.block2header(next_block), sync)
804                 self.last_hash = next_block_hash
805
806                 if self.height % 100 == 0 and not sync:
807                     t2 = time.time()
808                     print_log("catch_up: block %d (%.3fs)" % (self.height, t2 - t1))
809                     t1 = t2
810
811             else:
812                 # revert current block
813                 block = self.bitcoind('getblock', [self.last_hash, 1])
814                 print_log("blockchain reorg", self.height, block.get('previousblockhash'), self.last_hash)
815                 self.import_block(block, self.last_hash, self.height, sync, revert=True)
816                 self.pop_header()
817                 self.flush_headers()
818
819                 self.height -= 1
820
821                 # read previous header from disk
822                 self.header = self.read_header(self.height)
823                 self.last_hash = self.hash_header(self.header)
824
825         self.header = self.block2header(self.bitcoind('getblock', [self.last_hash]))
826
827     def memorypool_update(self):
828         mempool_hashes = self.bitcoind('getrawmempool')
829
830         touched_addresses = []
831         for tx_hash in mempool_hashes:
832             if tx_hash in self.mempool_hashes:
833                 continue
834
835             tx = self.get_mempool_transaction(tx_hash)
836             if not tx:
837                 continue
838
839             mpa = self.mempool_addresses.get(tx_hash, [])
840             for x in tx.get('inputs'):
841                 # we assume that the input address can be parsed by deserialize(); this is true for Electrum transactions
842                 addr = x.get('address')
843                 if addr and addr not in mpa:
844                     mpa.append(addr)
845                     touched_addresses.append(addr)
846
847             for x in tx.get('outputs'):
848                 addr = x.get('address')
849                 if addr and addr not in mpa:
850                     mpa.append(addr)
851                     touched_addresses.append(addr)
852
853             self.mempool_addresses[tx_hash] = mpa
854             self.mempool_hashes.append(tx_hash)
855
856         # remove older entries from mempool_hashes
857         self.mempool_hashes = mempool_hashes
858
859         # remove deprecated entries from mempool_addresses
860         for tx_hash, addresses in self.mempool_addresses.items():
861             if tx_hash not in self.mempool_hashes:
862                 self.mempool_addresses.pop(tx_hash)
863                 for addr in addresses:
864                     touched_addresses.append(addr)
865
866         # rebuild mempool histories
867         new_mempool_hist = {}
868         for tx_hash, addresses in self.mempool_addresses.items():
869             for addr in addresses:
870                 h = new_mempool_hist.get(addr, [])
871                 if tx_hash not in h:
872                     h.append(tx_hash)
873                 new_mempool_hist[addr] = h
874
875         with self.mempool_lock:
876             self.mempool_hist = new_mempool_hist
877
878         # invalidate cache for touched addresses
879         for addr in touched_addresses:
880             self.invalidate_cache(addr)
881
882
883     def invalidate_cache(self, address):
884         with self.cache_lock:
885             if address in self.history_cache:
886                 print_log("cache: invalidating", address)
887                 self.history_cache.pop(address)
888
889         if address in self.watched_addresses:
890             # TODO: update cache here. if new value equals cached value, do not send notification
891             self.address_queue.put(address)
892
893     def main_iteration(self):
894         if self.shared.stopped():
895             print_log("blockchain processor terminating")
896             return
897
898         with self.dblock:
899             t1 = time.time()
900             self.catch_up()
901             t2 = time.time()
902
903         self.memorypool_update()
904
905         if self.sent_height != self.height:
906             self.sent_height = self.height
907             self.push_response({
908                 'id': None,
909                 'method': 'blockchain.numblocks.subscribe',
910                 'params': [self.height],
911             })
912
913         if self.sent_header != self.header:
914             print_log("blockchain: %d (%.3fs)" % (self.height, t2 - t1))
915             self.sent_header = self.header
916             self.push_response({
917                 'id': None,
918                 'method': 'blockchain.headers.subscribe',
919                 'params': [self.header],
920             })
921
922         while True:
923             try:
924                 addr = self.address_queue.get(False)
925             except:
926                 break
927             if addr in self.watched_addresses:
928                 status = self.get_status(addr)
929                 self.push_response({
930                     'id': None,
931                     'method': 'blockchain.address.subscribe',
932                     'params': [addr, status],
933                 })
934
935         if not self.shared.stopped():
936             threading.Timer(10, self.main_iteration).start()
937         else:
938             print_log("blockchain processor terminating")