1 from json import dumps, loads
4 import ast, time, threading, hashlib
5 from Queue import Queue
6 import traceback, sys, os, random
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
13 class BlockchainProcessor(Processor):
15 def __init__(self, config, shared):
16 Processor.__init__(self)
20 self.up_to_date = False
21 self.watched_addresses = []
22 self.history_cache = {}
24 self.cache_lock = threading.Lock()
25 self.headers_data = ''
27 self.mempool_addresses = {}
28 self.mempool_hist = {}
29 self.mempool_hashes = []
30 self.mempool_lock = threading.Lock()
32 self.address_queue = Queue()
33 self.dbpath = config.get('leveldb', 'path')
35 self.dblock = threading.Lock()
37 self.db = leveldb.LevelDB(self.dbpath)
39 traceback.print_exc(file=sys.stdout)
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'))
51 self.sent_header = None
55 hist = self.deserialize(self.db.Get('height'))
56 self.last_hash, self.height, _ = hist[0]
57 print_log( "hist", hist )
59 #traceback.print_exc(file=sys.stdout)
60 print_log('initializing database')
62 self.last_hash = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
65 self.init_headers(self.height)
67 threading.Timer(0, lambda: self.catch_up(sync=False)).start()
68 while not shared.stopped() and not self.up_to_date:
72 print "keyboard interrupt: stopping threads"
76 print_log( "blockchain is up to date." )
78 threading.Timer(10, self.main_iteration).start()
82 def bitcoind(self, method, params=[]):
83 postdata = dumps({"method": method, 'params': params, 'id':'jsonrpc'})
84 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
86 if r['error'] != None:
87 raise BaseException(r['error'])
88 return r.get('result')
91 def serialize(self, h):
93 for txid, txpos, height in h:
94 s += txid + int_to_hex(txpos, 4) + int_to_hex(height, 4)
95 return s.decode('hex')
98 def deserialize(self, s):
101 txid = s[0:32].encode('hex')
102 txpos = int( rev_hex( s[32:36].encode('hex') ), 16 )
103 height = int( rev_hex( s[36:40].encode('hex') ), 16 )
104 h.append( ( txid, txpos, height ) )
109 def block2header(self, b):
110 return {"block_height":b.get('height'), "version":b.get('version'), "prev_block_hash":b.get('previousblockhash'),
111 "merkle_root":b.get('merkleroot'), "timestamp":b.get('time'), "bits":int(b.get('bits'),16), "nonce":b.get('nonce')}
114 def get_header(self, height):
115 block_hash = self.bitcoind('getblockhash', [height])
116 b = self.bitcoind('getblock', [block_hash])
117 return self.block2header(b)
120 def init_headers(self, db_height):
121 self.chunk_cache = {}
122 self.headers_filename = os.path.join( self.dbpath, 'blockchain_headers')
124 if os.path.exists(self.headers_filename):
125 height = os.path.getsize(self.headers_filename)/80 - 1 # the current height
127 prev_hash = self.hash_header(self.read_header(height))
131 open(self.headers_filename,'wb').close()
135 if height < db_height:
136 print_log( "catching up missing headers:", height, db_height)
139 while height < db_height:
141 header = self.get_header(height)
143 assert prev_hash == header.get('prev_block_hash')
144 self.write_header(header, sync=False)
145 prev_hash = self.hash_header(header)
146 if height%1000==0: print_log("headers file:",height)
147 except KeyboardInterrupt:
154 def hash_header(self, header):
155 return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
158 def read_header(self, block_height):
159 if os.path.exists(self.headers_filename):
160 f = open(self.headers_filename,'rb')
161 f.seek(block_height*80)
165 h = header_from_string(h)
169 def read_chunk(self, index):
170 f = open(self.headers_filename,'rb')
171 f.seek(index*2016*80)
172 chunk = f.read(2016*80)
174 return chunk.encode('hex')
177 def write_header(self, header, sync=True):
178 if not self.headers_data:
179 self.headers_offset = header.get('block_height')
181 self.headers_data += header_to_string(header).decode('hex')
182 if sync or len(self.headers_data) > 40*100:
185 with self.cache_lock:
186 chunk_index = header.get('block_height')/2016
187 if self.chunk_cache.get(chunk_index):
188 self.chunk_cache.pop(chunk_index)
190 def pop_header(self):
191 # we need to do this only if we have not flushed
192 if self.headers_data:
193 self.headers_data = self.headers_data[:-40]
195 def flush_headers(self):
196 if not self.headers_data: return
197 f = open(self.headers_filename,'rb+')
198 f.seek(self.headers_offset*80)
199 f.write(self.headers_data)
201 self.headers_data = ''
204 def get_chunk(self, i):
205 # store them on disk; store the current chunk in memory
206 with self.cache_lock:
207 chunk = self.chunk_cache.get(i)
209 chunk = self.read_chunk(i)
210 self.chunk_cache[i] = chunk
215 def get_transaction(self, txid, block_height=-1, is_coinbase = False):
216 raw_tx = self.bitcoind('getrawtransaction', [txid, 0, block_height])
217 vds = deserialize.BCDataStream()
218 vds.write(raw_tx.decode('hex'))
219 out = deserialize.parse_Transaction(vds, is_coinbase)
223 def get_history(self, addr, cache_only=False):
224 with self.cache_lock: hist = self.history_cache.get( addr )
225 if hist is not None: return hist
226 if cache_only: return -1
230 hash_160 = bc_address_to_hash_160(addr)
231 hist = self.deserialize(self.db.Get(hash_160))
237 # should not be necessary
238 hist.sort( key=lambda tup: tup[1])
239 # check uniqueness too...
242 with self.mempool_lock:
243 for txid in self.mempool_hist.get(addr,[]):
244 hist.append((txid, 0, 0))
246 hist = map(lambda x: {'tx_hash':x[0], 'height':x[2]}, hist)
247 # add something to distinguish between unused and empty addresses
248 if hist == [] and is_known: hist = ['*']
250 with self.cache_lock: self.history_cache[addr] = hist
254 def get_status(self, addr, cache_only=False):
255 tx_points = self.get_history(addr, cache_only)
256 if cache_only and tx_points == -1: return -1
258 if not tx_points: return None
259 if tx_points == ['*']: return '*'
262 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
263 return hashlib.sha256( status ).digest().encode('hex')
266 def get_merkle(self, tx_hash, height):
268 block_hash = self.bitcoind('getblockhash', [height])
269 b = self.bitcoind('getblock', [block_hash])
270 tx_list = b.get('tx')
271 tx_pos = tx_list.index(tx_hash)
273 merkle = map(hash_decode, tx_list)
274 target_hash = hash_decode(tx_hash)
276 while len(merkle) != 1:
277 if len(merkle)%2: merkle.append( merkle[-1] )
280 new_hash = Hash( merkle[0] + merkle[1] )
281 if merkle[0] == target_hash:
282 s.append( hash_encode( merkle[1]))
283 target_hash = new_hash
284 elif merkle[1] == target_hash:
285 s.append( hash_encode( merkle[0]))
286 target_hash = new_hash
291 return {"block_height":height, "merkle":s, "pos":tx_pos}
296 def add_to_history(self, addr, tx_hash, tx_pos, tx_height):
299 s = (tx_hash + int_to_hex(tx_pos, 4) + int_to_hex(tx_height, 4)).decode('hex')
301 serialized_hist = self.batch_list[addr]
303 l = len(serialized_hist)/40
304 for i in range(l-1, -1, -1):
305 item = serialized_hist[40*i:40*(i+1)]
306 item_height = int( rev_hex( item[36:40].encode('hex') ), 16 )
307 if item_height < tx_height:
308 serialized_hist = serialized_hist[0:40*(i+1)] + s + serialized_hist[40*(i+1):]
311 serialized_hist = s + serialized_hist
313 self.batch_list[addr] = serialized_hist
316 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
317 self.batch_txio[txo] = addr
320 def remove_from_history(self, addr, tx_hash, tx_pos):
322 txi = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
326 addr = self.batch_txio[txi]
328 raise BaseException(tx_hash, tx_pos)
330 serialized_hist = self.batch_list[addr]
332 l = len(serialized_hist)/40
334 item = serialized_hist[40*i:40*(i+1)]
335 if item[0:36] == txi:
336 height = int( rev_hex( item[36:40].encode('hex') ), 16 )
337 serialized_hist = serialized_hist[0:40*i] + serialized_hist[40*(i+1):]
340 hist = self.deserialize(serialized_hist)
341 raise BaseException("prevout not found", addr, hist, tx_hash, tx_pos)
343 self.batch_list[addr] = serialized_hist
347 def deserialize_block(self, block):
348 txlist = block.get('tx')
349 tx_hashes = [] # ordered txids
350 txdict = {} # deserialized tx
352 for raw_tx in txlist:
353 tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
354 tx_hashes.append(tx_hash)
355 vds = deserialize.BCDataStream()
356 vds.write(raw_tx.decode('hex'))
357 tx = deserialize.parse_Transaction(vds, is_coinbase)
360 return tx_hashes, txdict
362 def get_undo_info(self, height):
363 s = self.db.Get("undo%d"%(height%100))
366 def write_undo_info(self, batch, height, undo_info):
367 if self.is_test or height > self.bitcoind_height - 100:
368 batch.Put("undo%d"%(height%100), repr(undo_info))
371 def import_block(self, block, block_hash, block_height, sync, revert=False):
373 self.batch_list = {} # address -> history
374 self.batch_txio = {} # transaction i/o -> address
380 # deserialize transactions
382 tx_hashes, txdict = self.deserialize_block(block)
388 # read addresses of tx inputs
389 for tx in txdict.values():
390 for x in tx.get('inputs'):
391 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
392 block_inputs.append(txi)
395 for txi in block_inputs:
397 addr = self.db.Get(txi)
399 # the input could come from the same block
401 self.batch_txio[txi] = addr
402 addr_to_read.append(addr)
405 for txid, tx in txdict.items():
406 for x in tx.get('outputs'):
407 txo = (txid + int_to_hex(x.get('index'), 4)).decode('hex')
408 block_outputs.append(txo)
410 # read histories of addresses
411 for txid, tx in txdict.items():
412 for x in tx.get('outputs'):
413 hash_160 = bc_address_to_hash_160(x.get('address'))
414 addr_to_read.append(hash_160)
417 for addr in addr_to_read:
419 self.batch_list[addr] = self.db.Get(addr)
421 self.batch_list[addr] = ''
425 undo_info = self.get_undo_info(block_height)
426 # print "undo", block_height, undo_info
432 if revert: tx_hashes = tx_hashes[::-1]
433 for txid in tx_hashes: # must be ordered
438 for x in tx.get('inputs'):
439 prevout_height, prevout_addr = self.remove_from_history( None, x.get('prevout_hash'), x.get('prevout_n'))
440 undo.append( (prevout_height, prevout_addr) )
441 undo_info[txid] = undo
443 for x in tx.get('outputs'):
444 hash_160 = bc_address_to_hash_160(x.get('address'))
445 self.add_to_history( hash_160, txid, x.get('index'), block_height)
448 for x in tx.get('outputs'):
449 hash_160 = bc_address_to_hash_160(x.get('address'))
450 self.remove_from_history( hash_160, txid, x.get('index'))
453 for x in tx.get('inputs'):
454 prevout_height, prevout_addr = undo_info.get(txid)[i]
457 # read the history into batch list
458 if self.batch_list.get(prevout_addr) is None:
459 self.batch_list[prevout_addr] = self.db.Get(prevout_addr)
461 # re-add them to the history
462 self.add_to_history( prevout_addr, x.get('prevout_hash'), x.get('prevout_n'), prevout_height)
463 # print_log( "new hist for", hash_160_to_bc_address(prevout_addr), self.deserialize(self.batch_list[prevout_addr]) )
470 batch = leveldb.WriteBatch()
471 for addr, serialized_hist in self.batch_list.items():
472 batch.Put(addr, serialized_hist)
473 l = len(serialized_hist)
479 # add new created outputs
480 for txio, addr in self.batch_txio.items():
481 batch.Put(txio, addr)
482 # delete spent inputs
483 for txi in block_inputs:
486 self.write_undo_info(batch, block_height, undo_info)
488 # restore spent inputs
489 for txio, addr in self.batch_txio.items():
490 batch.Put(txio, addr)
491 # delete spent outputs
492 for txo in block_outputs:
497 batch.Put('height', self.serialize( [(block_hash, block_height, 0)] ) )
500 self.db.Write(batch, sync = sync)
503 if t3 - t0 > 10 and not sync:
504 print_log("block", block_height,
505 "parse:%0.2f "%(t00 - t0),
506 "read:%0.2f "%(t1 - t00),
507 "proc:%.2f "%(t2-t1),
508 "write:%.2f "%(t3-t2),
509 "max:", max_len, hash_160_to_bc_address(max_addr))
511 for h160 in self.batch_list.keys():
512 addr = hash_160_to_bc_address(h160)
513 self.invalidate_cache(addr)
517 def add_request(self, request):
518 # see if we can get if from cache. if not, add to queue
519 if self.process( request, cache_only = True) == -1:
520 self.queue.put(request)
524 def process(self, request, cache_only = False):
525 #print "abe process", request
527 message_id = request['id']
528 method = request['method']
529 params = request.get('params',[])
533 if method == 'blockchain.numblocks.subscribe':
536 elif method == 'blockchain.headers.subscribe':
539 elif method == 'blockchain.address.subscribe':
542 result = self.get_status(address, cache_only)
543 self.watch_address(address)
544 except BaseException, e:
545 error = str(e) + ': ' + address
546 print_log( "error:", error )
548 elif method == 'blockchain.address.unsubscribe':
552 if password == self.config.get('server','password'):
553 self.watched_addresses.remove(address)
554 print_log('unsubscribed', address)
557 print_log('incorrect password')
558 result = "authentication error"
559 except BaseException, e:
560 error = str(e) + ': ' + address
561 print_log( "error:", error )
563 elif method == 'blockchain.address.get_history':
566 result = self.get_history( address, cache_only )
567 except BaseException, e:
568 error = str(e) + ': ' + address
569 print_log( "error:", error )
571 elif method == 'blockchain.block.get_header':
577 result = self.get_header( height )
578 except BaseException, e:
579 error = str(e) + ': %d'% height
580 print_log( "error:", error )
582 elif method == 'blockchain.block.get_chunk':
588 result = self.get_chunk( index )
589 except BaseException, e:
590 error = str(e) + ': %d'% index
591 print_log( "error:", error)
593 elif method == 'blockchain.transaction.broadcast':
595 txo = self.bitcoind('sendrawtransaction', params)
596 print_log( "sent tx:", txo )
598 except BaseException, e:
599 result = str(e) # do not send an error
600 print_log( "error:", str(e), params )
602 elif method == 'blockchain.transaction.get_merkle':
608 tx_height = params[1]
609 result = self.get_merkle(tx_hash, tx_height)
610 except BaseException, e:
611 error = str(e) + ': ' + tx_hash
612 print_log( "error:", error )
614 elif method == 'blockchain.transaction.get':
618 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height] )
619 except BaseException, e:
620 error = str(e) + ': ' + tx_hash
621 print_log( "error:", error )
624 error = "unknown method:%s"%method
626 if cache_only and result == -1: return -1
629 response = { 'id':message_id, 'error':error }
630 self.push_response(response)
632 response = { 'id':message_id, 'result':result }
633 self.push_response(response)
636 def watch_address(self, addr):
637 if addr not in self.watched_addresses:
638 self.watched_addresses.append(addr)
642 def catch_up(self, sync = True):
646 while not self.shared.stopped():
649 info = self.bitcoind('getinfo')
650 self.bitcoind_height = info.get('blocks')
651 bitcoind_block_hash = self.bitcoind('getblockhash', [self.bitcoind_height])
652 if self.last_hash == bitcoind_block_hash:
653 self.up_to_date = True
657 self.up_to_date = False
658 next_block_hash = self.bitcoind('getblockhash', [self.height+1])
659 next_block = self.bitcoind('getblock', [next_block_hash, 1])
661 # fixme: this is unsafe, if we revert when the undo info is not yet written
662 revert = (random.randint(1, 100)==1) if self.is_test else False
664 if (next_block.get('previousblockhash') == self.last_hash) and not revert:
666 self.import_block(next_block, next_block_hash, self.height+1, sync)
667 self.height = self.height + 1
668 self.write_header(self.block2header(next_block), sync)
669 self.last_hash = next_block_hash
671 if (self.height)%100 == 0 and not sync:
673 print_log( "catch_up: block %d (%.3fs)"%( self.height, t2 - t1 ) )
677 # revert current block
678 block = self.bitcoind('getblock', [self.last_hash, 1])
679 print_log( "blockchain reorg", self.height, block.get('previousblockhash'), self.last_hash )
680 self.import_block(block, self.last_hash, self.height, sync, revert=True)
684 self.height = self.height -1
686 # read previous header from disk
687 self.header = self.read_header(self.height)
688 self.last_hash = self.hash_header(self.header)
691 self.header = self.block2header(self.bitcoind('getblock', [self.last_hash]))
696 def memorypool_update(self):
698 mempool_hashes = self.bitcoind('getrawmempool')
700 for tx_hash in mempool_hashes:
701 if tx_hash in self.mempool_hashes: continue
703 tx = self.get_transaction(tx_hash)
706 for x in tx.get('inputs'):
707 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
709 h160 = self.db.Get(txi)
710 addr = hash_160_to_bc_address(h160)
713 l = self.mempool_addresses.get(tx_hash, [])
716 self.mempool_addresses[tx_hash] = l
718 for x in tx.get('outputs'):
719 addr = x.get('address')
720 l = self.mempool_addresses.get(tx_hash, [])
723 self.mempool_addresses[tx_hash] = l
725 self.mempool_hashes.append(tx_hash)
727 # remove older entries from mempool_hashes
728 self.mempool_hashes = mempool_hashes
730 # remove deprecated entries from mempool_addresses
731 for tx_hash, addresses in self.mempool_addresses.items():
732 if tx_hash not in self.mempool_hashes:
733 self.mempool_addresses.pop(tx_hash)
736 new_mempool_hist = {}
737 for tx_hash, addresses in self.mempool_addresses.items():
738 for addr in addresses:
739 h = new_mempool_hist.get(addr, [])
742 new_mempool_hist[addr] = h
744 for addr in new_mempool_hist.keys():
745 if addr in self.mempool_hist.keys():
746 if self.mempool_hist[addr] != new_mempool_hist[addr]:
747 self.invalidate_cache(addr)
749 self.invalidate_cache(addr)
751 with self.mempool_lock:
752 self.mempool_hist = new_mempool_hist
756 def invalidate_cache(self, address):
757 with self.cache_lock:
758 if self.history_cache.has_key(address):
759 print_log( "cache: invalidating", address )
760 self.history_cache.pop(address)
762 if address in self.watched_addresses:
763 self.address_queue.put(address)
767 def main_iteration(self):
769 if self.shared.stopped():
770 print_log( "blockchain processor terminating" )
778 self.memorypool_update()
780 # print "mempool:", len(self.mempool_addresses), len(self.mempool_hist), "%.3fs"%(t3 - t2)
783 if self.sent_height != self.height:
784 self.sent_height = self.height
785 self.push_response({ 'id': None, 'method':'blockchain.numblocks.subscribe', 'params':[self.height] })
787 if self.sent_header != self.header:
788 print_log( "blockchain: %d (%.3fs)"%( self.height, t2 - t1 ) )
789 self.sent_header = self.header
790 self.push_response({ 'id': None, 'method':'blockchain.headers.subscribe', 'params':[self.header] })
794 addr = self.address_queue.get(False)
797 if addr in self.watched_addresses:
798 status = self.get_status( addr )
799 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe', 'params':[addr, status] })
801 if not self.shared.stopped():
802 threading.Timer(10, self.main_iteration).start()
804 print_log( "blockchain processor terminating" )