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