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)
90 traceback.print_exc(file=sys.stdout)
92 if lock: self.dblock.release()
95 raise BaseException('sql error')
100 def get_tx_outputs(self, tx_id, lock=True):
101 return self.safe_sql("""SELECT
103 txout.txout_scriptPubKey,
110 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
111 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
112 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
113 WHERE txout.tx_id = %d
114 ORDER BY txout.txout_pos
115 """%(tx_id), (), lock)
117 def get_tx_inputs(self, tx_id, lock=True):
118 return self.safe_sql(""" SELECT
122 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
124 COALESCE(txout.txout_pos, u.txout_pos),
127 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
128 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
129 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
130 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
131 WHERE txin.tx_id = %d
132 ORDER BY txin.txin_pos
133 """%(tx_id,), (), lock)
136 def get_address_out_rows(self, dbhash):
137 out = self.safe_sql(""" SELECT
147 FROM chain_candidate cc
148 JOIN block b ON (b.block_id = cc.block_id)
149 JOIN block_tx ON (block_tx.block_id = b.block_id)
150 JOIN tx ON (tx.tx_id = block_tx.tx_id)
151 JOIN txin ON (txin.tx_id = tx.tx_id)
152 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
153 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
154 WHERE pubkey.pubkey_hash = ?
155 AND cc.in_longest = 1
156 LIMIT ? """, (dbhash,self.sql_limit))
158 if len(out)==self.sql_limit:
159 raise BaseException('limit reached')
162 def get_address_out_rows_memorypool(self, dbhash):
163 out = self.safe_sql(""" SELECT
170 JOIN txin ON (txin.tx_id = tx.tx_id)
171 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
172 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
173 WHERE pubkey.pubkey_hash = ?
174 LIMIT ? """, (dbhash,self.sql_limit))
176 if len(out)==self.sql_limit:
177 raise BaseException('limit reached')
180 def get_address_in_rows(self, dbhash):
181 out = self.safe_sql(""" SELECT
191 FROM chain_candidate cc
192 JOIN block b ON (b.block_id = cc.block_id)
193 JOIN block_tx ON (block_tx.block_id = b.block_id)
194 JOIN tx ON (tx.tx_id = block_tx.tx_id)
195 JOIN txout ON (txout.tx_id = tx.tx_id)
196 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
197 WHERE pubkey.pubkey_hash = ?
198 AND cc.in_longest = 1
199 LIMIT ? """, (dbhash,self.sql_limit))
201 if len(out)==self.sql_limit:
202 raise BaseException('limit reached')
205 def get_address_in_rows_memorypool(self, dbhash):
206 out = self.safe_sql( """ SELECT
213 JOIN txout ON (txout.tx_id = tx.tx_id)
214 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
215 WHERE pubkey.pubkey_hash = ?
216 LIMIT ? """, (dbhash,self.sql_limit))
218 if len(out)==self.sql_limit:
219 raise BaseException('limit reached')
222 def get_history(self, addr):
224 cached_version = self.tx_cache.get( addr )
225 if cached_version is not None:
226 return cached_version
228 version, binaddr = decode_check_address(addr)
232 dbhash = self.binin(binaddr)
234 rows += self.get_address_out_rows( dbhash )
235 rows += self.get_address_in_rows( dbhash )
242 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
244 print "cannot unpack row", row
246 tx_hash = self.hashout_hex(tx_hash)
248 "timestamp": int(nTime),
249 "height": int(height),
250 "is_input": int(is_in),
251 "block_hash": self.hashout_hex(blk_hash),
258 txpoints.append(txpoint)
259 known_tx.append(self.hashout_hex(tx_hash))
262 # todo: sort them really...
263 txpoints = sorted(txpoints, key=operator.itemgetter("timestamp"))
267 rows += self.get_address_in_rows_memorypool( dbhash )
268 rows += self.get_address_out_rows_memorypool( dbhash )
269 address_has_mempool = False
271 current_id = self.safe_sql("""SELECT last_value FROM tx_seq""")
272 current_id = current_id[0][0]
275 is_in, tx_hash, tx_id, pos, value = row
276 tx_hash = self.hashout_hex(tx_hash)
277 if tx_hash in known_tx:
280 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
281 address_has_mempool = True
283 # fixme: we need to detect transactions that became invalid
284 if current_id - tx_id > 10000:
288 #print "mempool", tx_hash
292 "is_input": int(is_in),
293 "block_hash": 'mempool',
299 txpoints.append(txpoint)
302 for txpoint in txpoints:
303 tx_id = txpoint['tx_id']
306 inrows = self.get_tx_inputs(tx_id)
308 _hash = self.binout(row[6])
310 #print "WARNING: missing tx_in for tx", tx_id, addr
312 address = hash_to_address(chr(0), _hash)
313 txinputs.append(address)
314 txpoint['inputs'] = txinputs
316 outrows = self.get_tx_outputs(tx_id)
318 _hash = self.binout(row[6])
320 #print "WARNING: missing tx_out for tx", tx_id, addr
322 address = hash_to_address(chr(0), _hash)
323 txoutputs.append(address)
324 txpoint['outputs'] = txoutputs
326 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
327 if not txpoint['is_input']:
328 # detect if already redeemed...
330 if row[6] == dbhash: break
333 #row = self.get_tx_output(tx_id,dbhash)
334 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
335 # if not redeemed, we add the script
337 if not row[4]: txpoint['raw_output_script'] = row[1]
340 # do not cache mempool results because statuses are ambiguous
341 if not address_has_mempool:
342 self.tx_cache[addr] = txpoints
347 def get_status(self,addr):
348 # get address status, i.e. the last block for that address.
349 tx_points = self.get_history(addr)
353 lastpoint = tx_points[-1]
354 status = lastpoint['block_hash']
355 # this is a temporary hack; move it up once old clients have disappeared
356 if status == 'mempool': # and session['version'] != "old":
357 status = status + ':%d'% len(tx_points)
362 def memorypool_update(store):
364 ds = BCDataStream.BCDataStream()
365 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
367 respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
369 if r['error'] != None:
372 v = r['result'].get('transactions')
375 ds.write(hextx.decode('hex'))
376 tx = deserialize.parse_Transaction(ds)
377 tx['hash'] = util.double_sha256(tx['tx'])
378 tx_hash = store.hashin(tx['hash'])
380 if store.tx_find_id_and_value(tx):
383 tx_id = store.import_tx(tx, False)
384 store.update_tx_cache(tx_id)
390 def send_tx(self,tx):
391 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
392 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
394 if r['error'] != None:
395 msg = r['error'].get('message')
396 out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
402 def main_iteration(store):
405 store.memorypool_update()
406 block_number = store.get_block_number(1)
413 # if there is an exception, do rollback and then re-raise the exception
414 for dircfg in store.datadirs:
416 store.catch_up_dir(dircfg)
418 store.log.exception("Failed to catch up %s", dircfg)
425 from processor import Processor
427 class BlockchainProcessor(Processor):
429 def __init__(self, config):
430 Processor.__init__(self)
431 self.store = AbeStore(config)
432 self.block_number = -1
433 self.watched_addresses = []
434 threading.Timer(10, self.run_store_iteration).start()
436 def process(self, request):
437 #print "abe process", request
439 message_id = request['id']
440 method = request['method']
441 params = request.get('params',[])
445 if method == 'blockchain.numblocks.subscribe':
446 result = self.block_number
448 elif method == 'blockchain.address.subscribe':
451 result = self.store.get_status(address)
452 self.watch_address(address)
453 except BaseException, e:
454 error = str(e) + ': ' + address
455 print "error:", error
457 elif method == 'blockchain.address.get_history':
460 result = self.store.get_history( address )
461 except BaseException, e:
462 error = str(e) + ': ' + address
463 print "error:", error
465 elif method == 'blockchain.transaction.broadcast':
466 txo = self.store.send_tx(params[0])
467 print "sent tx:", txo
471 error = "unknown method:%s"%method
475 response = { 'id':message_id, 'error':error }
476 self.push_response(response)
478 response = { 'id':message_id, 'result':result }
479 self.push_response(response)
482 def watch_address(self, addr):
483 if addr not in self.watched_addresses:
484 self.watched_addresses.append(addr)
487 def run_store_iteration(self):
490 block_number = self.store.main_iteration()
492 traceback.print_exc(file=sys.stdout)
496 if self.shared.stopped():
500 if self.block_number != block_number:
501 self.block_number = block_number
502 print "block number:", self.block_number
503 self.push_response({ 'method':'blockchain.numblocks.subscribe', 'params':[self.block_number] })
507 addr = self.store.address_queue.get(False)
510 if addr in self.watched_addresses:
511 status = self.store.get_status( addr )
512 self.push_response({ 'method':'blockchain.address.subscribe', 'params':[addr, status] })
514 threading.Timer(10, self.run_store_iteration).start()