3 from json import dumps, loads
5 from Queue import Queue
12 from ltc_scrypt import getPoWHash
13 from backends.bitcoind import deserialize
14 from processor import Processor, print_log
17 from storage import Storage
20 class BlockchainProcessor(Processor):
22 def __init__(self, config, shared):
23 Processor.__init__(self)
25 self.mtimes = {} # monitoring
28 self.up_to_date = False
30 self.watch_lock = threading.Lock()
31 self.watch_blocks = []
32 self.watch_headers = []
33 self.watched_addresses = {}
35 self.history_cache = {}
37 self.cache_lock = threading.Lock()
38 self.headers_data = ''
39 self.headers_path = config.get('leveldb', 'path_fulltree')
41 self.mempool_values = {}
42 self.mempool_addresses = {}
43 self.mempool_hist = {}
44 self.mempool_hashes = set([])
45 self.mempool_lock = threading.Lock()
47 self.address_queue = Queue()
50 self.test_reorgs = config.getboolean('leveldb', 'test_reorgs') # simulate random blockchain reorgs
52 self.test_reorgs = False
53 self.storage = Storage(config, shared, self.test_reorgs)
55 self.dblock = threading.Lock()
57 self.bitcoind_url = 'http://%s:%s@%s:%s/' % (
58 config.get('bitcoind', 'user'),
59 config.get('bitcoind', 'password'),
60 config.get('bitcoind', 'host'),
61 config.get('bitcoind', 'port'))
65 self.bitcoind('getinfo')
68 print_log('cannot contact novacoind...')
73 self.sent_header = None
76 self.init_headers(self.storage.height)
78 threading.Timer(0, lambda: self.catch_up(sync=False)).start()
79 while not shared.stopped() and not self.up_to_date:
83 print "keyboard interrupt: stopping threads"
87 print_log("Blockchain is up to date.")
88 self.memorypool_update()
89 print_log("Memory pool initialized.")
91 self.timer = threading.Timer(10, self.main_iteration)
96 def mtime(self, name):
99 delta = now - self.now
100 t = self.mtimes.get(name, 0)
101 self.mtimes[name] = t + delta
104 def print_mtime(self):
106 for k, v in self.mtimes.items():
107 s += k+':'+"%.2f"%v+' '
111 def bitcoind(self, method, params=[]):
112 postdata = dumps({"method": method, 'params': params, 'id': 'jsonrpc'})
114 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
116 print_log("error calling novacoind")
117 traceback.print_exc(file=sys.stdout)
121 if r['error'] is not None:
122 raise BaseException(r['error'])
123 return r.get('result')
126 def block2header(self, b):
128 "block_height": b.get('height'),
129 "version": b.get('version'),
130 "prev_block_hash": b.get('previousblockhash'),
131 "merkle_root": b.get('merkleroot'),
132 "timestamp": b.get('time'),
133 "bits": int(b.get('bits'), 16),
134 "nonce": b.get('nonce'),
137 def get_header(self, height):
138 b = self.bitcoind('getblockbynumber', [height])
139 return self.block2header(b)
141 def init_headers(self, db_height):
142 self.chunk_cache = {}
143 self.headers_filename = os.path.join(self.headers_path, 'blockchain_headers')
145 if os.path.exists(self.headers_filename):
146 height = os.path.getsize(self.headers_filename)/80 - 1 # the current height
148 prev_hash = self.hash_header(self.read_header(height))
152 open(self.headers_filename, 'wb').close()
156 if height < db_height:
157 print_log("catching up missing headers:", height, db_height)
160 while height < db_height:
162 header = self.get_header(height)
164 if prev_hash != header.get('prev_block_hash'):
165 # The prev_hash block is orphaned, go back
166 print_log("reorganizing, a block in file is orphaned:", prev_hash)
167 # Go to the parent of the orphaned block
169 prev_hash = self.hash_header(self.read_header(height))
172 self.write_header(header, sync=False)
173 prev_hash = self.hash_header(header)
174 if (height % 1000) == 0:
175 print_log("headers file:", height)
176 except KeyboardInterrupt:
182 def hash_header(self, header):
183 return rev_hex(getPoWHash(header_to_string(header).decode('hex')).encode('hex'))
185 def read_header(self, block_height):
186 if os.path.exists(self.headers_filename):
187 with open(self.headers_filename, 'rb') as f:
188 f.seek(block_height * 80)
191 h = header_from_string(h)
194 def read_chunk(self, index):
195 with open(self.headers_filename, 'rb') as f:
196 f.seek(index*2016*80)
197 chunk = f.read(2016*80)
198 return chunk.encode('hex')
200 def write_header(self, header, sync=True):
201 if not self.headers_data:
202 self.headers_offset = header.get('block_height')
204 self.headers_data += header_to_string(header).decode('hex')
205 if sync or len(self.headers_data) > 40*100:
208 with self.cache_lock:
209 chunk_index = header.get('block_height')/2016
210 if self.chunk_cache.get(chunk_index):
211 self.chunk_cache.pop(chunk_index)
213 def pop_header(self):
214 # we need to do this only if we have not flushed
215 if self.headers_data:
216 self.headers_data = self.headers_data[:-40]
218 def flush_headers(self):
219 if not self.headers_data:
221 with open(self.headers_filename, 'rb+') as f:
222 f.seek(self.headers_offset*80)
223 f.write(self.headers_data)
224 self.headers_data = ''
226 def get_chunk(self, i):
227 # store them on disk; store the current chunk in memory
228 with self.cache_lock:
229 chunk = self.chunk_cache.get(i)
231 chunk = self.read_chunk(i)
232 self.chunk_cache[i] = chunk
236 def get_mempool_transaction(self, txid):
238 raw_tx = self.bitcoind('getrawtransaction', [txid, 0])
242 vds = deserialize.BCDataStream()
243 vds.write(raw_tx.decode('hex'))
245 return deserialize.parse_Transaction(vds, is_coinbase=False)
247 print_log("ERROR: cannot parse", txid)
251 def get_history(self, addr, cache_only=False):
252 with self.cache_lock:
253 hist = self.history_cache.get(addr)
261 hist = self.storage.get_history(addr)
264 print_log("error get_history")
265 traceback.print_exc(file=sys.stdout)
274 with self.mempool_lock:
275 for txid, delta in self.mempool_hist.get(addr, []):
276 hist.append({'tx_hash':txid, 'height':0})
278 # add something to distinguish between unused and empty addresses
279 if hist == [] and is_known:
282 with self.cache_lock:
283 self.history_cache[addr] = hist
287 def get_unconfirmed_value(self, addr):
289 with self.mempool_lock:
290 for txid, delta in self.mempool_hist.get(addr, []):
295 def get_status(self, addr, cache_only=False):
296 tx_points = self.get_history(addr, cache_only)
297 if cache_only and tx_points == -1:
302 if tx_points == ['*']:
306 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
307 return hashlib.sha256(status).digest().encode('hex')
309 def get_merkle(self, tx_hash, height):
311 b = self.bitcoind('getblockbynumber', [height])
312 tx_list = b.get('tx')
313 tx_pos = tx_list.index(tx_hash)
315 merkle = map(hash_decode, tx_list)
316 target_hash = hash_decode(tx_hash)
318 while len(merkle) != 1:
320 merkle.append(merkle[-1])
323 new_hash = Hash(merkle[0] + merkle[1])
324 if merkle[0] == target_hash:
325 s.append(hash_encode(merkle[1]))
326 target_hash = new_hash
327 elif merkle[1] == target_hash:
328 s.append(hash_encode(merkle[0]))
329 target_hash = new_hash
334 return {"block_height": height, "merkle": s, "pos": tx_pos}
337 def add_to_history(self, addr, tx_hash, tx_pos, tx_height):
339 s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0)
342 serialized_hist = self.batch_list[addr]
344 l = len(serialized_hist)/80
345 for i in range(l-1, -1, -1):
346 item = serialized_hist[80*i:80*(i+1)]
347 item_height = int(rev_hex(item[36:39].encode('hex')), 16)
348 if item_height <= tx_height:
349 serialized_hist = serialized_hist[0:80*(i+1)] + s + serialized_hist[80*(i+1):]
352 serialized_hist = s + serialized_hist
354 self.batch_list[addr] = serialized_hist
357 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
358 self.batch_txio[txo] = addr
365 def deserialize_block(self, block):
366 txlist = block.get('tx')
368 tx_hashes = [] # ordered txids
369 txdict = {} # deserialized tx
371 for i, raw_tx in enumerate(txlist):
372 tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
373 vds = deserialize.BCDataStream()
374 vds.write(raw_tx.decode('hex'))
376 tx = deserialize.parse_Transaction(vds, i == 0) # first transaction is always coinbase
378 print_log("ERROR: cannot parse", tx_hash)
380 tx_hashes.append(tx_hash)
382 return tx_hashes, txdict
386 def import_block(self, block, block_hash, block_height, sync, revert=False):
388 touched_addr = set([])
390 # deserialize transactions
391 tx_hashes, txdict = self.deserialize_block(block)
395 undo_info = self.storage.get_undo_info(block_height)
400 for txid in tx_hashes: # must be ordered
403 undo = self.storage.import_transaction(txid, tx, block_height, touched_addr)
404 undo_info[txid] = undo
406 undo = undo_info.pop(txid)
407 self.storage.revert_transaction(txid, tx, block_height, touched_addr, undo)
410 assert undo_info == {}
414 self.storage.write_undo_info(block_height, self.bitcoind_height, undo_info)
417 self.storage.db_undo.put('height', repr( (block_hash, block_height, self.storage.db_version) ))
419 for addr in touched_addr:
420 self.invalidate_cache(addr)
422 self.storage.update_hashes()
425 def add_request(self, session, request):
426 # see if we can get if from cache. if not, add to queue
427 if self.process(session, request, cache_only=True) == -1:
428 self.queue.put((session, request))
431 def do_subscribe(self, method, params, session):
432 with self.watch_lock:
433 if method == 'blockchain.numblocks.subscribe':
434 if session not in self.watch_blocks:
435 self.watch_blocks.append(session)
437 elif method == 'blockchain.headers.subscribe':
438 if session not in self.watch_headers:
439 self.watch_headers.append(session)
441 elif method == 'blockchain.address.subscribe':
443 l = self.watched_addresses.get(address)
445 self.watched_addresses[address] = [session]
446 elif session not in l:
450 def do_unsubscribe(self, method, params, session):
451 with self.watch_lock:
452 if method == 'blockchain.numblocks.subscribe':
453 if session in self.watch_blocks:
454 self.watch_blocks.remove(session)
455 elif method == 'blockchain.headers.subscribe':
456 if session in self.watch_headers:
457 self.watch_headers.remove(session)
458 elif method == "blockchain.address.subscribe":
460 l = self.watched_addresses.get(addr)
466 print_log("error rc!!")
469 self.watched_addresses.pop(addr)
472 def process(self, session, request, cache_only=False):
474 message_id = request['id']
475 method = request['method']
476 params = request.get('params', [])
480 if method == 'blockchain.numblocks.subscribe':
481 result = self.storage.height
483 elif method == 'blockchain.headers.subscribe':
486 elif method == 'blockchain.address.subscribe':
488 address = str(params[0])
489 result = self.get_status(address, cache_only)
490 except BaseException, e:
491 error = str(e) + ': ' + address
492 print_log("error:", error)
494 elif method == 'blockchain.address.get_history':
496 address = str(params[0])
497 result = self.get_history(address, cache_only)
498 except BaseException, e:
499 error = str(e) + ': ' + address
500 print_log("error:", error)
502 elif method == 'blockchain.address.get_mempool':
504 address = str(params[0])
505 result = self.get_unconfirmed_history(address, cache_only)
506 except BaseException, e:
507 error = str(e) + ': ' + address
508 print_log("error:", error)
510 elif method == 'blockchain.address.get_balance':
512 address = str(params[0])
513 confirmed = self.storage.get_balance(address)
514 unconfirmed = self.get_unconfirmed_value(address)
515 result = { 'confirmed':confirmed, 'unconfirmed':unconfirmed }
516 except BaseException, e:
517 error = str(e) + ': ' + address
518 print_log("error:", error)
520 elif method == 'blockchain.address.get_proof':
522 address = str(params[0])
523 result = self.storage.get_proof(address)
524 except BaseException, e:
525 error = str(e) + ': ' + address
526 print_log("error:", error)
528 elif method == 'blockchain.address.listunspent':
530 address = str(params[0])
531 result = self.storage.listunspent(address)
532 except BaseException, e:
533 error = str(e) + ': ' + address
534 print_log("error:", error)
536 elif method == 'blockchain.utxo.get_address':
538 txid = str(params[0])
540 txi = (txid + int_to_hex(pos, 4)).decode('hex')
541 result = self.storage.get_address(txi)
542 except BaseException, e:
544 print_log("error:", error, params)
546 elif method == 'blockchain.block.get_header':
551 height = int(params[0])
552 result = self.get_header(height)
553 except BaseException, e:
554 error = str(e) + ': %d' % height
555 print_log("error:", error)
557 elif method == 'blockchain.block.get_chunk':
562 index = int(params[0])
563 result = self.get_chunk(index)
564 except BaseException, e:
565 error = str(e) + ': %d' % index
566 print_log("error:", error)
568 elif method == 'blockchain.transaction.broadcast':
570 txo = self.bitcoind('sendrawtransaction', params)
571 print_log("sent tx:", txo)
573 except BaseException, e:
574 result = str(e) # do not send an error
575 print_log("error:", result, params)
577 elif method == 'blockchain.transaction.get_merkle':
583 tx_height = params[1]
584 result = self.get_merkle(tx_hash, tx_height)
585 except BaseException, e:
586 error = str(e) + ': ' + repr(params)
587 print_log("get_merkle error:", error)
589 elif method == 'blockchain.transaction.get':
592 result = self.bitcoind('getrawtransaction', [tx_hash, 0])
593 except BaseException, e:
594 error = str(e) + ': ' + repr(params)
595 print_log("tx get error:", error)
598 error = "unknown method:%s" % method
600 if cache_only and result == -1:
604 self.push_response(session, {'id': message_id, 'error': error})
606 self.push_response(session, {'id': message_id, 'result': result})
608 def catch_up(self, sync=True):
610 prev_root_hash = None
611 while not self.shared.stopped():
616 info = self.bitcoind('getinfo')
617 self.bitcoind_height = info.get('blocks')
618 bitcoind_block_hash = self.bitcoind('getblockhash', [self.bitcoind_height])
619 if self.storage.last_hash == bitcoind_block_hash:
620 self.up_to_date = True
623 # fixme: this is unsafe, if we revert when the undo info is not yet written
624 revert = (random.randint(1, 100) == 1) if self.test_reorgs else False
627 self.up_to_date = False
629 next_block = self.bitcoind('getblockbynumber', [self.storage.height + 1, True])
630 except BaseException, e:
631 next_block = self.bitcoind('getblock', [self.storage.last_hash, True])
634 next_block_hash = next_block.get('hash')
638 if (next_block.get('previousblockhash') == self.storage.last_hash) and not revert:
640 prev_root_hash = self.storage.get_root_hash()
642 self.import_block(next_block, next_block_hash, self.storage.height+1, sync)
643 self.storage.height = self.storage.height + 1
644 self.write_header(self.block2header(next_block), sync)
645 self.storage.last_hash = next_block_hash
648 if self.storage.height % 1000 == 0 and not sync:
649 t_daemon = self.mtimes.get('daemon')
650 t_import = self.mtimes.get('import')
651 print_log("catch_up: block %d (%.3fs %.3fs)" % (self.storage.height, t_daemon, t_import), self.storage.get_root_hash().encode('hex'))
652 self.mtimes['daemon'] = 0
653 self.mtimes['import'] = 0
657 # revert current block
658 block = self.bitcoind('getblock', [self.storage.last_hash, True])
659 print_log("blockchain reorg", self.storage.height, block.get('previousblockhash'), self.storage.last_hash)
660 self.import_block(block, self.storage.last_hash, self.storage.height, sync, revert=True)
664 self.storage.height -= 1
666 # read previous header from disk
667 self.header = self.read_header(self.storage.height)
668 self.storage.last_hash = self.hash_header(self.header)
671 assert prev_root_hash == self.storage.get_root_hash()
672 prev_root_hash = None
675 self.header = self.block2header(self.bitcoind('getblock', [self.storage.last_hash]))
676 self.header['utxo_root'] = self.storage.get_root_hash().encode('hex')
678 if self.shared.stopped():
679 print_log( "closing database" )
683 def memorypool_update(self):
684 mempool_hashes = set(self.bitcoind('getrawmempool'))
685 touched_addresses = set([])
687 # get new transactions
689 for tx_hash in mempool_hashes:
690 if tx_hash in self.mempool_hashes:
693 tx = self.get_mempool_transaction(tx_hash)
698 self.mempool_hashes.add(tx_hash)
700 # remove older entries from mempool_hashes
701 self.mempool_hashes = mempool_hashes
704 # check all tx outputs
705 for tx_hash, tx in new_tx.items():
706 mpa = self.mempool_addresses.get(tx_hash, {})
708 for x in tx.get('outputs'):
709 out_values.append( x['value'] )
711 addr = x.get('address')
717 touched_addresses.add(addr)
719 self.mempool_addresses[tx_hash] = mpa
720 self.mempool_values[tx_hash] = out_values
723 for tx_hash, tx in new_tx.items():
724 mpa = self.mempool_addresses.get(tx_hash, {})
725 for x in tx.get('inputs'):
726 # we assume that the input address can be parsed by deserialize(); this is true for Electrum transactions
727 addr = x.get('address')
731 v = self.mempool_values.get(x.get('prevout_hash'))
733 value = v[ x.get('prevout_n')]
735 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
737 value = self.storage.get_utxo_value(addr,txi)
739 print_log("utxo not in database; postponing mempool update")
745 touched_addresses.add(addr)
747 self.mempool_addresses[tx_hash] = mpa
750 # remove deprecated entries from mempool_addresses
751 for tx_hash, addresses in self.mempool_addresses.items():
752 if tx_hash not in self.mempool_hashes:
753 self.mempool_addresses.pop(tx_hash)
754 self.mempool_values.pop(tx_hash)
755 for addr in addresses:
756 touched_addresses.add(addr)
758 # rebuild mempool histories
759 new_mempool_hist = {}
760 for tx_hash, addresses in self.mempool_addresses.items():
761 for addr, delta in addresses.items():
762 h = new_mempool_hist.get(addr, [])
764 h.append((tx_hash, delta))
765 new_mempool_hist[addr] = h
767 with self.mempool_lock:
768 self.mempool_hist = new_mempool_hist
770 # invalidate cache for touched addresses
771 for addr in touched_addresses:
772 self.invalidate_cache(addr)
775 def invalidate_cache(self, address):
776 with self.cache_lock:
777 if address in self.history_cache:
778 print_log("cache: invalidating", address)
779 self.history_cache.pop(address)
781 with self.watch_lock:
782 sessions = self.watched_addresses.get(address)
785 # TODO: update cache here. if new value equals cached value, do not send notification
786 self.address_queue.put((address,sessions))
791 print_log("Closing database...")
793 print_log("Database is closed")
796 def main_iteration(self):
797 if self.shared.stopped():
798 print_log("Stopping timer")
806 self.memorypool_update()
808 if self.sent_height != self.storage.height:
809 self.sent_height = self.storage.height
810 for session in self.watch_blocks:
811 self.push_response(session, {
813 'method': 'blockchain.numblocks.subscribe',
814 'params': [self.storage.height],
817 if self.sent_header != self.header:
818 print_log("blockchain: %d (%.3fs)" % (self.storage.height, t2 - t1))
819 self.sent_header = self.header
820 for session in self.watch_headers:
821 self.push_response(session, {
823 'method': 'blockchain.headers.subscribe',
824 'params': [self.header],
829 addr, sessions = self.address_queue.get(False)
833 status = self.get_status(addr)
834 for session in sessions:
835 self.push_response(session, {
837 'method': 'blockchain.address.subscribe',
838 'params': [addr, status],
842 self.timer = threading.Timer(10, self.main_iteration)