1 from json import dumps, loads
4 import ast, time, threading, hashlib
5 from Queue import Queue
6 import traceback, sys, os, random
10 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
11 hash_encode = lambda x: x[::-1].encode('hex')
12 hash_decode = lambda x: x.decode('hex')[::-1]
17 return s.decode('hex')[::-1].encode('hex')
20 def int_to_hex(i, length=1):
21 s = hex(i)[2:].rstrip('L')
22 s = "0"*(2*length - len(s)) + s
25 def header_to_string(res):
26 pbh = res.get('prev_block_hash')
27 if pbh is None: pbh = '0'*64
28 s = int_to_hex(res.get('version'),4) \
30 + rev_hex(res.get('merkle_root')) \
31 + int_to_hex(int(res.get('timestamp')),4) \
32 + int_to_hex(int(res.get('bits')),4) \
33 + int_to_hex(int(res.get('nonce')),4)
36 def header_from_string( s):
37 hex_to_int = lambda s: eval('0x' + s[::-1].encode('hex'))
39 h['version'] = hex_to_int(s[0:4])
40 h['prev_block_hash'] = hash_encode(s[4:36])
41 h['merkle_root'] = hash_encode(s[36:68])
42 h['timestamp'] = hex_to_int(s[68:72])
43 h['bits'] = hex_to_int(s[72:76])
44 h['nonce'] = hex_to_int(s[76:80])
50 from processor import Processor, print_log
52 class BlockchainProcessor(Processor):
54 def __init__(self, config, shared):
55 Processor.__init__(self)
58 self.up_to_date = False
59 self.watched_addresses = []
60 self.history_cache = {}
62 self.cache_lock = threading.Lock()
63 self.headers_data = ''
65 self.mempool_addresses = {}
66 self.mempool_hist = {}
67 self.mempool_hashes = []
68 self.mempool_lock = threading.Lock()
70 self.address_queue = Queue()
71 self.dbpath = config.get('leveldb', 'path')
73 self.dblock = threading.Lock()
75 self.db = leveldb.LevelDB(self.dbpath)
77 traceback.print_exc(file=sys.stdout)
80 self.bitcoind_url = 'http://%s:%s@%s:%s/' % (
81 config.get('bitcoind','user'),
82 config.get('bitcoind','password'),
83 config.get('bitcoind','host'),
84 config.get('bitcoind','port'))
89 self.sent_header = None
93 hist = self.deserialize(self.db.Get('height'))
94 self.last_hash, self.height, _ = hist[0]
95 print_log( "hist", hist )
97 #traceback.print_exc(file=sys.stdout)
98 print_log('initializing database')
100 self.last_hash = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
103 self.init_headers(self.height)
105 threading.Timer(0, lambda: self.catch_up(sync=False)).start()
106 while not shared.stopped() and not self.up_to_date:
110 print "keyboard interrupt: stopping threads"
114 print_log( "blockchain is up to date." )
116 threading.Timer(10, self.main_iteration).start()
120 def bitcoind(self, method, params=[]):
121 postdata = dumps({"method": method, 'params': params, 'id':'jsonrpc'})
122 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
124 if r['error'] != None:
125 raise BaseException(r['error'])
126 return r.get('result')
129 def serialize(self, h):
131 for txid, txpos, height in h:
132 s += txid + int_to_hex(txpos, 4) + int_to_hex(height, 4)
133 return s.decode('hex')
136 def deserialize(self, s):
139 txid = s[0:32].encode('hex')
140 txpos = int( rev_hex( s[32:36].encode('hex') ), 16 )
141 height = int( rev_hex( s[36:40].encode('hex') ), 16 )
142 h.append( ( txid, txpos, height ) )
147 def block2header(self, b):
148 return {"block_height":b.get('height'), "version":b.get('version'), "prev_block_hash":b.get('previousblockhash'),
149 "merkle_root":b.get('merkleroot'), "timestamp":b.get('time'), "bits":int(b.get('bits'),16), "nonce":b.get('nonce')}
152 def get_header(self, height):
153 block_hash = self.bitcoind('getblockhash', [height])
154 b = self.bitcoind('getblock', [block_hash])
155 return self.block2header(b)
158 def init_headers(self, db_height):
159 self.chunk_cache = {}
160 self.headers_filename = os.path.join( self.dbpath, 'blockchain_headers')
162 if os.path.exists(self.headers_filename):
163 height = os.path.getsize(self.headers_filename)/80 - 1 # the current height
165 prev_hash = self.hash_header(self.read_header(height))
169 open(self.headers_filename,'wb').close()
173 if height < db_height:
174 print_log( "catching up missing headers:", height, db_height)
177 while height < db_height:
179 header = self.get_header(height)
181 assert prev_hash == header.get('prev_block_hash')
182 self.write_header(header, sync=False)
183 prev_hash = self.hash_header(header)
184 if height%1000==0: print_log("headers file:",height)
185 except KeyboardInterrupt:
192 def hash_header(self, header):
193 return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
196 def read_header(self, block_height):
197 if os.path.exists(self.headers_filename):
198 f = open(self.headers_filename,'rb')
199 f.seek(block_height*80)
203 h = header_from_string(h)
207 def read_chunk(self, index):
208 f = open(self.headers_filename,'rb')
209 f.seek(index*2016*80)
210 chunk = f.read(2016*80)
212 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 def pop_header(self):
224 # we need to do this only if we have not flushed
225 if self.headers_data:
226 self.headers_data = self.headers_data[:-40]
228 def flush_headers(self):
229 if not self.headers_data: return
230 f = open(self.headers_filename,'rb+')
231 f.seek(self.headers_offset*80)
232 f.write(self.headers_data)
234 self.headers_data = ''
237 def get_chunk(self, i):
238 # store them on disk; store the current chunk in memory
239 chunk = self.chunk_cache.get(i)
241 chunk = self.read_chunk(i)
242 self.chunk_cache[i] = chunk
246 def get_transaction(self, txid, block_height=-1, is_coinbase = False):
247 raw_tx = self.bitcoind('getrawtransaction', [txid, 0, block_height])
248 vds = deserialize.BCDataStream()
249 vds.write(raw_tx.decode('hex'))
250 out = deserialize.parse_Transaction(vds, is_coinbase)
254 def get_history(self, addr, cache_only=False):
255 with self.cache_lock: hist = self.history_cache.get( addr )
256 if hist is not None: return hist
257 if cache_only: return -1
261 hist = self.deserialize(self.db.Get(addr))
267 # should not be necessary
268 hist.sort( key=lambda tup: tup[1])
269 # check uniqueness too...
272 with self.mempool_lock:
273 for txid in self.mempool_hist.get(addr,[]):
274 hist.append((txid, 0, 0))
276 hist = map(lambda x: {'tx_hash':x[0], 'height':x[2]}, hist)
277 # add something to distinguish between unused and empty addresses
278 if hist == [] and is_known: hist = ['*']
280 with self.cache_lock: self.history_cache[addr] = hist
284 def get_status(self, addr, cache_only=False):
285 tx_points = self.get_history(addr, cache_only)
286 if cache_only and tx_points == -1: return -1
288 if not tx_points: return None
289 if tx_points == ['*']: return '*'
292 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
293 return hashlib.sha256( status ).digest().encode('hex')
296 def get_merkle(self, tx_hash, height):
298 block_hash = self.bitcoind('getblockhash', [height])
299 b = self.bitcoind('getblock', [block_hash])
300 tx_list = b.get('tx')
301 tx_pos = tx_list.index(tx_hash)
303 merkle = map(hash_decode, tx_list)
304 target_hash = hash_decode(tx_hash)
306 while len(merkle) != 1:
307 if len(merkle)%2: merkle.append( merkle[-1] )
310 new_hash = Hash( merkle[0] + merkle[1] )
311 if merkle[0] == target_hash:
312 s.append( hash_encode( merkle[1]))
313 target_hash = new_hash
314 elif merkle[1] == target_hash:
315 s.append( hash_encode( merkle[0]))
316 target_hash = new_hash
321 return {"block_height":height, "merkle":s, "pos":tx_pos}
326 def add_to_history(self, addr, tx_hash, tx_pos, tx_height):
329 s = (tx_hash + int_to_hex(tx_pos, 4) + int_to_hex(tx_height, 4)).decode('hex')
331 serialized_hist = self.batch_list[addr]
333 l = len(serialized_hist)/40
334 for i in range(l-1, -1, -1):
335 item = serialized_hist[40*i:40*(i+1)]
336 item_height = int( rev_hex( item[36:40].encode('hex') ), 16 )
337 if item_height < tx_height:
338 serialized_hist = serialized_hist[0:40*(i+1)] + s + serialized_hist[40*(i+1):]
341 serialized_hist = s + serialized_hist
343 self.batch_list[addr] = serialized_hist
346 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
347 self.batch_txio[txo] = addr
350 def remove_from_history(self, addr, tx_hash, tx_pos):
352 txi = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
356 addr = self.batch_txio[txi]
358 raise BaseException(tx_hash, tx_pos)
360 serialized_hist = self.batch_list[addr]
362 l = len(serialized_hist)/40
364 item = serialized_hist[40*i:40*(i+1)]
365 if item[0:36] == txi:
366 height = int( rev_hex( item[36:40].encode('hex') ), 16 )
367 serialized_hist = serialized_hist[0:40*i] + serialized_hist[40*(i+1):]
370 hist = self.deserialize(serialized_hist)
371 raise BaseException("prevout not found", addr, hist, tx_hash, tx_pos)
373 self.batch_list[addr] = serialized_hist
377 def deserialize_block(self, block):
378 txlist = block.get('tx')
379 tx_hashes = [] # ordered txids
380 txdict = {} # deserialized tx
382 for raw_tx in txlist:
383 tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
384 tx_hashes.append(tx_hash)
385 vds = deserialize.BCDataStream()
386 vds.write(raw_tx.decode('hex'))
387 tx = deserialize.parse_Transaction(vds, is_coinbase)
390 return tx_hashes, txdict
392 def get_undo_info(self, height):
393 s = self.db.Get("undo%d"%(height%100))
396 def write_undo_info(self, batch, height, undo_info):
397 batch.Put("undo%d"%(height%100), repr(undo_info))
400 def import_block(self, block, block_hash, block_height, sync, revert=False):
402 self.batch_list = {} # address -> history
403 self.batch_txio = {} # transaction i/o -> address
409 # deserialize transactions
411 tx_hashes, txdict = self.deserialize_block(block)
417 # read addresses of tx inputs
418 for tx in txdict.values():
419 for x in tx.get('inputs'):
420 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
421 block_inputs.append(txi)
424 for txi in block_inputs:
426 addr = self.db.Get(txi)
428 # the input could come from the same block
430 self.batch_txio[txi] = addr
431 addr_to_read.append(addr)
434 for txid, tx in txdict.items():
435 for x in tx.get('outputs'):
436 txo = (txid + int_to_hex(x.get('index'), 4)).decode('hex')
437 block_outputs.append(txo)
441 # read histories of addresses
442 for txid, tx in txdict.items():
443 for x in tx.get('outputs'):
444 addr_to_read.append(x.get('address'))
447 for addr in addr_to_read:
449 self.batch_list[addr] = self.db.Get(addr)
451 self.batch_list[addr] = ''
455 undo_info = self.get_undo_info(block_height)
456 print "undo", block_height, undo_info
462 if revert: tx_hashes = tx_hashes[::-1]
463 for txid in tx_hashes: # must be ordered
468 for x in tx.get('inputs'):
469 prevout_height, prevout_addr = self.remove_from_history( None, x.get('prevout_hash'), x.get('prevout_n'))
470 undo.append( (prevout_height, prevout_addr) )
471 undo_info[txid] = undo
473 for x in tx.get('outputs'):
474 self.add_to_history( x.get('address'), txid, x.get('index'), block_height)
477 for x in tx.get('outputs'):
478 self.remove_from_history( x.get('address'), txid, x.get('index'))
481 for x in tx.get('inputs'):
482 prevout_height, prevout_addr = undo_info.get(txid)[i]
485 # read the history into batch list
486 if self.batch_list.get(prevout_addr) is None:
487 self.batch_list[prevout_addr] = self.db.Get(prevout_addr)
489 # re-add them to the history
490 self.add_to_history( prevout_addr, x.get('prevout_hash'), x.get('prevout_n'), prevout_height)
491 print "new hist for", prevout_addr, self.deserialize(self.batch_list[prevout_addr])
498 batch = leveldb.WriteBatch()
499 for addr, serialized_hist in self.batch_list.items():
500 batch.Put(addr, serialized_hist)
501 l = len(serialized_hist)
507 # add new created outputs
508 for txio, addr in self.batch_txio.items():
509 batch.Put(txio, addr)
510 # delete spent inputs
511 for txi in block_inputs:
514 self.write_undo_info(batch, block_height, undo_info)
516 # restore spent inputs
517 for txio, addr in self.batch_txio.items():
518 batch.Put(txio, addr)
519 # delete spent outputs
520 for txo in block_outputs:
525 batch.Put('height', self.serialize( [(block_hash, block_height, 0)] ) )
528 self.db.Write(batch, sync = sync)
531 if t3 - t0 > 10 and not sync:
532 print_log("block", block_height,
533 "parse:%0.2f "%(t00 - t0),
534 "read:%0.2f "%(t1 - t00),
535 "proc:%.2f "%(t2-t1),
536 "write:%.2f "%(t3-t2),
537 "max:", max_len, max_addr)
539 for addr in self.batch_list.keys(): self.invalidate_cache(addr)
543 def add_request(self, request):
544 # see if we can get if from cache. if not, add to queue
545 if self.process( request, cache_only = True) == -1:
546 self.queue.put(request)
550 def process(self, request, cache_only = False):
551 #print "abe process", request
553 message_id = request['id']
554 method = request['method']
555 params = request.get('params',[])
559 if method == 'blockchain.numblocks.subscribe':
562 elif method == 'blockchain.headers.subscribe':
565 elif method == 'blockchain.address.subscribe':
568 result = self.get_status(address, cache_only)
569 self.watch_address(address)
570 except BaseException, e:
571 error = str(e) + ': ' + address
572 print_log( "error:", error )
574 elif method == 'blockchain.address.subscribe2':
577 result = self.get_status(address, cache_only)
578 self.watch_address(address)
579 except BaseException, e:
580 error = str(e) + ': ' + address
581 print_log( "error:", error )
583 elif method == 'blockchain.address.get_history2':
586 result = self.get_history( address, cache_only )
587 except BaseException, e:
588 error = str(e) + ': ' + address
589 print_log( "error:", error )
591 elif method == 'blockchain.block.get_header':
597 result = self.get_header( height )
598 except BaseException, e:
599 error = str(e) + ': %d'% height
600 print_log( "error:", error )
602 elif method == 'blockchain.block.get_chunk':
608 result = self.get_chunk( index )
609 except BaseException, e:
610 error = str(e) + ': %d'% index
611 print_log( "error:", error)
613 elif method == 'blockchain.transaction.broadcast':
614 txo = self.bitcoind('sendrawtransaction', params)
615 print_log( "sent tx:", txo )
618 elif method == 'blockchain.transaction.get_merkle':
624 tx_height = params[1]
625 result = self.get_merkle(tx_hash, tx_height)
626 except BaseException, e:
627 error = str(e) + ': ' + tx_hash
628 print_log( "error:", error )
630 elif method == 'blockchain.transaction.get':
634 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height] )
635 except BaseException, e:
636 error = str(e) + ': ' + tx_hash
637 print_log( "error:", error )
640 error = "unknown method:%s"%method
642 if cache_only and result == -1: return -1
645 response = { 'id':message_id, 'error':error }
646 self.push_response(response)
648 response = { 'id':message_id, 'result':result }
649 self.push_response(response)
652 def watch_address(self, addr):
653 if addr not in self.watched_addresses:
654 self.watched_addresses.append(addr)
658 def catch_up(self, sync = True):
662 while not self.shared.stopped():
665 info = self.bitcoind('getinfo')
666 bitcoind_height = info.get('blocks')
667 bitcoind_block_hash = self.bitcoind('getblockhash', [bitcoind_height])
668 if self.last_hash == bitcoind_block_hash:
669 self.up_to_date = True
673 self.up_to_date = False
674 next_block_hash = self.bitcoind('getblockhash', [self.height+1])
675 next_block = self.bitcoind('getblock', [next_block_hash, 1])
677 revert = (random.randint(1, 10)==1) if self.is_test else False
678 if (next_block.get('previousblockhash') == self.last_hash) and not revert:
680 self.import_block(next_block, next_block_hash, self.height+1, sync)
681 self.height = self.height + 1
682 self.write_header(self.block2header(next_block), sync)
683 self.last_hash = next_block_hash
685 if (self.height)%100 == 0 and not sync:
687 print_log( "catch_up: block %d (%.3fs)"%( self.height, t2 - t1 ) )
691 # revert current block
692 block = self.bitcoind('getblock', [self.last_hash, 1])
693 print_log( "blockchain reorg", self.height, block.get('previousblockhash'), self.last_hash )
694 self.import_block(block, self.last_hash, self.height, sync, revert=True)
698 self.height = self.height -1
700 # read previous header from disk
701 self.header = self.read_header(self.height)
702 self.last_hash = self.hash_header(self.header)
705 self.header = self.block2header(self.bitcoind('getblock', [self.last_hash]))
710 def memorypool_update(self):
712 mempool_hashes = self.bitcoind('getrawmempool')
714 for tx_hash in mempool_hashes:
715 if tx_hash in self.mempool_hashes: continue
717 tx = self.get_transaction(tx_hash)
720 for x in tx.get('inputs'):
721 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
723 addr = self.db.Get(txi)
726 l = self.mempool_addresses.get(tx_hash, [])
729 self.mempool_addresses[tx_hash] = l
731 for x in tx.get('outputs'):
732 addr = x.get('address')
733 l = self.mempool_addresses.get(tx_hash, [])
736 self.mempool_addresses[tx_hash] = l
738 self.mempool_hashes.append(tx_hash)
740 # remove older entries from mempool_hashes
741 self.mempool_hashes = mempool_hashes
743 # remove deprecated entries from mempool_addresses
744 for tx_hash, addresses in self.mempool_addresses.items():
745 if tx_hash not in self.mempool_hashes:
746 self.mempool_addresses.pop(tx_hash)
749 new_mempool_hist = {}
750 for tx_hash, addresses in self.mempool_addresses.items():
751 for addr in addresses:
752 h = new_mempool_hist.get(addr, [])
755 new_mempool_hist[addr] = h
757 for addr in new_mempool_hist.keys():
758 if addr in self.mempool_hist.keys():
759 if self.mempool_hist[addr] != new_mempool_hist[addr]:
760 self.invalidate_cache(addr)
762 self.invalidate_cache(addr)
764 with self.mempool_lock:
765 self.mempool_hist = new_mempool_hist
769 def invalidate_cache(self, address):
770 with self.cache_lock:
771 if self.history_cache.has_key(address):
772 print_log( "cache: invalidating", address )
773 self.history_cache.pop(address)
775 if address in self.watched_addresses:
776 self.address_queue.put(address)
780 def main_iteration(self):
782 if self.shared.stopped():
783 print_log( "blockchain processor terminating" )
791 self.memorypool_update()
793 # print "mempool:", len(self.mempool_addresses), len(self.mempool_hist), "%.3fs"%(t3 - t2)
796 if self.sent_height != self.height:
797 self.sent_height = self.height
798 self.push_response({ 'id': None, 'method':'blockchain.numblocks.subscribe', 'params':[self.height] })
800 if self.sent_header != self.header:
801 print_log( "blockchain: %d (%.3fs)"%( self.height, t2 - t1 ) )
802 self.sent_header = self.header
803 self.push_response({ 'id': None, 'method':'blockchain.headers.subscribe', 'params':[self.header] })
807 addr = self.address_queue.get(False)
810 if addr in self.watched_addresses:
811 status = self.get_status( addr )
812 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe', 'params':[addr, status] })
813 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe2', 'params':[addr, status] })
816 if not self.shared.stopped():
817 threading.Timer(10, self.main_iteration).start()
819 print_log( "blockchain processor terminating" )