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
12 class AbeStore(Datastore_class):
14 def __init__(self, config):
15 conf = DataStore.CONFIG_DEFAULTS
16 args, argv = readconf.parse_argv( [], conf)
17 args.dbtype = config.get('database','type')
18 if args.dbtype == 'sqlite3':
19 args.connect_args = { 'database' : config.get('database','database') }
20 elif args.dbtype == 'MySQLdb':
21 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
22 elif args.dbtype == 'psycopg2':
23 args.connect_args = { 'database' : config.get('database','database') }
25 Datastore_class.__init__(self,args)
28 self.bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
30 self.address_queue = Queue()
32 self.dblock = thread.allocate_lock()
36 def import_block(self, b, chain_ids=frozenset()):
38 block_id = super(AbeStore, self).import_block(b, chain_ids)
39 for pos in xrange(len(b['transactions'])):
40 tx = b['transactions'][pos]
42 tx['hash'] = util.double_sha256(tx['tx'])
43 tx_id = self.tx_find_id_and_value(tx)
45 self.update_tx_cache(tx_id)
47 print "error: import_block: no tx_id"
51 def update_tx_cache(self, txid):
52 inrows = self.get_tx_inputs(txid, False)
54 _hash = self.binout(row[6])
56 print "WARNING: missing tx_in for tx", txid
59 address = hash_to_address(chr(0), _hash)
60 if self.tx_cache.has_key(address):
61 print "cache: invalidating", address
62 self.tx_cache.pop(address)
63 self.address_queue.put(address)
65 outrows = self.get_tx_outputs(txid, False)
67 _hash = self.binout(row[6])
69 print "WARNING: missing tx_out for tx", txid
72 address = hash_to_address(chr(0), _hash)
73 if self.tx_cache.has_key(address):
74 print "cache: invalidating", address
75 self.tx_cache.pop(address)
76 self.address_queue.put(address)
78 def safe_sql(self,sql, params=(), lock=True):
80 if lock: self.dblock.acquire()
81 ret = self.selectall(sql,params)
83 print "sql error", sql
86 if lock: self.dblock.release()
91 def get_tx_outputs(self, tx_id, lock=True):
92 return self.safe_sql("""SELECT
94 txout.txout_scriptPubKey,
101 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
102 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
103 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
104 WHERE txout.tx_id = %d
105 ORDER BY txout.txout_pos
106 """%(tx_id), (), lock)
108 def get_tx_inputs(self, tx_id, lock=True):
109 return self.safe_sql(""" SELECT
113 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
115 COALESCE(txout.txout_pos, u.txout_pos),
118 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
119 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
120 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
121 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
122 WHERE txin.tx_id = %d
123 ORDER BY txin.txin_pos
124 """%(tx_id,), (), lock)
126 def get_address_out_rows(self, dbhash):
127 return self.safe_sql(""" SELECT
137 FROM chain_candidate cc
138 JOIN block b ON (b.block_id = cc.block_id)
139 JOIN block_tx ON (block_tx.block_id = b.block_id)
140 JOIN tx ON (tx.tx_id = block_tx.tx_id)
141 JOIN txin ON (txin.tx_id = tx.tx_id)
142 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
143 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
144 WHERE pubkey.pubkey_hash = ?
145 AND cc.in_longest = 1""", (dbhash,))
147 def get_address_out_rows_memorypool(self, dbhash):
148 return self.safe_sql(""" SELECT
155 JOIN txin ON (txin.tx_id = tx.tx_id)
156 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
157 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
158 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
160 def get_address_in_rows(self, dbhash):
161 return self.safe_sql(""" SELECT
171 FROM chain_candidate cc
172 JOIN block b ON (b.block_id = cc.block_id)
173 JOIN block_tx ON (block_tx.block_id = b.block_id)
174 JOIN tx ON (tx.tx_id = block_tx.tx_id)
175 JOIN txout ON (txout.tx_id = tx.tx_id)
176 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
177 WHERE pubkey.pubkey_hash = ?
178 AND cc.in_longest = 1""", (dbhash,))
180 def get_address_in_rows_memorypool(self, dbhash):
181 return self.safe_sql( """ SELECT
188 JOIN txout ON (txout.tx_id = tx.tx_id)
189 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
190 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
192 def get_history(self, addr):
194 cached_version = self.tx_cache.get( addr )
195 if cached_version is not None:
196 return cached_version
198 version, binaddr = decode_check_address(addr)
202 dbhash = self.binin(binaddr)
204 rows += self.get_address_out_rows( dbhash )
205 rows += self.get_address_in_rows( dbhash )
212 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
214 print "cannot unpack row", row
216 tx_hash = self.hashout_hex(tx_hash)
218 "timestamp": int(nTime),
219 "height": int(height),
220 "is_input": int(is_in),
221 "block_hash": self.hashout_hex(blk_hash),
228 txpoints.append(txpoint)
229 known_tx.append(self.hashout_hex(tx_hash))
232 # todo: sort them really...
233 txpoints = sorted(txpoints, key=operator.itemgetter("timestamp"))
237 rows += self.get_address_in_rows_memorypool( dbhash )
238 rows += self.get_address_out_rows_memorypool( dbhash )
239 address_has_mempool = False
241 current_id = self.new_id("tx")
244 is_in, tx_hash, tx_id, pos, value = row
245 tx_hash = self.hashout_hex(tx_hash)
246 if tx_hash in known_tx:
249 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
250 address_has_mempool = True
252 # fixme: we need to detect transactions that became invalid
253 if current_id - tx_id > 10000:
257 #print "mempool", tx_hash
261 "is_input": int(is_in),
262 "block_hash": 'mempool',
268 txpoints.append(txpoint)
271 for txpoint in txpoints:
272 tx_id = txpoint['tx_id']
275 inrows = self.get_tx_inputs(tx_id)
277 _hash = self.binout(row[6])
279 print "WARNING: missing tx_in for tx", tx_id, addr
281 address = hash_to_address(chr(0), _hash)
282 txinputs.append(address)
283 txpoint['inputs'] = txinputs
285 outrows = self.get_tx_outputs(tx_id)
287 _hash = self.binout(row[6])
289 print "WARNING: missing tx_out for tx", tx_id, addr
291 address = hash_to_address(chr(0), _hash)
292 txoutputs.append(address)
293 txpoint['outputs'] = txoutputs
295 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
296 if not txpoint['is_input']:
297 # detect if already redeemed...
299 if row[6] == dbhash: break
302 #row = self.get_tx_output(tx_id,dbhash)
303 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
304 # if not redeemed, we add the script
306 if not row[4]: txpoint['raw_output_script'] = row[1]
309 if not address_has_mempool:
310 self.tx_cache[addr] = txpoints
315 def get_status(self,addr):
316 # get address status, i.e. the last block for that address.
317 tx_points = self.get_history(addr)
321 lastpoint = tx_points[-1]
322 status = lastpoint['block_hash']
323 # this is a temporary hack; move it up once old clients have disappeared
324 if status == 'mempool': # and session['version'] != "old":
325 status = status + ':%d'% len(tx_points)
330 def memorypool_update(store):
332 ds = BCDataStream.BCDataStream()
333 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
335 respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
337 if r['error'] != None:
340 v = r['result'].get('transactions')
343 ds.write(hextx.decode('hex'))
344 tx = deserialize.parse_Transaction(ds)
345 tx['hash'] = util.double_sha256(tx['tx'])
346 tx_hash = store.hashin(tx['hash'])
348 if store.tx_find_id_and_value(tx):
351 tx_id = store.import_tx(tx, False)
352 store.update_tx_cache(tx_id)
357 def send_tx(self,tx):
358 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
359 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
361 if r['error'] != None:
362 msg = r['error'].get('message')
363 out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
369 def main_iteration(store):
371 store.dblock.acquire()
373 store.memorypool_update()
374 block_number = store.get_block_number(1)
377 print "IOError: cannot reach bitcoind"
380 traceback.print_exc(file=sys.stdout)
383 store.dblock.release()
389 # if there is an exception, do rollback and then re-raise the exception
390 for dircfg in store.datadirs:
392 store.catch_up_dir(dircfg)
394 store.log.exception("Failed to catch up %s", dircfg)
401 from processor import Processor
403 class BlockchainProcessor(Processor):
405 def __init__(self, config):
406 Processor.__init__(self)
407 self.store = AbeStore(config)
408 self.block_number = -1
409 self.watched_addresses = []
410 threading.Timer(10, self.run_store_iteration).start()
412 def process(self, request):
413 #print "abe process", request
415 message_id = request['id']
416 method = request['method']
417 params = request.get('params',[])
419 if method == 'blockchain.numblocks.subscribe':
420 result = self.block_number
421 elif method == 'blockchain.address.subscribe':
423 self.watch_address(address)
424 status = self.store.get_status(address)
426 elif method == 'blockchain.address.get_history':
428 result = self.store.get_history( address )
429 elif method == 'blockchain.transaction.broadcast':
430 txo = self.store.send_tx(params[0])
431 print "sent tx:", txo
434 print "unknown method", request
437 response = { 'id':message_id, 'result':result }
438 self.push_response(response)
441 def watch_address(self, addr):
442 if addr not in self.watched_addresses:
443 self.watched_addresses.append(addr)
446 def run_store_iteration(self):
447 if self.shared.stopped():
451 block_number = self.store.main_iteration()
452 if self.block_number != block_number:
453 self.block_number = block_number
454 print "block number:", self.block_number
455 self.push_response({ 'method':'blockchain.numblocks.subscribe', 'params':[self.block_number] })
459 addr = self.store.address_queue.get(False)
462 if addr in self.watched_addresses:
463 status = self.store.get_status( addr )
464 self.push_response({ 'method':'blockchain.address.subscribe', 'params':[addr, status] })
466 threading.Timer(10, self.run_store_iteration).start()