1 from json import dumps, loads
4 import ast, time, threading, hashlib
5 from Queue import Queue
6 import traceback, sys, os
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'))
88 self.sent_header = None
92 hist = self.deserialize(self.db.Get('0'))
93 hh, self.height, _ = hist[0]
94 self.block_hashes = [hh]
95 print_log( "hist", hist )
97 #traceback.print_exc(file=sys.stdout)
98 print_log('initializing database')
100 self.block_hashes = [ '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 "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')
163 if os.path.exists(self.headers_filename):
164 height = os.path.getsize(self.headers_filename)/80
167 prev_header = self.read_header(height -1)
168 prev_hash = self.hash_header(prev_header)
170 open(self.headers_filename,'wb').close()
173 if height != db_height:
174 print_log( "catching up missing headers:", height, db_height)
178 for i in range(height, db_height):
179 header = self.get_header(i)
180 assert prev_hash == header.get('prev_block_hash')
181 self.write_header(header, sync=False)
182 prev_hash = self.hash_header(header)
183 if i%1000==0: print_log("headers file:",i)
184 except KeyboardInterrupt:
191 def hash_header(self, header):
192 return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex'))
195 def read_header(self, block_height):
196 if os.path.exists(self.headers_filename):
197 f = open(self.headers_filename,'rb')
198 f.seek(block_height*80)
202 h = header_from_string(h)
206 def read_chunk(self, index):
207 f = open(self.headers_filename,'rb')
208 f.seek(index*2016*80)
209 chunk = f.read(2016*80)
211 return chunk.encode('hex')
214 def write_header(self, header, sync=True):
215 if not self.headers_data:
216 self.headers_offset = header.get('block_height')
217 self.headers_data += header_to_string(header).decode('hex')
218 if sync or len(self.headers_data) > 40*100:
221 def pop_header(self):
222 # we need to do this only if we have not flushed
223 if self.headers_data:
224 self.headers_data = self.headers_data[:-40]
226 def flush_headers(self):
227 if not self.headers_data: return
228 f = open(self.headers_filename,'rb+')
229 f.seek(self.headers_offset*80)
230 f.write(self.headers_data)
232 self.headers_data = ''
235 def get_chunk(self, i):
236 # store them on disk; store the current chunk in memory
237 chunk = self.chunk_cache.get(i)
239 chunk = self.read_chunk(i)
240 self.chunk_cache[i] = chunk
244 def get_transaction(self, txid, block_height=-1, is_coinbase = False):
245 raw_tx = self.bitcoind('getrawtransaction', [txid, 0, block_height])
246 vds = deserialize.BCDataStream()
247 vds.write(raw_tx.decode('hex'))
248 out = deserialize.parse_Transaction(vds, is_coinbase)
252 def get_history(self, addr, cache_only=False):
253 with self.cache_lock: hist = self.history_cache.get( addr )
254 if hist is not None: return hist
255 if cache_only: return -1
259 hist = self.deserialize(self.db.Get(addr))
265 # should not be necessary
266 hist.sort( key=lambda tup: tup[1])
267 # check uniqueness too...
270 with self.mempool_lock:
271 for txid in self.mempool_hist.get(addr,[]):
272 hist.append((txid, 0, 0))
274 hist = map(lambda x: {'tx_hash':x[0], 'height':x[2]}, hist)
275 # add something to distinguish between unused and empty addresses
276 if hist == [] and is_known: hist = ['*']
278 with self.cache_lock: self.history_cache[addr] = hist
282 def get_status(self, addr, cache_only=False):
283 tx_points = self.get_history(addr, cache_only)
284 if cache_only and tx_points == -1: return -1
286 if not tx_points: return None
287 if tx_points == ['*']: return '*'
290 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
291 return hashlib.sha256( status ).digest().encode('hex')
294 def get_merkle(self, tx_hash, height):
296 block_hash = self.bitcoind('getblockhash', [height])
297 b = self.bitcoind('getblock', [block_hash])
298 tx_list = b.get('tx')
299 tx_pos = tx_list.index(tx_hash)
301 merkle = map(hash_decode, tx_list)
302 target_hash = hash_decode(tx_hash)
304 while len(merkle) != 1:
305 if len(merkle)%2: merkle.append( merkle[-1] )
308 new_hash = Hash( merkle[0] + merkle[1] )
309 if merkle[0] == target_hash:
310 s.append( hash_encode( merkle[1]))
311 target_hash = new_hash
312 elif merkle[1] == target_hash:
313 s.append( hash_encode( merkle[0]))
314 target_hash = new_hash
319 return {"block_height":height, "merkle":s, "pos":tx_pos}
322 def add_to_batch(self, addr, tx_hash, tx_pos, tx_height):
324 # we do it chronologically, so nothing wrong can happen...
325 s = (tx_hash + int_to_hex(tx_pos, 4) + int_to_hex(tx_height, 4)).decode('hex')
326 self.batch_list[addr] += s
329 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
330 self.batch_txio[txo] = addr
333 def remove_from_batch(self, tx_hash, tx_pos):
335 txi = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
337 addr = self.batch_txio[txi]
339 #raise BaseException(tx_hash, tx_pos)
340 print "WARNING: cannot find address for", (tx_hash, tx_pos)
343 serialized_hist = self.batch_list[addr]
345 l = len(serialized_hist)/40
347 if serialized_hist[40*i:40*i+36] == txi:
348 serialized_hist = serialized_hist[0:40*i] + serialized_hist[40*(i+1):]
351 raise BaseException("prevout not found", addr, hist, tx_hash, tx_pos)
352 self.batch_list[addr] = serialized_hist
355 def deserialize_block(self, block):
356 txlist = block.get('tx')
357 tx_hashes = [] # ordered txids
358 txdict = {} # deserialized tx
360 for raw_tx in txlist:
361 tx_hash = hash_encode(Hash(raw_tx.decode('hex')))
362 tx_hashes.append(tx_hash)
363 vds = deserialize.BCDataStream()
364 vds.write(raw_tx.decode('hex'))
365 tx = deserialize.parse_Transaction(vds, is_coinbase)
368 return tx_hashes, txdict
371 def import_block(self, block, block_hash, block_height, sync, revert=False):
373 self.batch_list = {} # address -> history
374 self.batch_txio = {} # transaction i/o -> address
379 # deserialize transactions
381 tx_hashes, txdict = self.deserialize_block(block)
383 # read addresses of tx inputs
385 for tx in txdict.values():
386 for x in tx.get('inputs'):
387 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
388 inputs_to_read.append(txi)
390 inputs_to_read.sort()
391 for txi in inputs_to_read:
393 addr = self.db.Get(txi)
395 # the input could come from the same block
397 self.batch_txio[txi] = addr
398 addr_to_read.append(addr)
400 # read histories of addresses
401 for txid, tx in txdict.items():
402 for x in tx.get('outputs'):
403 addr_to_read.append(x.get('address'))
406 for addr in addr_to_read:
408 self.batch_list[addr] = self.db.Get(addr)
410 self.batch_list[addr] = ''
415 for txid in tx_hashes: # must be ordered
418 for x in tx.get('inputs'):
419 self.remove_from_batch( x.get('prevout_hash'), x.get('prevout_n'))
420 for x in tx.get('outputs'):
421 self.add_to_batch( x.get('address'), txid, x.get('index'), block_height)
423 for x in tx.get('outputs'):
424 self.remove_from_batch( x.get('prevout_hash'), x.get('prevout_n'))
425 for x in tx.get('inputs'):
426 self.add_to_batch( x.get('address'), txid, x.get('index'), block_height)
433 batch = leveldb.WriteBatch()
434 for addr, serialized_hist in self.batch_list.items():
435 batch.Put(addr, serialized_hist)
436 l = len(serialized_hist)
441 for txio, addr in self.batch_txio.items():
442 batch.Put(txio, addr)
443 # delete spent inputs
444 for txi in inputs_to_read:
446 batch.Put('0', self.serialize( [(block_hash, block_height, 0)] ) )
449 self.db.Write(batch, sync = sync)
453 print_log("block", block_height,
454 "parse:%0.2f "%(t00 - t0),
455 "read:%0.2f "%(t1 - t00),
456 "proc:%.2f "%(t2-t1),
457 "write:%.2f "%(t3-t2),
458 "max:", max_len, max_addr)
460 for addr in self.batch_list.keys(): self.invalidate_cache(addr)
464 def add_request(self, request):
465 # see if we can get if from cache. if not, add to queue
466 if self.process( request, cache_only = True) == -1:
467 self.queue.put(request)
471 def process(self, request, cache_only = False):
472 #print "abe process", request
474 message_id = request['id']
475 method = request['method']
476 params = request.get('params',[])
480 if method == 'blockchain.numblocks.subscribe':
483 elif method == 'blockchain.headers.subscribe':
486 elif method == 'blockchain.address.subscribe':
489 result = self.get_status(address, cache_only)
490 self.watch_address(address)
491 except BaseException, e:
492 error = str(e) + ': ' + address
493 print_log( "error:", error )
495 elif method == 'blockchain.address.subscribe2':
498 result = self.get_status(address, cache_only)
499 self.watch_address(address)
500 except BaseException, e:
501 error = str(e) + ': ' + address
502 print_log( "error:", error )
504 elif method == 'blockchain.address.get_history2':
507 result = self.get_history( address, cache_only )
508 except BaseException, e:
509 error = str(e) + ': ' + address
510 print_log( "error:", error )
512 elif method == 'blockchain.block.get_header':
518 result = self.get_header( height )
519 except BaseException, e:
520 error = str(e) + ': %d'% height
521 print_log( "error:", error )
523 elif method == 'blockchain.block.get_chunk':
529 result = self.get_chunk( index )
530 except BaseException, e:
531 error = str(e) + ': %d'% index
532 print_log( "error:", error)
534 elif method == 'blockchain.transaction.broadcast':
535 txo = self.bitcoind('sendrawtransaction', params)
536 print_log( "sent tx:", txo )
539 elif method == 'blockchain.transaction.get_merkle':
545 tx_height = params[1]
546 result = self.get_merkle(tx_hash, tx_height)
547 except BaseException, e:
548 error = str(e) + ': ' + tx_hash
549 print_log( "error:", error )
551 elif method == 'blockchain.transaction.get':
555 result = self.bitcoind('getrawtransaction', [tx_hash, 0, height] )
556 except BaseException, e:
557 error = str(e) + ': ' + tx_hash
558 print_log( "error:", error )
561 error = "unknown method:%s"%method
563 if cache_only and result == -1: return -1
566 response = { 'id':message_id, 'error':error }
567 self.push_response(response)
569 response = { 'id':message_id, 'result':result }
570 self.push_response(response)
573 def watch_address(self, addr):
574 if addr not in self.watched_addresses:
575 self.watched_addresses.append(addr)
580 return self.block_hashes[-1]
583 def catch_up(self, sync = True):
586 while not self.shared.stopped():
589 info = self.bitcoind('getinfo')
590 bitcoind_height = info.get('blocks')
591 bitcoind_block_hash = self.bitcoind('getblockhash', [bitcoind_height])
592 if self.last_hash() == bitcoind_block_hash:
593 self.up_to_date = True
597 self.up_to_date = False
598 block_hash = self.bitcoind('getblockhash', [self.height+1])
599 block = self.bitcoind('getblock', [block_hash, 1])
601 if block.get('previousblockhash') == self.last_hash():
603 self.import_block(block, block_hash, self.height+1, sync)
604 self.height = self.height + 1
605 self.write_header(self.block2header(block), sync)
607 self.block_hashes.append(block_hash)
608 self.block_hashes = self.block_hashes[-10:]
610 if (self.height+1)%100 == 0 and not sync:
612 print_log( "catch_up: block %d (%.3fs)"%( self.height, t2 - t1 ) )
617 # revert current block
618 print_log( "bc2: reorg", self.height, block.get('previousblockhash'), self.last_hash() )
619 block_hash = self.last_hash()
620 block = self.bitcoind('getblock', [block_hash, 1])
621 self.height = self.height -1
624 self.block_hashes.remove(block_hash)
625 self.import_block(block, self.last_hash(), self.height, revert=True)
628 self.header = self.block2header(self.bitcoind('getblock', [self.last_hash()]))
633 def memorypool_update(self):
635 mempool_hashes = self.bitcoind('getrawmempool')
637 for tx_hash in mempool_hashes:
638 if tx_hash in self.mempool_hashes: continue
640 tx = self.get_transaction(tx_hash)
643 for x in tx.get('inputs'):
644 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
646 addr = self.db.Get(txi)
649 l = self.mempool_addresses.get(tx_hash, [])
652 self.mempool_addresses[tx_hash] = l
654 for x in tx.get('outputs'):
655 addr = x.get('address')
656 l = self.mempool_addresses.get(tx_hash, [])
659 self.mempool_addresses[tx_hash] = l
661 self.mempool_hashes.append(tx_hash)
663 # remove older entries from mempool_hashes
664 self.mempool_hashes = mempool_hashes
666 # remove deprecated entries from mempool_addresses
667 for tx_hash, addresses in self.mempool_addresses.items():
668 if tx_hash not in self.mempool_hashes:
669 self.mempool_addresses.pop(tx_hash)
672 new_mempool_hist = {}
673 for tx_hash, addresses in self.mempool_addresses.items():
674 for addr in addresses:
675 h = new_mempool_hist.get(addr, [])
678 new_mempool_hist[addr] = h
680 for addr in self.mempool_hist.keys():
681 if self.mempool_hist[addr] != new_mempool_hist[addr]:
682 self.invalidate_cache(addr)
684 with self.mempool_lock:
685 self.mempool_hist = new_mempool_hist
689 def invalidate_cache(self, address):
690 with self.cache_lock:
691 if self.history_cache.has_key(address):
692 print_log( "cache: invalidating", address )
693 self.history_cache.pop(address)
695 self.address_queue.put(address)
699 def main_iteration(self):
701 if self.shared.stopped():
702 print_log( "blockchain processor terminating" )
710 self.memorypool_update()
712 # print "mempool:", len(self.mempool_addresses), len(self.mempool_hist), "%.3fs"%(t3 - t2)
715 if self.sent_height != self.height:
716 self.sent_height = self.height
717 self.push_response({ 'id': None, 'method':'blockchain.numblocks.subscribe', 'params':[self.height] })
719 if self.sent_header != self.header:
720 print_log( "blockchain: %d (%.3fs)"%( self.height, t2 - t1 ) )
721 self.sent_header = self.header
722 self.push_response({ 'id': None, 'method':'blockchain.headers.subscribe', 'params':[self.header] })
726 addr = self.address_queue.get(False)
729 if addr in self.watched_addresses:
730 status = self.get_status( addr )
731 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe', 'params':[addr, status] })
732 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe2', 'params':[addr, status] })
735 if not self.shared.stopped():
736 threading.Timer(10, self.main_iteration).start()
738 print_log( "blockchain processor terminating" )