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