add sql limit to config
[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
13
14 class AbeStore(Datastore_class):
15
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') }
26
27         Datastore_class.__init__(self,args)
28
29         self.sql_limit = config.get('database','limit')
30
31         self.tx_cache = {}
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'))
33
34         self.address_queue = Queue()
35
36         self.dblock = thread.allocate_lock()
37
38
39
40     def import_block(self, b, chain_ids=frozenset()):
41         #print "import block"
42         block_id = super(AbeStore, self).import_block(b, chain_ids)
43         for pos in xrange(len(b['transactions'])):
44             tx = b['transactions'][pos]
45             if 'hash' not in tx:
46                 tx['hash'] = util.double_sha256(tx['tx'])
47             tx_id = self.tx_find_id_and_value(tx)
48             if tx_id:
49                 self.update_tx_cache(tx_id)
50             else:
51                 print "error: import_block: no tx_id"
52         return block_id
53
54
55     def update_tx_cache(self, txid):
56         inrows = self.get_tx_inputs(txid, False)
57         for row in inrows:
58             _hash = self.binout(row[6])
59             if not _hash:
60                 #print "WARNING: missing tx_in for tx", txid
61                 continue
62
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)
68
69         outrows = self.get_tx_outputs(txid, False)
70         for row in outrows:
71             _hash = self.binout(row[6])
72             if not _hash:
73                 #print "WARNING: missing tx_out for tx", txid
74                 continue
75
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)
81
82     def safe_sql(self,sql, params=(), lock=True):
83
84         error = False
85         try:
86             if lock: self.dblock.acquire()
87             ret = self.selectall(sql,params)
88         except:
89             error = True
90         finally:
91             if lock: self.dblock.release()
92
93         if error: 
94             raise BaseException('sql error')
95
96         return ret
97             
98
99     def get_tx_outputs(self, tx_id, lock=True):
100         return self.safe_sql("""SELECT
101                 txout.txout_pos,
102                 txout.txout_scriptPubKey,
103                 txout.txout_value,
104                 nexttx.tx_hash,
105                 nexttx.tx_id,
106                 txin.txin_pos,
107                 pubkey.pubkey_hash
108               FROM txout
109               LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
110               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
111               LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
112              WHERE txout.tx_id = %d 
113              ORDER BY txout.txout_pos
114         """%(tx_id), (), lock)
115
116     def get_tx_inputs(self, tx_id, lock=True):
117         return self.safe_sql(""" SELECT
118                 txin.txin_pos,
119                 txin.txin_scriptSig,
120                 txout.txout_value,
121                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
122                 prevtx.tx_id,
123                 COALESCE(txout.txout_pos, u.txout_pos),
124                 pubkey.pubkey_hash
125               FROM txin
126               LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
127               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
128               LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
129               LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
130              WHERE txin.tx_id = %d
131              ORDER BY txin.txin_pos
132              """%(tx_id,), (), lock)
133
134
135     def get_address_out_rows(self, dbhash):
136         out = self.safe_sql(""" SELECT
137                 b.block_nTime,
138                 cc.chain_id,
139                 b.block_height,
140                 1,
141                 b.block_hash,
142                 tx.tx_hash,
143                 tx.tx_id,
144                 txin.txin_pos,
145                 -prevout.txout_value
146               FROM chain_candidate cc
147               JOIN block b ON (b.block_id = cc.block_id)
148               JOIN block_tx ON (block_tx.block_id = b.block_id)
149               JOIN tx ON (tx.tx_id = block_tx.tx_id)
150               JOIN txin ON (txin.tx_id = tx.tx_id)
151               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
152               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
153              WHERE pubkey.pubkey_hash = ?
154                AND cc.in_longest = 1
155              LIMIT ? """, (dbhash,self.sql_limit))
156
157         if len(out)==self.sql_limit: 
158             raise BaseException('limit reached')
159         return out
160
161     def get_address_out_rows_memorypool(self, dbhash):
162         out = self.safe_sql(""" SELECT
163                 1,
164                 tx.tx_hash,
165                 tx.tx_id,
166                 txin.txin_pos,
167                 -prevout.txout_value
168               FROM tx 
169               JOIN txin ON (txin.tx_id = tx.tx_id)
170               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
171               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
172              WHERE pubkey.pubkey_hash = ?
173              LIMIT ? """, (dbhash,self.sql_limit))
174
175         if len(out)==self.sql_limit: 
176             raise BaseException('limit reached')
177         return out
178
179     def get_address_in_rows(self, dbhash):
180         out = self.safe_sql(""" SELECT
181                 b.block_nTime,
182                 cc.chain_id,
183                 b.block_height,
184                 0,
185                 b.block_hash,
186                 tx.tx_hash,
187                 tx.tx_id,
188                 txout.txout_pos,
189                 txout.txout_value
190               FROM chain_candidate cc
191               JOIN block b ON (b.block_id = cc.block_id)
192               JOIN block_tx ON (block_tx.block_id = b.block_id)
193               JOIN tx ON (tx.tx_id = block_tx.tx_id)
194               JOIN txout ON (txout.tx_id = tx.tx_id)
195               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
196              WHERE pubkey.pubkey_hash = ?
197                AND cc.in_longest = 1
198                LIMIT ? """, (dbhash,self.sql_limit))
199
200         if len(out)==self.sql_limit: 
201             raise BaseException('limit reached')
202         return out
203
204     def get_address_in_rows_memorypool(self, dbhash):
205         out = self.safe_sql( """ SELECT
206                 0,
207                 tx.tx_hash,
208                 tx.tx_id,
209                 txout.txout_pos,
210                 txout.txout_value
211               FROM tx
212               JOIN txout ON (txout.tx_id = tx.tx_id)
213               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
214              WHERE pubkey.pubkey_hash = ?
215              LIMIT ? """, (dbhash,self.sql_limit))
216
217         if len(out)==self.sql_limit: 
218             raise BaseException('limit reached')
219         return out
220
221     def get_history(self, addr):
222
223         cached_version = self.tx_cache.get( addr )
224         if cached_version is not None:
225             return cached_version
226
227         version, binaddr = decode_check_address(addr)
228         if binaddr is None:
229             return None
230
231         dbhash = self.binin(binaddr)
232         rows = []
233         rows += self.get_address_out_rows( dbhash )
234         rows += self.get_address_in_rows( dbhash )
235
236         txpoints = []
237         known_tx = []
238
239         for row in rows:
240             try:
241                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
242             except:
243                 print "cannot unpack row", row
244                 break
245             tx_hash = self.hashout_hex(tx_hash)
246             txpoint = {
247                     "timestamp":    int(nTime),
248                     "height":   int(height),
249                     "is_input":    int(is_in),
250                     "block_hash": self.hashout_hex(blk_hash),
251                     "tx_hash":  tx_hash,
252                     "tx_id":    int(tx_id),
253                     "index":      int(pos),
254                     "value":    int(value),
255                     }
256
257             txpoints.append(txpoint)
258             known_tx.append(self.hashout_hex(tx_hash))
259
260
261         # todo: sort them really...
262         txpoints = sorted(txpoints, key=operator.itemgetter("timestamp"))
263
264         # read memory pool
265         rows = []
266         rows += self.get_address_in_rows_memorypool( dbhash )
267         rows += self.get_address_out_rows_memorypool( dbhash )
268         address_has_mempool = False
269
270         current_id = self.new_id("tx")
271
272         for row in rows:
273             is_in, tx_hash, tx_id, pos, value = row
274             tx_hash = self.hashout_hex(tx_hash)
275             if tx_hash in known_tx:
276                 continue
277
278             # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
279             address_has_mempool = True
280
281             # fixme: we need to detect transactions that became invalid
282             if current_id - tx_id > 10000:
283                 continue
284
285
286             #print "mempool", tx_hash
287             txpoint = {
288                     "timestamp":    0,
289                     "height":   0,
290                     "is_input":    int(is_in),
291                     "block_hash": 'mempool', 
292                     "tx_hash":  tx_hash,
293                     "tx_id":    int(tx_id),
294                     "index":      int(pos),
295                     "value":    int(value),
296                     }
297             txpoints.append(txpoint)
298
299
300         for txpoint in txpoints:
301             tx_id = txpoint['tx_id']
302             
303             txinputs = []
304             inrows = self.get_tx_inputs(tx_id)
305             for row in inrows:
306                 _hash = self.binout(row[6])
307                 if not _hash:
308                     #print "WARNING: missing tx_in for tx", tx_id, addr
309                     continue
310                 address = hash_to_address(chr(0), _hash)
311                 txinputs.append(address)
312             txpoint['inputs'] = txinputs
313             txoutputs = []
314             outrows = self.get_tx_outputs(tx_id)
315             for row in outrows:
316                 _hash = self.binout(row[6])
317                 if not _hash:
318                     #print "WARNING: missing tx_out for tx", tx_id, addr
319                     continue
320                 address = hash_to_address(chr(0), _hash)
321                 txoutputs.append(address)
322             txpoint['outputs'] = txoutputs
323
324             # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
325             if not txpoint['is_input']:
326                 # detect if already redeemed...
327                 for row in outrows:
328                     if row[6] == dbhash: break
329                 else:
330                     raise
331                 #row = self.get_tx_output(tx_id,dbhash)
332                 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
333                 # if not redeemed, we add the script
334                 if row:
335                     if not row[4]: txpoint['raw_output_script'] = row[1]
336
337         # cache result
338         # do not cache mempool results because statuses are ambiguous
339         if not address_has_mempool:
340             self.tx_cache[addr] = txpoints
341         
342         return txpoints
343
344
345     def get_status(self,addr):
346         # get address status, i.e. the last block for that address.
347         tx_points = self.get_history(addr)
348         if not tx_points:
349             status = None
350         else:
351             lastpoint = tx_points[-1]
352             status = lastpoint['block_hash']
353             # this is a temporary hack; move it up once old clients have disappeared
354             if status == 'mempool': # and session['version'] != "old":
355                 status = status + ':%d'% len(tx_points)
356         return status
357
358
359
360     def memorypool_update(store):
361
362         ds = BCDataStream.BCDataStream()
363         postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
364
365         respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
366         r = loads(respdata)
367         if r['error'] != None:
368             return
369
370         v = r['result'].get('transactions')
371         for hextx in v:
372             ds.clear()
373             ds.write(hextx.decode('hex'))
374             tx = deserialize.parse_Transaction(ds)
375             tx['hash'] = util.double_sha256(tx['tx'])
376             tx_hash = store.hashin(tx['hash'])
377
378             if store.tx_find_id_and_value(tx):
379                 pass
380             else:
381                 tx_id = store.import_tx(tx, False)
382                 store.update_tx_cache(tx_id)
383     
384         store.commit()
385
386
387     def send_tx(self,tx):
388         postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
389         respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
390         r = loads(respdata)
391         if r['error'] != None:
392             msg = r['error'].get('message')
393             out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
394         else:
395             out = r['result']
396         return out
397
398
399     def main_iteration(store):
400         try:
401             store.dblock.acquire()
402             store.catch_up()
403             store.memorypool_update()
404             block_number = store.get_block_number(1)
405
406         except IOError:
407             print "IOError: cannot reach bitcoind"
408             block_number = 0
409         except:
410             traceback.print_exc(file=sys.stdout)
411             block_number = 0
412         finally:
413             store.dblock.release()
414
415         return block_number
416
417
418     def catch_up(store):
419         # if there is an exception, do rollback and then re-raise the exception
420         for dircfg in store.datadirs:
421             try:
422                 store.catch_up_dir(dircfg)
423             except Exception, e:
424                 store.log.exception("Failed to catch up %s", dircfg)
425                 store.rollback()
426                 raise e
427
428
429
430
431 from processor import Processor
432
433 class BlockchainProcessor(Processor):
434
435     def __init__(self, config):
436         Processor.__init__(self)
437         self.store = AbeStore(config)
438         self.block_number = -1
439         self.watched_addresses = []
440         threading.Timer(10, self.run_store_iteration).start()
441
442     def process(self, request):
443         #print "abe process", request
444
445         message_id = request['id']
446         method = request['method']
447         params = request.get('params',[])
448         result = None
449         error = None
450
451         if method == 'blockchain.numblocks.subscribe':
452             result = self.block_number
453
454         elif method == 'blockchain.address.subscribe':
455             try:
456                 address = params[0]
457                 result = self.store.get_status(address)
458                 self.watch_address(address)
459             except BaseException, e:
460                 error = str(e) + ': ' + address
461                 print "error:", error
462
463         elif method == 'blockchain.address.get_history':
464             try:
465                 address = params[0]
466                 result = self.store.get_history( address ) 
467             except BaseException, e:
468                 error = str(e) + ': ' + address
469                 print "error:", error
470
471         elif method == 'blockchain.transaction.broadcast':
472             txo = self.store.send_tx(params[0])
473             print "sent tx:", txo
474             result = txo 
475
476         else:
477             error = "unknown method:%s"%method
478
479
480         if error:
481             response = { 'id':message_id, 'error':error }
482             self.push_response(response)
483         elif result != '':
484             response = { 'id':message_id, 'result':result }
485             self.push_response(response)
486
487
488     def watch_address(self, addr):
489         if addr not in self.watched_addresses:
490             self.watched_addresses.append(addr)
491
492
493     def run_store_iteration(self):
494         if self.shared.stopped(): 
495             print "exit timer"
496             return
497         
498         block_number = self.store.main_iteration()
499         if self.block_number != block_number:
500             self.block_number = block_number
501             print "block number:", self.block_number
502             self.push_response({ 'method':'blockchain.numblocks.subscribe', 'params':[self.block_number] })
503
504         while True:
505             try:
506                 addr = self.store.address_queue.get(False)
507             except:
508                 break
509             if addr in self.watched_addresses:
510                 status = self.store.get_status( addr )
511                 self.push_response({ 'method':'blockchain.address.subscribe', 'params':[addr, status] })
512
513         threading.Timer(10, self.run_store_iteration).start()
514
515