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'
73 if self.db_version != db_version:
74 print_log("Your database '%s' is deprecated. Please create a new database"%self.dbpath)
79 self.init_headers(self.height)
81 threading.Timer(0, lambda: self.catch_up(sync=False)).start()
82 while not shared.stopped() and not self.up_to_date:
86 print "keyboard interrupt: stopping threads"
90 print_log("blockchain is up to date.")
92 threading.Timer(10, self.main_iteration).start()
94 def bitcoind(self, method, params=[]):
95 postdata = dumps({"method": method, 'params': params, 'id': 'jsonrpc'})
97 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
99 traceback.print_exc(file=sys.stdout)
103 if r['error'] is not None:
104 raise BaseException(r['error'])
105 return r.get('result')
107 def serialize(self, h):
109 for txid, txpos, height in h:
110 s += self.serialize_item(txid, txpos, height)
113 def serialize_item(self, txid, txpos, height, spent=chr(0)):
114 s = (txid + int_to_hex(txpos, 4) + int_to_hex(height, 3)).decode('hex') + spent
117 def deserialize_item(self,s):
118 txid = s[0:32].encode('hex')
119 txpos = int(rev_hex(s[32:36].encode('hex')), 16)
120 height = int(rev_hex(s[36:39].encode('hex')), 16)
122 return (txid, txpos, height, spent)
124 def deserialize(self, s):
127 txid, txpos, height, spent = self.deserialize_item(s[0:40])
128 h.append((txid, txpos, height))
130 txid, txpos, height, spent = self.deserialize_item(s[40:80])
131 h.append((txid, txpos, height))
135 def block2header(self, b):
137 "block_height": b.get('height'),
138 "version": b.get('version'),
139 "prev_block_hash": b.get('previousblockhash'),
140 "merkle_root": b.get('merkleroot'),
141 "timestamp": b.get('time'),
142 "bits": int(b.get('bits'), 16),
143 "nonce": b.get('nonce'),
146 def get_header(self, height):
147 block_hash = self.bitcoind('getblockhash', [height])
148 b = self.bitcoind('getblock', [block_hash])
149 return self.block2header(b)
151 def init_headers(self, db_height):
152 self.chunk_cache = {}
153 self.headers_filename = os.path.join(self.dbpath, 'blockchain_headers')
155 if os.path.exists(self.headers_filename):
156 height = os.path.getsize(self.headers_filename)/80 - 1 # the current height
158 prev_hash = self.hash_header(self.read_header(height))
162 open(self.headers_filename, 'wb').close()
166 if height < db_height:
167 print_log("catching up missing headers:", height, db_height)
170 while height < db_height:
172 header = self.get_header(height)
174 assert prev_hash == header.get('prev_block_hash')
175 self.write_header(header, sync=False)
176 prev_hash = self.hash_header(header)
177 if (height % 1000) == 0:
178 print_log("headers file:", height)
179 except KeyboardInterrupt:
185 def hash_header(self, header):
186 return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
188 def read_header(self, block_height):
189 if os.path.exists(self.headers_filename):
190 with open(self.headers_filename, 'rb') as f:
191 f.seek(block_height * 80)
194 h = header_from_string(h)
197 def read_chunk(self, index):
198 with open(self.headers_filename, 'rb') as f:
199 f.seek(index*2016*80)
200 chunk = f.read(2016*80)
201 return chunk.encode('hex')
203 def write_header(self, header, sync=True):
204 if not self.headers_data:
205 self.headers_offset = header.get('block_height')
207 self.headers_data += header_to_string(header).decode('hex')
208 if sync or len(self.headers_data) > 40*100:
211 with self.cache_lock:
212 chunk_index = header.get('block_height')/2016
213 if self.chunk_cache.get(chunk_index):
214 self.chunk_cache.pop(chunk_index)
216 def pop_header(self):
217 # we need to do this only if we have not flushed
218 if self.headers_data:
219 self.headers_data = self.headers_data[:-40]
221 def flush_headers(self):
222 if not self.headers_data:
224 with open(self.headers_filename, 'rb+') as f:
225 f.seek(self.headers_offset*80)
226 f.write(self.headers_data)
227 self.headers_data = ''
229 def get_chunk(self, i):
230 # store them on disk; store the current chunk in memory
231 with self.cache_lock:
232 chunk = self.chunk_cache.get(i)
234 chunk = self.read_chunk(i)
235 self.chunk_cache[i] = chunk
239 def get_mempool_transaction(self, txid):
241 raw_tx = self.bitcoind('getrawtransaction', [txid, 0, -1])
245 vds = deserialize.BCDataStream()
246 vds.write(raw_tx.decode('hex'))
248 return deserialize.parse_Transaction(vds, is_coinbase=False)
250 def get_history(self, addr, cache_only=False):
251 with self.cache_lock:
252 hist = self.history_cache.get(addr)
260 hist = self.deserialize(self.db.Get(addr))
266 # sort history, because redeeming transactions are next to the corresponding txout
267 hist.sort(key=lambda tup: tup[2])
270 with self.mempool_lock:
271 for txid in self.mempool_hist.get(addr, []):
272 hist.append((txid, 0, 0))
275 hist = set(map(lambda x: (x[0], x[2]), hist))
278 hist = map(lambda x: {'tx_hash': x[0], 'height': x[1]}, hist)
280 # add something to distinguish between unused and empty addresses
281 if hist == [] and is_known:
284 with self.cache_lock:
285 self.history_cache[addr] = hist
288 def get_status(self, addr, cache_only=False):
289 tx_points = self.get_history(addr, cache_only)
290 if cache_only and tx_points == -1:
295 if tx_points == ['*']:
299 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
300 return hashlib.sha256(status).digest().encode('hex')
302 def get_merkle(self, tx_hash, height):
304 block_hash = self.bitcoind('getblockhash', [height])
305 b = self.bitcoind('getblock', [block_hash])
306 tx_list = b.get('tx')
307 tx_pos = tx_list.index(tx_hash)
309 merkle = map(hash_decode, tx_list)
310 target_hash = hash_decode(tx_hash)
312 while len(merkle) != 1:
314 merkle.append(merkle[-1])
317 new_hash = Hash(merkle[0] + merkle[1])
318 if merkle[0] == target_hash:
319 s.append(hash_encode(merkle[1]))
320 target_hash = new_hash
321 elif merkle[1] == target_hash:
322 s.append(hash_encode(merkle[0]))
323 target_hash = new_hash
328 return {"block_height": height, "merkle": s, "pos": tx_pos}
331 def add_to_history(self, addr, tx_hash, tx_pos, tx_height):
333 s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
336 serialized_hist = self.batch_list[addr]
338 l = len(serialized_hist)/80
339 for i in range(l-1, -1, -1):
340 item = serialized_hist[80*i:80*(i+1)]
341 item_height = int(rev_hex(item[36:39].encode('hex')), 16)
342 if item_height < tx_height:
343 serialized_hist = serialized_hist[0:80*(i+1)] + s + serialized_hist[80*(i+1):]
346 serialized_hist = s + serialized_hist
348 self.batch_list[addr] = serialized_hist
351 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
352 self.batch_txio[txo] = addr
356 def revert_add_to_history(self, addr, tx_hash, tx_pos, tx_height):
358 serialized_hist = self.batch_list[addr]
359 s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
360 if serialized_hist.find(s) == -1: raise
361 serialized_hist = serialized_hist.replace(s, '')
362 self.batch_list[addr] = serialized_hist
366 def prune_history(self, addr, undo):
367 # remove items that have bit set to one
368 if undo.get(addr) is None: undo[addr] = []
370 serialized_hist = self.batch_list[addr]
371 l = len(serialized_hist)/80
373 if len(serialized_hist)/80 < self.pruning_limit: break
374 item = serialized_hist[80*i:80*(i+1)]
375 if item[39:40] == chr(1):
376 assert item[79:80] == chr(2)
377 serialized_hist = serialized_hist[0:80*i] + serialized_hist[80*(i+1):]
378 undo[addr].append(item) # items are ordered
379 self.batch_list[addr] = serialized_hist
382 def revert_prune_history(self, addr, undo):
383 # restore removed items
384 serialized_hist = self.batch_list[addr]
386 if undo.get(addr) is not None:
387 itemlist = undo.pop(addr)
391 if not itemlist: return
393 l = len(serialized_hist)/80
395 for i in range(l-1, -1, -1):
400 tx_item = itemlist.pop(-1) # get the last element
401 tx_height = int(rev_hex(tx_item[36:39].encode('hex')), 16)
403 item = serialized_hist[80*i:80*(i+1)]
404 item_height = int(rev_hex(item[36:39].encode('hex')), 16)
406 if item_height < tx_height:
407 serialized_hist = serialized_hist[0:80*(i+1)] + tx_item + serialized_hist[80*(i+1):]
411 serialized_hist = ''.join(itemlist) + tx_item + serialized_hist
413 self.batch_list[addr] = serialized_hist
416 def set_spent_bit(self, addr, txi, is_spent, txid=None, index=None, height=None):
417 serialized_hist = self.batch_list[addr]
418 l = len(serialized_hist)/80
420 item = serialized_hist[80*i:80*(i+1)]
421 if item[0:36] == txi:
423 new_item = item[0:39] + chr(1) + self.serialize_item(txid, index, height, chr(2))
425 new_item = item[0:39] + chr(0) + chr(0)*40
426 serialized_hist = serialized_hist[0:80*i] + new_item + serialized_hist[80*(i+1):]
429 hist = self.deserialize(serialized_hist)
430 raise BaseException("prevout not found", addr, hist, txi.encode('hex'))
432 self.batch_list[addr] = serialized_hist
435 def unset_spent_bit(self, addr, txi):
436 self.set_spent_bit(addr, txi, False)
437 self.batch_txio[txi] = addr
440 def deserialize_block(self, block):
441 txlist = block.get('tx')
442 tx_hashes = [] # ordered txids
443 txdict = {} # deserialized tx
445 for raw_tx in txlist:
446 tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
447 tx_hashes.append(tx_hash)
448 vds = deserialize.BCDataStream()
449 vds.write(raw_tx.decode('hex'))
450 tx = deserialize.parse_Transaction(vds, is_coinbase)
453 return tx_hashes, txdict
455 def get_undo_info(self, height):
456 s = self.db.Get("undo%d" % (height % 100))
459 def write_undo_info(self, batch, height, undo_info):
460 if self.is_test or height > self.bitcoind_height - 100:
461 batch.Put("undo%d" % (height % 100), repr(undo_info))
463 def import_block(self, block, block_hash, block_height, sync, revert=False):
465 self.batch_list = {} # address -> history
466 self.batch_txio = {} # transaction i/o -> address
472 # deserialize transactions
474 tx_hashes, txdict = self.deserialize_block(block)
480 undo_info = self.get_undo_info(block_height)
486 # read addresses of tx inputs
487 for tx in txdict.values():
488 for x in tx.get('inputs'):
489 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
490 block_inputs.append(txi)
493 for txi in block_inputs:
495 addr = self.db.Get(txi)
497 # print "addr not in db", txi.encode('hex')
498 # the input could come from the same block
500 self.batch_txio[txi] = addr
501 addr_to_read.append(addr)
504 for txid, tx in txdict.items():
505 for x in tx.get('outputs'):
506 txo = (txid + int_to_hex(x.get('index'), 4)).decode('hex')
507 block_outputs.append(txo)
508 addr_to_read.append( x.get('address') )
510 undo = undo_info.get(txid)
511 for i, x in enumerate(tx.get('inputs')):
512 addr = undo['prev_addr'][i]
513 addr_to_read.append(addr)
519 # read histories of addresses
520 for txid, tx in txdict.items():
521 for x in tx.get('outputs'):
522 addr_to_read.append(x.get('address'))
525 for addr in addr_to_read:
527 self.batch_list[addr] = self.db.Get(addr)
529 self.batch_list[addr] = ''
536 tx_hashes = tx_hashes[::-1]
539 for txid in tx_hashes: # must be ordered
543 undo = { 'prev_addr':[] } # contains the list of pruned items for each address in the tx; also, 'prev_addr' is a list of prev addresses
546 for i, x in enumerate(tx.get('inputs')):
547 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
548 addr = self.batch_txio[txi]
550 # add redeem item to the history.
551 # add it right next to the input txi? this will break history sorting, but it's ok if I neglect tx inputs during search
552 self.set_spent_bit(addr, txi, True, txid, i, block_height)
554 # when I prune, prune a pair
555 self.prune_history(addr, undo)
556 prev_addr.append(addr)
558 undo['prev_addr'] = prev_addr
560 # here I add only the outputs to history; maybe I want to add inputs too (that's in the other loop)
561 for x in tx.get('outputs'):
562 addr = x.get('address')
563 self.add_to_history(addr, txid, x.get('index'), block_height)
564 self.prune_history(addr, undo) # prune here because we increased the length of the history
566 undo_info[txid] = undo
570 undo = undo_info.pop(txid)
572 for x in tx.get('outputs'):
573 addr = x.get('address')
574 self.revert_prune_history(addr, undo)
575 self.revert_add_to_history(addr, txid, x.get('index'), block_height)
577 prev_addr = undo.pop('prev_addr')
578 for i, x in enumerate(tx.get('inputs')):
580 self.revert_prune_history(addr, undo)
581 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
582 self.unset_spent_bit(addr, txi)
587 assert undo_info == {}
595 batch = leveldb.WriteBatch()
596 for addr, serialized_hist in self.batch_list.items():
597 batch.Put(addr, serialized_hist)
598 l = len(serialized_hist)/80
604 # add new created outputs
605 for txio, addr in self.batch_txio.items():
606 batch.Put(txio, addr)
607 # delete spent inputs
608 for txi in block_inputs:
611 self.write_undo_info(batch, block_height, undo_info)
613 # restore spent inputs
614 for txio, addr in self.batch_txio.items():
615 # print "restoring spent input", repr(txio)
616 batch.Put(txio, addr)
617 # delete spent outputs
618 for txo in block_outputs:
622 batch.Put('height', self.serialize([(block_hash, block_height, self.db_version)]))
625 self.db.Write(batch, sync=sync)
628 if t3 - t0 > 10 and not sync:
629 print_log("block", block_height,
630 "parse:%0.2f " % (t00 - t0),
631 "read:%0.2f " % (t1 - t00),
632 "proc:%.2f " % (t2-t1),
633 "write:%.2f " % (t3-t2),
634 "max:", max_len, max_addr)
636 for addr in self.batch_list.keys():
637 self.invalidate_cache(addr)
639 def add_request(self, request):
640 # see if we can get if from cache. if not, add to queue
641 if self.process(request, cache_only=True) == -1:
642 self.queue.put(request)
644 def process(self, request, cache_only=False):
645 #print "abe process", request
647 message_id = request['id']
648 method = request['method']
649 params = request.get('params', [])
653 if method == 'blockchain.numblocks.subscribe':
656 elif method == 'blockchain.headers.subscribe':
659 elif method == 'blockchain.address.subscribe':
662 result = self.get_status(address, cache_only)
663 self.watch_address(address)
664 except BaseException, e:
665 error = str(e) + ': ' + address
666 print_log("error:", error)
668 elif method == 'blockchain.address.unsubscribe':
672 if password == self.config.get('server', 'password'):
673 self.watched_addresses.remove(address)
674 # print_log('unsubscribed', address)
677 print_log('incorrect password')
678 result = "authentication error"
679 except BaseException, e:
680 error = str(e) + ': ' + address
681 print_log("error:", error)
683 elif method == 'blockchain.address.get_history':
686 result = self.get_history(address, cache_only)
687 except BaseException, e:
688 error = str(e) + ': ' + address
689 print_log("error:", error)
691 elif method == 'blockchain.block.get_header':
697 result = self.get_header(height)
698 except BaseException, e:
699 error = str(e) + ': %d' % height
700 print_log("error:", error)
702 elif method == 'blockchain.block.get_chunk':
708 result = self.get_chunk(index)
709 except BaseException, e:
710 error = str(e) + ': %d' % index
711 print_log("error:", error)
713 elif method == 'blockchain.transaction.broadcast':
715 txo = self.bitcoind('sendrawtransaction', params)
716 print_log("sent tx:", txo)
718 except BaseException, e:
719 result = str(e) # do not send an error
720 print_log("error:", result, params)
722 elif method == 'blockchain.transaction.get_merkle':
728 tx_height = params[1]
729 result = self.get_merkle(tx_hash, tx_height)
730 except BaseException, e:
731 error = str(e) + ': ' + repr(params)
732 print_log("get_merkle error:", error)
734 elif method == 'blockchain.transaction.get':
738 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height])
739 except BaseException, e:
740 error = str(e) + ': ' + repr(params)
741 print_log("tx get error:", error)
744 error = "unknown method:%s" % method
746 if cache_only and result == -1:
750 self.push_response({'id': message_id, 'error': error})
752 self.push_response({'id': message_id, 'result': result})
754 def watch_address(self, addr):
755 if addr not in self.watched_addresses:
756 self.watched_addresses.append(addr)
758 def catch_up(self, sync=True):
761 while not self.shared.stopped():
763 info = self.bitcoind('getinfo')
764 self.bitcoind_height = info.get('blocks')
765 bitcoind_block_hash = self.bitcoind('getblockhash', [self.bitcoind_height])
766 if self.last_hash == bitcoind_block_hash:
767 self.up_to_date = True
771 self.up_to_date = False
772 next_block_hash = self.bitcoind('getblockhash', [self.height + 1])
773 next_block = self.bitcoind('getblock', [next_block_hash, 1])
775 # fixme: this is unsafe, if we revert when the undo info is not yet written
776 revert = (random.randint(1, 100) == 1) if self.is_test else False
778 if (next_block.get('previousblockhash') == self.last_hash) and not revert:
780 self.import_block(next_block, next_block_hash, self.height+1, sync)
781 self.height = self.height + 1
782 self.write_header(self.block2header(next_block), sync)
783 self.last_hash = next_block_hash
785 if self.height % 100 == 0 and not sync:
787 print_log("catch_up: block %d (%.3fs)" % (self.height, t2 - t1))
791 # revert current block
792 block = self.bitcoind('getblock', [self.last_hash, 1])
793 print_log("blockchain reorg", self.height, block.get('previousblockhash'), self.last_hash)
794 self.import_block(block, self.last_hash, self.height, sync, revert=True)
800 # read previous header from disk
801 self.header = self.read_header(self.height)
802 self.last_hash = self.hash_header(self.header)
804 self.header = self.block2header(self.bitcoind('getblock', [self.last_hash]))
806 def memorypool_update(self):
807 mempool_hashes = self.bitcoind('getrawmempool')
809 for tx_hash in mempool_hashes:
810 if tx_hash in self.mempool_hashes:
813 tx = self.get_mempool_transaction(tx_hash)
817 for x in tx.get('inputs'):
818 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
820 addr = self.db.Get(txi)
823 l = self.mempool_addresses.get(tx_hash, [])
826 self.mempool_addresses[tx_hash] = l
828 for x in tx.get('outputs'):
829 addr = x.get('address')
830 l = self.mempool_addresses.get(tx_hash, [])
833 self.mempool_addresses[tx_hash] = l
835 self.mempool_hashes.append(tx_hash)
837 # remove older entries from mempool_hashes
838 self.mempool_hashes = mempool_hashes
840 # remove deprecated entries from mempool_addresses
841 for tx_hash, addresses in self.mempool_addresses.items():
842 if tx_hash not in self.mempool_hashes:
843 self.mempool_addresses.pop(tx_hash)
845 # rebuild mempool histories
846 new_mempool_hist = {}
847 for tx_hash, addresses in self.mempool_addresses.items():
848 for addr in addresses:
849 h = new_mempool_hist.get(addr, [])
852 new_mempool_hist[addr] = h
854 # invalidate cache for mempool addresses whose mempool history has changed
855 new_mempool_hist_keys = new_mempool_hist.keys()
856 self_mempool_hist_keys = self.mempool_hist.keys()
858 for addr in new_mempool_hist_keys:
859 if addr in self_mempool_hist_keys:
860 if self.mempool_hist[addr] != new_mempool_hist[addr]:
861 self.invalidate_cache(addr)
863 self.invalidate_cache(addr)
865 # invalidate cache for addresses that are removed from mempool ?
866 # this should not be necessary if they go into a block, but they might not
867 for addr in self_mempool_hist_keys:
868 if addr not in new_mempool_hist_keys:
869 self.invalidate_cache(addr)
872 with self.mempool_lock:
873 self.mempool_hist = new_mempool_hist
875 def invalidate_cache(self, address):
876 with self.cache_lock:
877 if address in self.history_cache:
878 print_log("cache: invalidating", address)
879 self.history_cache.pop(address)
881 if address in self.watched_addresses:
882 self.address_queue.put(address)
884 def main_iteration(self):
885 if self.shared.stopped():
886 print_log("blockchain processor terminating")
894 self.memorypool_update()
896 # print "mempool:", len(self.mempool_addresses), len(self.mempool_hist), "%.3fs"%(t3 - t2)
898 if self.sent_height != self.height:
899 self.sent_height = self.height
902 'method': 'blockchain.numblocks.subscribe',
903 'params': [self.height],
906 if self.sent_header != self.header:
907 print_log("blockchain: %d (%.3fs)" % (self.height, t2 - t1))
908 self.sent_header = self.header
911 'method': 'blockchain.headers.subscribe',
912 'params': [self.header],
917 addr = self.address_queue.get(False)
920 if addr in self.watched_addresses:
921 status = self.get_status(addr)
924 'method': 'blockchain.address.subscribe',
925 'params': [addr, status],
928 if not self.shared.stopped():
929 threading.Timer(10, self.main_iteration).start()
931 print_log("blockchain processor terminating")