reduce verbosity
[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', 'ircname', 'Electrum server')
54 config.add_section('database')
55 config.set('database', 'type', 'psycopg2')
56 config.set('database', 'database', 'abe')
57
58 try:
59     f = open('/etc/electrum.conf','r')
60     config.readfp(f)
61     f.close()
62 except:
63     print "Could not read electrum.conf. I will use the default values."
64
65 try:
66     f = open('/etc/electrum.banner','r')
67     config.set('server','banner', f.read())
68     f.close()
69 except:
70     pass
71
72 password = config.get('server','password')
73 bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port'))
74
75 stopping = False
76 block_number = -1
77 old_block_number = -1
78 sessions = {}
79 sessions_sub_numblocks = {} # sessions that have subscribed to the service
80
81 m_sessions = [{}] # served by http
82
83 dblock = thread.allocate_lock()
84 peer_list = {}
85
86 wallets = {} # for ultra-light clients such as bccapi
87
88 from Queue import Queue
89 input_queue = Queue()
90 output_queue = Queue()
91 address_queue = Queue()
92
93
94
95 class MyStore(Datastore_class):
96
97     def import_block(self, b, chain_ids=frozenset()):
98         block_id = super(MyStore, self).import_block(b, chain_ids)
99         #print "block", block_id
100         for pos in xrange(len(b['transactions'])):
101             tx = b['transactions'][pos]
102             if 'hash' not in tx:
103                 tx['hash'] = util.double_sha256(tx['tx'])
104             tx_id = store.tx_find_id_and_value(tx)
105             if tx_id:
106                 self.update_tx_cache(tx_id)
107             else:
108                 print "error: import_block: no tx_id"
109         return block_id
110
111
112     def update_tx_cache(self, txid):
113         inrows = self.get_tx_inputs(txid, False)
114         for row in inrows:
115             _hash = store.binout(row[6])
116             address = hash_to_address(chr(0), _hash)
117             if self.tx_cache.has_key(address):
118                 print "cache: invalidating", address
119                 self.tx_cache.pop(address)
120             address_queue.put(address)
121
122         outrows = self.get_tx_outputs(txid, False)
123         for row in outrows:
124             _hash = store.binout(row[6])
125             address = hash_to_address(chr(0), _hash)
126             if self.tx_cache.has_key(address):
127                 print "cache: invalidating", address
128                 self.tx_cache.pop(address)
129             address_queue.put(address)
130
131     def safe_sql(self,sql, params=(), lock=True):
132         try:
133             if lock: dblock.acquire()
134             ret = self.selectall(sql,params)
135             if lock: dblock.release()
136             return ret
137         except:
138             print "sql error", sql
139             return []
140
141     def get_tx_outputs(self, tx_id, lock=True):
142         return self.safe_sql("""SELECT
143                 txout.txout_pos,
144                 txout.txout_scriptPubKey,
145                 txout.txout_value,
146                 nexttx.tx_hash,
147                 nexttx.tx_id,
148                 txin.txin_pos,
149                 pubkey.pubkey_hash
150               FROM txout
151               LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
152               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
153               LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
154              WHERE txout.tx_id = %d 
155              ORDER BY txout.txout_pos
156         """%(tx_id), (), lock)
157
158     def get_tx_inputs(self, tx_id, lock=True):
159         return self.safe_sql(""" SELECT
160                 txin.txin_pos,
161                 txin.txin_scriptSig,
162                 txout.txout_value,
163                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
164                 prevtx.tx_id,
165                 COALESCE(txout.txout_pos, u.txout_pos),
166                 pubkey.pubkey_hash
167               FROM txin
168               LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
169               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
170               LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
171               LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
172              WHERE txin.tx_id = %d
173              ORDER BY txin.txin_pos
174              """%(tx_id,), (), lock)
175
176     def get_address_out_rows(self, dbhash):
177         return self.safe_sql(""" SELECT
178                 b.block_nTime,
179                 cc.chain_id,
180                 b.block_height,
181                 1,
182                 b.block_hash,
183                 tx.tx_hash,
184                 tx.tx_id,
185                 txin.txin_pos,
186                 -prevout.txout_value
187               FROM chain_candidate cc
188               JOIN block b ON (b.block_id = cc.block_id)
189               JOIN block_tx ON (block_tx.block_id = b.block_id)
190               JOIN tx ON (tx.tx_id = block_tx.tx_id)
191               JOIN txin ON (txin.tx_id = tx.tx_id)
192               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
193               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
194              WHERE pubkey.pubkey_hash = ?
195                AND cc.in_longest = 1""", (dbhash,))
196
197     def get_address_out_rows_memorypool(self, dbhash):
198         return self.safe_sql(""" SELECT
199                 1,
200                 tx.tx_hash,
201                 tx.tx_id,
202                 txin.txin_pos,
203                 -prevout.txout_value
204               FROM tx 
205               JOIN txin ON (txin.tx_id = tx.tx_id)
206               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
207               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
208              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
209
210     def get_address_in_rows(self, dbhash):
211         return self.safe_sql(""" SELECT
212                 b.block_nTime,
213                 cc.chain_id,
214                 b.block_height,
215                 0,
216                 b.block_hash,
217                 tx.tx_hash,
218                 tx.tx_id,
219                 txout.txout_pos,
220                 txout.txout_value
221               FROM chain_candidate cc
222               JOIN block b ON (b.block_id = cc.block_id)
223               JOIN block_tx ON (block_tx.block_id = b.block_id)
224               JOIN tx ON (tx.tx_id = block_tx.tx_id)
225               JOIN txout ON (txout.tx_id = tx.tx_id)
226               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
227              WHERE pubkey.pubkey_hash = ?
228                AND cc.in_longest = 1""", (dbhash,))
229
230     def get_address_in_rows_memorypool(self, dbhash):
231         return self.safe_sql( """ SELECT
232                 0,
233                 tx.tx_hash,
234                 tx.tx_id,
235                 txout.txout_pos,
236                 txout.txout_value
237               FROM tx
238               JOIN txout ON (txout.tx_id = tx.tx_id)
239               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
240              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
241
242     def get_history(self, addr):
243         
244         cached_version = self.tx_cache.get( addr )
245         if cached_version is not None:
246             return cached_version
247
248         version, binaddr = decode_check_address(addr)
249         if binaddr is None:
250             return None
251
252         dbhash = self.binin(binaddr)
253         rows = []
254         rows += self.get_address_out_rows( dbhash )
255         rows += self.get_address_in_rows( dbhash )
256
257         txpoints = []
258         known_tx = []
259
260         for row in rows:
261             try:
262                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
263             except:
264                 print "cannot unpack row", row
265                 break
266             tx_hash = self.hashout_hex(tx_hash)
267             txpoint = {
268                     "nTime":    int(nTime),
269                     "height":   int(height),
270                     "is_in":    int(is_in),
271                     "blk_hash": self.hashout_hex(blk_hash),
272                     "tx_hash":  tx_hash,
273                     "tx_id":    int(tx_id),
274                     "pos":      int(pos),
275                     "value":    int(value),
276                     }
277
278             txpoints.append(txpoint)
279             known_tx.append(self.hashout_hex(tx_hash))
280
281
282         # todo: sort them really...
283         txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
284
285         # read memory pool
286         rows = []
287         rows += self.get_address_in_rows_memorypool( dbhash )
288         rows += self.get_address_out_rows_memorypool( dbhash )
289         address_has_mempool = False
290
291         for row in rows:
292             is_in, tx_hash, tx_id, pos, value = row
293             tx_hash = self.hashout_hex(tx_hash)
294             if tx_hash in known_tx:
295                 continue
296
297             # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
298             address_has_mempool = True
299
300             # this means pending transactions are returned by getmemorypool
301             if tx_hash not in self.mempool_keys:
302                 continue
303
304             #print "mempool", tx_hash
305             txpoint = {
306                     "nTime":    0,
307                     "height":   0,
308                     "is_in":    int(is_in),
309                     "blk_hash": 'mempool', 
310                     "tx_hash":  tx_hash,
311                     "tx_id":    int(tx_id),
312                     "pos":      int(pos),
313                     "value":    int(value),
314                     }
315             txpoints.append(txpoint)
316
317
318         for txpoint in txpoints:
319             tx_id = txpoint['tx_id']
320             
321             txinputs = []
322             inrows = self.get_tx_inputs(tx_id)
323             for row in inrows:
324                 _hash = self.binout(row[6])
325                 address = hash_to_address(chr(0), _hash)
326                 txinputs.append(address)
327             txpoint['inputs'] = txinputs
328             txoutputs = []
329             outrows = self.get_tx_outputs(tx_id)
330             for row in outrows:
331                 _hash = self.binout(row[6])
332                 address = hash_to_address(chr(0), _hash)
333                 txoutputs.append(address)
334             txpoint['outputs'] = txoutputs
335
336             # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
337             if not txpoint['is_in']:
338                 # detect if already redeemed...
339                 for row in outrows:
340                     if row[6] == dbhash: break
341                 else:
342                     raise
343                 #row = self.get_tx_output(tx_id,dbhash)
344                 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
345                 # if not redeemed, we add the script
346                 if row:
347                     if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
348
349         # cache result
350         if not address_has_mempool:
351             self.tx_cache[addr] = txpoints
352         
353         return txpoints
354
355
356
357 class Direct_Interface(Interface):
358     def __init__(self):
359         pass
360
361     def handler(self, method, params = ''):
362         cmds = {'session.new':new_session,
363                 'session.poll':poll_session,
364                 'session.update':update_session,
365                 'transaction.broadcast':send_tx,
366                 'address.get_history':store.get_history
367                 }
368         func = cmds[method]
369         return func( params )
370
371
372
373 def send_tx(tx):
374     postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'})
375     respdata = urllib.urlopen(bitcoind_url, postdata).read()
376     r = loads(respdata)
377     if r['error'] != None:
378         out = "error: transaction rejected by memorypool\n"+tx
379     else:
380         out = r['result']
381     return out
382
383
384
385 def random_string(N):
386     import random, string
387     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
388
389     
390
391 def cmd_stop(_,__,pw):
392     global stopping
393     if password == pw:
394         stopping = True
395         return 'ok'
396     else:
397         return 'wrong password'
398
399 def cmd_load(_,__,pw):
400     if password == pw:
401         return repr( len(sessions) )
402     else:
403         return 'wrong password'
404
405
406 def clear_cache(_,__,pw):
407     if password == pw:
408         store.tx_cache = {}
409         return 'ok'
410     else:
411         return 'wrong password'
412
413 def get_cache(_,__,pw,addr):
414     if password == pw:
415         return store.tx_cache.get(addr)
416     else:
417         return 'wrong password'
418
419
420
421
422 def modified_addresses(session):
423     if 1:
424         t1 = time.time()
425         addresses = session['addresses']
426         session['last_time'] = time.time()
427         ret = {}
428         k = 0
429         for addr in addresses:
430             if store.tx_cache.get( addr ) is not None: k += 1
431             status = get_address_status( addr )
432             msg_id, last_status = addresses.get( addr )
433             if last_status != status:
434                 addresses[addr] = msg_id, status
435                 ret[addr] = status
436
437         t2 = time.time() - t1 
438         #if t2 > 10: print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
439         return ret, addresses
440
441
442 def poll_session(session_id): 
443     # native
444     session = sessions.get(session_id)
445     if session is None:
446         print time.asctime(), "session not found", session_id
447         return -1, {}
448     else:
449         ret, addresses = modified_addresses(session)
450         if ret: sessions[session_id]['addresses'] = addresses
451         return repr( (block_number,ret))
452
453
454 def poll_session_json(session_id, message_id):
455     session = m_sessions[0].get(session_id)
456     if session is None:
457         raise BaseException("session not found %s"%session_id)
458     else:
459         out = []
460         ret, addresses = modified_addresses(session)
461         if ret: 
462             m_sessions[0][session_id]['addresses'] = addresses
463             for addr in ret:
464                 msg_id, status = addresses[addr]
465                 out.append(  { 'id':msg_id, 'result':status } )
466
467         msg_id, last_nb = session.get('numblocks')
468         if last_nb:
469             if last_nb != block_number:
470                 m_sessions[0][session_id]['numblocks'] = msg_id, block_number
471                 out.append( {'id':msg_id, 'result':block_number} )
472
473         return out
474
475
476 def do_update_address(addr):
477     # an address was involved in a transaction; we check if it was subscribed to in a session
478     # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
479
480     for session_id in sessions.keys():
481         session = sessions[session_id]
482         if session.get('type') != 'persistent': continue
483         addresses = session['addresses'].keys()
484
485         if addr in addresses:
486             status = get_address_status( addr )
487             message_id, last_status = session['addresses'][addr]
488             if last_status != status:
489                 #print "sending new status for %s:"%addr, status
490                 send_status(session_id,message_id,addr,status)
491                 sessions[session_id]['addresses'][addr] = (message_id,status)
492
493 def get_address_status(addr):
494     # get address status, i.e. the last block for that address.
495     tx_points = store.get_history(addr)
496     if not tx_points:
497         status = None
498     else:
499         lastpoint = tx_points[-1]
500         status = lastpoint['blk_hash']
501         # this is a temporary hack; move it up once old clients have disappeared
502         if status == 'mempool': # and session['version'] != "old":
503             status = status + ':%d'% len(tx_points)
504     return status
505
506
507 def send_numblocks(session_id):
508     message_id = sessions_sub_numblocks[session_id]
509     out = json.dumps( {'id':message_id, 'result':block_number} )
510     output_queue.put((session_id, out))
511
512 def send_status(session_id, message_id, address, status):
513     out = json.dumps( { 'id':message_id, 'result':status } )
514     output_queue.put((session_id, out))
515
516 def address_get_history_json(_,message_id,address):
517     return store.get_history(address)
518
519 def subscribe_to_numblocks(session_id, message_id):
520     sessions_sub_numblocks[session_id] = message_id
521     send_numblocks(session_id)
522
523 def subscribe_to_numblocks_json(session_id, message_id):
524     global m_sessions
525     m_sessions[0][session_id]['numblocks'] = message_id,block_number
526     return block_number
527
528 def subscribe_to_address(session_id, message_id, address):
529     status = get_address_status(address)
530     sessions[session_id]['addresses'][address] = (message_id, status)
531     sessions[session_id]['last_time'] = time.time()
532     send_status(session_id, message_id, address, status)
533
534 def add_address_to_session_json(session_id, message_id, address):
535     global m_sessions
536     sessions = m_sessions[0]
537     status = get_address_status(address)
538     sessions[session_id]['addresses'][address] = (message_id, status)
539     sessions[session_id]['last_time'] = time.time()
540     m_sessions[0] = sessions
541     return status
542
543 def add_address_to_session(session_id, address):
544     status = get_address_status(address)
545     sessions[session_id]['addresses'][addr] = ("", status)
546     sessions[session_id]['last_time'] = time.time()
547     return status
548
549 def new_session(version, addresses):
550     session_id = random_string(10)
551     sessions[session_id] = { 'addresses':{}, 'version':version }
552     for a in addresses:
553         sessions[session_id]['addresses'][a] = ('','')
554     out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
555     sessions[session_id]['last_time'] = time.time()
556     return out
557
558
559 def client_version_json(session_id, _, version):
560     global m_sessions
561     sessions = m_sessions[0]
562     sessions[session_id]['version'] = version
563     m_sessions[0] = sessions
564
565 def create_session_json(_, __):
566     sessions = m_sessions[0]
567     session_id = random_string(10)
568     print "creating session", session_id
569     sessions[session_id] = { 'addresses':{}, 'numblocks':('','') }
570     sessions[session_id]['last_time'] = time.time()
571     m_sessions[0] = sessions
572     return session_id
573
574
575
576 def get_banner(_,__):
577     return config.get('server','banner').replace('\\n','\n')
578
579 def update_session(session_id,addresses):
580     """deprecated in 0.42"""
581     sessions[session_id]['addresses'] = {}
582     for a in addresses:
583         sessions[session_id]['addresses'][a] = ''
584     sessions[session_id]['last_time'] = time.time()
585     return 'ok'
586
587 def native_server_thread():
588     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
589     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
590     s.bind((config.get('server','host'), config.getint('server','port')))
591     s.listen(1)
592     while not stopping:
593         conn, addr = s.accept()
594         try:
595             thread.start_new_thread(native_client_thread, (addr, conn,))
596         except:
597             # can't start new thread if there is no memory..
598             traceback.print_exc(file=sys.stdout)
599
600
601 def native_client_thread(ipaddr,conn):
602     #print "client thread", ipaddr
603     try:
604         ipaddr = ipaddr[0]
605         msg = ''
606         while 1:
607             d = conn.recv(1024)
608             msg += d
609             if not d: 
610                 break
611             if '#' in msg:
612                 msg = msg.split('#', 1)[0]
613                 break
614         try:
615             cmd, data = ast.literal_eval(msg)
616         except:
617             print "syntax error", repr(msg), ipaddr
618             conn.close()
619             return
620
621         out = do_command(cmd, data, ipaddr)
622         if out:
623             #print ipaddr, cmd, len(out)
624             try:
625                 conn.send(out)
626             except:
627                 print "error, could not send"
628
629     finally:
630         conn.close()
631
632
633 def timestr():
634     return time.strftime("[%d/%m/%Y-%H:%M:%S]")
635
636 # used by the native handler
637 def do_command(cmd, data, ipaddr):
638
639     if cmd=='b':
640         out = "%d"%block_number
641
642     elif cmd in ['session','new_session']:
643         try:
644             if cmd == 'session':
645                 addresses = ast.literal_eval(data)
646                 version = "old"
647             else:
648                 version, addresses = ast.literal_eval(data)
649                 if version[0]=="0": version = "v" + version
650         except:
651             print "error", data
652             return None
653         print timestr(), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
654         out = new_session(version, addresses)
655
656     elif cmd=='address.subscribe':
657         try:
658             session_id, addr = ast.literal_eval(data)
659         except:
660             print "error"
661             return None
662         out = add_address_to_session(session_id,addr)
663
664     elif cmd=='update_session':
665         try:
666             session_id, addresses = ast.literal_eval(data)
667         except:
668             print "error"
669             return None
670         print timestr(), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
671         out = update_session(session_id,addresses)
672
673     elif cmd == 'bccapi_login':
674         import electrum
675         print "data",data
676         v, k = ast.literal_eval(data)
677         master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
678         print master_public_key
679         wallet_id = random_string(10)
680         w = Wallet( Direct_Interface() )
681         w.master_public_key = master_public_key.decode('hex')
682         w.synchronize()
683         wallets[wallet_id] = w
684         out = wallet_id
685         print "wallets", wallets
686
687     elif cmd == 'bccapi_getAccountInfo':
688         from wallet import int_to_hex
689         v, wallet_id = ast.literal_eval(data)
690         w = wallets.get(wallet_id)
691         if w is not None:
692             num = len(w.addresses)
693             c, u = w.get_balance()
694             out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
695             out = out.decode('hex')
696         else:
697             print "error",data
698             out = "error"
699
700     elif cmd == 'bccapi_getAccountStatement':
701         from wallet import int_to_hex
702         v, wallet_id = ast.literal_eval(data)
703         w = wallets.get(wallet_id)
704         if w is not None:
705             num = len(w.addresses)
706             c, u = w.get_balance()
707             total_records = num_records = 0
708             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 )
709             out = out.decode('hex')
710         else:
711             print "error",data
712             out = "error"
713
714     elif cmd == 'bccapi_getSendCoinForm':
715         out = ''
716
717     elif cmd == 'bccapi_submitTransaction':
718         out = ''
719             
720     elif cmd=='poll': 
721         out = poll_session(data)
722
723     elif cmd == 'h': 
724         # history
725         address = data
726         out = repr( store.get_history( address ) )
727
728     elif cmd == 'load': 
729         out = cmd_load(data)
730
731     elif cmd =='tx':
732         out = send_tx(data)
733         print timestr(), "sent tx:", ipaddr, out
734
735     elif cmd == 'stop':
736         out = cmd_stop(data)
737
738     elif cmd == 'peers':
739         out = repr(peer_list.values())
740
741     else:
742         out = None
743
744     return out
745
746
747
748 ####################################################################
749
750 def tcp_server_thread():
751     thread.start_new_thread(process_input_queue, ())
752     thread.start_new_thread(process_output_queue, ())
753
754     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
755     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
756     s.bind((config.get('server','host'), 50001))
757     s.listen(1)
758     while not stopping:
759         conn, addr = s.accept()
760         try:
761             thread.start_new_thread(tcp_client_thread, (addr, conn,))
762         except:
763             # can't start new thread if there is no memory..
764             traceback.print_exc(file=sys.stdout)
765
766
767 def close_session(session_id):
768     #print "lost connection", session_id
769     sessions.pop(session_id)
770     if session_id in sessions_sub_numblocks:
771         sessions_sub_numblocks.pop(session_id)
772
773
774 # one thread per client. put requests in a queue.
775 def tcp_client_thread(ipaddr,conn):
776     """ use a persistent connection. put commands in a queue."""
777
778     print timestr(), "TCP session", ipaddr
779     global sessions
780
781     session_id = random_string(10)
782     sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown', 'type':'persistent' }
783
784     ipaddr = ipaddr[0]
785     msg = ''
786
787     while not stopping:
788         try:
789             d = conn.recv(1024)
790         except socket.error:
791             d = ''
792         if not d:
793             close_session(session_id)
794             break
795
796         msg += d
797         while True:
798             s = msg.find('\n')
799             if s ==-1:
800                 break
801             else:
802                 c = msg[0:s].strip()
803                 msg = msg[s+1:]
804                 if c == 'quit': 
805                     conn.close()
806                     close_session(session_id)
807                     return
808                 try:
809                     c = json.loads(c)
810                 except:
811                     print "json error", repr(c)
812                     continue
813                 try:
814                     message_id = c.get('id')
815                     method = c.get('method')
816                     params = c.get('params')
817                 except:
818                     print "syntax error", repr(c), ipaddr
819                     continue
820
821                 # add to queue
822                 input_queue.put((session_id, message_id, method, params))
823
824
825
826 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
827 def process_input_queue():
828     while not stopping:
829         session_id, message_id, method, data = input_queue.get()
830         if session_id not in sessions.keys():
831             continue
832         out = None
833         if method == 'address.subscribe':
834             address = data[0]
835             subscribe_to_address(session_id,message_id,address)
836         elif method == 'numblocks.subscribe':
837             subscribe_to_numblocks(session_id,message_id)
838         elif method == 'client.version':
839             sessions[session_id]['version'] = data[0]
840         elif method == 'server.banner':
841             out = { 'result':config.get('server','banner').replace('\\n','\n') } 
842         elif method == 'server.peers':
843             out = { 'result':peer_list.values() } 
844         elif method == 'address.get_history':
845             address = data[0]
846             out = { 'result':store.get_history( address ) } 
847         elif method == 'transaction.broadcast':
848             postdata = dumps({"method": 'importtransaction', 'params': [data], 'id':'jsonrpc'})
849             txo = urllib.urlopen(bitcoind_url, postdata).read()
850             print "sent tx:", txo
851             out = json.loads(txo)
852         else:
853             print "unknown command", method
854         if out:
855             out['id'] = message_id
856             out = json.dumps( out )
857             output_queue.put((session_id, out))
858
859 # this is a separate thread
860 def process_output_queue():
861     while not stopping:
862         session_id, out = output_queue.get()
863         session = sessions.get(session_id)
864         if session: 
865             try:
866                 conn = session.get('conn')
867                 conn.send(out+'\n')
868             except:
869                 close_session(session_id)
870                 
871
872
873
874 ####################################################################
875
876
877 def memorypool_update(store):
878
879     ds = BCDataStream.BCDataStream()
880     previous_transactions = store.mempool_keys
881     store.mempool_keys = []
882
883     postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
884     respdata = urllib.urlopen(bitcoind_url, postdata).read()
885     r = loads(respdata)
886     if r['error'] != None:
887         return
888
889     v = r['result'].get('transactions')
890     for hextx in v:
891         ds.clear()
892         ds.write(hextx.decode('hex'))
893         tx = deserialize.parse_Transaction(ds)
894         tx['hash'] = util.double_sha256(tx['tx'])
895         tx_hash = store.hashin(tx['hash'])
896
897         store.mempool_keys.append(tx_hash)
898         if store.tx_find_id_and_value(tx):
899             pass
900         else:
901             tx_id = store.import_tx(tx, False)
902             store.update_tx_cache(tx_id)
903
904     store.commit()
905
906
907 def clean_session_thread():
908     while not stopping:
909         time.sleep(30)
910         t = time.time()
911         for k,s in sessions.items():
912             if s.get('type') == 'persistent': continue
913             t0 = s['last_time']
914             if t - t0 > 5*60:
915                 sessions.pop(k)
916                 print "lost session", k
917             
918
919 def irc_thread():
920     global peer_list
921     NICK = 'E_'+random_string(10)
922     while not stopping:
923         try:
924             s = socket.socket()
925             s.connect(('irc.freenode.net', 6667))
926             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
927             s.send('NICK '+NICK+'\n')
928             s.send('JOIN #electrum\n')
929             sf = s.makefile('r', 0)
930             t = 0
931             while not stopping:
932                 line = sf.readline()
933                 line = line.rstrip('\r\n')
934                 line = line.split()
935                 if line[0]=='PING': 
936                     s.send('PONG '+line[1]+'\n')
937                 elif '353' in line: # answer to /names
938                     k = line.index('353')
939                     for item in line[k+1:]:
940                         if item[0:2] == 'E_':
941                             s.send('WHO %s\n'%item)
942                 elif '352' in line: # answer to /who
943                     # warning: this is a horrible hack which apparently works
944                     k = line.index('352')
945                     ip = line[k+4]
946                     ip = socket.gethostbyname(ip)
947                     name = line[k+6]
948                     host = line[k+9]
949                     peer_list[name] = (ip,host)
950                 if time.time() - t > 5*60:
951                     s.send('NAMES #electrum\n')
952                     t = time.time()
953                     peer_list = {}
954         except:
955             traceback.print_exc(file=sys.stdout)
956         finally:
957             sf.close()
958             s.close()
959
960
961 def get_peers_json(_,__):
962     return peer_list.values()
963
964 def http_server_thread(store):
965     # see http://code.google.com/p/jsonrpclib/
966     from SocketServer import ThreadingMixIn
967     from StratumJSONRPCServer import StratumJSONRPCServer
968     class StratumThreadedJSONRPCServer(ThreadingMixIn, StratumJSONRPCServer): pass
969     server = StratumThreadedJSONRPCServer(( config.get('server','host'), 8081))
970     server.register_function(get_peers_json, 'server.peers')
971     server.register_function(cmd_stop, 'stop')
972     server.register_function(cmd_load, 'load')
973     server.register_function(clear_cache, 'clear_cache')
974     server.register_function(get_cache, 'get_cache')
975     server.register_function(get_banner, 'server.banner')
976     server.register_function(lambda a,b,c: send_tx(c), 'transaction.broadcast')
977     server.register_function(address_get_history_json, 'address.get_history')
978     server.register_function(add_address_to_session_json, 'address.subscribe')
979     server.register_function(subscribe_to_numblocks_json, 'numblocks.subscribe')
980     server.register_function(client_version_json, 'client.version')
981     server.register_function(create_session_json, 'session.create')   # internal message (not part of protocol)
982     server.register_function(poll_session_json, 'session.poll')       # internal message (not part of protocol)
983     server.serve_forever()
984
985
986 import traceback
987
988
989 if __name__ == '__main__':
990
991     if len(sys.argv)>1:
992         import jsonrpclib
993         server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
994         cmd = sys.argv[1]
995         if cmd == 'load':
996             out = server.load(password)
997         elif cmd == 'peers':
998             out = server.server.peers()
999         elif cmd == 'stop':
1000             out = server.stop(password)
1001         elif cmd == 'clear_cache':
1002             out = server.clear_cache(password)
1003         elif cmd == 'get_cache':
1004             out = server.get_cache(password,sys.argv[2])
1005         elif cmd == 'h':
1006             out = server.address.get_history(sys.argv[2])
1007         elif cmd == 'tx':
1008             out = server.transaction.broadcast(sys.argv[2])
1009         elif cmd == 'b':
1010             out = server.numblocks.subscribe()
1011         else:
1012             out = "Unknown command: '%s'" % cmd
1013         print out
1014         sys.exit(0)
1015
1016
1017     print "starting Electrum server"
1018
1019     conf = DataStore.CONFIG_DEFAULTS
1020     args, argv = readconf.parse_argv( [], conf)
1021     args.dbtype= config.get('database','type')
1022     if args.dbtype == 'sqlite3':
1023         args.connect_args = { 'database' : config.get('database','database') }
1024     elif args.dbtype == 'MySQLdb':
1025         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
1026     elif args.dbtype == 'psycopg2':
1027         args.connect_args = { 'database' : config.get('database','database') }
1028     store = MyStore(args)
1029     store.tx_cache = {}
1030     store.mempool_keys = {}
1031
1032     # supported protocols
1033     thread.start_new_thread(native_server_thread, ())
1034     thread.start_new_thread(tcp_server_thread, ())
1035     thread.start_new_thread(http_server_thread, (store,))
1036
1037     thread.start_new_thread(clean_session_thread, ())
1038
1039     if (config.get('server','irc') == 'yes' ):
1040         thread.start_new_thread(irc_thread, ())
1041
1042     while not stopping:
1043         try:
1044             dblock.acquire()
1045             store.catch_up()
1046             memorypool_update(store)
1047
1048             block_number = store.get_block_number(1)
1049             if block_number != old_block_number:
1050                 old_block_number = block_number
1051                 for session_id in sessions_sub_numblocks.keys():
1052                     send_numblocks(session_id)
1053
1054         except IOError:
1055             print "IOError: cannot reach bitcoind"
1056             block_number = 0
1057         except:
1058             traceback.print_exc(file=sys.stdout)
1059             block_number = 0
1060         finally:
1061             dblock.release()
1062
1063         # do addresses
1064         while True:
1065             try:
1066                 addr = address_queue.get(False)
1067             except:
1068                 break
1069             do_update_address(addr)
1070
1071         time.sleep(10)
1072
1073     print "server stopped"
1074