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)
19 self.up_to_date = False
20 self.watched_addresses = []
21 self.history_cache = {}
23 self.cache_lock = threading.Lock()
24 self.headers_data = ''
26 self.mempool_addresses = {}
27 self.mempool_hist = {}
28 self.mempool_hashes = []
29 self.mempool_lock = threading.Lock()
31 self.address_queue = Queue()
32 self.dbpath = config.get('leveldb', 'path')
34 self.dblock = threading.Lock()
36 self.db = leveldb.LevelDB(self.dbpath)
38 traceback.print_exc(file=sys.stdout)
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'))
50 self.sent_header = None
54 hist = self.deserialize(self.db.Get('height'))
55 self.last_hash, self.height, _ = hist[0]
56 print_log( "hist", hist )
58 #traceback.print_exc(file=sys.stdout)
59 print_log('initializing database')
61 self.last_hash = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
64 self.init_headers(self.height)
66 threading.Timer(0, lambda: self.catch_up(sync=False)).start()
67 while not shared.stopped() and not self.up_to_date:
71 print "keyboard interrupt: stopping threads"
75 print_log( "blockchain is up to date." )
77 threading.Timer(10, self.main_iteration).start()
81 def bitcoind(self, method, params=[]):
82 postdata = dumps({"method": method, 'params': params, 'id':'jsonrpc'})
83 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
85 if r['error'] != None:
86 raise BaseException(r['error'])
87 return r.get('result')
90 def serialize(self, h):
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')
97 def deserialize(self, 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 ) )
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')}
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)
119 def init_headers(self, db_height):
120 self.chunk_cache = {}
121 self.headers_filename = os.path.join( self.dbpath, 'blockchain_headers')
123 if os.path.exists(self.headers_filename):
124 height = os.path.getsize(self.headers_filename)/80 - 1 # the current height
126 prev_hash = self.hash_header(self.read_header(height))
130 open(self.headers_filename,'wb').close()
134 if height < db_height:
135 print_log( "catching up missing headers:", height, db_height)
138 while height < db_height:
140 header = self.get_header(height)
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:
153 def hash_header(self, header):
154 return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
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)
164 h = header_from_string(h)
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)
173 return chunk.encode('hex')
176 def write_header(self, header, sync=True):
177 if not self.headers_data:
178 self.headers_offset = header.get('block_height')
180 self.headers_data += header_to_string(header).decode('hex')
181 if sync or len(self.headers_data) > 40*100:
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]
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)
195 self.headers_data = ''
198 def get_chunk(self, i):
199 # store them on disk; store the current chunk in memory
200 chunk = self.chunk_cache.get(i)
202 chunk = self.read_chunk(i)
203 self.chunk_cache[i] = chunk
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)
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
222 hash_160 = bc_address_to_hash_160(addr)
223 hist = self.deserialize(self.db.Get(hash_160))
229 # should not be necessary
230 hist.sort( key=lambda tup: tup[1])
231 # check uniqueness too...
234 with self.mempool_lock:
235 for txid in self.mempool_hist.get(addr,[]):
236 hist.append((txid, 0, 0))
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 = ['*']
242 with self.cache_lock: self.history_cache[addr] = hist
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
250 if not tx_points: return None
251 if tx_points == ['*']: return '*'
254 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
255 return hashlib.sha256( status ).digest().encode('hex')
258 def get_merkle(self, tx_hash, height):
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)
265 merkle = map(hash_decode, tx_list)
266 target_hash = hash_decode(tx_hash)
268 while len(merkle) != 1:
269 if len(merkle)%2: merkle.append( merkle[-1] )
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
283 return {"block_height":height, "merkle":s, "pos":tx_pos}
288 def add_to_history(self, addr, tx_hash, tx_pos, tx_height):
291 s = (tx_hash + int_to_hex(tx_pos, 4) + int_to_hex(tx_height, 4)).decode('hex')
293 serialized_hist = self.batch_list[addr]
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):]
303 serialized_hist = s + serialized_hist
305 self.batch_list[addr] = serialized_hist
308 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
309 self.batch_txio[txo] = addr
312 def remove_from_history(self, addr, tx_hash, tx_pos):
314 txi = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
318 addr = self.batch_txio[txi]
320 raise BaseException(tx_hash, tx_pos)
322 serialized_hist = self.batch_list[addr]
324 l = len(serialized_hist)/40
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):]
332 hist = self.deserialize(serialized_hist)
333 raise BaseException("prevout not found", addr, hist, tx_hash, tx_pos)
335 self.batch_list[addr] = serialized_hist
339 def deserialize_block(self, block):
340 txlist = block.get('tx')
341 tx_hashes = [] # ordered txids
342 txdict = {} # deserialized tx
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)
352 return tx_hashes, txdict
354 def get_undo_info(self, height):
355 s = self.db.Get("undo%d"%(height%100))
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))
363 def import_block(self, block, block_hash, block_height, sync, revert=False):
365 self.batch_list = {} # address -> history
366 self.batch_txio = {} # transaction i/o -> address
372 # deserialize transactions
374 tx_hashes, txdict = self.deserialize_block(block)
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)
387 for txi in block_inputs:
389 addr = self.db.Get(txi)
391 # the input could come from the same block
393 self.batch_txio[txi] = addr
394 addr_to_read.append(addr)
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)
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)
409 for addr in addr_to_read:
411 self.batch_list[addr] = self.db.Get(addr)
413 self.batch_list[addr] = ''
417 undo_info = self.get_undo_info(block_height)
418 # print "undo", block_height, undo_info
424 if revert: tx_hashes = tx_hashes[::-1]
425 for txid in tx_hashes: # must be ordered
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
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)
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'))
445 for x in tx.get('inputs'):
446 prevout_height, prevout_addr = undo_info.get(txid)[i]
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)
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]) )
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)
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:
478 self.write_undo_info(batch, block_height, undo_info)
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:
489 batch.Put('height', self.serialize( [(block_hash, block_height, 0)] ) )
492 self.db.Write(batch, sync = sync)
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, max_addr)
503 for addr in self.batch_list.keys(): self.invalidate_cache(addr)
507 def add_request(self, request):
508 # see if we can get if from cache. if not, add to queue
509 if self.process( request, cache_only = True) == -1:
510 self.queue.put(request)
514 def process(self, request, cache_only = False):
515 #print "abe process", request
517 message_id = request['id']
518 method = request['method']
519 params = request.get('params',[])
523 if method == 'blockchain.numblocks.subscribe':
526 elif method == 'blockchain.headers.subscribe':
529 elif method == 'blockchain.address.subscribe':
532 result = self.get_status(address, cache_only)
533 self.watch_address(address)
534 except BaseException, e:
535 error = str(e) + ': ' + address
536 print_log( "error:", error )
538 elif method == 'blockchain.address.subscribe2':
541 result = self.get_status(address, cache_only)
542 self.watch_address(address)
543 except BaseException, e:
544 error = str(e) + ': ' + address
545 print_log( "error:", error )
547 elif method == 'blockchain.address.get_history2':
550 result = self.get_history( address, cache_only )
551 except BaseException, e:
552 error = str(e) + ': ' + address
553 print_log( "error:", error )
555 elif method == 'blockchain.block.get_header':
561 result = self.get_header( height )
562 except BaseException, e:
563 error = str(e) + ': %d'% height
564 print_log( "error:", error )
566 elif method == 'blockchain.block.get_chunk':
572 result = self.get_chunk( index )
573 except BaseException, e:
574 error = str(e) + ': %d'% index
575 print_log( "error:", error)
577 elif method == 'blockchain.transaction.broadcast':
578 txo = self.bitcoind('sendrawtransaction', params)
579 print_log( "sent tx:", txo )
582 elif method == 'blockchain.transaction.get_merkle':
588 tx_height = params[1]
589 result = self.get_merkle(tx_hash, tx_height)
590 except BaseException, e:
591 error = str(e) + ': ' + tx_hash
592 print_log( "error:", error )
594 elif method == 'blockchain.transaction.get':
598 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height] )
599 except BaseException, e:
600 error = str(e) + ': ' + tx_hash
601 print_log( "error:", error )
604 error = "unknown method:%s"%method
606 if cache_only and result == -1: return -1
609 response = { 'id':message_id, 'error':error }
610 self.push_response(response)
612 response = { 'id':message_id, 'result':result }
613 self.push_response(response)
616 def watch_address(self, addr):
617 if addr not in self.watched_addresses:
618 self.watched_addresses.append(addr)
622 def catch_up(self, sync = True):
626 while not self.shared.stopped():
629 info = self.bitcoind('getinfo')
630 self.bitcoind_height = info.get('blocks')
631 bitcoind_block_hash = self.bitcoind('getblockhash', [self.bitcoind_height])
632 if self.last_hash == bitcoind_block_hash:
633 self.up_to_date = True
637 self.up_to_date = False
638 next_block_hash = self.bitcoind('getblockhash', [self.height+1])
639 next_block = self.bitcoind('getblock', [next_block_hash, 1])
641 # fixme: this is unsafe, if we revert when the undo info is not yet written
642 revert = (random.randint(1, 100)==1) if self.is_test else False
644 if (next_block.get('previousblockhash') == self.last_hash) and not revert:
646 self.import_block(next_block, next_block_hash, self.height+1, sync)
647 self.height = self.height + 1
648 self.write_header(self.block2header(next_block), sync)
649 self.last_hash = next_block_hash
651 if (self.height)%100 == 0 and not sync:
653 print_log( "catch_up: block %d (%.3fs)"%( self.height, t2 - t1 ) )
657 # revert current block
658 block = self.bitcoind('getblock', [self.last_hash, 1])
659 print_log( "blockchain reorg", self.height, block.get('previousblockhash'), self.last_hash )
660 self.import_block(block, self.last_hash, self.height, sync, revert=True)
664 self.height = self.height -1
666 # read previous header from disk
667 self.header = self.read_header(self.height)
668 self.last_hash = self.hash_header(self.header)
671 self.header = self.block2header(self.bitcoind('getblock', [self.last_hash]))
676 def memorypool_update(self):
678 mempool_hashes = self.bitcoind('getrawmempool')
680 for tx_hash in mempool_hashes:
681 if tx_hash in self.mempool_hashes: continue
683 tx = self.get_transaction(tx_hash)
686 for x in tx.get('inputs'):
687 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
689 addr = self.db.Get(txi)
692 l = self.mempool_addresses.get(tx_hash, [])
695 self.mempool_addresses[tx_hash] = l
697 for x in tx.get('outputs'):
698 addr = x.get('address')
699 l = self.mempool_addresses.get(tx_hash, [])
702 self.mempool_addresses[tx_hash] = l
704 self.mempool_hashes.append(tx_hash)
706 # remove older entries from mempool_hashes
707 self.mempool_hashes = mempool_hashes
709 # remove deprecated entries from mempool_addresses
710 for tx_hash, addresses in self.mempool_addresses.items():
711 if tx_hash not in self.mempool_hashes:
712 self.mempool_addresses.pop(tx_hash)
715 new_mempool_hist = {}
716 for tx_hash, addresses in self.mempool_addresses.items():
717 for addr in addresses:
718 h = new_mempool_hist.get(addr, [])
721 new_mempool_hist[addr] = h
723 for addr in new_mempool_hist.keys():
724 if addr in self.mempool_hist.keys():
725 if self.mempool_hist[addr] != new_mempool_hist[addr]:
726 self.invalidate_cache(addr)
728 self.invalidate_cache(addr)
730 with self.mempool_lock:
731 self.mempool_hist = new_mempool_hist
735 def invalidate_cache(self, address):
736 with self.cache_lock:
737 if self.history_cache.has_key(address):
738 print_log( "cache: invalidating", address )
739 self.history_cache.pop(address)
741 if address in self.watched_addresses:
742 self.address_queue.put(address)
746 def main_iteration(self):
748 if self.shared.stopped():
749 print_log( "blockchain processor terminating" )
757 self.memorypool_update()
759 # print "mempool:", len(self.mempool_addresses), len(self.mempool_hist), "%.3fs"%(t3 - t2)
762 if self.sent_height != self.height:
763 self.sent_height = self.height
764 self.push_response({ 'id': None, 'method':'blockchain.numblocks.subscribe', 'params':[self.height] })
766 if self.sent_header != self.header:
767 print_log( "blockchain: %d (%.3fs)"%( self.height, t2 - t1 ) )
768 self.sent_header = self.header
769 self.push_response({ 'id': None, 'method':'blockchain.headers.subscribe', 'params':[self.header] })
773 addr = self.address_queue.get(False)
776 if addr in self.watched_addresses:
777 status = self.get_status( addr )
778 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe', 'params':[addr, status] })
779 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe2', 'params':[addr, status] })
782 if not self.shared.stopped():
783 threading.Timer(10, self.main_iteration).start()
785 print_log( "blockchain processor terminating" )