1 from Abe.abe 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
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.mempool_keys = {}
29 self.bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
31 self.address_queue = Queue()
33 self.dblock = thread.allocate_lock()
37 def import_block(self, b, chain_ids=frozenset()):
39 block_id = super(AbeStore, self).import_block(b, chain_ids)
40 for pos in xrange(len(b['transactions'])):
41 tx = b['transactions'][pos]
43 tx['hash'] = util.double_sha256(tx['tx'])
44 tx_id = self.tx_find_id_and_value(tx)
46 self.update_tx_cache(tx_id)
48 print "error: import_block: no tx_id"
52 def update_tx_cache(self, txid):
53 inrows = self.get_tx_inputs(txid, False)
55 _hash = self.binout(row[6])
56 address = hash_to_address(chr(0), _hash)
57 if self.tx_cache.has_key(address):
58 print "cache: invalidating", address
59 self.tx_cache.pop(address)
60 self.address_queue.put(address)
62 outrows = self.get_tx_outputs(txid, False)
64 _hash = self.binout(row[6])
65 address = hash_to_address(chr(0), _hash)
66 if self.tx_cache.has_key(address):
67 print "cache: invalidating", address
68 self.tx_cache.pop(address)
69 self.address_queue.put(address)
71 def safe_sql(self,sql, params=(), lock=True):
73 if lock: self.dblock.acquire()
74 ret = self.selectall(sql,params)
76 print "sql error", sql
79 if lock: self.dblock.release()
84 def get_tx_outputs(self, tx_id, lock=True):
85 return self.safe_sql("""SELECT
87 txout.txout_scriptPubKey,
94 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
95 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
96 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
97 WHERE txout.tx_id = %d
98 ORDER BY txout.txout_pos
99 """%(tx_id), (), lock)
101 def get_tx_inputs(self, tx_id, lock=True):
102 return self.safe_sql(""" SELECT
106 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
108 COALESCE(txout.txout_pos, u.txout_pos),
111 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
112 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
113 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
114 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
115 WHERE txin.tx_id = %d
116 ORDER BY txin.txin_pos
117 """%(tx_id,), (), lock)
119 def get_address_out_rows(self, dbhash):
120 return self.safe_sql(""" SELECT
130 FROM chain_candidate cc
131 JOIN block b ON (b.block_id = cc.block_id)
132 JOIN block_tx ON (block_tx.block_id = b.block_id)
133 JOIN tx ON (tx.tx_id = block_tx.tx_id)
134 JOIN txin ON (txin.tx_id = tx.tx_id)
135 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
136 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
137 WHERE pubkey.pubkey_hash = ?
138 AND cc.in_longest = 1""", (dbhash,))
140 def get_address_out_rows_memorypool(self, dbhash):
141 return self.safe_sql(""" SELECT
148 JOIN txin ON (txin.tx_id = tx.tx_id)
149 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
150 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
151 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
153 def get_address_in_rows(self, dbhash):
154 return self.safe_sql(""" SELECT
164 FROM chain_candidate cc
165 JOIN block b ON (b.block_id = cc.block_id)
166 JOIN block_tx ON (block_tx.block_id = b.block_id)
167 JOIN tx ON (tx.tx_id = block_tx.tx_id)
168 JOIN txout ON (txout.tx_id = tx.tx_id)
169 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
170 WHERE pubkey.pubkey_hash = ?
171 AND cc.in_longest = 1""", (dbhash,))
173 def get_address_in_rows_memorypool(self, dbhash):
174 return self.safe_sql( """ SELECT
181 JOIN txout ON (txout.tx_id = tx.tx_id)
182 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
183 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
185 def get_history(self, addr):
187 cached_version = self.tx_cache.get( addr )
188 if cached_version is not None:
189 return cached_version
191 version, binaddr = decode_check_address(addr)
195 dbhash = self.binin(binaddr)
197 rows += self.get_address_out_rows( dbhash )
198 rows += self.get_address_in_rows( dbhash )
205 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
207 print "cannot unpack row", row
209 tx_hash = self.hashout_hex(tx_hash)
211 "timestamp": int(nTime),
212 "height": int(height),
213 "is_input": int(is_in),
214 "block_hash": self.hashout_hex(blk_hash),
221 txpoints.append(txpoint)
222 known_tx.append(self.hashout_hex(tx_hash))
225 # todo: sort them really...
226 txpoints = sorted(txpoints, key=operator.itemgetter("timestamp"))
230 rows += self.get_address_in_rows_memorypool( dbhash )
231 rows += self.get_address_out_rows_memorypool( dbhash )
232 address_has_mempool = False
235 is_in, tx_hash, tx_id, pos, value = row
236 tx_hash = self.hashout_hex(tx_hash)
237 if tx_hash in known_tx:
240 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
241 address_has_mempool = True
243 # this means pending transactions are returned by getmemorypool
244 if tx_hash not in self.mempool_keys:
247 #print "mempool", tx_hash
251 "is_input": int(is_in),
252 "block_hash": 'mempool',
258 txpoints.append(txpoint)
261 for txpoint in txpoints:
262 tx_id = txpoint['tx_id']
265 inrows = self.get_tx_inputs(tx_id)
267 _hash = self.binout(row[6])
268 address = hash_to_address(chr(0), _hash)
269 txinputs.append(address)
270 txpoint['inputs'] = txinputs
272 outrows = self.get_tx_outputs(tx_id)
274 _hash = self.binout(row[6])
275 address = hash_to_address(chr(0), _hash)
276 txoutputs.append(address)
277 txpoint['outputs'] = txoutputs
279 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
280 if not txpoint['is_input']:
281 # detect if already redeemed...
283 if row[6] == dbhash: break
286 #row = self.get_tx_output(tx_id,dbhash)
287 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
288 # if not redeemed, we add the script
290 if not row[4]: txpoint['raw_output_script'] = row[1]
293 if not address_has_mempool:
294 self.tx_cache[addr] = txpoints
299 def get_status(self,addr):
300 # get address status, i.e. the last block for that address.
301 tx_points = self.get_history(addr)
305 lastpoint = tx_points[-1]
306 status = lastpoint['block_hash']
307 # this is a temporary hack; move it up once old clients have disappeared
308 if status == 'mempool': # and session['version'] != "old":
309 status = status + ':%d'% len(tx_points)
314 def memorypool_update(store):
316 ds = BCDataStream.BCDataStream()
317 previous_transactions = store.mempool_keys
318 store.mempool_keys = []
320 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
322 respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
324 if r['error'] != None:
327 v = r['result'].get('transactions')
330 ds.write(hextx.decode('hex'))
331 tx = deserialize.parse_Transaction(ds)
332 tx['hash'] = util.double_sha256(tx['tx'])
333 tx_hash = store.hashin(tx['hash'])
335 store.mempool_keys.append(tx_hash)
336 if store.tx_find_id_and_value(tx):
339 tx_id = store.import_tx(tx, False)
340 store.update_tx_cache(tx_id)
345 def send_tx(self,tx):
346 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
347 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
349 if r['error'] != None:
350 msg = r['error'].get('message')
351 out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
357 def main_iteration(store):
359 store.dblock.acquire()
361 store.memorypool_update()
362 block_number = store.get_block_number(1)
365 print "IOError: cannot reach bitcoind"
368 traceback.print_exc(file=sys.stdout)
371 store.dblock.release()
377 # if there is an exception, do rollback and then re-raise the exception
378 for dircfg in store.datadirs:
380 store.catch_up_dir(dircfg)
382 store.log.exception("Failed to catch up %s", dircfg)
389 from processor import Processor
391 class BlockchainProcessor(Processor):
393 def __init__(self, config):
394 Processor.__init__(self)
395 self.store = AbeStore(config)
396 self.block_number = -1
397 self.watched_addresses = []
399 def process(self, request):
400 message_id = request['id']
401 method = request['method']
402 params = request.get('params',[])
404 if method == 'blockchain.numblocks.subscribe':
405 result = self.block_number
406 elif method == 'blockchain.address.subscribe':
408 self.watch_address(address)
409 status = self.store.get_status(address)
411 elif method == 'blockchain.address.get_history':
413 result = self.store.get_history( address )
414 elif method == 'blockchain.transaction.broadcast':
415 txo = self.store.send_tx(params[0])
416 print "sent tx:", txo
419 print "unknown method", request
422 response = { 'id':message_id, 'result':result }
423 self.push_response(response)
426 def watch_address(self, addr):
427 if addr not in self.watched_addresses:
428 self.watched_addresses.append(addr)
433 old_block_number = None
434 while not self.shared.stopped():
435 self.block_number = self.store.main_iteration()
437 if self.block_number != old_block_number:
438 old_block_number = self.block_number
439 self.push_response({ 'method':'blockchain.numblocks.subscribe', 'params':[self.block_number] })
443 addr = self.store.address_queue.get(False)
446 if addr in self.watched_addresses:
447 status = self.store.get_status( addr )
448 self.push_response({ 'method':'blockchain.address.subscribe', 'params':[addr, status] })