workaround to detect old mempool transactions: use tx_id
[electrum-server.git] / backends / abe / __init__.py
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
4
5 import binascii
6
7 import thread, traceback, sys, urllib, operator
8 from json import dumps, loads
9 from Queue import Queue
10 import time, threading
11
12 class AbeStore(Datastore_class):
13
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') }
24
25         Datastore_class.__init__(self,args)
26
27         self.tx_cache = {}
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'))
29
30         self.address_queue = Queue()
31
32         self.dblock = thread.allocate_lock()
33
34
35
36     def import_block(self, b, chain_ids=frozenset()):
37         #print "import block"
38         block_id = super(AbeStore, self).import_block(b, chain_ids)
39         for pos in xrange(len(b['transactions'])):
40             tx = b['transactions'][pos]
41             if 'hash' not in tx:
42                 tx['hash'] = util.double_sha256(tx['tx'])
43             tx_id = self.tx_find_id_and_value(tx)
44             if tx_id:
45                 self.update_tx_cache(tx_id)
46             else:
47                 print "error: import_block: no tx_id"
48         return block_id
49
50
51     def update_tx_cache(self, txid):
52         inrows = self.get_tx_inputs(txid, False)
53         for row in inrows:
54             _hash = self.binout(row[6])
55             if not _hash:
56                 print "WARNING: missing tx_in for tx", txid
57                 continue
58
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)
64
65         outrows = self.get_tx_outputs(txid, False)
66         for row in outrows:
67             _hash = self.binout(row[6])
68             if not _hash:
69                 print "WARNING: missing tx_out for tx", txid
70                 continue
71
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)
77
78     def safe_sql(self,sql, params=(), lock=True):
79         try:
80             if lock: self.dblock.acquire()
81             ret = self.selectall(sql,params)
82         except:
83             print "sql error", sql
84             ret = []
85         finally:
86             if lock: self.dblock.release()
87
88         return ret
89             
90
91     def get_tx_outputs(self, tx_id, lock=True):
92         return self.safe_sql("""SELECT
93                 txout.txout_pos,
94                 txout.txout_scriptPubKey,
95                 txout.txout_value,
96                 nexttx.tx_hash,
97                 nexttx.tx_id,
98                 txin.txin_pos,
99                 pubkey.pubkey_hash
100               FROM txout
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)
107
108     def get_tx_inputs(self, tx_id, lock=True):
109         return self.safe_sql(""" SELECT
110                 txin.txin_pos,
111                 txin.txin_scriptSig,
112                 txout.txout_value,
113                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
114                 prevtx.tx_id,
115                 COALESCE(txout.txout_pos, u.txout_pos),
116                 pubkey.pubkey_hash
117               FROM txin
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)
125
126     def get_address_out_rows(self, dbhash):
127         return self.safe_sql(""" SELECT
128                 b.block_nTime,
129                 cc.chain_id,
130                 b.block_height,
131                 1,
132                 b.block_hash,
133                 tx.tx_hash,
134                 tx.tx_id,
135                 txin.txin_pos,
136                 -prevout.txout_value
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,))
146
147     def get_address_out_rows_memorypool(self, dbhash):
148         return self.safe_sql(""" SELECT
149                 1,
150                 tx.tx_hash,
151                 tx.tx_id,
152                 txin.txin_pos,
153                 -prevout.txout_value
154               FROM tx 
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,))
159
160     def get_address_in_rows(self, dbhash):
161         return self.safe_sql(""" SELECT
162                 b.block_nTime,
163                 cc.chain_id,
164                 b.block_height,
165                 0,
166                 b.block_hash,
167                 tx.tx_hash,
168                 tx.tx_id,
169                 txout.txout_pos,
170                 txout.txout_value
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,))
179
180     def get_address_in_rows_memorypool(self, dbhash):
181         return self.safe_sql( """ SELECT
182                 0,
183                 tx.tx_hash,
184                 tx.tx_id,
185                 txout.txout_pos,
186                 txout.txout_value
187               FROM tx
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,))
191
192     def get_history(self, addr):
193
194         cached_version = self.tx_cache.get( addr )
195         if cached_version is not None:
196             return cached_version
197
198         version, binaddr = decode_check_address(addr)
199         if binaddr is None:
200             return None
201
202         dbhash = self.binin(binaddr)
203         rows = []
204         rows += self.get_address_out_rows( dbhash )
205         rows += self.get_address_in_rows( dbhash )
206
207         txpoints = []
208         known_tx = []
209
210         for row in rows:
211             try:
212                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
213             except:
214                 print "cannot unpack row", row
215                 break
216             tx_hash = self.hashout_hex(tx_hash)
217             txpoint = {
218                     "timestamp":    int(nTime),
219                     "height":   int(height),
220                     "is_input":    int(is_in),
221                     "block_hash": self.hashout_hex(blk_hash),
222                     "tx_hash":  tx_hash,
223                     "tx_id":    int(tx_id),
224                     "index":      int(pos),
225                     "value":    int(value),
226                     }
227
228             txpoints.append(txpoint)
229             known_tx.append(self.hashout_hex(tx_hash))
230
231
232         # todo: sort them really...
233         txpoints = sorted(txpoints, key=operator.itemgetter("timestamp"))
234
235         # read memory pool
236         rows = []
237         rows += self.get_address_in_rows_memorypool( dbhash )
238         rows += self.get_address_out_rows_memorypool( dbhash )
239         address_has_mempool = False
240
241         current_id = self.new_id("tx")
242
243         for row in rows:
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:
247                 continue
248
249             # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
250             address_has_mempool = True
251
252             # fixme: we need to detect transactions that became invalid
253             if current_id - tx_id > 10000:
254                 continue
255
256
257             #print "mempool", tx_hash
258             txpoint = {
259                     "timestamp":    0,
260                     "height":   0,
261                     "is_input":    int(is_in),
262                     "block_hash": 'mempool', 
263                     "tx_hash":  tx_hash,
264                     "tx_id":    int(tx_id),
265                     "index":      int(pos),
266                     "value":    int(value),
267                     }
268             txpoints.append(txpoint)
269
270
271         for txpoint in txpoints:
272             tx_id = txpoint['tx_id']
273             
274             txinputs = []
275             inrows = self.get_tx_inputs(tx_id)
276             for row in inrows:
277                 _hash = self.binout(row[6])
278                 if not _hash:
279                     print "WARNING: missing tx_in for tx", tx_id, addr
280                     continue
281                 address = hash_to_address(chr(0), _hash)
282                 txinputs.append(address)
283             txpoint['inputs'] = txinputs
284             txoutputs = []
285             outrows = self.get_tx_outputs(tx_id)
286             for row in outrows:
287                 _hash = self.binout(row[6])
288                 if not _hash:
289                     print "WARNING: missing tx_out for tx", tx_id, addr
290                     continue
291                 address = hash_to_address(chr(0), _hash)
292                 txoutputs.append(address)
293             txpoint['outputs'] = txoutputs
294
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...
298                 for row in outrows:
299                     if row[6] == dbhash: break
300                 else:
301                     raise
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
305                 if row:
306                     if not row[4]: txpoint['raw_output_script'] = row[1]
307
308         # cache result
309         if not address_has_mempool:
310             self.tx_cache[addr] = txpoints
311         
312         return txpoints
313
314
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)
318         if not tx_points:
319             status = None
320         else:
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)
326         return status
327
328
329
330     def memorypool_update(store):
331
332         ds = BCDataStream.BCDataStream()
333         postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
334
335         respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
336         r = loads(respdata)
337         if r['error'] != None:
338             return
339
340         v = r['result'].get('transactions')
341         for hextx in v:
342             ds.clear()
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'])
347
348             if store.tx_find_id_and_value(tx):
349                 pass
350             else:
351                 tx_id = store.import_tx(tx, False)
352                 store.update_tx_cache(tx_id)
353     
354         store.commit()
355
356
357     def send_tx(self,tx):
358         postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
359         respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
360         r = loads(respdata)
361         if r['error'] != None:
362             msg = r['error'].get('message')
363             out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
364         else:
365             out = r['result']
366         return out
367
368
369     def main_iteration(store):
370         try:
371             store.dblock.acquire()
372             store.catch_up()
373             store.memorypool_update()
374             block_number = store.get_block_number(1)
375
376         except IOError:
377             print "IOError: cannot reach bitcoind"
378             block_number = 0
379         except:
380             traceback.print_exc(file=sys.stdout)
381             block_number = 0
382         finally:
383             store.dblock.release()
384
385         return block_number
386
387
388     def catch_up(store):
389         # if there is an exception, do rollback and then re-raise the exception
390         for dircfg in store.datadirs:
391             try:
392                 store.catch_up_dir(dircfg)
393             except Exception, e:
394                 store.log.exception("Failed to catch up %s", dircfg)
395                 store.rollback()
396                 raise e
397
398
399
400
401 from processor import Processor
402
403 class BlockchainProcessor(Processor):
404
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()
411
412     def process(self, request):
413         #print "abe process", request
414
415         message_id = request['id']
416         method = request['method']
417         params = request.get('params',[])
418         result = ''
419         if method == 'blockchain.numblocks.subscribe':
420             result = self.block_number
421         elif method == 'blockchain.address.subscribe':
422             address = params[0]
423             self.watch_address(address)
424             status = self.store.get_status(address)
425             result = status
426         elif method == 'blockchain.address.get_history':
427             address = params[0]
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
432             result = txo 
433         else:
434             print "unknown method", request
435
436         if result != '':
437             response = { 'id':message_id, 'result':result }
438             self.push_response(response)
439
440
441     def watch_address(self, addr):
442         if addr not in self.watched_addresses:
443             self.watched_addresses.append(addr)
444
445
446     def run_store_iteration(self):
447         if self.shared.stopped(): 
448             print "exit timer"
449             return
450         
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] })
456
457         while True:
458             try:
459                 addr = self.store.address_queue.get(False)
460             except:
461                 break
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] })
465
466         threading.Timer(10, self.run_store_iteration).start()
467
468