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