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