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, paranoid_checks=True)
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'))
58 self.bitcoind('getinfo')
61 print_log('cannot contact bitcoind...')
68 self.sent_header = None
71 hist = self.deserialize(self.db.Get('height'))
72 self.last_hash, self.height, db_version = hist[0]
73 print_log("Database version", self.db_version)
74 print_log("Blockchain height", self.height)
76 traceback.print_exc(file=sys.stdout)
77 print_log('initializing database')
79 self.last_hash = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
80 db_version = self.db_version
83 if self.db_version != db_version:
84 print_log("Your database '%s' is deprecated. Please create a new database"%self.dbpath)
89 self.init_headers(self.height)
91 threading.Timer(0, lambda: self.catch_up(sync=False)).start()
92 while not shared.stopped() and not self.up_to_date:
96 print "keyboard interrupt: stopping threads"
100 print_log("Blockchain is up to date.")
101 self.memorypool_update()
102 print_log("Memory pool initialized.")
104 threading.Timer(10, self.main_iteration).start()
106 def bitcoind(self, method, params=[]):
107 postdata = dumps({"method": method, 'params': params, 'id': 'jsonrpc'})
109 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
111 traceback.print_exc(file=sys.stdout)
115 if r['error'] is not None:
116 raise BaseException(r['error'])
117 return r.get('result')
119 def serialize(self, h):
121 for txid, txpos, height in h:
122 s += self.serialize_item(txid, txpos, height)
125 def serialize_item(self, txid, txpos, height, spent=chr(0)):
126 s = (txid + int_to_hex(txpos, 4) + int_to_hex(height, 3)).decode('hex') + spent
129 def deserialize_item(self,s):
130 txid = s[0:32].encode('hex')
131 txpos = int(rev_hex(s[32:36].encode('hex')), 16)
132 height = int(rev_hex(s[36:39].encode('hex')), 16)
134 return (txid, txpos, height, spent)
136 def deserialize(self, s):
139 txid, txpos, height, spent = self.deserialize_item(s[0:40])
140 h.append((txid, txpos, height))
142 txid, txpos, height, spent = self.deserialize_item(s[40:80])
143 h.append((txid, txpos, height))
147 def block2header(self, b):
149 "block_height": b.get('height'),
150 "version": b.get('version'),
151 "prev_block_hash": b.get('previousblockhash'),
152 "merkle_root": b.get('merkleroot'),
153 "timestamp": b.get('time'),
154 "bits": int(b.get('bits'), 16),
155 "nonce": b.get('nonce'),
158 def get_header(self, height):
159 block_hash = self.bitcoind('getblockhash', [height])
160 b = self.bitcoind('getblock', [block_hash])
161 return self.block2header(b)
163 def init_headers(self, db_height):
164 self.chunk_cache = {}
165 self.headers_filename = os.path.join(self.dbpath, 'blockchain_headers')
167 if os.path.exists(self.headers_filename):
168 height = os.path.getsize(self.headers_filename)/80 - 1 # the current height
170 prev_hash = self.hash_header(self.read_header(height))
174 open(self.headers_filename, 'wb').close()
178 if height < db_height:
179 print_log("catching up missing headers:", height, db_height)
182 while height < db_height:
184 header = self.get_header(height)
186 assert prev_hash == header.get('prev_block_hash')
187 self.write_header(header, sync=False)
188 prev_hash = self.hash_header(header)
189 if (height % 1000) == 0:
190 print_log("headers file:", height)
191 except KeyboardInterrupt:
197 def hash_header(self, header):
198 return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
200 def read_header(self, block_height):
201 if os.path.exists(self.headers_filename):
202 with open(self.headers_filename, 'rb') as f:
203 f.seek(block_height * 80)
206 h = header_from_string(h)
209 def read_chunk(self, index):
210 with open(self.headers_filename, 'rb') as f:
211 f.seek(index*2016*80)
212 chunk = f.read(2016*80)
213 return chunk.encode('hex')
215 def write_header(self, header, sync=True):
216 if not self.headers_data:
217 self.headers_offset = header.get('block_height')
219 self.headers_data += header_to_string(header).decode('hex')
220 if sync or len(self.headers_data) > 40*100:
223 with self.cache_lock:
224 chunk_index = header.get('block_height')/2016
225 if self.chunk_cache.get(chunk_index):
226 self.chunk_cache.pop(chunk_index)
228 def pop_header(self):
229 # we need to do this only if we have not flushed
230 if self.headers_data:
231 self.headers_data = self.headers_data[:-40]
233 def flush_headers(self):
234 if not self.headers_data:
236 with open(self.headers_filename, 'rb+') as f:
237 f.seek(self.headers_offset*80)
238 f.write(self.headers_data)
239 self.headers_data = ''
241 def get_chunk(self, i):
242 # store them on disk; store the current chunk in memory
243 with self.cache_lock:
244 chunk = self.chunk_cache.get(i)
246 chunk = self.read_chunk(i)
247 self.chunk_cache[i] = chunk
251 def get_mempool_transaction(self, txid):
253 raw_tx = self.bitcoind('getrawtransaction', [txid, 0, -1])
257 vds = deserialize.BCDataStream()
258 vds.write(raw_tx.decode('hex'))
260 return deserialize.parse_Transaction(vds, is_coinbase=False)
262 def get_history(self, addr, cache_only=False):
263 with self.cache_lock:
264 hist = self.history_cache.get(addr)
272 hist = self.deserialize(self.db.Get(addr))
278 # sort history, because redeeming transactions are next to the corresponding txout
279 hist.sort(key=lambda tup: tup[2])
282 with self.mempool_lock:
283 for txid in self.mempool_hist.get(addr, []):
284 hist.append((txid, 0, 0))
287 hist = set(map(lambda x: (x[0], x[2]), hist))
290 hist = map(lambda x: {'tx_hash': x[0], 'height': x[1]}, hist)
292 # add something to distinguish between unused and empty addresses
293 if hist == [] and is_known:
296 with self.cache_lock:
297 self.history_cache[addr] = hist
300 def get_status(self, addr, cache_only=False):
301 tx_points = self.get_history(addr, cache_only)
302 if cache_only and tx_points == -1:
307 if tx_points == ['*']:
311 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
312 return hashlib.sha256(status).digest().encode('hex')
314 def get_merkle(self, tx_hash, height):
316 block_hash = self.bitcoind('getblockhash', [height])
317 b = self.bitcoind('getblock', [block_hash])
318 tx_list = b.get('tx')
319 tx_pos = tx_list.index(tx_hash)
321 merkle = map(hash_decode, tx_list)
322 target_hash = hash_decode(tx_hash)
324 while len(merkle) != 1:
326 merkle.append(merkle[-1])
329 new_hash = Hash(merkle[0] + merkle[1])
330 if merkle[0] == target_hash:
331 s.append(hash_encode(merkle[1]))
332 target_hash = new_hash
333 elif merkle[1] == target_hash:
334 s.append(hash_encode(merkle[0]))
335 target_hash = new_hash
340 return {"block_height": height, "merkle": s, "pos": tx_pos}
343 def add_to_history(self, addr, tx_hash, tx_pos, tx_height):
345 s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
348 serialized_hist = self.batch_list[addr]
350 l = len(serialized_hist)/80
351 for i in range(l-1, -1, -1):
352 item = serialized_hist[80*i:80*(i+1)]
353 item_height = int(rev_hex(item[36:39].encode('hex')), 16)
354 if item_height <= tx_height:
355 serialized_hist = serialized_hist[0:80*(i+1)] + s + serialized_hist[80*(i+1):]
358 serialized_hist = s + serialized_hist
360 self.batch_list[addr] = serialized_hist
363 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
364 self.batch_txio[txo] = addr
368 def revert_add_to_history(self, addr, tx_hash, tx_pos, tx_height):
370 serialized_hist = self.batch_list[addr]
371 s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
372 if serialized_hist.find(s) == -1: raise
373 serialized_hist = serialized_hist.replace(s, '')
374 self.batch_list[addr] = serialized_hist
378 def prune_history(self, addr, undo):
379 # remove items that have bit set to one
380 if undo.get(addr) is None: undo[addr] = []
382 serialized_hist = self.batch_list[addr]
383 l = len(serialized_hist)/80
385 if len(serialized_hist)/80 < self.pruning_limit: break
386 item = serialized_hist[80*i:80*(i+1)]
387 if item[39:40] == chr(1):
388 assert item[79:80] == chr(2)
389 serialized_hist = serialized_hist[0:80*i] + serialized_hist[80*(i+1):]
390 undo[addr].append(item) # items are ordered
391 self.batch_list[addr] = serialized_hist
394 def revert_prune_history(self, addr, undo):
395 # restore removed items
396 serialized_hist = self.batch_list[addr]
398 if undo.get(addr) is not None:
399 itemlist = undo.pop(addr)
403 if not itemlist: return
405 l = len(serialized_hist)/80
407 for i in range(l-1, -1, -1):
412 tx_item = itemlist.pop(-1) # get the last element
413 tx_height = int(rev_hex(tx_item[36:39].encode('hex')), 16)
415 item = serialized_hist[80*i:80*(i+1)]
416 item_height = int(rev_hex(item[36:39].encode('hex')), 16)
418 if item_height < tx_height:
419 serialized_hist = serialized_hist[0:80*(i+1)] + tx_item + serialized_hist[80*(i+1):]
423 serialized_hist = ''.join(itemlist) + tx_item + serialized_hist
425 self.batch_list[addr] = serialized_hist
428 def set_spent_bit(self, addr, txi, is_spent, txid=None, index=None, height=None):
429 serialized_hist = self.batch_list[addr]
430 l = len(serialized_hist)/80
432 item = serialized_hist[80*i:80*(i+1)]
433 if item[0:36] == txi:
435 new_item = item[0:39] + chr(1) + self.serialize_item(txid, index, height, chr(2))
437 new_item = item[0:39] + chr(0) + chr(0)*40
438 serialized_hist = serialized_hist[0:80*i] + new_item + serialized_hist[80*(i+1):]
442 hist = self.deserialize(serialized_hist)
443 raise BaseException("prevout not found", addr, hist, txi.encode('hex'))
445 self.batch_list[addr] = serialized_hist
448 def unset_spent_bit(self, addr, txi):
449 self.set_spent_bit(addr, txi, False)
450 self.batch_txio[txi] = addr
453 def deserialize_block(self, block):
454 txlist = block.get('tx')
455 tx_hashes = [] # ordered txids
456 txdict = {} # deserialized tx
458 for raw_tx in txlist:
459 tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
460 tx_hashes.append(tx_hash)
461 vds = deserialize.BCDataStream()
462 vds.write(raw_tx.decode('hex'))
463 tx = deserialize.parse_Transaction(vds, is_coinbase)
466 return tx_hashes, txdict
468 def get_undo_info(self, height):
469 s = self.db.Get("undo%d" % (height % 100))
472 def write_undo_info(self, batch, height, undo_info):
473 if self.is_test or height > self.bitcoind_height - 100:
474 batch.Put("undo%d" % (height % 100), repr(undo_info))
476 def import_block(self, block, block_hash, block_height, sync, revert=False):
478 self.batch_list = {} # address -> history
479 self.batch_txio = {} # transaction i/o -> address
485 # deserialize transactions
487 tx_hashes, txdict = self.deserialize_block(block)
493 undo_info = self.get_undo_info(block_height)
499 # read addresses of tx inputs
500 for tx in txdict.values():
501 for x in tx.get('inputs'):
502 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
503 block_inputs.append(txi)
506 for txi in block_inputs:
508 addr = self.db.Get(txi)
510 # the input could come from the same block
513 traceback.print_exc(file=sys.stdout)
517 self.batch_txio[txi] = addr
518 addr_to_read.append(addr)
521 for txid, tx in txdict.items():
522 for x in tx.get('outputs'):
523 txo = (txid + int_to_hex(x.get('index'), 4)).decode('hex')
524 block_outputs.append(txo)
525 addr_to_read.append( x.get('address') )
527 undo = undo_info.get(txid)
528 for i, x in enumerate(tx.get('inputs')):
529 addr = undo['prev_addr'][i]
530 addr_to_read.append(addr)
536 # read histories of addresses
537 for txid, tx in txdict.items():
538 for x in tx.get('outputs'):
539 addr_to_read.append(x.get('address'))
542 for addr in addr_to_read:
544 self.batch_list[addr] = self.db.Get(addr)
546 self.batch_list[addr] = ''
548 traceback.print_exc(file=sys.stdout)
557 tx_hashes = tx_hashes[::-1]
560 for txid in tx_hashes: # must be ordered
564 undo = { 'prev_addr':[] } # contains the list of pruned items for each address in the tx; also, 'prev_addr' is a list of prev addresses
567 for i, x in enumerate(tx.get('inputs')):
568 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
569 addr = self.batch_txio[txi]
571 # add redeem item to the history.
572 # add it right next to the input txi? this will break history sorting, but it's ok if I neglect tx inputs during search
573 self.set_spent_bit(addr, txi, True, txid, i, block_height)
575 # when I prune, prune a pair
576 self.prune_history(addr, undo)
577 prev_addr.append(addr)
579 undo['prev_addr'] = prev_addr
581 # here I add only the outputs to history; maybe I want to add inputs too (that's in the other loop)
582 for x in tx.get('outputs'):
583 addr = x.get('address')
584 self.add_to_history(addr, txid, x.get('index'), block_height)
585 self.prune_history(addr, undo) # prune here because we increased the length of the history
587 undo_info[txid] = undo
591 undo = undo_info.pop(txid)
593 for x in tx.get('outputs'):
594 addr = x.get('address')
595 self.revert_prune_history(addr, undo)
596 self.revert_add_to_history(addr, txid, x.get('index'), block_height)
598 prev_addr = undo.pop('prev_addr')
599 for i, x in enumerate(tx.get('inputs')):
601 self.revert_prune_history(addr, undo)
602 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
603 self.unset_spent_bit(addr, txi)
608 assert undo_info == {}
616 batch = leveldb.WriteBatch()
617 for addr, serialized_hist in self.batch_list.items():
618 batch.Put(addr, serialized_hist)
619 l = len(serialized_hist)/80
625 # add new created outputs
626 for txio, addr in self.batch_txio.items():
627 batch.Put(txio, addr)
628 # delete spent inputs
629 for txi in block_inputs:
632 self.write_undo_info(batch, block_height, undo_info)
634 # restore spent inputs
635 for txio, addr in self.batch_txio.items():
636 # print "restoring spent input", repr(txio)
637 batch.Put(txio, addr)
638 # delete spent outputs
639 for txo in block_outputs:
643 batch.Put('height', self.serialize([(block_hash, block_height, self.db_version)]))
646 self.db.Write(batch, sync=sync)
649 if t3 - t0 > 10 and not sync:
650 print_log("block", block_height,
651 "parse:%0.2f " % (t00 - t0),
652 "read:%0.2f " % (t1 - t00),
653 "proc:%.2f " % (t2-t1),
654 "write:%.2f " % (t3-t2),
655 "max:", max_len, max_addr)
657 for addr in self.batch_list.keys():
658 self.invalidate_cache(addr)
660 def add_request(self, request):
661 # see if we can get if from cache. if not, add to queue
662 if self.process(request, cache_only=True) == -1:
663 self.queue.put(request)
665 def process(self, request, cache_only=False):
666 #print "abe process", request
668 message_id = request['id']
669 method = request['method']
670 params = request.get('params', [])
674 if method == 'blockchain.numblocks.subscribe':
677 elif method == 'blockchain.headers.subscribe':
680 elif method == 'blockchain.address.subscribe':
683 result = self.get_status(address, cache_only)
684 self.watch_address(address)
685 except BaseException, e:
686 error = str(e) + ': ' + address
687 print_log("error:", error)
689 elif method == 'blockchain.address.unsubscribe':
693 if password == self.config.get('server', 'password'):
694 self.watched_addresses.remove(address)
695 # print_log('unsubscribed', address)
698 print_log('incorrect password')
699 result = "authentication error"
700 except BaseException, e:
701 error = str(e) + ': ' + address
702 print_log("error:", error)
704 elif method == 'blockchain.address.get_history':
707 result = self.get_history(address, cache_only)
708 except BaseException, e:
709 error = str(e) + ': ' + address
710 print_log("error:", error)
712 elif method == 'blockchain.block.get_header':
718 result = self.get_header(height)
719 except BaseException, e:
720 error = str(e) + ': %d' % height
721 print_log("error:", error)
723 elif method == 'blockchain.block.get_chunk':
729 result = self.get_chunk(index)
730 except BaseException, e:
731 error = str(e) + ': %d' % index
732 print_log("error:", error)
734 elif method == 'blockchain.transaction.broadcast':
736 txo = self.bitcoind('sendrawtransaction', params)
737 print_log("sent tx:", txo)
739 except BaseException, e:
740 result = str(e) # do not send an error
741 print_log("error:", result, params)
743 elif method == 'blockchain.transaction.get_merkle':
749 tx_height = params[1]
750 result = self.get_merkle(tx_hash, tx_height)
751 except BaseException, e:
752 error = str(e) + ': ' + repr(params)
753 print_log("get_merkle error:", error)
755 elif method == 'blockchain.transaction.get':
759 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height])
760 except BaseException, e:
761 error = str(e) + ': ' + repr(params)
762 print_log("tx get error:", error)
765 error = "unknown method:%s" % method
767 if cache_only and result == -1:
771 self.push_response({'id': message_id, 'error': error})
773 self.push_response({'id': message_id, 'result': result})
775 def watch_address(self, addr):
776 if addr not in self.watched_addresses:
777 self.watched_addresses.append(addr)
779 def catch_up(self, sync=True):
782 while not self.shared.stopped():
784 info = self.bitcoind('getinfo')
785 self.bitcoind_height = info.get('blocks')
786 bitcoind_block_hash = self.bitcoind('getblockhash', [self.bitcoind_height])
787 if self.last_hash == bitcoind_block_hash:
788 self.up_to_date = True
792 self.up_to_date = False
793 next_block_hash = self.bitcoind('getblockhash', [self.height + 1])
794 next_block = self.bitcoind('getblock', [next_block_hash, 1])
796 # fixme: this is unsafe, if we revert when the undo info is not yet written
797 revert = (random.randint(1, 100) == 1) if self.is_test else False
799 if (next_block.get('previousblockhash') == self.last_hash) and not revert:
801 self.import_block(next_block, next_block_hash, self.height+1, sync)
802 self.height = self.height + 1
803 self.write_header(self.block2header(next_block), sync)
804 self.last_hash = next_block_hash
806 if self.height % 100 == 0 and not sync:
808 print_log("catch_up: block %d (%.3fs)" % (self.height, t2 - t1))
812 # revert current block
813 block = self.bitcoind('getblock', [self.last_hash, 1])
814 print_log("blockchain reorg", self.height, block.get('previousblockhash'), self.last_hash)
815 self.import_block(block, self.last_hash, self.height, sync, revert=True)
821 # read previous header from disk
822 self.header = self.read_header(self.height)
823 self.last_hash = self.hash_header(self.header)
825 self.header = self.block2header(self.bitcoind('getblock', [self.last_hash]))
827 def memorypool_update(self):
828 mempool_hashes = self.bitcoind('getrawmempool')
830 touched_addresses = []
831 for tx_hash in mempool_hashes:
832 if tx_hash in self.mempool_hashes:
835 tx = self.get_mempool_transaction(tx_hash)
839 mpa = self.mempool_addresses.get(tx_hash, [])
840 for x in tx.get('inputs'):
841 # we assume that the input address can be parsed by deserialize(); this is true for Electrum transactions
842 addr = x.get('address')
843 if addr and addr not in mpa:
845 touched_addresses.append(addr)
847 for x in tx.get('outputs'):
848 addr = x.get('address')
849 if addr and addr not in mpa:
851 touched_addresses.append(addr)
853 self.mempool_addresses[tx_hash] = mpa
854 self.mempool_hashes.append(tx_hash)
856 # remove older entries from mempool_hashes
857 self.mempool_hashes = mempool_hashes
859 # remove deprecated entries from mempool_addresses
860 for tx_hash, addresses in self.mempool_addresses.items():
861 if tx_hash not in self.mempool_hashes:
862 self.mempool_addresses.pop(tx_hash)
863 for addr in addresses:
864 touched_addresses.append(addr)
866 # rebuild mempool histories
867 new_mempool_hist = {}
868 for tx_hash, addresses in self.mempool_addresses.items():
869 for addr in addresses:
870 h = new_mempool_hist.get(addr, [])
873 new_mempool_hist[addr] = h
875 with self.mempool_lock:
876 self.mempool_hist = new_mempool_hist
878 # invalidate cache for touched addresses
879 for addr in touched_addresses:
880 self.invalidate_cache(addr)
883 def invalidate_cache(self, address):
884 with self.cache_lock:
885 if address in self.history_cache:
886 print_log("cache: invalidating", address)
887 self.history_cache.pop(address)
889 if address in self.watched_addresses:
890 # TODO: update cache here. if new value equals cached value, do not send notification
891 self.address_queue.put(address)
893 def main_iteration(self):
894 if self.shared.stopped():
895 print_log("blockchain processor terminating")
903 self.memorypool_update()
905 if self.sent_height != self.height:
906 self.sent_height = self.height
909 'method': 'blockchain.numblocks.subscribe',
910 'params': [self.height],
913 if self.sent_header != self.header:
914 print_log("blockchain: %d (%.3fs)" % (self.height, t2 - t1))
915 self.sent_header = self.header
918 'method': 'blockchain.headers.subscribe',
919 'params': [self.header],
924 addr = self.address_queue.get(False)
927 if addr in self.watched_addresses:
928 status = self.get_status(addr)
931 'method': 'blockchain.address.subscribe',
932 'params': [addr, status],
935 if not self.shared.stopped():
936 threading.Timer(10, self.main_iteration).start()
938 print_log("blockchain processor terminating")