disambiguate mempool blocks
[electrum-server.git] / server.py
1 #!/usr/bin/env python
2 # Copyright(C) 2011 thomasv@gitorious
3
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as
6 # published by the Free Software Foundation, either version 3 of the
7 # License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public
15 # License along with this program.  If not, see
16 # <http://www.gnu.org/licenses/agpl.html>.
17
18 """
19 Todo:
20    * server should check and return bitcoind status..
21    * improve txpoint sorting
22    * command to check cache
23 """
24
25
26 import time, socket, operator, thread, ast, sys,re
27 import psycopg2, binascii
28 import bitcoinrpc
29
30 from Abe.abe import hash_to_address, decode_check_address
31 from Abe.DataStore import DataStore as Datastore_class
32 from Abe import DataStore, readconf, BCDataStream,  deserialize, util, base58
33
34 import ConfigParser
35
36 config = ConfigParser.ConfigParser()
37 # set some defaults, which will be overwritten by the config file
38 config.add_section('server')
39 config.set('server','banner', 'Welcome to Electrum!')
40 config.set('server', 'host', 'localhost')
41 config.set('server', 'port', 50000)
42 config.set('server', 'password', '')
43 config.set('server', 'irc', 'yes')
44 config.set('server', 'cache', 'no') 
45 config.set('server', 'ircname', 'Electrum server')
46 config.add_section('database')
47 config.set('database', 'type', 'psycopg2')
48 config.set('database', 'database', 'abe')
49
50 try:
51     f = open('/etc/electrum.conf','r')
52     config.readfp(f)
53     f.close()
54 except:
55     print "Could not read electrum.conf. I will use the default values."
56
57 stopping = False
58 block_number = -1
59 sessions = {}
60 dblock = thread.allocate_lock()
61 peer_list = {}
62
63
64 class MyStore(Datastore_class):
65
66     def import_tx(self, tx, is_coinbase):
67         tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
68         if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
69
70     def update_tx_cache(self, txid):
71         inrows = self.get_tx_inputs(txid, False)
72         for row in inrows:
73             _hash = store.binout(row[6])
74             address = hash_to_address(chr(0), _hash)
75             if self.tx_cache.has_key(address):
76                 print "cache: invalidating", address, self.ismempool
77                 self.tx_cache.pop(address)
78         outrows = self.get_tx_outputs(txid, False)
79         for row in outrows:
80             _hash = store.binout(row[6])
81             address = hash_to_address(chr(0), _hash)
82             if self.tx_cache.has_key(address):
83                 print "cache: invalidating", address, self.ismempool
84                 self.tx_cache.pop(address)
85
86     def safe_sql(self,sql, params=(), lock=True):
87         try:
88             if lock: dblock.acquire()
89             ret = self.selectall(sql,params)
90             if lock: dblock.release()
91             return ret
92         except:
93             print "sql error", sql
94             return []
95
96     def get_tx_outputs(self, tx_id, lock=True):
97         return self.safe_sql("""SELECT
98                 txout.txout_pos,
99                 txout.txout_scriptPubKey,
100                 txout.txout_value,
101                 nexttx.tx_hash,
102                 nexttx.tx_id,
103                 txin.txin_pos,
104                 pubkey.pubkey_hash
105               FROM txout
106               LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
107               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
108               LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
109              WHERE txout.tx_id = %d 
110              ORDER BY txout.txout_pos
111         """%(tx_id), (), lock)
112
113     def get_tx_inputs(self, tx_id, lock=True):
114         return self.safe_sql(""" SELECT
115                 txin.txin_pos,
116                 txin.txin_scriptSig,
117                 txout.txout_value,
118                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
119                 prevtx.tx_id,
120                 COALESCE(txout.txout_pos, u.txout_pos),
121                 pubkey.pubkey_hash
122               FROM txin
123               LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
124               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
125               LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
126               LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
127              WHERE txin.tx_id = %d
128              ORDER BY txin.txin_pos
129              """%(tx_id,), (), lock)
130
131     def get_address_out_rows(self, dbhash):
132         return self.safe_sql(""" SELECT
133                 b.block_nTime,
134                 cc.chain_id,
135                 b.block_height,
136                 1,
137                 b.block_hash,
138                 tx.tx_hash,
139                 tx.tx_id,
140                 txin.txin_pos,
141                 -prevout.txout_value
142               FROM chain_candidate cc
143               JOIN block b ON (b.block_id = cc.block_id)
144               JOIN block_tx ON (block_tx.block_id = b.block_id)
145               JOIN tx ON (tx.tx_id = block_tx.tx_id)
146               JOIN txin ON (txin.tx_id = tx.tx_id)
147               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
148               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
149              WHERE pubkey.pubkey_hash = ?
150                AND cc.in_longest = 1""", (dbhash,))
151
152     def get_address_out_rows_memorypool(self, dbhash):
153         return self.safe_sql(""" SELECT
154                 1,
155                 tx.tx_hash,
156                 tx.tx_id,
157                 txin.txin_pos,
158                 -prevout.txout_value
159               FROM tx 
160               JOIN txin ON (txin.tx_id = tx.tx_id)
161               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
162               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
163              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
164
165     def get_address_in_rows(self, dbhash):
166         return self.safe_sql(""" SELECT
167                 b.block_nTime,
168                 cc.chain_id,
169                 b.block_height,
170                 0,
171                 b.block_hash,
172                 tx.tx_hash,
173                 tx.tx_id,
174                 txout.txout_pos,
175                 txout.txout_value
176               FROM chain_candidate cc
177               JOIN block b ON (b.block_id = cc.block_id)
178               JOIN block_tx ON (block_tx.block_id = b.block_id)
179               JOIN tx ON (tx.tx_id = block_tx.tx_id)
180               JOIN txout ON (txout.tx_id = tx.tx_id)
181               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
182              WHERE pubkey.pubkey_hash = ?
183                AND cc.in_longest = 1""", (dbhash,))
184
185     def get_address_in_rows_memorypool(self, dbhash):
186         return self.safe_sql( """ SELECT
187                 0,
188                 tx.tx_hash,
189                 tx.tx_id,
190                 txout.txout_pos,
191                 txout.txout_value
192               FROM tx
193               JOIN txout ON (txout.tx_id = tx.tx_id)
194               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
195              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
196
197     def get_txpoints(self, addr):
198         
199         if config.get('server','cache') == 'yes':
200             cached_version = self.tx_cache.get( addr ) 
201             if cached_version is not None: 
202                 return cached_version
203
204         version, binaddr = decode_check_address(addr)
205         if binaddr is None:
206             return "err"
207         dbhash = self.binin(binaddr)
208         rows = []
209         rows += self.get_address_out_rows( dbhash )
210         rows += self.get_address_in_rows( dbhash )
211
212         txpoints = []
213         known_tx = []
214
215         for row in rows:
216             try:
217                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
218             except:
219                 print "cannot unpack row", row
220                 break
221             tx_hash = self.hashout_hex(tx_hash)
222             txpoint = {
223                     "nTime":    int(nTime),
224                     #"chain_id": int(chain_id),
225                     "height":   int(height),
226                     "is_in":    int(is_in),
227                     "blk_hash": self.hashout_hex(blk_hash),
228                     "tx_hash":  tx_hash,
229                     "tx_id":    int(tx_id),
230                     "pos":      int(pos),
231                     "value":    int(value),
232                     }
233
234             txpoints.append(txpoint)
235             known_tx.append(self.hashout_hex(tx_hash))
236
237
238         # todo: sort them really...
239         txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
240
241         # read memory pool
242         rows = []
243         rows += self.get_address_in_rows_memorypool( dbhash )
244         rows += self.get_address_out_rows_memorypool( dbhash )
245         address_has_mempool = False
246
247         for row in rows:
248             is_in, tx_hash, tx_id, pos, value = row
249             tx_hash = self.hashout_hex(tx_hash)
250             if tx_hash in known_tx:
251                 continue
252
253             address_has_mempool = True
254             #print "mempool", tx_hash
255             txpoint = {
256                     "nTime":    0,
257                     #"chain_id": 1,
258                     "height":   0,
259                     "is_in":    int(is_in),
260                     "blk_hash": 'mempool', 
261                     "tx_hash":  tx_hash,
262                     "tx_id":    int(tx_id),
263                     "pos":      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_in']:
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_scriptPubKey'] = row[1]
299
300         # cache result
301         if config.get('server','cache') == 'yes' and not address_has_mempool:
302             self.tx_cache[addr] = txpoints
303         
304         return txpoints
305
306
307
308
309 def send_tx(tx):
310     import bitcoinrpc
311     conn = bitcoinrpc.connect_to_local()
312     try:
313         v = conn.importtransaction(tx)
314     except:
315         v = "error: transaction rejected by memorypool"
316     return v
317
318
319 def listen_thread(store):
320     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
321     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
322     s.bind((config.get('server','host'), config.getint('server','port')))
323     s.listen(1)
324     while not stopping:
325         conn, addr = s.accept()
326         thread.start_new_thread(client_thread, (addr, conn,))
327
328 def random_string(N):
329     import random, string
330     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
331
332 def client_thread(ipaddr,conn):
333     #print "client thread", ipaddr
334     try:
335         ipaddr = ipaddr[0]
336         msg = ''
337         while 1:
338             d = conn.recv(1024)
339             msg += d
340             if not d: 
341                 break
342             if d[-1]=='#':
343                 break
344
345         #print msg
346
347         try:
348             cmd, data = ast.literal_eval(msg[:-1])
349         except:
350             print "syntax error", repr(msg)
351             conn.close()
352             return
353
354         if cmd=='b':
355             out = "%d"%block_number
356
357         elif cmd in ['session','new_session']:
358             session_id = random_string(10)
359             try:
360                 if cmd == 'session':
361                     addresses = ast.literal_eval(data)
362                     version = "old"
363                 else:
364                     version, addresses = ast.literal_eval(data)
365             except:
366                 print "error"
367                 conn.close()
368                 return
369
370             print time.asctime(), "new session", version, ipaddr, session_id, addresses[0] if addresses else addresses, len(addresses)
371
372             sessions[session_id] = { 'addresses':{}, 'version':version }
373             for a in addresses:
374                 sessions[session_id]['addresses'][a] = ''
375             out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
376             sessions[session_id]['last_time'] = time.time()
377
378         elif cmd=='update_session':
379             try:
380                 session_id, addresses = ast.literal_eval(data)
381             except:
382                 print "error"
383                 conn.close()
384                 return
385
386             print time.asctime(), "update session", ipaddr, session_id, addresses[0] if addresses else addresses, len(addresses)
387
388             sessions[session_id]['addresses'] = {}
389             for a in addresses:
390                 sessions[session_id]['addresses'][a] = ''
391             out = 'ok'
392             sessions[session_id]['last_time'] = time.time()
393
394         elif cmd=='poll': 
395             session_id = data
396             session = sessions.get(session_id)
397             if session is None:
398                 print time.asctime(), "session not found", session_id, ipaddr
399                 out = repr( (-1, {}))
400             else:
401                 t1 = time.time()
402                 addresses = session['addresses']
403                 session['last_time'] = time.time()
404                 ret = {}
405                 k = 0
406                 for addr in addresses:
407                     if store.tx_cache.get( addr ) is not None: k += 1
408
409                     # get addtess status, i.e. the last block for that address.
410                     tx_points = store.get_txpoints(addr)
411                     if not tx_points:
412                         status = None
413                     else:
414                         lastpoint = tx_points[-1]
415                         status = lastpoint['blk_hash']
416                         # this is a temporary hack; move it up once old clients have disappeared
417                         if status == 'mempool' and session['version'] != "old":
418                             status = status + ':%s'% lastpoint['tx_hash']
419
420                     last_status = addresses.get( addr )
421                     if last_status != status:
422                         addresses[addr] = status
423                         ret[addr] = status
424                 if ret:
425                     sessions[session_id]['addresses'] = addresses
426                 out = repr( (block_number, ret ) )
427                 t2 = time.time() - t1 
428                 if t2 > 10:
429                     print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
430
431         elif cmd == 'h': 
432             # history
433             address = data
434             out = repr( store.get_txpoints( address ) )
435
436         elif cmd == 'load': 
437             if config.get('server','password') == data:
438                 out = repr( len(sessions) )
439             else:
440                 out = 'wrong password'
441
442         elif cmd =='tx':        
443             out = send_tx(data)
444             print "sent tx:", out
445
446         elif cmd =='clear_cache':
447             if config.get('server','password') == data:
448                 self.tx_cache = {}
449                 out = 'ok'
450             else:
451                 out = 'wrong password'
452
453         elif cmd =='get_cache':
454             try:
455                 pw, addr = data
456             except:
457                 addr = None
458             if addr:
459                 if config.get('server','password') == pw:
460                     out = store.tx_cache.get(addr)
461                     out = repr(out)
462                 else:
463                     out = 'wrong password'
464             else:
465                 out = "error: "+ repr(data)
466
467         elif cmd == 'stop':
468             global stopping
469             if config.get('server','password') == data:
470                 stopping = True
471                 out = 'ok'
472             else:
473                 out = 'wrong password'
474
475         elif cmd == 'peers':
476             out = repr(peer_list.values())
477
478         else:
479             out = None
480
481         if out:
482             #print ipaddr, cmd, len(out)
483             try:
484                 conn.send(out)
485             except:
486                 print "error, could not send"
487
488     finally:
489         conn.close()
490     
491
492 ds = BCDataStream.BCDataStream()
493
494
495
496
497 def memorypool_update(store):
498     conn = bitcoinrpc.connect_to_local()
499     try:
500         v = conn.getmemorypool()
501     except:
502         print "cannot contact bitcoin daemon"
503         return
504     v = v['transactions']
505     for hextx in v:
506         ds.clear()
507         ds.write(hextx.decode('hex'))
508         tx = deserialize.parse_Transaction(ds)
509         tx['hash'] = util.double_sha256(tx['tx'])
510         if store.tx_find_id_and_value(tx):
511             pass
512         else:
513             #print "new tx", tx['hash'][::-1].encode('hex')
514             store.import_tx(tx, False)
515
516     store.commit()
517
518
519
520
521 def clean_session_thread():
522     while not stopping:
523         time.sleep(30)
524         t = time.time()
525         for k,s in sessions.items():
526             t0 = s['last_time']
527             if t - t0 > 5*60:
528                 print time.asctime(), "lost session",k
529                 sessions.pop(k)
530             
531
532 def irc_thread():
533     global peer_list
534     NICK = 'E_'+random_string(10)
535     while not stopping:
536         try:
537             s = socket.socket()
538             s.connect(('irc.freenode.net', 6667))
539             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
540             s.send('NICK '+NICK+'\n')
541             s.send('JOIN #electrum\n')
542             sf = s.makefile('r', 0)
543             t = 0
544             while not stopping:
545                 line = sf.readline()
546                 line = line.rstrip('\r\n')
547                 line = line.split()
548                 if line[0]=='PING': 
549                     s.send('PONG '+line[1]+'\n')
550                 elif '353' in line: # answer to /names
551                     k = line.index('353')
552                     for item in line[k+1:]:
553                         if item[0:2] == 'E_':
554                             s.send('WHO %s\n'%item)
555                 elif '352' in line: # answer to /who
556                     # warning: this is a horrible hack which apparently works
557                     k = line.index('352')
558                     ip = line[k+4]
559                     ip = socket.gethostbyname(ip)
560                     name = line[k+6]
561                     host = line[k+9]
562                     peer_list[name] = (ip,host)
563                 if time.time() - t > 5*60:
564                     s.send('NAMES #electrum\n')
565                     t = time.time()
566                     peer_list = {}
567         except:
568             traceback.print_exc(file=sys.stdout)
569         finally:
570             sf.close()
571             s.close()
572
573
574 import traceback
575
576
577 if __name__ == '__main__':
578
579     if len(sys.argv)>1:
580         cmd = sys.argv[1]
581         if cmd == 'load':
582             request = "('load','%s')#"%config.get('server','password')
583         elif cmd == 'peers':
584             request = "('peers','')#"
585         elif cmd == 'stop':
586             request = "('stop','%s')#"%config.get('server','password')
587         elif cmd == 'clear_cache':
588             request = "('clear_cache','%s')#"%config.get('server','password')
589         elif cmd == 'get_cache':
590             request = "('get_cache',('%s','%s'))#"%(config.get('server','password'),sys.argv[2])
591         elif cmd == 'h':
592             request = "('h','%s')#"%sys.argv[2]
593         elif cmd == 'b':
594             request = "('b','')#"
595
596         s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
597         s.connect((config.get('server','host'), config.getint('server','port')))
598         s.send( request )
599         out = ''
600         while 1:
601             msg = s.recv(1024)
602             if msg: out += msg
603             else: break
604         s.close()
605         print out
606         sys.exit(0)
607
608
609     print "starting Electrum server"
610     print "cache:", config.get('server', 'cache')
611
612     conf = DataStore.CONFIG_DEFAULTS
613     args, argv = readconf.parse_argv( [], conf)
614     args.dbtype= config.get('database','type')
615     if args.dbtype == 'sqlite3':
616         args.connect_args = { 'database' : config.get('database','database') }
617     elif args.dbtype == 'MySQLdb':
618         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
619     elif args.dbtype == 'psycopg2':
620         args.connect_args = { 'database' : config.get('database','database') }
621     store = MyStore(args)
622     store.tx_cache = {}
623     store.ismempool = False
624
625     thread.start_new_thread(listen_thread, (store,))
626     thread.start_new_thread(clean_session_thread, ())
627     if (config.get('server','irc') == 'yes' ):
628         thread.start_new_thread(irc_thread, ())
629
630     while not stopping:
631         try:
632             dblock.acquire()
633             store.catch_up()
634             store.ismempool = True
635             memorypool_update(store)
636             store.ismempool = False
637             block_number = store.get_block_number(1)
638             dblock.release()
639         except:
640             traceback.print_exc(file=sys.stdout)
641         time.sleep(10)
642
643     print "server stopped"
644