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 class AbeStore(Datastore_class):
16 def __init__(self, config):
17 conf = DataStore.CONFIG_DEFAULTS
18 args, argv = readconf.parse_argv( [], conf)
19 args.dbtype = config.get('database','type')
20 if args.dbtype == 'sqlite3':
21 args.connect_args = { 'database' : config.get('database','database') }
22 elif args.dbtype == 'MySQLdb':
23 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
24 elif args.dbtype == 'psycopg2':
25 args.connect_args = { 'database' : config.get('database','database') }
27 Datastore_class.__init__(self,args)
29 self.sql_limit = int( config.get('database','limit') )
32 self.bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
34 self.address_queue = Queue()
36 self.dblock = thread.allocate_lock()
40 def import_block(self, b, chain_ids=frozenset()):
42 block_id = super(AbeStore, self).import_block(b, chain_ids)
43 for pos in xrange(len(b['transactions'])):
44 tx = b['transactions'][pos]
46 tx['hash'] = util.double_sha256(tx['tx'])
47 tx_id = self.tx_find_id_and_value(tx)
49 self.update_tx_cache(tx_id)
51 print "error: import_block: no tx_id"
55 def update_tx_cache(self, txid):
56 inrows = self.get_tx_inputs(txid, False)
58 _hash = self.binout(row[6])
60 #print "WARNING: missing tx_in for tx", txid
63 address = hash_to_address(chr(0), _hash)
64 if self.tx_cache.has_key(address):
65 print "cache: invalidating", address
66 self.tx_cache.pop(address)
67 self.address_queue.put(address)
69 outrows = self.get_tx_outputs(txid, False)
71 _hash = self.binout(row[6])
73 #print "WARNING: missing tx_out for tx", txid
76 address = hash_to_address(chr(0), _hash)
77 if self.tx_cache.has_key(address):
78 print "cache: invalidating", address
79 self.tx_cache.pop(address)
80 self.address_queue.put(address)
82 def safe_sql(self,sql, params=(), lock=True):
86 if lock: self.dblock.acquire()
87 ret = self.selectall(sql,params)
91 if lock: self.dblock.release()
94 raise BaseException('sql error')
99 def get_tx_outputs(self, tx_id, lock=True):
100 return self.safe_sql("""SELECT
102 txout.txout_scriptPubKey,
109 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
110 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
111 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
112 WHERE txout.tx_id = %d
113 ORDER BY txout.txout_pos
114 """%(tx_id), (), lock)
116 def get_tx_inputs(self, tx_id, lock=True):
117 return self.safe_sql(""" SELECT
121 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
123 COALESCE(txout.txout_pos, u.txout_pos),
126 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
127 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
128 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
129 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
130 WHERE txin.tx_id = %d
131 ORDER BY txin.txin_pos
132 """%(tx_id,), (), lock)
135 def get_address_out_rows(self, dbhash):
136 out = self.safe_sql(""" SELECT
146 FROM chain_candidate cc
147 JOIN block b ON (b.block_id = cc.block_id)
148 JOIN block_tx ON (block_tx.block_id = b.block_id)
149 JOIN tx ON (tx.tx_id = block_tx.tx_id)
150 JOIN txin ON (txin.tx_id = tx.tx_id)
151 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
152 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
153 WHERE pubkey.pubkey_hash = ?
154 AND cc.in_longest = 1
155 LIMIT ? """, (dbhash,self.sql_limit))
157 if len(out)==self.sql_limit:
158 raise BaseException('limit reached')
161 def get_address_out_rows_memorypool(self, dbhash):
162 out = self.safe_sql(""" SELECT
169 JOIN txin ON (txin.tx_id = tx.tx_id)
170 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
171 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
172 WHERE pubkey.pubkey_hash = ?
173 LIMIT ? """, (dbhash,self.sql_limit))
175 if len(out)==self.sql_limit:
176 raise BaseException('limit reached')
179 def get_address_in_rows(self, dbhash):
180 out = self.safe_sql(""" SELECT
190 FROM chain_candidate cc
191 JOIN block b ON (b.block_id = cc.block_id)
192 JOIN block_tx ON (block_tx.block_id = b.block_id)
193 JOIN tx ON (tx.tx_id = block_tx.tx_id)
194 JOIN txout ON (txout.tx_id = tx.tx_id)
195 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
196 WHERE pubkey.pubkey_hash = ?
197 AND cc.in_longest = 1
198 LIMIT ? """, (dbhash,self.sql_limit))
200 if len(out)==self.sql_limit:
201 raise BaseException('limit reached')
204 def get_address_in_rows_memorypool(self, dbhash):
205 out = self.safe_sql( """ SELECT
212 JOIN txout ON (txout.tx_id = tx.tx_id)
213 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
214 WHERE pubkey.pubkey_hash = ?
215 LIMIT ? """, (dbhash,self.sql_limit))
217 if len(out)==self.sql_limit:
218 raise BaseException('limit reached')
221 def get_history(self, addr):
223 cached_version = self.tx_cache.get( addr )
224 if cached_version is not None:
225 return cached_version
227 version, binaddr = decode_check_address(addr)
231 dbhash = self.binin(binaddr)
233 rows += self.get_address_out_rows( dbhash )
234 rows += self.get_address_in_rows( dbhash )
241 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
243 print "cannot unpack row", row
245 tx_hash = self.hashout_hex(tx_hash)
247 "timestamp": int(nTime),
248 "height": int(height),
249 "is_input": int(is_in),
250 "block_hash": self.hashout_hex(blk_hash),
257 txpoints.append(txpoint)
258 known_tx.append(self.hashout_hex(tx_hash))
261 # todo: sort them really...
262 txpoints = sorted(txpoints, key=operator.itemgetter("timestamp"))
266 rows += self.get_address_in_rows_memorypool( dbhash )
267 rows += self.get_address_out_rows_memorypool( dbhash )
268 address_has_mempool = False
270 current_id = self.new_id("tx")
273 is_in, tx_hash, tx_id, pos, value = row
274 tx_hash = self.hashout_hex(tx_hash)
275 if tx_hash in known_tx:
278 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
279 address_has_mempool = True
281 # fixme: we need to detect transactions that became invalid
282 if current_id - tx_id > 10000:
286 #print "mempool", tx_hash
290 "is_input": int(is_in),
291 "block_hash": 'mempool',
297 txpoints.append(txpoint)
300 for txpoint in txpoints:
301 tx_id = txpoint['tx_id']
304 inrows = self.get_tx_inputs(tx_id)
306 _hash = self.binout(row[6])
308 #print "WARNING: missing tx_in for tx", tx_id, addr
310 address = hash_to_address(chr(0), _hash)
311 txinputs.append(address)
312 txpoint['inputs'] = txinputs
314 outrows = self.get_tx_outputs(tx_id)
316 _hash = self.binout(row[6])
318 #print "WARNING: missing tx_out for tx", tx_id, addr
320 address = hash_to_address(chr(0), _hash)
321 txoutputs.append(address)
322 txpoint['outputs'] = txoutputs
324 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
325 if not txpoint['is_input']:
326 # detect if already redeemed...
328 if row[6] == dbhash: break
331 #row = self.get_tx_output(tx_id,dbhash)
332 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
333 # if not redeemed, we add the script
335 if not row[4]: txpoint['raw_output_script'] = row[1]
338 # do not cache mempool results because statuses are ambiguous
339 if not address_has_mempool:
340 self.tx_cache[addr] = txpoints
345 def get_status(self,addr):
346 # get address status, i.e. the last block for that address.
347 tx_points = self.get_history(addr)
351 lastpoint = tx_points[-1]
352 status = lastpoint['block_hash']
353 # this is a temporary hack; move it up once old clients have disappeared
354 if status == 'mempool': # and session['version'] != "old":
355 status = status + ':%d'% len(tx_points)
360 def memorypool_update(store):
362 ds = BCDataStream.BCDataStream()
363 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
365 respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
367 if r['error'] != None:
370 v = r['result'].get('transactions')
373 ds.write(hextx.decode('hex'))
374 tx = deserialize.parse_Transaction(ds)
375 tx['hash'] = util.double_sha256(tx['tx'])
376 tx_hash = store.hashin(tx['hash'])
378 if store.tx_find_id_and_value(tx):
381 tx_id = store.import_tx(tx, False)
382 store.update_tx_cache(tx_id)
387 def send_tx(self,tx):
388 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
389 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
391 if r['error'] != None:
392 msg = r['error'].get('message')
393 out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
399 def main_iteration(store):
401 store.dblock.acquire()
403 store.memorypool_update()
404 block_number = store.get_block_number(1)
407 print "IOError: cannot reach bitcoind"
410 traceback.print_exc(file=sys.stdout)
413 store.dblock.release()
419 # if there is an exception, do rollback and then re-raise the exception
420 for dircfg in store.datadirs:
422 store.catch_up_dir(dircfg)
424 store.log.exception("Failed to catch up %s", dircfg)
431 from processor import Processor
433 class BlockchainProcessor(Processor):
435 def __init__(self, config):
436 Processor.__init__(self)
437 self.store = AbeStore(config)
438 self.block_number = -1
439 self.watched_addresses = []
440 threading.Timer(10, self.run_store_iteration).start()
442 def process(self, request):
443 #print "abe process", request
445 message_id = request['id']
446 method = request['method']
447 params = request.get('params',[])
451 if method == 'blockchain.numblocks.subscribe':
452 result = self.block_number
454 elif method == 'blockchain.address.subscribe':
457 result = self.store.get_status(address)
458 self.watch_address(address)
459 except BaseException, e:
460 error = str(e) + ': ' + address
461 print "error:", error
463 elif method == 'blockchain.address.get_history':
466 result = self.store.get_history( address )
467 except BaseException, e:
468 error = str(e) + ': ' + address
469 print "error:", error
471 elif method == 'blockchain.transaction.broadcast':
472 txo = self.store.send_tx(params[0])
473 print "sent tx:", txo
477 error = "unknown method:%s"%method
481 response = { 'id':message_id, 'error':error }
482 self.push_response(response)
484 response = { 'id':message_id, 'result':result }
485 self.push_response(response)
488 def watch_address(self, addr):
489 if addr not in self.watched_addresses:
490 self.watched_addresses.append(addr)
493 def run_store_iteration(self):
494 if self.shared.stopped():
498 block_number = self.store.main_iteration()
499 if self.block_number != block_number:
500 self.block_number = block_number
501 print "block number:", self.block_number
502 self.push_response({ 'method':'blockchain.numblocks.subscribe', 'params':[self.block_number] })
506 addr = self.store.address_queue.get(False)
509 if addr in self.watched_addresses:
510 status = self.store.get_status( addr )
511 self.push_response({ 'method':'blockchain.address.subscribe', 'params':[addr, status] })
513 threading.Timer(10, self.run_store_iteration).start()