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, hash_160_to_bc_address(max_addr))
503 for h160 in self.batch_list.keys():
504 addr = hash_160_to_bc_address(h160)
505 self.invalidate_cache(addr)
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)
516 def process(self, request, cache_only = False):
517 #print "abe process", request
519 message_id = request['id']
520 method = request['method']
521 params = request.get('params',[])
525 if method == 'blockchain.numblocks.subscribe':
528 elif method == 'blockchain.headers.subscribe':
531 elif method == 'blockchain.address.subscribe':
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 )
540 elif method == 'blockchain.address.subscribe2':
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 )
549 elif method == 'blockchain.address.get_history2':
552 result = self.get_history( address, cache_only )
553 except BaseException, e:
554 error = str(e) + ': ' + address
555 print_log( "error:", error )
557 elif method == 'blockchain.block.get_header':
563 result = self.get_header( height )
564 except BaseException, e:
565 error = str(e) + ': %d'% height
566 print_log( "error:", error )
568 elif method == 'blockchain.block.get_chunk':
574 result = self.get_chunk( index )
575 except BaseException, e:
576 error = str(e) + ': %d'% index
577 print_log( "error:", error)
579 elif method == 'blockchain.transaction.broadcast':
580 txo = self.bitcoind('sendrawtransaction', params)
581 print_log( "sent tx:", txo )
584 elif method == 'blockchain.transaction.get_merkle':
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 )
596 elif method == 'blockchain.transaction.get':
600 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height] )
601 except BaseException, e:
602 error = str(e) + ': ' + tx_hash
603 print_log( "error:", error )
606 error = "unknown method:%s"%method
608 if cache_only and result == -1: return -1
611 response = { 'id':message_id, 'error':error }
612 self.push_response(response)
614 response = { 'id':message_id, 'result':result }
615 self.push_response(response)
618 def watch_address(self, addr):
619 if addr not in self.watched_addresses:
620 self.watched_addresses.append(addr)
624 def catch_up(self, sync = True):
628 while not self.shared.stopped():
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
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])
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
646 if (next_block.get('previousblockhash') == self.last_hash) and not revert:
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
653 if (self.height)%100 == 0 and not sync:
655 print_log( "catch_up: block %d (%.3fs)"%( self.height, t2 - t1 ) )
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)
666 self.height = self.height -1
668 # read previous header from disk
669 self.header = self.read_header(self.height)
670 self.last_hash = self.hash_header(self.header)
673 self.header = self.block2header(self.bitcoind('getblock', [self.last_hash]))
678 def memorypool_update(self):
680 mempool_hashes = self.bitcoind('getrawmempool')
682 for tx_hash in mempool_hashes:
683 if tx_hash in self.mempool_hashes: continue
685 tx = self.get_transaction(tx_hash)
688 for x in tx.get('inputs'):
689 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
691 h160 = self.db.Get(txi)
692 addr = hash_160_to_bc_address(h160)
695 l = self.mempool_addresses.get(tx_hash, [])
698 self.mempool_addresses[tx_hash] = l
700 for x in tx.get('outputs'):
701 addr = x.get('address')
702 l = self.mempool_addresses.get(tx_hash, [])
705 self.mempool_addresses[tx_hash] = l
707 self.mempool_hashes.append(tx_hash)
709 # remove older entries from mempool_hashes
710 self.mempool_hashes = mempool_hashes
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)
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, [])
724 new_mempool_hist[addr] = h
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)
731 self.invalidate_cache(addr)
733 with self.mempool_lock:
734 self.mempool_hist = new_mempool_hist
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)
744 if address in self.watched_addresses:
745 self.address_queue.put(address)
749 def main_iteration(self):
751 if self.shared.stopped():
752 print_log( "blockchain processor terminating" )
760 self.memorypool_update()
762 # print "mempool:", len(self.mempool_addresses), len(self.mempool_hist), "%.3fs"%(t3 - t2)
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] })
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] })
776 addr = self.address_queue.get(False)
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] })
785 if not self.shared.stopped():
786 threading.Timer(10, self.main_iteration).start()
788 print_log( "blockchain processor terminating" )