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