workaround
[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                 address = hash_to_address(chr(0), _hash)
277                 txinputs.append(address)
278             txpoint['inputs'] = txinputs
279             txoutputs = []
280             outrows = self.get_tx_outputs(tx_id)
281             for row in outrows:
282                 _hash = self.binout(row[6])
283                 address = hash_to_address(chr(0), _hash)
284                 txoutputs.append(address)
285             txpoint['outputs'] = txoutputs
286
287             # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
288             if not txpoint['is_input']:
289                 # detect if already redeemed...
290                 for row in outrows:
291                     if row[6] == dbhash: break
292                 else:
293                     raise
294                 #row = self.get_tx_output(tx_id,dbhash)
295                 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
296                 # if not redeemed, we add the script
297                 if row:
298                     if not row[4]: txpoint['raw_output_script'] = row[1]
299
300         # cache result
301         if not address_has_mempool:
302             self.tx_cache[addr] = txpoints
303         
304         return txpoints
305
306
307     def get_status(self,addr):
308         # get address status, i.e. the last block for that address.
309         tx_points = self.get_history(addr)
310         if not tx_points:
311             status = None
312         else:
313             lastpoint = tx_points[-1]
314             status = lastpoint['block_hash']
315             # this is a temporary hack; move it up once old clients have disappeared
316             if status == 'mempool': # and session['version'] != "old":
317                 status = status + ':%d'% len(tx_points)
318         return status
319
320
321
322     def memorypool_update(store):
323
324         ds = BCDataStream.BCDataStream()
325         previous_transactions = store.mempool_keys
326         store.mempool_keys = []
327
328         postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
329
330         respdata = urllib.urlopen(store.bitcoind_url, postdata).read()
331         r = loads(respdata)
332         if r['error'] != None:
333             return
334
335         v = r['result'].get('transactions')
336         for hextx in v:
337             ds.clear()
338             ds.write(hextx.decode('hex'))
339             tx = deserialize.parse_Transaction(ds)
340             tx['hash'] = util.double_sha256(tx['tx'])
341             tx_hash = store.hashin(tx['hash'])
342
343             store.mempool_keys.append(tx_hash)
344             if store.tx_find_id_and_value(tx):
345                 pass
346             else:
347                 tx_id = store.import_tx(tx, False)
348                 store.update_tx_cache(tx_id)
349     
350         store.commit()
351
352
353     def send_tx(self,tx):
354         postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
355         respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
356         r = loads(respdata)
357         if r['error'] != None:
358             msg = r['error'].get('message')
359             out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
360         else:
361             out = r['result']
362         return out
363
364
365     def main_iteration(store):
366         try:
367             store.dblock.acquire()
368             store.catch_up()
369             store.memorypool_update()
370             block_number = store.get_block_number(1)
371
372         except IOError:
373             print "IOError: cannot reach bitcoind"
374             block_number = 0
375         except:
376             traceback.print_exc(file=sys.stdout)
377             block_number = 0
378         finally:
379             store.dblock.release()
380
381         return block_number
382
383
384     def catch_up(store):
385         # if there is an exception, do rollback and then re-raise the exception
386         for dircfg in store.datadirs:
387             try:
388                 store.catch_up_dir(dircfg)
389             except Exception, e:
390                 store.log.exception("Failed to catch up %s", dircfg)
391                 store.rollback()
392                 raise e
393
394
395
396
397 from processor import Processor
398
399 class BlockchainProcessor(Processor):
400
401     def __init__(self, config):
402         Processor.__init__(self)
403         self.store = AbeStore(config)
404         self.block_number = -1
405         self.watched_addresses = []
406
407     def process(self, request):
408         message_id = request['id']
409         method = request['method']
410         params = request.get('params',[])
411         result = ''
412         if method == 'blockchain.numblocks.subscribe':
413             result = self.block_number
414         elif method == 'blockchain.address.subscribe':
415             address = params[0]
416             self.watch_address(address)
417             status = self.store.get_status(address)
418             result = status
419         elif method == 'blockchain.address.get_history':
420             address = params[0]
421             result = self.store.get_history( address ) 
422         elif method == 'blockchain.transaction.broadcast':
423             txo = self.store.send_tx(params[0])
424             print "sent tx:", txo
425             result = txo 
426         else:
427             print "unknown method", request
428
429         if result != '':
430             response = { 'id':message_id, 'result':result }
431             self.push_response(response)
432
433
434     def watch_address(self, addr):
435         if addr not in self.watched_addresses:
436             self.watched_addresses.append(addr)
437
438
439     def run(self):
440         
441         old_block_number = None
442         while not self.shared.stopped():
443             self.block_number = self.store.main_iteration()
444
445             if self.block_number != old_block_number:
446                 old_block_number = self.block_number
447                 print "block number:", self.block_number
448                 self.push_response({ 'method':'blockchain.numblocks.subscribe', 'params':[self.block_number] })
449
450             while True:
451                 try:
452                     addr = self.store.address_queue.get(False)
453                 except:
454                     break
455                 if addr in self.watched_addresses:
456                     status = self.store.get_status( addr )
457                     self.push_response({ 'method':'blockchain.address.subscribe', 'params':[addr, status] })
458
459             time.sleep(10)
460
461
462