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