1 from Abe.util import hash_to_address, decode_check_address
2 from Abe.DataStore import DataStore as Datastore_class
3 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
7 import thread, traceback, sys, urllib, operator
8 from json import dumps, loads
9 from Queue import Queue
10 import time, threading
14 encode = lambda x: x[::-1].encode('hex')
15 decode = lambda x: x.decode('hex')[::-1]
16 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
19 return s.decode('hex')[::-1].encode('hex')
21 def int_to_hex(i, length=1):
22 s = hex(i)[2:].rstrip('L')
23 s = "0"*(2*length - len(s)) + s
26 def header_to_string(res):
27 s = int_to_hex(res.get('version'),4) \
28 + rev_hex(res.get('prev_block_hash')) \
29 + rev_hex(res.get('merkle_root')) \
30 + int_to_hex(int(res.get('timestamp')),4) \
31 + int_to_hex(int(res.get('bits')),4) \
32 + int_to_hex(int(res.get('nonce')),4)
36 class AbeStore(Datastore_class):
38 def __init__(self, config):
39 conf = DataStore.CONFIG_DEFAULTS
40 args, argv = readconf.parse_argv( [], conf)
41 args.dbtype = config.get('database','type')
42 if args.dbtype == 'sqlite3':
43 args.connect_args = { 'database' : config.get('database','database') }
44 elif args.dbtype == 'MySQLdb':
45 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
46 elif args.dbtype == 'psycopg2':
47 args.connect_args = { 'database' : config.get('database','database') }
49 coin = config.get('server', 'coin')
51 if coin == 'litecoin':
52 print 'Litecoin settings:'
53 datadir = config.get('server','datadir')
54 print ' datadir = ' + datadir
55 args.datadir = [{"dirname":datadir,"chain":"Litecoin","code3":"LTC","address_version":"\u0030"}]
56 print ' addrtype = 48'
59 Datastore_class.__init__(self,args)
61 # Use 1 (Bitcoin) if chain_id is not sent
62 self.chain_id = self.datadirs[0]["chain_id"] or 1
63 print 'Coin chain_id = %d' % self.chain_id
65 self.sql_limit = int( config.get('database','limit') )
68 self.bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
72 self.address_queue = Queue()
74 self.lock = threading.Lock() # for the database
75 self.cache_lock = threading.Lock() # for the cache
77 self.known_mempool_hashes = []
81 def import_tx(self, tx, is_coinbase):
82 tx_id = super(AbeStore, self).import_tx(tx, is_coinbase)
83 self.last_tx_id = tx_id
89 def import_block(self, b, chain_ids=frozenset()):
91 block_id = super(AbeStore, self).import_block(b, chain_ids)
92 for pos in xrange(len(b['transactions'])):
93 tx = b['transactions'][pos]
95 tx['hash'] = util.double_sha256(tx['tx'])
96 tx_id = self.tx_find_id_and_value(tx)
98 self.update_tx_cache(tx_id)
100 print "error: import_block: no tx_id"
104 def update_tx_cache(self, txid):
105 inrows = self.get_tx_inputs(txid, False)
107 _hash = self.binout(row[6])
109 #print "WARNING: missing tx_in for tx", txid
112 address = hash_to_address(chr(self.addrtype), _hash)
113 with self.cache_lock:
114 if self.tx_cache.has_key(address):
115 print "cache: invalidating", address
116 self.tx_cache.pop(address)
118 self.address_queue.put(address)
120 outrows = self.get_tx_outputs(txid, False)
122 _hash = self.binout(row[6])
124 #print "WARNING: missing tx_out for tx", txid
127 address = hash_to_address(chr(self.addrtype), _hash)
128 with self.cache_lock:
129 if self.tx_cache.has_key(address):
130 print "cache: invalidating", address
131 self.tx_cache.pop(address)
133 self.address_queue.put(address)
135 def safe_sql(self,sql, params=(), lock=True):
139 if lock: self.lock.acquire()
140 ret = self.selectall(sql,params)
143 traceback.print_exc(file=sys.stdout)
145 if lock: self.lock.release()
148 raise BaseException('sql error')
153 def get_tx_outputs(self, tx_id, lock=True):
154 return self.safe_sql("""SELECT
156 txout.txout_scriptPubKey,
163 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
164 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
165 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
166 WHERE txout.tx_id = %d
167 ORDER BY txout.txout_pos
168 """%(tx_id), (), lock)
170 def get_tx_inputs(self, tx_id, lock=True):
171 return self.safe_sql(""" SELECT
175 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
177 COALESCE(txout.txout_pos, u.txout_pos),
180 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
181 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
182 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
183 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
184 WHERE txin.tx_id = %d
185 ORDER BY txin.txin_pos
186 """%(tx_id,), (), lock)
189 def get_address_out_rows(self, dbhash):
190 out = self.safe_sql(""" SELECT
200 FROM chain_candidate cc
201 JOIN block b ON (b.block_id = cc.block_id)
202 JOIN block_tx ON (block_tx.block_id = b.block_id)
203 JOIN tx ON (tx.tx_id = block_tx.tx_id)
204 JOIN txin ON (txin.tx_id = tx.tx_id)
205 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
206 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
207 WHERE pubkey.pubkey_hash = ?
209 AND cc.in_longest = 1
210 LIMIT ? """, (dbhash, self.chain_id, self.sql_limit))
212 if len(out)==self.sql_limit:
213 raise BaseException('limit reached')
216 def get_address_out_rows_memorypool(self, dbhash):
217 out = self.safe_sql(""" SELECT
224 JOIN txin ON (txin.tx_id = tx.tx_id)
225 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
226 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
227 WHERE pubkey.pubkey_hash = ?
228 LIMIT ? """, (dbhash,self.sql_limit))
230 if len(out)==self.sql_limit:
231 raise BaseException('limit reached')
234 def get_address_in_rows(self, dbhash):
235 out = self.safe_sql(""" SELECT
245 FROM chain_candidate cc
246 JOIN block b ON (b.block_id = cc.block_id)
247 JOIN block_tx ON (block_tx.block_id = b.block_id)
248 JOIN tx ON (tx.tx_id = block_tx.tx_id)
249 JOIN txout ON (txout.tx_id = tx.tx_id)
250 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
251 WHERE pubkey.pubkey_hash = ?
253 AND cc.in_longest = 1
254 LIMIT ? """, (dbhash, self.chain_id, self.sql_limit))
256 if len(out)==self.sql_limit:
257 raise BaseException('limit reached')
260 def get_address_in_rows_memorypool(self, dbhash):
261 out = self.safe_sql( """ SELECT
268 JOIN txout ON (txout.tx_id = tx.tx_id)
269 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
270 WHERE pubkey.pubkey_hash = ?
271 LIMIT ? """, (dbhash,self.sql_limit))
273 if len(out)==self.sql_limit:
274 raise BaseException('limit reached')
279 def get_history(self, addr, cache_only=False):
280 with self.cache_lock:
281 cached_version = self.tx_cache.get( addr )
282 if cached_version is not None:
283 return cached_version
285 if cache_only: return -1
287 version, binaddr = decode_check_address(addr)
291 dbhash = self.binin(binaddr)
293 rows += self.get_address_out_rows( dbhash )
294 rows += self.get_address_in_rows( dbhash )
301 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
303 print "cannot unpack row", row
305 tx_hash = self.hashout_hex(tx_hash)
307 "timestamp": int(nTime),
308 "height": int(height),
309 "is_input": int(is_in),
310 "block_hash": self.hashout_hex(blk_hash),
317 txpoints.append(txpoint)
318 known_tx.append(self.hashout_hex(tx_hash))
321 # todo: sort them really...
322 txpoints = sorted(txpoints, key=operator.itemgetter("timestamp"))
326 rows += self.get_address_in_rows_memorypool( dbhash )
327 rows += self.get_address_out_rows_memorypool( dbhash )
328 address_has_mempool = False
331 is_in, tx_hash, tx_id, pos, value = row
332 tx_hash = self.hashout_hex(tx_hash)
333 if tx_hash in known_tx:
336 # discard transactions that are too old
337 if self.last_tx_id - tx_id > 50000:
338 print "discarding tx id", tx_id
341 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
342 address_has_mempool = True
344 #print "mempool", tx_hash
348 "is_input": int(is_in),
349 "block_hash": 'mempool',
355 txpoints.append(txpoint)
358 for txpoint in txpoints:
359 tx_id = txpoint['tx_id']
362 inrows = self.get_tx_inputs(tx_id)
364 _hash = self.binout(row[6])
366 #print "WARNING: missing tx_in for tx", tx_id, addr
368 address = hash_to_address(chr(self.addrtype), _hash)
369 txinputs.append(address)
370 txpoint['inputs'] = txinputs
372 outrows = self.get_tx_outputs(tx_id)
374 _hash = self.binout(row[6])
376 #print "WARNING: missing tx_out for tx", tx_id, addr
378 address = hash_to_address(chr(self.addrtype), _hash)
379 txoutputs.append(address)
380 txpoint['outputs'] = txoutputs
382 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
383 if not txpoint['is_input']:
384 # detect if already redeemed...
386 if row[6] == dbhash: break
389 #row = self.get_tx_output(tx_id,dbhash)
390 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
391 # if not redeemed, we add the script
393 if not row[4]: txpoint['raw_output_script'] = row[1]
398 txpoints = map(lambda x: {'tx_hash':x['tx_hash'], 'height':x['height']}, txpoints)
400 for item in txpoints:
401 if item not in out: out.append(item)
404 ## do not cache mempool results because statuses are ambiguous
405 #if not address_has_mempool:
406 with self.cache_lock:
407 self.tx_cache[addr] = out
412 def get_status(self, addr, cache_only=False):
414 tx_points = self.get_history(addr, cache_only)
415 if cache_only and tx_points == -1: return -1
417 if not tx_points: return None
420 status += tx.get('tx_hash') + ':%d:' % tx.get('height')
421 return hashlib.sha256( status ).digest().encode('hex')
424 def get_block_header(self, block_height):
425 out = self.safe_sql("""
429 block_hashMerkleRoot,
437 WHERE block_height = %d AND in_longest = 1"""%block_height)
439 if not out: raise BaseException("block not found")
441 (block_hash, block_version, hashMerkleRoot, nTime, nBits, nNonce, height,prev_block_hash, block_id) \
442 = ( self.hashout_hex(row[0]), int(row[1]), self.hashout_hex(row[2]), int(row[3]), int(row[4]), int(row[5]), int(row[6]), self.hashout_hex(row[7]), int(row[8]) )
444 out = {"block_height":block_height, "version":block_version, "prev_block_hash":prev_block_hash,
445 "merkle_root":hashMerkleRoot, "timestamp":nTime, "bits":nBits, "nonce":nNonce}
449 def get_chunk(self, index):
450 with self.cache_lock:
451 msg = self.chunk_cache.get(index)
458 block_hashMerkleRoot,
466 WHERE block_height >= %d AND block_height< %d AND in_longest = 1 ORDER BY block_height"""%(index*2016, (index+1)*2016)
468 out = self.safe_sql(sql)
471 (block_hash, block_version, hashMerkleRoot, nTime, nBits, nNonce, height, prev_block_hash, block_height) \
472 = ( self.hashout_hex(row[0]), int(row[1]), self.hashout_hex(row[2]), int(row[3]), int(row[4]), int(row[5]), int(row[6]), self.hashout_hex(row[7]), int(row[8]) )
473 h = {"block_height":block_height, "version":block_version, "prev_block_hash":prev_block_hash,
474 "merkle_root":hashMerkleRoot, "timestamp":nTime, "bits":nBits, "nonce":nNonce}
476 if h.get('block_height')==0: h['prev_block_hash'] = "0"*64
477 msg += header_to_string(h)
479 #print "hash", encode(Hash(msg.decode('hex')))
480 #if h.get('block_height')==1:break
482 with self.cache_lock:
483 self.chunk_cache[index] = msg
484 print "get_chunk", index, len(msg)
489 def get_raw_tx(self, tx_hash, height):
490 postdata = dumps({"method": 'getrawtransaction', 'params': [tx_hash, 0, height], 'id':'jsonrpc'})
491 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
493 if r['error'] != None:
494 raise BaseException(r['error'])
496 hextx = r.get('result')
500 def get_tx_merkle(self, tx_hash):
502 out = self.safe_sql("""
503 SELECT block_tx.block_id FROM tx
504 JOIN block_tx on tx.tx_id = block_tx.tx_id
505 JOIN chain_summary on chain_summary.block_id = block_tx.block_id
506 WHERE tx_hash='%s' AND in_longest = 1"""%tx_hash)
508 if not out: raise BaseException("not in a block")
509 block_id = int(out[0][0])
512 out = self.safe_sql("SELECT block_height FROM chain_summary WHERE block_id = %d AND in_longest = 1"%block_id)
514 if not out: raise BaseException("block not found")
515 block_height = int(out[0][0])
520 # list all tx in block
521 for row in self.safe_sql("""
522 SELECT DISTINCT tx_id, tx_pos, tx_hash
525 ORDER BY tx_pos""", (block_id,)):
526 _id, _pos, _hash = row
528 if _hash == tx_hash: tx_pos = int(_pos)
531 # TODO: do not compute this on client request, better store the hash tree of each block in a database...
533 merkle = map(decode, merkle)
534 target_hash = decode(tx_hash)
537 while len(merkle) != 1:
538 if len(merkle)%2: merkle.append( merkle[-1] )
541 new_hash = Hash( merkle[0] + merkle[1] )
542 if merkle[0] == target_hash:
543 s.append( encode(merkle[1]))
544 target_hash = new_hash
545 elif merkle[1] == target_hash:
546 s.append( encode(merkle[0]))
547 target_hash = new_hash
553 return {"block_height":block_height, "merkle":s, "pos":tx_pos}
558 def memorypool_update(store):
560 ds = BCDataStream.BCDataStream()
561 postdata = dumps({"method": 'getrawmempool', 'params': [], 'id':'jsonrpc'})
562 respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
565 if r['error'] != None:
569 mempool_hashes = r.get('result')
572 for tx_hash in mempool_hashes:
574 if tx_hash in store.known_mempool_hashes: continue
575 store.known_mempool_hashes.append(tx_hash)
578 postdata = dumps({"method": 'getrawtransaction', 'params': [tx_hash], 'id':'jsonrpc'})
579 respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
581 if r['error'] != None:
583 hextx = r.get('result')
585 ds.write(hextx.decode('hex'))
586 tx = deserialize.parse_Transaction(ds)
587 tx['hash'] = util.double_sha256(tx['tx'])
589 if store.tx_find_id_and_value(tx):
592 tx_id = store.import_tx(tx, False)
593 store.update_tx_cache(tx_id)
597 store.known_mempool_hashes = mempool_hashes
601 def send_tx(self,tx):
602 postdata = dumps({"method": 'sendrawtransaction', 'params': [tx], 'id':'jsonrpc'})
603 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
605 if r['error'] != None:
606 msg = r['error'].get('message')
607 out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
613 def main_iteration(self):
618 time_catch_up = t2 - t1
619 n = self.memorypool_update()
620 time_mempool = time.time() - t2
621 height = self.get_block_number( self.chain_id )
623 with self.cache_lock:
625 self.chunk_cache.pop(height/2016)
629 block_header = self.get_block_header( height )
630 return block_header, time_catch_up, time_mempool, n
636 # if there is an exception, do rollback and then re-raise the exception
637 for dircfg in store.datadirs:
639 store.catch_up_dir(dircfg)
641 store.log.exception("Failed to catch up %s", dircfg)
648 from processor import Processor
650 class BlockchainProcessor(Processor):
652 def __init__(self, config, shared):
653 Processor.__init__(self)
654 self.store = AbeStore(config)
655 self.watched_addresses = []
659 self.block_header, time_catch_up, time_mempool, n = self.store.main_iteration()
660 self.block_number = self.block_header.get('block_height')
661 print "blockchain: %d blocks"%self.block_number
663 threading.Timer(10, self.run_store_iteration).start()
666 def add_request(self, request):
667 # see if we can get if from cache. if not, add to queue
668 if self.process( request, cache_only = True) == -1:
669 self.queue.put(request)
672 def process(self, request, cache_only = False):
673 #print "abe process", request
675 message_id = request['id']
676 method = request['method']
677 params = request.get('params',[])
681 if method == 'blockchain.numblocks.subscribe':
682 result = self.block_number
684 elif method == 'blockchain.headers.subscribe':
685 result = self.block_header
687 elif method == 'blockchain.address.subscribe':
690 result = self.store.get_status(address, cache_only)
691 self.watch_address(address)
692 except BaseException, e:
693 error = str(e) + ': ' + address
694 print "error:", error
696 elif method == 'blockchain.address.get_history':
699 result = self.store.get_history( address, cache_only )
700 except BaseException, e:
701 error = str(e) + ': ' + address
702 print "error:", error
704 elif method == 'blockchain.block.get_header':
710 result = self.store.get_block_header( height )
711 except BaseException, e:
712 error = str(e) + ': %d'% height
713 print "error:", error
715 elif method == 'blockchain.block.get_chunk':
721 result = self.store.get_chunk( index )
722 except BaseException, e:
723 error = str(e) + ': %d'% index
724 print "error:", error
726 elif method == 'blockchain.transaction.broadcast':
727 txo = self.store.send_tx(params[0])
728 print "sent tx:", txo
731 elif method == 'blockchain.transaction.get_merkle':
737 result = self.store.get_tx_merkle(tx_hash )
738 except BaseException, e:
739 error = str(e) + ': ' + tx_hash
740 print "error:", error
742 elif method == 'blockchain.transaction.get':
746 result = self.store.get_raw_tx(tx_hash, height )
747 except BaseException, e:
748 error = str(e) + ': ' + tx_hash
749 print "error:", error
752 error = "unknown method:%s"%method
754 if cache_only and result == -1: return -1
757 response = { 'id':message_id, 'error':error }
758 self.push_response(response)
760 response = { 'id':message_id, 'result':result }
761 self.push_response(response)
764 def watch_address(self, addr):
765 if addr not in self.watched_addresses:
766 self.watched_addresses.append(addr)
769 def run_store_iteration(self):
772 block_header, time_catch_up, time_mempool, n = self.store.main_iteration()
774 traceback.print_exc(file=sys.stdout)
778 if self.shared.stopped():
782 #print "block number: %d (%.3fs) mempool:%d (%.3fs)"%(self.block_number, time_catch_up, n, time_mempool)
784 if self.block_number != block_header.get('block_height'):
785 self.block_number = block_header.get('block_height')
786 print "block number: %d (%.3fs)"%(self.block_number, time_catch_up)
787 self.push_response({ 'id': None, 'method':'blockchain.numblocks.subscribe', 'params':[self.block_number] })
789 if self.block_header != block_header:
790 self.block_header = block_header
791 self.push_response({ 'id': None, 'method':'blockchain.headers.subscribe', 'params':[self.block_header] })
796 addr = self.store.address_queue.get(False)
799 if addr in self.watched_addresses:
800 status = self.store.get_status( addr )
801 self.push_response({ 'id': None, 'method':'blockchain.address.subscribe', 'params':[addr, status] })
803 threading.Timer(10, self.run_store_iteration).start()