slightly improved messages
[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
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.sent_height = 0
88         self.sent_header = None
89
90
91         try:
92             hist = self.deserialize(self.db.Get('0'))
93             hh, self.height, _ = hist[0] 
94             self.block_hashes = [hh]
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.block_hashes = [ '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 "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         height = 0
163         if os.path.exists(self.headers_filename):
164             height = os.path.getsize(self.headers_filename)/80
165
166         if height:
167             prev_header = self.read_header(height -1)
168             prev_hash = self.hash_header(prev_header)
169         else:
170             open(self.headers_filename,'wb').close()
171             prev_hash = None
172
173         if height != db_height:
174             print_log( "catching up missing headers:", height, db_height)
175
176         s = ''
177         try:
178             for i in range(height, db_height):
179                 header = self.get_header(i)
180                 assert prev_hash == header.get('prev_block_hash')
181                 self.write_header(header, sync=False)
182                 prev_hash = self.hash_header(header)
183                 if i%1000==0: print_log("headers file:",i)
184         except KeyboardInterrupt:
185             self.flush_headers()
186             sys.exit()
187
188         self.flush_headers()
189
190
191     def hash_header(self, header):
192         return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
193
194
195     def read_header(self, block_height):
196         if os.path.exists(self.headers_filename):
197             f = open(self.headers_filename,'rb')
198             f.seek(block_height*80)
199             h = f.read(80)
200             f.close()
201             if len(h) == 80:
202                 h = header_from_string(h)
203                 return h
204
205
206     def read_chunk(self, index):
207         f = open(self.headers_filename,'rb')
208         f.seek(index*2016*80)
209         chunk = f.read(2016*80)
210         f.close()
211         return chunk.encode('hex')
212
213
214     def write_header(self, header, sync=True):
215         if not self.headers_data:
216             self.headers_offset = header.get('block_height')
217         self.headers_data += header_to_string(header).decode('hex')
218         if sync or len(self.headers_data) > 40*100:
219             self.flush_headers()
220
221     def pop_header(self):
222         # we need to do this only if we have not flushed
223         if self.headers_data:
224             self.headers_data = self.headers_data[:-40]
225
226     def flush_headers(self):
227         if not self.headers_data: return
228         f = open(self.headers_filename,'rb+')
229         f.seek(self.headers_offset*80)
230         f.write(self.headers_data)
231         f.close()
232         self.headers_data = ''
233
234
235     def get_chunk(self, i):
236         # store them on disk; store the current chunk in memory
237         chunk = self.chunk_cache.get(i)
238         if not chunk:
239             chunk = self.read_chunk(i)
240             self.chunk_cache[i] = chunk
241         return chunk
242
243
244     def get_transaction(self, txid, block_height=-1, is_coinbase = False):
245         raw_tx = self.bitcoind('getrawtransaction', [txid, 0, block_height])
246         vds = deserialize.BCDataStream()
247         vds.write(raw_tx.decode('hex'))
248         out = deserialize.parse_Transaction(vds, is_coinbase)
249         return out
250
251
252     def get_history(self, addr, cache_only=False):
253         with self.cache_lock: hist = self.history_cache.get( addr )
254         if hist is not None: return hist
255         if cache_only: return -1
256
257         with self.dblock:
258             try:
259                 hist = self.deserialize(self.db.Get(addr))
260                 is_known = True
261             except: 
262                 hist = []
263                 is_known = False
264
265         # should not be necessary
266         hist.sort( key=lambda tup: tup[1])
267         # check uniqueness too...
268
269         # add memory pool
270         with self.mempool_lock:
271             for txid in self.mempool_hist.get(addr,[]):
272                 hist.append((txid, 0, 0))
273
274         hist = map(lambda x: {'tx_hash':x[0], 'height':x[2]}, hist)
275         # add something to distinguish between unused and empty addresses
276         if hist == [] and is_known: hist = ['*']
277
278         with self.cache_lock: self.history_cache[addr] = hist
279         return hist
280
281
282     def get_status(self, addr, cache_only=False):
283         tx_points = self.get_history(addr, cache_only)
284         if cache_only and tx_points == -1: return -1
285
286         if not tx_points: return None
287         if tx_points == ['*']: return '*'
288         status = ''
289         for tx in tx_points:
290             status += tx.get('tx_hash') + ':%d:' % tx.get('height')
291         return hashlib.sha256( status ).digest().encode('hex')
292
293
294     def get_merkle(self, tx_hash, height):
295
296         block_hash = self.bitcoind('getblockhash', [height])
297         b = self.bitcoind('getblock', [block_hash])
298         tx_list = b.get('tx')
299         tx_pos = tx_list.index(tx_hash)
300         
301         merkle = map(hash_decode, tx_list)
302         target_hash = hash_decode(tx_hash)
303         s = []
304         while len(merkle) != 1:
305             if len(merkle)%2: merkle.append( merkle[-1] )
306             n = []
307             while merkle:
308                 new_hash = Hash( merkle[0] + merkle[1] )
309                 if merkle[0] == target_hash:
310                     s.append( hash_encode( merkle[1]))
311                     target_hash = new_hash
312                 elif merkle[1] == target_hash:
313                     s.append( hash_encode( merkle[0]))
314                     target_hash = new_hash
315                 n.append( new_hash )
316                 merkle = merkle[2:]
317             merkle = n
318
319         return {"block_height":height, "merkle":s, "pos":tx_pos}
320
321         
322     def add_to_batch(self, addr, tx_hash, tx_pos, tx_height):
323
324         # we do it chronologically, so nothing wrong can happen...
325         s = (tx_hash + int_to_hex(tx_pos, 4) + int_to_hex(tx_height, 4)).decode('hex')
326         self.batch_list[addr] += s
327
328         # backlink
329         txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
330         self.batch_txio[txo] = addr
331
332
333     def remove_from_batch(self, tx_hash, tx_pos):
334                     
335         txi = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
336         try:
337             addr = self.batch_txio[txi]
338         except:
339             #raise BaseException(tx_hash, tx_pos)
340             print "WARNING: cannot find address for", (tx_hash, tx_pos)
341             return
342
343         serialized_hist = self.batch_list[addr]
344
345         l = len(serialized_hist)/40
346         for i in range(l):
347             if serialized_hist[40*i:40*i+36] == txi:
348                 serialized_hist = serialized_hist[0:40*i] + serialized_hist[40*(i+1):]
349                 break
350         else:
351             raise BaseException("prevout not found", addr, hist, tx_hash, tx_pos)
352         self.batch_list[addr] = serialized_hist
353
354
355     def deserialize_block(self, block):
356         txlist = block.get('tx')
357         tx_hashes = []  # ordered txids
358         txdict = {}     # deserialized tx
359         is_coinbase = True
360         for raw_tx in txlist:
361             tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
362             tx_hashes.append(tx_hash)
363             vds = deserialize.BCDataStream()
364             vds.write(raw_tx.decode('hex'))
365             tx = deserialize.parse_Transaction(vds, is_coinbase)
366             txdict[tx_hash] = tx
367             is_coinbase = False
368         return tx_hashes, txdict
369
370
371     def import_block(self, block, block_hash, block_height, sync, revert=False):
372
373         self.batch_list = {}  # address -> history
374         self.batch_txio = {}  # transaction i/o -> address
375
376         inputs_to_read = []
377         addr_to_read = []
378
379         # deserialize transactions
380         t0 = time.time()
381         tx_hashes, txdict = self.deserialize_block(block)
382
383         # read addresses of tx inputs
384         t00 = time.time()
385         for tx in txdict.values():
386             for x in tx.get('inputs'):
387                 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
388                 inputs_to_read.append(txi)
389
390         inputs_to_read.sort()
391         for txi in inputs_to_read:
392             try:
393                 addr = self.db.Get(txi)    
394             except:
395                 # the input could come from the same block
396                 continue
397             self.batch_txio[txi] = addr
398             addr_to_read.append(addr)
399
400         # read histories of addresses
401         for txid, tx in txdict.items():
402             for x in tx.get('outputs'):
403                 addr_to_read.append(x.get('address'))
404
405         addr_to_read.sort()
406         for addr in addr_to_read:
407             try:
408                 self.batch_list[addr] = self.db.Get(addr)
409             except: 
410                 self.batch_list[addr] = ''
411               
412         # process
413         t1 = time.time()
414
415         for txid in tx_hashes: # must be ordered
416             tx = txdict[txid]
417             if not revert:
418                 for x in tx.get('inputs'):
419                     self.remove_from_batch( x.get('prevout_hash'), x.get('prevout_n'))
420                 for x in tx.get('outputs'):
421                     self.add_to_batch( x.get('address'), txid, x.get('index'), block_height)
422             else:
423                 for x in tx.get('outputs'):
424                     self.remove_from_batch( x.get('prevout_hash'), x.get('prevout_n'))
425                 for x in tx.get('inputs'):
426                     self.add_to_batch( x.get('address'), txid, x.get('index'), block_height)
427
428         # write
429         max_len = 0
430         max_addr = ''
431         t2 = time.time()
432
433         batch = leveldb.WriteBatch()
434         for addr, serialized_hist in self.batch_list.items():
435             batch.Put(addr, serialized_hist)
436             l = len(serialized_hist)
437             if l > max_len:
438                 max_len = l
439                 max_addr = addr
440
441         for txio, addr in self.batch_txio.items():
442             batch.Put(txio, addr)
443         # delete spent inputs
444         for txi in inputs_to_read:
445             batch.Delete(txi)
446         batch.Put('0', self.serialize( [(block_hash, block_height, 0)] ) )
447
448         # actual write
449         self.db.Write(batch, sync = sync)
450
451         t3 = time.time()
452         if t3 - t0 > 10: 
453             print_log("block", block_height, 
454                       "parse:%0.2f "%(t00 - t0), 
455                       "read:%0.2f "%(t1 - t00), 
456                       "proc:%.2f "%(t2-t1), 
457                       "write:%.2f "%(t3-t2), 
458                       "max:", max_len, max_addr)
459
460         for addr in self.batch_list.keys(): self.invalidate_cache(addr)
461
462
463
464     def add_request(self, request):
465         # see if we can get if from cache. if not, add to queue
466         if self.process( request, cache_only = True) == -1:
467             self.queue.put(request)
468
469
470
471     def process(self, request, cache_only = False):
472         #print "abe process", request
473
474         message_id = request['id']
475         method = request['method']
476         params = request.get('params',[])
477         result = None
478         error = None
479
480         if method == 'blockchain.numblocks.subscribe':
481             result = self.height
482
483         elif method == 'blockchain.headers.subscribe':
484             result = self.header
485
486         elif method == 'blockchain.address.subscribe':
487             try:
488                 address = params[0]
489                 result = self.get_status(address, cache_only)
490                 self.watch_address(address)
491             except BaseException, e:
492                 error = str(e) + ': ' + address
493                 print_log( "error:", error )
494
495         elif method == 'blockchain.address.subscribe2':
496             try:
497                 address = params[0]
498                 result = self.get_status(address, cache_only)
499                 self.watch_address(address)
500             except BaseException, e:
501                 error = str(e) + ': ' + address
502                 print_log( "error:", error )
503
504         elif method == 'blockchain.address.get_history2':
505             try:
506                 address = params[0]
507                 result = self.get_history( address, cache_only )
508             except BaseException, e:
509                 error = str(e) + ': ' + address
510                 print_log( "error:", error )
511
512         elif method == 'blockchain.block.get_header':
513             if cache_only: 
514                 result = -1
515             else:
516                 try:
517                     height = params[0]
518                     result = self.get_header( height ) 
519                 except BaseException, e:
520                     error = str(e) + ': %d'% height
521                     print_log( "error:", error )
522                     
523         elif method == 'blockchain.block.get_chunk':
524             if cache_only:
525                 result = -1
526             else:
527                 try:
528                     index = params[0]
529                     result = self.get_chunk( index ) 
530                 except BaseException, e:
531                     error = str(e) + ': %d'% index
532                     print_log( "error:", error)
533
534         elif method == 'blockchain.transaction.broadcast':
535             txo = self.bitcoind('sendrawtransaction', params)
536             print_log( "sent tx:", txo )
537             result = txo 
538
539         elif method == 'blockchain.transaction.get_merkle':
540             if cache_only:
541                 result = -1
542             else:
543                 try:
544                     tx_hash = params[0]
545                     tx_height = params[1]
546                     result = self.get_merkle(tx_hash, tx_height) 
547                 except BaseException, e:
548                     error = str(e) + ': ' + tx_hash
549                     print_log( "error:", error )
550                     
551         elif method == 'blockchain.transaction.get':
552             try:
553                 tx_hash = params[0]
554                 height = params[1]
555                 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height] ) 
556             except BaseException, e:
557                 error = str(e) + ': ' + tx_hash
558                 print_log( "error:", error )
559
560         else:
561             error = "unknown method:%s"%method
562
563         if cache_only and result == -1: return -1
564
565         if error:
566             response = { 'id':message_id, 'error':error }
567             self.push_response(response)
568         elif result != '':
569             response = { 'id':message_id, 'result':result }
570             self.push_response(response)
571
572
573     def watch_address(self, addr):
574         if addr not in self.watched_addresses:
575             self.watched_addresses.append(addr)
576
577
578
579     def last_hash(self):
580         return self.block_hashes[-1]
581
582
583     def catch_up(self, sync = True):
584         t1 = time.time()
585
586         while not self.shared.stopped():
587
588             # are we done yet?
589             info = self.bitcoind('getinfo')
590             bitcoind_height = info.get('blocks')
591             bitcoind_block_hash = self.bitcoind('getblockhash', [bitcoind_height])
592             if self.last_hash() == bitcoind_block_hash: 
593                 self.up_to_date = True
594                 break
595
596             # not done..
597             self.up_to_date = False
598             block_hash = self.bitcoind('getblockhash', [self.height+1])
599             block = self.bitcoind('getblock', [block_hash, 1])
600
601             if block.get('previousblockhash') == self.last_hash():
602
603                 self.import_block(block, block_hash, self.height+1, sync)
604                 self.height = self.height + 1
605                 self.write_header(self.block2header(block), sync)
606
607                 self.block_hashes.append(block_hash)
608                 self.block_hashes = self.block_hashes[-10:]
609
610                 if (self.height+1)%100 == 0 and not sync: 
611                     t2 = time.time()
612                     print_log( "catch_up: block %d (%.3fs)"%( self.height, t2 - t1 ) )
613                     t1 = t2
614
615                     
616             else:
617                 # revert current block
618                 print_log( "bc2: reorg", self.height, block.get('previousblockhash'), self.last_hash() )
619                 block_hash = self.last_hash()
620                 block = self.bitcoind('getblock', [block_hash, 1])
621                 self.height = self.height -1
622                 self.pop_header()
623
624                 self.block_hashes.remove(block_hash)
625                 self.import_block(block, self.last_hash(), self.height, revert=True)
626         
627
628         self.header = self.block2header(self.bitcoind('getblock', [self.last_hash()]))
629
630         
631
632             
633     def memorypool_update(self):
634
635         mempool_hashes = self.bitcoind('getrawmempool')
636
637         for tx_hash in mempool_hashes:
638             if tx_hash in self.mempool_hashes: continue
639
640             tx = self.get_transaction(tx_hash)
641             if not tx: continue
642
643             for x in tx.get('inputs'):
644                 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
645                 try:
646                     addr = self.db.Get(txi)    
647                 except:
648                     continue
649                 l = self.mempool_addresses.get(tx_hash, [])
650                 if addr not in l: 
651                     l.append( addr )
652                     self.mempool_addresses[tx_hash] = l
653
654             for x in tx.get('outputs'):
655                 addr = x.get('address')
656                 l = self.mempool_addresses.get(tx_hash, [])
657                 if addr not in l: 
658                     l.append( addr )
659                     self.mempool_addresses[tx_hash] = l
660
661             self.mempool_hashes.append(tx_hash)
662
663         # remove older entries from mempool_hashes
664         self.mempool_hashes = mempool_hashes
665
666         # remove deprecated entries from mempool_addresses
667         for tx_hash, addresses in self.mempool_addresses.items():
668             if tx_hash not in self.mempool_hashes:
669                 self.mempool_addresses.pop(tx_hash)
670
671         # rebuild histories
672         with self.mempool_lock:
673             self.mempool_hist = {}
674             for tx_hash, addresses in self.mempool_addresses.items():
675                 for addr in addresses:
676                     h = self.mempool_hist.get(addr, [])
677                     if tx_hash not in h: 
678                         h.append( tx_hash )
679                         self.mempool_hist[addr] = h
680                         self.invalidate_cache(addr)
681
682
683
684
685     def invalidate_cache(self, address):
686         with self.cache_lock:
687             if self.history_cache.has_key(address):
688                 print_log( "cache: invalidating", address )
689                 self.history_cache.pop(address)
690
691
692
693     def main_iteration(self):
694
695         if self.shared.stopped(): 
696             print_log( "blockchain processor terminating" )
697             return
698
699         with self.dblock:
700             t1 = time.time()
701             self.catch_up()
702             t2 = time.time()
703
704         self.memorypool_update()
705         t3 = time.time()
706         # print "mempool:", len(self.mempool_addresses), len(self.mempool_hist), "%.3fs"%(t3 - t2)
707
708
709         if self.sent_height != self.height:
710             self.sent_height = self.height
711             self.push_response({ 'id': None, 'method':'blockchain.numblocks.subscribe', 'params':[self.height] })
712
713         if self.sent_header != self.header:
714             print_log( "blockchain: %d (%.3fs)"%( self.height, t2 - t1 ) )
715             self.sent_header = self.header
716             self.push_response({ 'id': None, 'method':'blockchain.headers.subscribe', 'params':[self.header] })
717
718         while True:
719             try:
720                 addr = self.address_queue.get(False)
721             except:
722                 break
723             if addr in self.watched_addresses:
724                 status = self.get_status( addr )
725                 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe', 'params':[addr, status] })
726
727
728         if not self.shared.stopped(): 
729             threading.Timer(10, self.main_iteration).start()
730         else:
731             print_log( "blockchain processor terminating" )
732
733
734
735