new protocol
[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, json, socket, operator, thread, ast, sys,re
29 import psycopg2, binascii
30
31 from Abe.abe import hash_to_address, decode_check_address
32 from Abe.DataStore import DataStore as Datastore_class
33 from Abe import DataStore, readconf, BCDataStream,  deserialize, util, base58
34
35 import ConfigParser
36 from json import dumps, loads
37 import urllib
38
39 # we need to import electrum
40 sys.path.append('../client/')
41 from wallet import Wallet
42 from interface import Interface
43
44
45 config = ConfigParser.ConfigParser()
46 # set some defaults, which will be overwritten by the config file
47 config.add_section('server')
48 config.set('server','banner', 'Welcome to Electrum!')
49 config.set('server', 'host', 'localhost')
50 config.set('server', 'port', 50000)
51 config.set('server', 'password', '')
52 config.set('server', 'irc', 'yes')
53 config.set('server', 'cache', 'no') 
54 config.set('server', 'ircname', 'Electrum server')
55 config.add_section('database')
56 config.set('database', 'type', 'psycopg2')
57 config.set('database', 'database', 'abe')
58
59 try:
60     f = open('/etc/electrum.conf','r')
61     config.readfp(f)
62     f.close()
63 except:
64     print "Could not read electrum.conf. I will use the default values."
65
66 try:
67     f = open('/etc/electrum.banner','r')
68     config.set('server','banner', f.read())
69     f.close()
70 except:
71     pass
72
73 password = config.get('server','password')
74 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
75
76 stopping = False
77 block_number = -1
78 sessions = {}
79 dblock = thread.allocate_lock()
80 peer_list = {}
81
82 wallets = {} # for ultra-light clients such as bccapi
83
84 class MyStore(Datastore_class):
85
86     def import_tx(self, tx, is_coinbase):
87         tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
88         if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
89
90     def update_tx_cache(self, txid):
91         inrows = self.get_tx_inputs(txid, False)
92         for row in inrows:
93             _hash = store.binout(row[6])
94             address = hash_to_address(chr(0), _hash)
95             if self.tx_cache.has_key(address):
96                 print "cache: invalidating", address
97                 self.tx_cache.pop(address)
98         outrows = self.get_tx_outputs(txid, False)
99         for row in outrows:
100             _hash = store.binout(row[6])
101             address = hash_to_address(chr(0), _hash)
102             if self.tx_cache.has_key(address):
103                 print "cache: invalidating", address
104                 self.tx_cache.pop(address)
105
106     def safe_sql(self,sql, params=(), lock=True):
107         try:
108             if lock: dblock.acquire()
109             ret = self.selectall(sql,params)
110             if lock: dblock.release()
111             return ret
112         except:
113             print "sql error", sql
114             return []
115
116     def get_tx_outputs(self, tx_id, lock=True):
117         return self.safe_sql("""SELECT
118                 txout.txout_pos,
119                 txout.txout_scriptPubKey,
120                 txout.txout_value,
121                 nexttx.tx_hash,
122                 nexttx.tx_id,
123                 txin.txin_pos,
124                 pubkey.pubkey_hash
125               FROM txout
126               LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
127               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
128               LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
129              WHERE txout.tx_id = %d 
130              ORDER BY txout.txout_pos
131         """%(tx_id), (), lock)
132
133     def get_tx_inputs(self, tx_id, lock=True):
134         return self.safe_sql(""" SELECT
135                 txin.txin_pos,
136                 txin.txin_scriptSig,
137                 txout.txout_value,
138                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
139                 prevtx.tx_id,
140                 COALESCE(txout.txout_pos, u.txout_pos),
141                 pubkey.pubkey_hash
142               FROM txin
143               LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
144               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
145               LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
146               LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
147              WHERE txin.tx_id = %d
148              ORDER BY txin.txin_pos
149              """%(tx_id,), (), lock)
150
151     def get_address_out_rows(self, dbhash):
152         return self.safe_sql(""" SELECT
153                 b.block_nTime,
154                 cc.chain_id,
155                 b.block_height,
156                 1,
157                 b.block_hash,
158                 tx.tx_hash,
159                 tx.tx_id,
160                 txin.txin_pos,
161                 -prevout.txout_value
162               FROM chain_candidate cc
163               JOIN block b ON (b.block_id = cc.block_id)
164               JOIN block_tx ON (block_tx.block_id = b.block_id)
165               JOIN tx ON (tx.tx_id = block_tx.tx_id)
166               JOIN txin ON (txin.tx_id = tx.tx_id)
167               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
168               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
169              WHERE pubkey.pubkey_hash = ?
170                AND cc.in_longest = 1""", (dbhash,))
171
172     def get_address_out_rows_memorypool(self, dbhash):
173         return self.safe_sql(""" SELECT
174                 1,
175                 tx.tx_hash,
176                 tx.tx_id,
177                 txin.txin_pos,
178                 -prevout.txout_value
179               FROM tx 
180               JOIN txin ON (txin.tx_id = tx.tx_id)
181               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
182               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
183              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
184
185     def get_address_in_rows(self, dbhash):
186         return self.safe_sql(""" SELECT
187                 b.block_nTime,
188                 cc.chain_id,
189                 b.block_height,
190                 0,
191                 b.block_hash,
192                 tx.tx_hash,
193                 tx.tx_id,
194                 txout.txout_pos,
195                 txout.txout_value
196               FROM chain_candidate cc
197               JOIN block b ON (b.block_id = cc.block_id)
198               JOIN block_tx ON (block_tx.block_id = b.block_id)
199               JOIN tx ON (tx.tx_id = block_tx.tx_id)
200               JOIN txout ON (txout.tx_id = tx.tx_id)
201               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
202              WHERE pubkey.pubkey_hash = ?
203                AND cc.in_longest = 1""", (dbhash,))
204
205     def get_address_in_rows_memorypool(self, dbhash):
206         return self.safe_sql( """ SELECT
207                 0,
208                 tx.tx_hash,
209                 tx.tx_id,
210                 txout.txout_pos,
211                 txout.txout_value
212               FROM tx
213               JOIN txout ON (txout.tx_id = tx.tx_id)
214               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
215              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
216
217     def get_history(self, addr):
218         
219         if config.get('server','cache') == 'yes':
220             cached_version = self.tx_cache.get( addr ) 
221             if cached_version is not None: 
222                 return cached_version
223
224         version, binaddr = decode_check_address(addr)
225         if binaddr is None:
226             return None
227
228         dbhash = self.binin(binaddr)
229         rows = []
230         rows += self.get_address_out_rows( dbhash )
231         rows += self.get_address_in_rows( dbhash )
232
233         txpoints = []
234         known_tx = []
235
236         for row in rows:
237             try:
238                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
239             except:
240                 print "cannot unpack row", row
241                 break
242             tx_hash = self.hashout_hex(tx_hash)
243             txpoint = {
244                     "nTime":    int(nTime),
245                     #"chain_id": int(chain_id),
246                     "height":   int(height),
247                     "is_in":    int(is_in),
248                     "blk_hash": self.hashout_hex(blk_hash),
249                     "tx_hash":  tx_hash,
250                     "tx_id":    int(tx_id),
251                     "pos":      int(pos),
252                     "value":    int(value),
253                     }
254
255             txpoints.append(txpoint)
256             known_tx.append(self.hashout_hex(tx_hash))
257
258
259         # todo: sort them really...
260         txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
261
262         # read memory pool
263         rows = []
264         rows += self.get_address_in_rows_memorypool( dbhash )
265         rows += self.get_address_out_rows_memorypool( dbhash )
266         address_has_mempool = False
267
268         for row in rows:
269             is_in, tx_hash, tx_id, pos, value = row
270             tx_hash = self.hashout_hex(tx_hash)
271             if tx_hash in known_tx:
272                 continue
273
274             # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
275             address_has_mempool = True
276
277             # this means pending transactions are returned by getmemorypool
278             if tx_hash not in self.mempool_keys:
279                 continue
280
281             #print "mempool", tx_hash
282             txpoint = {
283                     "nTime":    0,
284                     #"chain_id": 1,
285                     "height":   0,
286                     "is_in":    int(is_in),
287                     "blk_hash": 'mempool', 
288                     "tx_hash":  tx_hash,
289                     "tx_id":    int(tx_id),
290                     "pos":      int(pos),
291                     "value":    int(value),
292                     }
293             txpoints.append(txpoint)
294
295
296         for txpoint in txpoints:
297             tx_id = txpoint['tx_id']
298             
299             txinputs = []
300             inrows = self.get_tx_inputs(tx_id)
301             for row in inrows:
302                 _hash = self.binout(row[6])
303                 address = hash_to_address(chr(0), _hash)
304                 txinputs.append(address)
305             txpoint['inputs'] = txinputs
306             txoutputs = []
307             outrows = self.get_tx_outputs(tx_id)
308             for row in outrows:
309                 _hash = self.binout(row[6])
310                 address = hash_to_address(chr(0), _hash)
311                 txoutputs.append(address)
312             txpoint['outputs'] = txoutputs
313
314             # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
315             if not txpoint['is_in']:
316                 # detect if already redeemed...
317                 for row in outrows:
318                     if row[6] == dbhash: break
319                 else:
320                     raise
321                 #row = self.get_tx_output(tx_id,dbhash)
322                 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
323                 # if not redeemed, we add the script
324                 if row:
325                     if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
326
327         # cache result
328         if config.get('server','cache') == 'yes' and not address_has_mempool:
329             self.tx_cache[addr] = txpoints
330         
331         return txpoints
332
333
334
335 class Direct_Interface(Interface):
336     def __init__(self):
337         pass
338
339     def handler(self, method, params = ''):
340         cmds = {'session.new':new_session,
341                 'session.poll':poll_session,
342                 'session.update':update_session,
343                 'blockchain.transaction.broadcast':send_tx,
344                 'blockchain.address.get_history':store.get_history
345                 }
346         func = cmds[method]
347         return func( params )
348
349
350
351 def send_tx(tx):
352     postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
353     respdata = urllib.urlopen(bitcoind_url, postdata).read()
354     r = loads(respdata)
355     if r['error'] != None:
356         out = "error: transaction rejected by memorypool\n"+tx
357     else:
358         out = r['result']
359     return out
360
361
362
363 def random_string(N):
364     import random, string
365     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
366
367     
368
369 def cmd_stop(data):
370     global stopping
371     if password == data:
372         stopping = True
373         return 'ok'
374     else:
375         return 'wrong password'
376
377 def cmd_load(pw):
378     if password == pw:
379         return repr( len(sessions) )
380     else:
381         return 'wrong password'
382
383
384 def clear_cache(pw):
385     if password == pw:
386         store.tx_cache = {}
387         return 'ok'
388     else:
389         return 'wrong password'
390
391 def get_cache(pw,addr):
392     if password == pw:
393         return store.tx_cache.get(addr)
394     else:
395         return 'wrong password'
396
397
398 def poll_session(session_id):
399     session = sessions.get(session_id)
400     if session is None:
401         print time.asctime(), "session not found", session_id
402         out = repr( (-1, {}))
403     else:
404         t1 = time.time()
405         addresses = session['addresses']
406         session['last_time'] = time.time()
407         ret = {}
408         k = 0
409         for addr in addresses:
410             if store.tx_cache.get( addr ) is not None: k += 1
411
412             # get addtess status, i.e. the last block for that address.
413             tx_points = store.get_history(addr)
414             if not tx_points:
415                 status = None
416             else:
417                 lastpoint = tx_points[-1]
418                 status = lastpoint['blk_hash']
419                 # this is a temporary hack; move it up once old clients have disappeared
420                 if status == 'mempool' and session['version'] != "old":
421                     status = status + ':%d'% len(tx_points)
422
423             last_status = addresses.get( addr )
424             if last_status != status:
425                 addresses[addr] = status
426                 ret[addr] = status
427         if ret:
428             sessions[session_id]['addresses'] = addresses
429         out = repr( (block_number, ret ) )
430         t2 = time.time() - t1 
431         if t2 > 10:
432             print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
433
434         return out
435
436
437 def new_session(version, addresses):
438     session_id = random_string(10)
439     sessions[session_id] = { 'addresses':{}, 'version':version }
440     for a in addresses:
441         sessions[session_id]['addresses'][a] = ''
442     out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
443     sessions[session_id]['last_time'] = time.time()
444     return out
445
446 def subscribe_to_address(session_id, address):
447     sessions[session_id]['addresses'][address] = ''
448     sessions[session_id]['last_time'] = time.time()
449
450
451 def update_session(session_id,addresses):
452     sessions[session_id]['addresses'] = {}
453     for a in addresses:
454         sessions[session_id]['addresses'][a] = ''
455     sessions[session_id]['last_time'] = time.time()
456     return 'ok'
457
458 def native_server_thread():
459     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
460     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
461     s.bind((config.get('server','host'), config.getint('server','port')))
462     s.listen(1)
463     while not stopping:
464         conn, addr = s.accept()
465         try:
466             thread.start_new_thread(native_client_thread, (addr, conn,))
467         except:
468             # can't start new thread if there is no memory..
469             traceback.print_exc(file=sys.stdout)
470
471
472 def native_client_thread(ipaddr,conn):
473     #print "client thread", ipaddr
474     try:
475         ipaddr = ipaddr[0]
476         msg = ''
477         while 1:
478             d = conn.recv(1024)
479             msg += d
480             if not d: 
481                 break
482             if '#' in msg:
483                 msg = msg.split('#', 1)[0]
484                 break
485         try:
486             cmd, data = ast.literal_eval(msg)
487         except:
488             print "syntax error", repr(msg), ipaddr
489             conn.close()
490             return
491
492         out = do_command(cmd, data, ipaddr)
493         if out:
494             #print ipaddr, cmd, len(out)
495             try:
496                 conn.send(out)
497             except:
498                 print "error, could not send"
499
500     finally:
501         conn.close()
502
503
504
505 # used by the native handler
506 def do_command(cmd, data, ipaddr):
507
508     timestr = time.strftime("[%d/%m/%Y-%H:%M:%S]")
509
510     if cmd=='b':
511         out = "%d"%block_number
512
513     elif cmd in ['session','new_session']:
514         try:
515             if cmd == 'session':
516                 addresses = ast.literal_eval(data)
517                 version = "old"
518             else:
519                 version, addresses = ast.literal_eval(data)
520                 if version[0]=="0": version = "v" + version
521         except:
522             print "error", data
523             return None
524         print timestr, "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
525         out = new_session(version, addresses)
526
527     elif cmd=='update_session':
528         try:
529             session_id, addresses = ast.literal_eval(data)
530         except:
531             print "error"
532             return None
533         print timestr, "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
534         out = update_session(session_id,addresses)
535
536     elif cmd == 'bccapi_login':
537         import electrum
538         print "data",data
539         v, k = ast.literal_eval(data)
540         master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
541         print master_public_key
542         wallet_id = random_string(10)
543         w = Wallet( Direct_Interface() )
544         w.master_public_key = master_public_key.decode('hex')
545         w.synchronize()
546         wallets[wallet_id] = w
547         out = wallet_id
548         print "wallets", wallets
549
550     elif cmd == 'bccapi_getAccountInfo':
551         from wallet import int_to_hex
552         v, wallet_id = ast.literal_eval(data)
553         w = wallets.get(wallet_id)
554         if w is not None:
555             num = len(w.addresses)
556             c, u = w.get_balance()
557             out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
558             out = out.decode('hex')
559         else:
560             print "error",data
561             out = "error"
562
563     elif cmd == 'bccapi_getAccountStatement':
564         from wallet import int_to_hex
565         v, wallet_id = ast.literal_eval(data)
566         w = wallets.get(wallet_id)
567         if w is not None:
568             num = len(w.addresses)
569             c, u = w.get_balance()
570             total_records = num_records = 0
571             out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 ) + int_to_hex( total_records ) + int_to_hex( num_records )
572             out = out.decode('hex')
573         else:
574             print "error",data
575             out = "error"
576
577     elif cmd == 'bccapi_getSendCoinForm':
578         out = ''
579
580     elif cmd == 'bccapi_submitTransaction':
581         out = ''
582             
583     elif cmd=='poll': 
584         out = poll_session(data)
585
586     elif cmd == 'h': 
587         # history
588         address = data
589         out = repr( store.get_history( address ) )
590
591     elif cmd == 'load': 
592         out = cmd_load(data)
593
594     elif cmd =='tx':
595         out = send_tx(data)
596         print timestr, "sent tx:", ipaddr, out
597
598     elif cmd == 'stop':
599         out = cmd_stop(data)
600
601     elif cmd == 'peers':
602         out = repr(peer_list.values())
603
604     else:
605         out = None
606
607     return out
608
609
610
611 ####################################################################
612
613 def tcp_server_thread():
614     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
615     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
616     s.bind((config.get('server','host'), 50001))
617     s.listen(1)
618     while not stopping:
619         conn, addr = s.accept()
620         try:
621             thread.start_new_thread(tcp_client_thread, (addr, conn,))
622         except:
623             # can't start new thread if there is no memory..
624             traceback.print_exc(file=sys.stdout)
625
626
627
628 def tcp_client_thread(ipaddr,conn):
629     """ use a persistent connection. put commands in a queue."""
630     print "persistent client thread", ipaddr
631     global sessions
632
633     session_id = random_string(10)
634     sessions[session_id] = { 'addresses':{}, 'version':'unknown' }
635
636     ipaddr = ipaddr[0]
637     msg = ''
638
639     while True:
640         d = conn.recv(1024)
641         msg += d
642         if not d: break
643         while True:
644             s = msg.find('\n')
645             if s ==-1:
646                 break
647             else:
648                 c = msg[0:s]
649                 msg = msg[s+1:]
650                 c = json.loads(c)
651                 try:
652                     cmd = c['method']
653                     data = c['params']
654                 except:
655                     print "syntax error", repr(c), ipaddr
656                     continue
657
658                 out = None
659                 if cmd == 'blockchain.address.subscribe':
660                     subscribe_to_address(session_id,data)
661                 elif cmd == 'client.version':
662                     sessions[session_id]['version'] = data
663                 elif cmd == 'server.banner':
664                     out = json.dumps( { 'method':'server.banner', 'result':config.get('server','banner').replace('\\n','\n') } )
665                 else:
666                     print "unknown command", cmd
667
668                 if out:
669                     conn.send(out+'\n')
670
671
672
673 ####################################################################
674
675
676 def memorypool_update(store):
677     ds = BCDataStream.BCDataStream()
678     store.mempool_keys = []
679
680     postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
681     respdata = urllib.urlopen(bitcoind_url, postdata).read()
682     r = loads(respdata)
683     if r['error'] != None:
684         return
685
686     v = r['result'].get('transactions')
687     for hextx in v:
688         ds.clear()
689         ds.write(hextx.decode('hex'))
690         tx = deserialize.parse_Transaction(ds)
691         tx['hash'] = util.double_sha256(tx['tx'])
692         tx_hash = tx['hash'][::-1].encode('hex')
693         store.mempool_keys.append(tx_hash)
694         if store.tx_find_id_and_value(tx):
695             pass
696         else:
697             store.import_tx(tx, False)
698
699     store.commit()
700
701
702
703 def clean_session_thread():
704     while not stopping:
705         time.sleep(30)
706         t = time.time()
707         for k,s in sessions.items():
708             t0 = s['last_time']
709             if t - t0 > 5*60:
710                 sessions.pop(k)
711             
712
713 def irc_thread():
714     global peer_list
715     NICK = 'E_'+random_string(10)
716     while not stopping:
717         try:
718             s = socket.socket()
719             s.connect(('irc.freenode.net', 6667))
720             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
721             s.send('NICK '+NICK+'\n')
722             s.send('JOIN #electrum\n')
723             sf = s.makefile('r', 0)
724             t = 0
725             while not stopping:
726                 line = sf.readline()
727                 line = line.rstrip('\r\n')
728                 line = line.split()
729                 if line[0]=='PING': 
730                     s.send('PONG '+line[1]+'\n')
731                 elif '353' in line: # answer to /names
732                     k = line.index('353')
733                     for item in line[k+1:]:
734                         if item[0:2] == 'E_':
735                             s.send('WHO %s\n'%item)
736                 elif '352' in line: # answer to /who
737                     # warning: this is a horrible hack which apparently works
738                     k = line.index('352')
739                     ip = line[k+4]
740                     ip = socket.gethostbyname(ip)
741                     name = line[k+6]
742                     host = line[k+9]
743                     peer_list[name] = (ip,host)
744                 if time.time() - t > 5*60:
745                     s.send('NAMES #electrum\n')
746                     t = time.time()
747                     peer_list = {}
748         except:
749             traceback.print_exc(file=sys.stdout)
750         finally:
751             sf.close()
752             s.close()
753
754
755
756 def http_server_thread(store):
757     # see http://code.google.com/p/jsonrpclib/
758     from SocketServer import ThreadingMixIn
759     from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
760     class SimpleThreadedJSONRPCServer(ThreadingMixIn, SimpleJSONRPCServer): pass
761     server = SimpleThreadedJSONRPCServer(( config.get('server','host'), 8081))
762     server.register_function(lambda : peer_list.values(), 'peers')
763     server.register_function(cmd_stop, 'stop')
764     server.register_function(cmd_load, 'load')
765     server.register_function(lambda : block_number, 'blocks')
766     server.register_function(clear_cache, 'clear_cache')
767     server.register_function(get_cache, 'get_cache')
768     server.register_function(send_tx, 'blockchain.transaction.broadcast')
769     server.register_function(store.get_history, 'blockchain.address.get_history')
770     server.register_function(new_session, 'session.new')
771     server.register_function(update_session, 'session.update')
772     server.register_function(poll_session, 'session.poll')
773     server.serve_forever()
774
775
776 import traceback
777
778
779 if __name__ == '__main__':
780
781     if len(sys.argv)>1:
782         import jsonrpclib
783         server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
784         cmd = sys.argv[1]
785         if cmd == 'load':
786             out = server.load(password)
787         elif cmd == 'peers':
788             out = server.peers()
789         elif cmd == 'stop':
790             out = server.stop(password)
791         elif cmd == 'clear_cache':
792             out = server.clear_cache(password)
793         elif cmd == 'get_cache':
794             out = server.get_cache(password,sys.argv[2])
795         elif cmd == 'h':
796             out = server.blockchain.address.get_history(sys.argv[2])
797         elif cmd == 'tx':
798             out = server.blockchain.transaction.broadcast(sys.argv[2])
799         elif cmd == 'b':
800             out = server.blocks()
801         else:
802             out = "Unknown command: '%s'" % cmd
803         print out
804         sys.exit(0)
805
806
807     print "starting Electrum server"
808     print "cache:", config.get('server', 'cache')
809
810     conf = DataStore.CONFIG_DEFAULTS
811     args, argv = readconf.parse_argv( [], conf)
812     args.dbtype= config.get('database','type')
813     if args.dbtype == 'sqlite3':
814         args.connect_args = { 'database' : config.get('database','database') }
815     elif args.dbtype == 'MySQLdb':
816         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
817     elif args.dbtype == 'psycopg2':
818         args.connect_args = { 'database' : config.get('database','database') }
819     store = MyStore(args)
820     store.tx_cache = {}
821     store.mempool_keys = {}
822
823     # supported protocols
824     thread.start_new_thread(native_server_thread, ())
825     thread.start_new_thread(tcp_server_thread, ())
826     thread.start_new_thread(http_server_thread, (store,))
827
828     thread.start_new_thread(clean_session_thread, ())
829     if (config.get('server','irc') == 'yes' ):
830         thread.start_new_thread(irc_thread, ())
831
832     while not stopping:
833         try:
834             dblock.acquire()
835             store.catch_up()
836             memorypool_update(store)
837             block_number = store.get_block_number(1)
838         except IOError:
839             print "IOError: cannot reach bitcoind"
840             block_number = 0
841         except:
842             traceback.print_exc(file=sys.stdout)
843             block_number = 0
844         finally:
845             dblock.release()
846         time.sleep(10)
847
848     print "server stopped"
849