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