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