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
5 import psycopg2, binascii
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)
75 if lock: self.dblock.release()
78 print "sql error", sql
81 def get_tx_outputs(self, tx_id, lock=True):
82 return self.safe_sql("""SELECT
84 txout.txout_scriptPubKey,
91 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
92 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
93 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
94 WHERE txout.tx_id = %d
95 ORDER BY txout.txout_pos
96 """%(tx_id), (), lock)
98 def get_tx_inputs(self, tx_id, lock=True):
99 return self.safe_sql(""" SELECT
103 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
105 COALESCE(txout.txout_pos, u.txout_pos),
108 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
109 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
110 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
111 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
112 WHERE txin.tx_id = %d
113 ORDER BY txin.txin_pos
114 """%(tx_id,), (), lock)
116 def get_address_out_rows(self, dbhash):
117 return self.safe_sql(""" SELECT
127 FROM chain_candidate cc
128 JOIN block b ON (b.block_id = cc.block_id)
129 JOIN block_tx ON (block_tx.block_id = b.block_id)
130 JOIN tx ON (tx.tx_id = block_tx.tx_id)
131 JOIN txin ON (txin.tx_id = tx.tx_id)
132 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
133 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
134 WHERE pubkey.pubkey_hash = ?
135 AND cc.in_longest = 1""", (dbhash,))
137 def get_address_out_rows_memorypool(self, dbhash):
138 return self.safe_sql(""" SELECT
145 JOIN txin ON (txin.tx_id = tx.tx_id)
146 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
147 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
148 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
150 def get_address_in_rows(self, dbhash):
151 return self.safe_sql(""" SELECT
161 FROM chain_candidate cc
162 JOIN block b ON (b.block_id = cc.block_id)
163 JOIN block_tx ON (block_tx.block_id = b.block_id)
164 JOIN tx ON (tx.tx_id = block_tx.tx_id)
165 JOIN txout ON (txout.tx_id = tx.tx_id)
166 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
167 WHERE pubkey.pubkey_hash = ?
168 AND cc.in_longest = 1""", (dbhash,))
170 def get_address_in_rows_memorypool(self, dbhash):
171 return self.safe_sql( """ SELECT
178 JOIN txout ON (txout.tx_id = tx.tx_id)
179 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
180 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
182 def get_history(self, addr):
184 cached_version = self.tx_cache.get( addr )
185 if cached_version is not None:
186 return cached_version
188 version, binaddr = decode_check_address(addr)
192 dbhash = self.binin(binaddr)
194 rows += self.get_address_out_rows( dbhash )
195 rows += self.get_address_in_rows( dbhash )
202 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
204 print "cannot unpack row", row
206 tx_hash = self.hashout_hex(tx_hash)
209 "height": int(height),
211 "blk_hash": self.hashout_hex(blk_hash),
218 txpoints.append(txpoint)
219 known_tx.append(self.hashout_hex(tx_hash))
222 # todo: sort them really...
223 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
227 rows += self.get_address_in_rows_memorypool( dbhash )
228 rows += self.get_address_out_rows_memorypool( dbhash )
229 address_has_mempool = False
232 is_in, tx_hash, tx_id, pos, value = row
233 tx_hash = self.hashout_hex(tx_hash)
234 if tx_hash in known_tx:
237 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
238 address_has_mempool = True
240 # this means pending transactions are returned by getmemorypool
241 if tx_hash not in self.mempool_keys:
244 #print "mempool", tx_hash
249 "blk_hash": 'mempool',
255 txpoints.append(txpoint)
258 for txpoint in txpoints:
259 tx_id = txpoint['tx_id']
262 inrows = self.get_tx_inputs(tx_id)
264 _hash = self.binout(row[6])
265 address = hash_to_address(chr(0), _hash)
266 txinputs.append(address)
267 txpoint['inputs'] = txinputs
269 outrows = self.get_tx_outputs(tx_id)
271 _hash = self.binout(row[6])
272 address = hash_to_address(chr(0), _hash)
273 txoutputs.append(address)
274 txpoint['outputs'] = txoutputs
276 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
277 if not txpoint['is_in']:
278 # detect if already redeemed...
280 if row[6] == dbhash: break
283 #row = self.get_tx_output(tx_id,dbhash)
284 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
285 # if not redeemed, we add the script
287 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
290 if not address_has_mempool:
291 self.tx_cache[addr] = txpoints
296 def get_status(self,addr):
297 # get address status, i.e. the last block for that address.
298 tx_points = self.get_history(addr)
302 lastpoint = tx_points[-1]
303 status = lastpoint['blk_hash']
304 # this is a temporary hack; move it up once old clients have disappeared
305 if status == 'mempool': # and session['version'] != "old":
306 status = status + ':%d'% len(tx_points)
311 def memorypool_update(store):
313 ds = BCDataStream.BCDataStream()
314 previous_transactions = store.mempool_keys
315 store.mempool_keys = []
317 postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
319 respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
321 if r['error'] != None:
324 v = r['result'].get('transactions')
327 ds.write(hextx.decode('hex'))
328 tx = deserialize.parse_Transaction(ds)
329 tx['hash'] = util.double_sha256(tx['tx'])
330 tx_hash = store.hashin(tx['hash'])
332 store.mempool_keys.append(tx_hash)
333 if store.tx_find_id_and_value(tx):
336 tx_id = store.import_tx(tx, False)
337 store.update_tx_cache(tx_id)
342 def send_tx(self,tx):
343 postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
344 respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
346 if r['error'] != None:
347 out = "error: transaction rejected by memorypool\n"+tx
353 def main_iteration(store):
355 store.dblock.acquire()
357 store.memorypool_update()
358 block_number = store.get_block_number(1)
361 print "IOError: cannot reach bitcoind"
364 traceback.print_exc(file=sys.stdout)
367 store.dblock.release()
372 from processor import Processor
374 class AbeProcessor(Processor):
376 def __init__(self, config):
377 Processor.__init__(self)
378 self.store = AbeStore(config)
379 self.block_number = -1
380 self.watched_addresses = []
382 def process(self, request):
383 message_id = request['id']
384 method = request['method']
385 params = request.get('params',[])
387 if method == 'blockchain.numblocks.subscribe':
388 result = self.block_number
389 elif method == 'blockchain.address.subscribe':
391 self.watch_address(address)
392 status = self.store.get_status(address)
394 elif method == 'blockchain.address.get_history':
396 result = self.store.get_history( address )
397 elif method == 'blockchain.transaction.broadcast':
398 txo = self.store.send_tx(params[0])
399 print "sent tx:", txo
402 print "unknown method", request
405 response = { 'id':message_id, 'method':method, 'params':params, 'result':result }
406 self.push_response(response)
409 def watch_address(self, addr):
410 if addr not in self.watched_addresses:
411 self.watched_addresses.append(addr)
416 old_block_number = None
417 while not self.shared.stopped():
418 self.block_number = self.store.main_iteration()
420 if self.block_number != old_block_number:
421 old_block_number = self.block_number
422 self.push_response({ 'method':'blockchain.numblocks.subscribe', 'result':self.block_number })
426 addr = self.store.address_queue.get(False)
429 if addr in self.watched_addresses:
430 status = self.get_status( addr )
431 self.push_response({ 'method':'blockchain.address.subscribe', 'params':[addr], 'result':status })