extra bit of explanation
[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         # do not cache mempool results because statuses are ambiguous
310         if not address_has_mempool:
311             self.tx_cache[addr] = txpoints
312         
313         return txpoints
314
315
316     def get_status(self,addr):
317         # get address status, i.e. the last block for that address.
318         tx_points = self.get_history(addr)
319         if not tx_points:
320             status = None
321         else:
322             lastpoint = tx_points[-1]
323             status = lastpoint['block_hash']
324             # this is a temporary hack; move it up once old clients have disappeared
325             if status == 'mempool': # and session['version'] != "old":
326                 status = status + ':%d'% len(tx_points)
327         return status
328
329
330
331     def memorypool_update(store):
332
333         ds = BCDataStream.BCDataStream()
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             if store.tx_find_id_and_value(tx):
350                 pass
351             else:
352                 tx_id = store.import_tx(tx, False)
353                 store.update_tx_cache(tx_id)
354     
355         store.commit()
356
357
358     def send_tx(self,tx):
359         postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
360         respdata = urllib.urlopen(self.bitcoind_url, postdata).read()
361         r = loads(respdata)
362         if r['error'] != None:
363             msg = r['error'].get('message')
364             out = "error: transaction rejected by memorypool: " + msg + "\n" + tx
365         else:
366             out = r['result']
367         return out
368
369
370     def main_iteration(store):
371         try:
372             store.dblock.acquire()
373             store.catch_up()
374             store.memorypool_update()
375             block_number = store.get_block_number(1)
376
377         except IOError:
378             print "IOError: cannot reach bitcoind"
379             block_number = 0
380         except:
381             traceback.print_exc(file=sys.stdout)
382             block_number = 0
383         finally:
384             store.dblock.release()
385
386         return block_number
387
388
389     def catch_up(store):
390         # if there is an exception, do rollback and then re-raise the exception
391         for dircfg in store.datadirs:
392             try:
393                 store.catch_up_dir(dircfg)
394             except Exception, e:
395                 store.log.exception("Failed to catch up %s", dircfg)
396                 store.rollback()
397                 raise e
398
399
400
401
402 from processor import Processor
403
404 class BlockchainProcessor(Processor):
405
406     def __init__(self, config):
407         Processor.__init__(self)
408         self.store = AbeStore(config)
409         self.block_number = -1
410         self.watched_addresses = []
411         threading.Timer(10, self.run_store_iteration).start()
412
413     def process(self, request):
414         #print "abe process", request
415
416         message_id = request['id']
417         method = request['method']
418         params = request.get('params',[])
419         result = ''
420         if method == 'blockchain.numblocks.subscribe':
421             result = self.block_number
422         elif method == 'blockchain.address.subscribe':
423             address = params[0]
424             self.watch_address(address)
425             status = self.store.get_status(address)
426             result = status
427         elif method == 'blockchain.address.get_history':
428             address = params[0]
429             result = self.store.get_history( address ) 
430         elif method == 'blockchain.transaction.broadcast':
431             txo = self.store.send_tx(params[0])
432             print "sent tx:", txo
433             result = txo 
434         else:
435             print "unknown method", request
436
437         if result != '':
438             response = { 'id':message_id, 'result':result }
439             self.push_response(response)
440
441
442     def watch_address(self, addr):
443         if addr not in self.watched_addresses:
444             self.watched_addresses.append(addr)
445
446
447     def run_store_iteration(self):
448         if self.shared.stopped(): 
449             print "exit timer"
450             return
451         
452         block_number = self.store.main_iteration()
453         if self.block_number != block_number:
454             self.block_number = block_number
455             print "block number:", self.block_number
456             self.push_response({ 'method':'blockchain.numblocks.subscribe', 'params':[self.block_number] })
457
458         while True:
459             try:
460                 addr = self.store.address_queue.get(False)
461             except:
462                 break
463             if addr in self.watched_addresses:
464                 status = self.store.get_status( addr )
465                 self.push_response({ 'method':'blockchain.address.subscribe', 'params':[addr, status] })
466
467         threading.Timer(10, self.run_store_iteration).start()
468
469