3 from json import dumps, loads
6 from Queue import Queue
14 from backends.bitcoind import deserialize
15 from processor import Processor, print_log
19 class BlockchainProcessor(Processor):
21 def __init__(self, config, shared):
22 Processor.__init__(self)
26 self.up_to_date = False
27 self.watched_addresses = []
28 self.history_cache = {}
30 self.cache_lock = threading.Lock()
31 self.headers_data = ''
33 self.mempool_addresses = {}
34 self.mempool_hist = {}
35 self.mempool_hashes = []
36 self.mempool_lock = threading.Lock()
38 self.address_queue = Queue()
39 self.dbpath = config.get('leveldb', 'path')
40 self.pruning_limit = config.getint('leveldb', 'pruning_limit')
41 self.db_version = 1 # increase this when database needs to be updated
43 self.dblock = threading.Lock()
45 self.db = leveldb.LevelDB(self.dbpath)
47 traceback.print_exc(file=sys.stdout)
50 self.bitcoind_url = 'http://%s:%s@%s:%s/' % (
51 config.get('bitcoind', 'user'),
52 config.get('bitcoind', 'password'),
53 config.get('bitcoind', 'host'),
54 config.get('bitcoind', 'port'))
59 self.sent_header = None
62 hist = self.deserialize(self.db.Get('height'))
63 self.last_hash, self.height, db_version = hist[0]
64 print_log("Database version", self.db_version)
65 print_log("Blockchain height", self.height)
67 traceback.print_exc(file=sys.stdout)
68 print_log('initializing database')
70 self.last_hash = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
71 db_version = self.db_version
74 if self.db_version != db_version:
75 print_log("Your database '%s' is deprecated. Please create a new database"%self.dbpath)
80 self.init_headers(self.height)
82 threading.Timer(0, lambda: self.catch_up(sync=False)).start()
83 while not shared.stopped() and not self.up_to_date:
87 print "keyboard interrupt: stopping threads"
91 print_log("Blockchain is up to date.")
92 self.memorypool_update()
93 print_log("Memory pool initialized.")
95 threading.Timer(10, self.main_iteration).start()
97 def bitcoind(self, method, params=[]):
98 postdata = dumps({"method": method, 'params': params, 'id': 'jsonrpc'})
100 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
102 traceback.print_exc(file=sys.stdout)
106 if r['error'] is not None:
107 raise BaseException(r['error'])
108 return r.get('result')
110 def serialize(self, h):
112 for txid, txpos, height in h:
113 s += self.serialize_item(txid, txpos, height)
116 def serialize_item(self, txid, txpos, height, spent=chr(0)):
117 s = (txid + int_to_hex(txpos, 4) + int_to_hex(height, 3)).decode('hex') + spent
120 def deserialize_item(self,s):
121 txid = s[0:32].encode('hex')
122 txpos = int(rev_hex(s[32:36].encode('hex')), 16)
123 height = int(rev_hex(s[36:39].encode('hex')), 16)
125 return (txid, txpos, height, spent)
127 def deserialize(self, s):
130 txid, txpos, height, spent = self.deserialize_item(s[0:40])
131 h.append((txid, txpos, height))
133 txid, txpos, height, spent = self.deserialize_item(s[40:80])
134 h.append((txid, txpos, height))
138 def block2header(self, b):
140 "block_height": b.get('height'),
141 "version": b.get('version'),
142 "prev_block_hash": b.get('previousblockhash'),
143 "merkle_root": b.get('merkleroot'),
144 "timestamp": b.get('time'),
145 "bits": int(b.get('bits'), 16),
146 "nonce": b.get('nonce'),
149 def get_header(self, height):
150 block_hash = self.bitcoind('getblockhash', [height])
151 b = self.bitcoind('getblock', [block_hash])
152 return self.block2header(b)
154 def init_headers(self, db_height):
155 self.chunk_cache = {}
156 self.headers_filename = os.path.join(self.dbpath, 'blockchain_headers')
158 if os.path.exists(self.headers_filename):
159 height = os.path.getsize(self.headers_filename)/80 - 1 # the current height
161 prev_hash = self.hash_header(self.read_header(height))
165 open(self.headers_filename, 'wb').close()
169 if height < db_height:
170 print_log("catching up missing headers:", height, db_height)
173 while height < db_height:
175 header = self.get_header(height)
177 assert prev_hash == header.get('prev_block_hash')
178 self.write_header(header, sync=False)
179 prev_hash = self.hash_header(header)
180 if (height % 1000) == 0:
181 print_log("headers file:", height)
182 except KeyboardInterrupt:
188 def hash_header(self, header):
189 return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
191 def read_header(self, block_height):
192 if os.path.exists(self.headers_filename):
193 with open(self.headers_filename, 'rb') as f:
194 f.seek(block_height * 80)
197 h = header_from_string(h)
200 def read_chunk(self, index):
201 with open(self.headers_filename, 'rb') as f:
202 f.seek(index*2016*80)
203 chunk = f.read(2016*80)
204 return chunk.encode('hex')
206 def write_header(self, header, sync=True):
207 if not self.headers_data:
208 self.headers_offset = header.get('block_height')
210 self.headers_data += header_to_string(header).decode('hex')
211 if sync or len(self.headers_data) > 40*100:
214 with self.cache_lock:
215 chunk_index = header.get('block_height')/2016
216 if self.chunk_cache.get(chunk_index):
217 self.chunk_cache.pop(chunk_index)
219 def pop_header(self):
220 # we need to do this only if we have not flushed
221 if self.headers_data:
222 self.headers_data = self.headers_data[:-40]
224 def flush_headers(self):
225 if not self.headers_data:
227 with open(self.headers_filename, 'rb+') as f:
228 f.seek(self.headers_offset*80)
229 f.write(self.headers_data)
230 self.headers_data = ''
232 def get_chunk(self, i):
233 # store them on disk; store the current chunk in memory
234 with self.cache_lock:
235 chunk = self.chunk_cache.get(i)
237 chunk = self.read_chunk(i)
238 self.chunk_cache[i] = chunk
242 def get_mempool_transaction(self, txid):
244 raw_tx = self.bitcoind('getrawtransaction', [txid, 0, -1])
248 vds = deserialize.BCDataStream()
249 vds.write(raw_tx.decode('hex'))
251 return deserialize.parse_Transaction(vds, is_coinbase=False)
253 def get_history(self, addr, cache_only=False):
254 with self.cache_lock:
255 hist = self.history_cache.get(addr)
263 hist = self.deserialize(self.db.Get(addr))
269 # sort history, because redeeming transactions are next to the corresponding txout
270 hist.sort(key=lambda tup: tup[2])
273 with self.mempool_lock:
274 for txid in self.mempool_hist.get(addr, []):
275 hist.append((txid, 0, 0))
278 hist = set(map(lambda x: (x[0], x[2]), hist))
281 hist = map(lambda x: {'tx_hash': x[0], 'height': x[1]}, hist)
283 # add something to distinguish between unused and empty addresses
284 if hist == [] and is_known:
287 with self.cache_lock:
288 self.history_cache[addr] = hist
291 def get_status(self, addr, cache_only=False):
292 tx_points = self.get_history(addr, cache_only)
293 if cache_only and tx_points == -1:
298 if tx_points == ['*']:
302 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
303 return hashlib.sha256(status).digest().encode('hex')
305 def get_merkle(self, tx_hash, height):
307 block_hash = self.bitcoind('getblockhash', [height])
308 b = self.bitcoind('getblock', [block_hash])
309 tx_list = b.get('tx')
310 tx_pos = tx_list.index(tx_hash)
312 merkle = map(hash_decode, tx_list)
313 target_hash = hash_decode(tx_hash)
315 while len(merkle) != 1:
317 merkle.append(merkle[-1])
320 new_hash = Hash(merkle[0] + merkle[1])
321 if merkle[0] == target_hash:
322 s.append(hash_encode(merkle[1]))
323 target_hash = new_hash
324 elif merkle[1] == target_hash:
325 s.append(hash_encode(merkle[0]))
326 target_hash = new_hash
331 return {"block_height": height, "merkle": s, "pos": tx_pos}
334 def add_to_history(self, addr, tx_hash, tx_pos, tx_height):
336 s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
339 serialized_hist = self.batch_list[addr]
341 l = len(serialized_hist)/80
342 for i in range(l-1, -1, -1):
343 item = serialized_hist[80*i:80*(i+1)]
344 item_height = int(rev_hex(item[36:39].encode('hex')), 16)
345 if item_height <= tx_height:
346 serialized_hist = serialized_hist[0:80*(i+1)] + s + serialized_hist[80*(i+1):]
349 serialized_hist = s + serialized_hist
351 self.batch_list[addr] = serialized_hist
354 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
355 self.batch_txio[txo] = addr
359 def revert_add_to_history(self, addr, tx_hash, tx_pos, tx_height):
361 serialized_hist = self.batch_list[addr]
362 s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
363 if serialized_hist.find(s) == -1: raise
364 serialized_hist = serialized_hist.replace(s, '')
365 self.batch_list[addr] = serialized_hist
369 def prune_history(self, addr, undo):
370 # remove items that have bit set to one
371 if undo.get(addr) is None: undo[addr] = []
373 serialized_hist = self.batch_list[addr]
374 l = len(serialized_hist)/80
376 if len(serialized_hist)/80 < self.pruning_limit: break
377 item = serialized_hist[80*i:80*(i+1)]
378 if item[39:40] == chr(1):
379 assert item[79:80] == chr(2)
380 serialized_hist = serialized_hist[0:80*i] + serialized_hist[80*(i+1):]
381 undo[addr].append(item) # items are ordered
382 self.batch_list[addr] = serialized_hist
385 def revert_prune_history(self, addr, undo):
386 # restore removed items
387 serialized_hist = self.batch_list[addr]
389 if undo.get(addr) is not None:
390 itemlist = undo.pop(addr)
394 if not itemlist: return
396 l = len(serialized_hist)/80
398 for i in range(l-1, -1, -1):
403 tx_item = itemlist.pop(-1) # get the last element
404 tx_height = int(rev_hex(tx_item[36:39].encode('hex')), 16)
406 item = serialized_hist[80*i:80*(i+1)]
407 item_height = int(rev_hex(item[36:39].encode('hex')), 16)
409 if item_height < tx_height:
410 serialized_hist = serialized_hist[0:80*(i+1)] + tx_item + serialized_hist[80*(i+1):]
414 serialized_hist = ''.join(itemlist) + tx_item + serialized_hist
416 self.batch_list[addr] = serialized_hist
419 def set_spent_bit(self, addr, txi, is_spent, txid=None, index=None, height=None):
420 serialized_hist = self.batch_list[addr]
421 l = len(serialized_hist)/80
423 item = serialized_hist[80*i:80*(i+1)]
424 if item[0:36] == txi:
426 new_item = item[0:39] + chr(1) + self.serialize_item(txid, index, height, chr(2))
428 new_item = item[0:39] + chr(0) + chr(0)*40
429 serialized_hist = serialized_hist[0:80*i] + new_item + serialized_hist[80*(i+1):]
433 hist = self.deserialize(serialized_hist)
434 raise BaseException("prevout not found", addr, hist, txi.encode('hex'))
436 self.batch_list[addr] = serialized_hist
439 def unset_spent_bit(self, addr, txi):
440 self.set_spent_bit(addr, txi, False)
441 self.batch_txio[txi] = addr
444 def deserialize_block(self, block):
445 txlist = block.get('tx')
446 tx_hashes = [] # ordered txids
447 txdict = {} # deserialized tx
449 for raw_tx in txlist:
450 tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
451 tx_hashes.append(tx_hash)
452 vds = deserialize.BCDataStream()
453 vds.write(raw_tx.decode('hex'))
454 tx = deserialize.parse_Transaction(vds, is_coinbase)
457 return tx_hashes, txdict
459 def get_undo_info(self, height):
460 s = self.db.Get("undo%d" % (height % 100))
463 def write_undo_info(self, batch, height, undo_info):
464 if self.is_test or height > self.bitcoind_height - 100:
465 batch.Put("undo%d" % (height % 100), repr(undo_info))
467 def import_block(self, block, block_hash, block_height, sync, revert=False):
469 self.batch_list = {} # address -> history
470 self.batch_txio = {} # transaction i/o -> address
476 # deserialize transactions
478 tx_hashes, txdict = self.deserialize_block(block)
484 undo_info = self.get_undo_info(block_height)
490 # read addresses of tx inputs
491 for tx in txdict.values():
492 for x in tx.get('inputs'):
493 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
494 block_inputs.append(txi)
497 for txi in block_inputs:
499 addr = self.db.Get(txi)
501 # the input could come from the same block
504 traceback.print_exc(file=sys.stdout)
508 self.batch_txio[txi] = addr
509 addr_to_read.append(addr)
512 for txid, tx in txdict.items():
513 for x in tx.get('outputs'):
514 txo = (txid + int_to_hex(x.get('index'), 4)).decode('hex')
515 block_outputs.append(txo)
516 addr_to_read.append( x.get('address') )
518 undo = undo_info.get(txid)
519 for i, x in enumerate(tx.get('inputs')):
520 addr = undo['prev_addr'][i]
521 addr_to_read.append(addr)
527 # read histories of addresses
528 for txid, tx in txdict.items():
529 for x in tx.get('outputs'):
530 addr_to_read.append(x.get('address'))
533 for addr in addr_to_read:
535 self.batch_list[addr] = self.db.Get(addr)
537 self.batch_list[addr] = ''
539 traceback.print_exc(file=sys.stdout)
548 tx_hashes = tx_hashes[::-1]
551 for txid in tx_hashes: # must be ordered
555 undo = { 'prev_addr':[] } # contains the list of pruned items for each address in the tx; also, 'prev_addr' is a list of prev addresses
558 for i, x in enumerate(tx.get('inputs')):
559 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
560 addr = self.batch_txio[txi]
562 # add redeem item to the history.
563 # add it right next to the input txi? this will break history sorting, but it's ok if I neglect tx inputs during search
564 self.set_spent_bit(addr, txi, True, txid, i, block_height)
566 # when I prune, prune a pair
567 self.prune_history(addr, undo)
568 prev_addr.append(addr)
570 undo['prev_addr'] = prev_addr
572 # here I add only the outputs to history; maybe I want to add inputs too (that's in the other loop)
573 for x in tx.get('outputs'):
574 addr = x.get('address')
575 self.add_to_history(addr, txid, x.get('index'), block_height)
576 self.prune_history(addr, undo) # prune here because we increased the length of the history
578 undo_info[txid] = undo
582 undo = undo_info.pop(txid)
584 for x in tx.get('outputs'):
585 addr = x.get('address')
586 self.revert_prune_history(addr, undo)
587 self.revert_add_to_history(addr, txid, x.get('index'), block_height)
589 prev_addr = undo.pop('prev_addr')
590 for i, x in enumerate(tx.get('inputs')):
592 self.revert_prune_history(addr, undo)
593 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
594 self.unset_spent_bit(addr, txi)
599 assert undo_info == {}
607 batch = leveldb.WriteBatch()
608 for addr, serialized_hist in self.batch_list.items():
609 batch.Put(addr, serialized_hist)
610 l = len(serialized_hist)/80
616 # add new created outputs
617 for txio, addr in self.batch_txio.items():
618 batch.Put(txio, addr)
619 # delete spent inputs
620 for txi in block_inputs:
623 self.write_undo_info(batch, block_height, undo_info)
625 # restore spent inputs
626 for txio, addr in self.batch_txio.items():
627 # print "restoring spent input", repr(txio)
628 batch.Put(txio, addr)
629 # delete spent outputs
630 for txo in block_outputs:
634 batch.Put('height', self.serialize([(block_hash, block_height, self.db_version)]))
637 self.db.Write(batch, sync=sync)
640 if t3 - t0 > 10 and not sync:
641 print_log("block", block_height,
642 "parse:%0.2f " % (t00 - t0),
643 "read:%0.2f " % (t1 - t00),
644 "proc:%.2f " % (t2-t1),
645 "write:%.2f " % (t3-t2),
646 "max:", max_len, max_addr)
648 for addr in self.batch_list.keys():
649 self.invalidate_cache(addr)
651 def add_request(self, request):
652 # see if we can get if from cache. if not, add to queue
653 if self.process(request, cache_only=True) == -1:
654 self.queue.put(request)
656 def process(self, request, cache_only=False):
657 #print "abe process", request
659 message_id = request['id']
660 method = request['method']
661 params = request.get('params', [])
665 if method == 'blockchain.numblocks.subscribe':
668 elif method == 'blockchain.headers.subscribe':
671 elif method == 'blockchain.address.subscribe':
674 result = self.get_status(address, cache_only)
675 self.watch_address(address)
676 except BaseException, e:
677 error = str(e) + ': ' + address
678 print_log("error:", error)
680 elif method == 'blockchain.address.unsubscribe':
684 if password == self.config.get('server', 'password'):
685 self.watched_addresses.remove(address)
686 # print_log('unsubscribed', address)
689 print_log('incorrect password')
690 result = "authentication error"
691 except BaseException, e:
692 error = str(e) + ': ' + address
693 print_log("error:", error)
695 elif method == 'blockchain.address.get_history':
698 result = self.get_history(address, cache_only)
699 except BaseException, e:
700 error = str(e) + ': ' + address
701 print_log("error:", error)
703 elif method == 'blockchain.block.get_header':
709 result = self.get_header(height)
710 except BaseException, e:
711 error = str(e) + ': %d' % height
712 print_log("error:", error)
714 elif method == 'blockchain.block.get_chunk':
720 result = self.get_chunk(index)
721 except BaseException, e:
722 error = str(e) + ': %d' % index
723 print_log("error:", error)
725 elif method == 'blockchain.transaction.broadcast':
727 txo = self.bitcoind('sendrawtransaction', params)
728 print_log("sent tx:", txo)
730 except BaseException, e:
731 result = str(e) # do not send an error
732 print_log("error:", result, params)
734 elif method == 'blockchain.transaction.get_merkle':
740 tx_height = params[1]
741 result = self.get_merkle(tx_hash, tx_height)
742 except BaseException, e:
743 error = str(e) + ': ' + repr(params)
744 print_log("get_merkle error:", error)
746 elif method == 'blockchain.transaction.get':
750 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height])
751 except BaseException, e:
752 error = str(e) + ': ' + repr(params)
753 print_log("tx get error:", error)
756 error = "unknown method:%s" % method
758 if cache_only and result == -1:
762 self.push_response({'id': message_id, 'error': error})
764 self.push_response({'id': message_id, 'result': result})
766 def watch_address(self, addr):
767 if addr not in self.watched_addresses:
768 self.watched_addresses.append(addr)
770 def catch_up(self, sync=True):
773 while not self.shared.stopped():
775 info = self.bitcoind('getinfo')
776 self.bitcoind_height = info.get('blocks')
777 bitcoind_block_hash = self.bitcoind('getblockhash', [self.bitcoind_height])
778 if self.last_hash == bitcoind_block_hash:
779 self.up_to_date = True
783 self.up_to_date = False
784 next_block_hash = self.bitcoind('getblockhash', [self.height + 1])
785 next_block = self.bitcoind('getblock', [next_block_hash, 1])
787 # fixme: this is unsafe, if we revert when the undo info is not yet written
788 revert = (random.randint(1, 100) == 1) if self.is_test else False
790 if (next_block.get('previousblockhash') == self.last_hash) and not revert:
792 self.import_block(next_block, next_block_hash, self.height+1, sync)
793 self.height = self.height + 1
794 self.write_header(self.block2header(next_block), sync)
795 self.last_hash = next_block_hash
797 if self.height % 100 == 0 and not sync:
799 print_log("catch_up: block %d (%.3fs)" % (self.height, t2 - t1))
803 # revert current block
804 block = self.bitcoind('getblock', [self.last_hash, 1])
805 print_log("blockchain reorg", self.height, block.get('previousblockhash'), self.last_hash)
806 self.import_block(block, self.last_hash, self.height, sync, revert=True)
812 # read previous header from disk
813 self.header = self.read_header(self.height)
814 self.last_hash = self.hash_header(self.header)
816 self.header = self.block2header(self.bitcoind('getblock', [self.last_hash]))
818 def memorypool_update(self):
819 mempool_hashes = self.bitcoind('getrawmempool')
821 touched_addresses = []
822 for tx_hash in mempool_hashes:
823 if tx_hash in self.mempool_hashes:
826 tx = self.get_mempool_transaction(tx_hash)
830 for x in tx.get('inputs'):
831 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
833 addr = self.db.Get(txi)
835 tx_prev = self.get_mempool_transaction(x.get('prevout_hash'))
837 addr = tx_prev['outputs'][x.get('prevout_n')]['address']
838 if not addr: continue
841 l = self.mempool_addresses.get(tx_hash, [])
844 self.mempool_addresses[tx_hash] = l
845 if addr not in touched_addresses: touched_addresses.append(addr)
847 for x in tx.get('outputs'):
848 addr = x.get('address')
849 l = self.mempool_addresses.get(tx_hash, [])
852 self.mempool_addresses[tx_hash] = l
853 if addr not in touched_addresses: touched_addresses.append(addr)
855 self.mempool_hashes.append(tx_hash)
857 # remove older entries from mempool_hashes
858 self.mempool_hashes = mempool_hashes
860 # remove deprecated entries from mempool_addresses
861 for tx_hash, addresses in self.mempool_addresses.items():
862 if tx_hash not in self.mempool_hashes:
863 self.mempool_addresses.pop(tx_hash)
864 for addr in addresses:
865 if addr not in touched_addresses: touched_addresses.append(addr)
867 # rebuild mempool histories
868 new_mempool_hist = {}
869 for tx_hash, addresses in self.mempool_addresses.items():
870 for addr in addresses:
871 h = new_mempool_hist.get(addr, [])
874 new_mempool_hist[addr] = h
876 with self.mempool_lock:
877 self.mempool_hist = new_mempool_hist
879 # invalidate cache for touched addresses
880 for addr in touched_addresses:
881 self.invalidate_cache(addr)
884 def invalidate_cache(self, address):
885 with self.cache_lock:
886 if address in self.history_cache:
887 print_log("cache: invalidating", address)
888 self.history_cache.pop(address)
890 if address in self.watched_addresses:
891 # TODO: update cache here. if new value equals cached value, do not send notification
892 self.address_queue.put(address)
894 def main_iteration(self):
895 if self.shared.stopped():
896 print_log("blockchain processor terminating")
904 self.memorypool_update()
906 if self.sent_height != self.height:
907 self.sent_height = self.height
910 'method': 'blockchain.numblocks.subscribe',
911 'params': [self.height],
914 if self.sent_header != self.header:
915 print_log("blockchain: %d (%.3fs)" % (self.height, t2 - t1))
916 self.sent_header = self.header
919 'method': 'blockchain.headers.subscribe',
920 'params': [self.header],
925 addr = self.address_queue.get(False)
928 if addr in self.watched_addresses:
929 status = self.get_status(addr)
932 'method': 'blockchain.address.subscribe',
933 'params': [addr, status],
936 if not self.shared.stopped():
937 threading.Timer(10, self.main_iteration).start()
939 print_log("blockchain processor terminating")