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, 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         print "poll: session found", session_id
460         out = []
461         ret, addresses = modified_addresses(session)
462         if ret: 
463             m_sessions[0][session_id]['addresses'] = addresses
464             for addr in ret:
465                 msg_id, status = addresses[addr]
466                 out.append(  { 'id':msg_id, 'result':status } )
467
468         msg_id, last_nb = session.get('numblocks')
469         if last_nb:
470             if last_nb != block_number:
471                 m_sessions[0][session_id]['numblocks'] = msg_id, block_number
472                 out.append( {'id':msg_id, 'result':block_number} )
473
474         return out
475
476
477 def do_update_address(addr):
478     # an address was involved in a transaction; we check if it was subscribed to in a session
479     # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests
480
481     for session_id in sessions.keys():
482         session = sessions[session_id]
483         if session.get('type') != 'persistent': continue
484         addresses = session['addresses'].keys()
485
486         if addr in addresses:
487             status = get_address_status( addr )
488             message_id, last_status = session['addresses'][addr]
489             if last_status != status:
490                 #print "sending new status for %s:"%addr, status
491                 send_status(session_id,message_id,addr,status)
492                 sessions[session_id]['addresses'][addr] = (message_id,status)
493
494 def get_address_status(addr):
495     # get address status, i.e. the last block for that address.
496     tx_points = store.get_history(addr)
497     if not tx_points:
498         status = None
499     else:
500         lastpoint = tx_points[-1]
501         status = lastpoint['blk_hash']
502         # this is a temporary hack; move it up once old clients have disappeared
503         if status == 'mempool': # and session['version'] != "old":
504             status = status + ':%d'% len(tx_points)
505     return status
506
507
508 def send_numblocks(session_id):
509     message_id = sessions_sub_numblocks[session_id]
510     out = json.dumps( {'id':message_id, 'result':block_number} )
511     output_queue.put((session_id, out))
512
513 def send_status(session_id, message_id, address, status):
514     out = json.dumps( { 'id':message_id, 'result':status } )
515     output_queue.put((session_id, out))
516
517 def address_get_history_json(_,message_id,address):
518     return store.get_history(address)
519
520 def subscribe_to_numblocks(session_id, message_id):
521     sessions_sub_numblocks[session_id] = message_id
522     send_numblocks(session_id)
523
524 def subscribe_to_numblocks_json(session_id, message_id):
525     global m_sessions
526     m_sessions[0][session_id]['numblocks'] = message_id,block_number
527     return block_number
528
529 def subscribe_to_address(session_id, message_id, address):
530     status = get_address_status(address)
531     sessions[session_id]['addresses'][address] = (message_id, status)
532     sessions[session_id]['last_time'] = time.time()
533     send_status(session_id, message_id, address, status)
534
535 def add_address_to_session_json(session_id, message_id, address):
536     global m_sessions
537     sessions = m_sessions[0]
538     status = get_address_status(address)
539     sessions[session_id]['addresses'][address] = (message_id, status)
540     sessions[session_id]['last_time'] = time.time()
541     m_sessions[0] = sessions
542     return status
543
544 def add_address_to_session(session_id, address):
545     status = get_address_status(address)
546     sessions[session_id]['addresses'][addr] = ("", status)
547     sessions[session_id]['last_time'] = time.time()
548     return status
549
550 def new_session(version, addresses):
551     session_id = random_string(10)
552     sessions[session_id] = { 'addresses':{}, 'version':version }
553     for a in addresses:
554         sessions[session_id]['addresses'][a] = ('','')
555     out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
556     sessions[session_id]['last_time'] = time.time()
557     return out
558
559
560 def client_version_json(session_id, _, version):
561     global m_sessions
562     sessions = m_sessions[0]
563     sessions[session_id]['version'] = version
564     m_sessions[0] = sessions
565
566 def create_session_json(_, __):
567     sessions = m_sessions[0]
568     session_id = random_string(10)
569     print "creating session", session_id
570     sessions[session_id] = { 'addresses':{}, 'numblocks':('','') }
571     sessions[session_id]['last_time'] = time.time()
572     m_sessions[0] = sessions
573     return session_id
574
575
576
577 def get_banner(_,__):
578     return config.get('server','banner').replace('\\n','\n')
579
580 def update_session(session_id,addresses):
581     """deprecated in 0.42"""
582     sessions[session_id]['addresses'] = {}
583     for a in addresses:
584         sessions[session_id]['addresses'][a] = ''
585     sessions[session_id]['last_time'] = time.time()
586     return 'ok'
587
588 def native_server_thread():
589     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
590     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
591     s.bind((config.get('server','host'), config.getint('server','port')))
592     s.listen(1)
593     while not stopping:
594         conn, addr = s.accept()
595         try:
596             thread.start_new_thread(native_client_thread, (addr, conn,))
597         except:
598             # can't start new thread if there is no memory..
599             traceback.print_exc(file=sys.stdout)
600
601
602 def native_client_thread(ipaddr,conn):
603     #print "client thread", ipaddr
604     try:
605         ipaddr = ipaddr[0]
606         msg = ''
607         while 1:
608             d = conn.recv(1024)
609             msg += d
610             if not d: 
611                 break
612             if '#' in msg:
613                 msg = msg.split('#', 1)[0]
614                 break
615         try:
616             cmd, data = ast.literal_eval(msg)
617         except:
618             print "syntax error", repr(msg), ipaddr
619             conn.close()
620             return
621
622         out = do_command(cmd, data, ipaddr)
623         if out:
624             #print ipaddr, cmd, len(out)
625             try:
626                 conn.send(out)
627             except:
628                 print "error, could not send"
629
630     finally:
631         conn.close()
632
633
634 def timestr():
635     return time.strftime("[%d/%m/%Y-%H:%M:%S]")
636
637 # used by the native handler
638 def do_command(cmd, data, ipaddr):
639
640     if cmd=='b':
641         out = "%d"%block_number
642
643     elif cmd in ['session','new_session']:
644         try:
645             if cmd == 'session':
646                 addresses = ast.literal_eval(data)
647                 version = "old"
648             else:
649                 version, addresses = ast.literal_eval(data)
650                 if version[0]=="0": version = "v" + version
651         except:
652             print "error", data
653             return None
654         print timestr(), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
655         out = new_session(version, addresses)
656
657     elif cmd=='address.subscribe':
658         try:
659             session_id, addr = ast.literal_eval(data)
660         except:
661             print "error"
662             return None
663         out = add_address_to_session(session_id,addr)
664
665     elif cmd=='update_session':
666         try:
667             session_id, addresses = ast.literal_eval(data)
668         except:
669             print "error"
670             return None
671         print timestr(), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
672         out = update_session(session_id,addresses)
673
674     elif cmd == 'bccapi_login':
675         import electrum
676         print "data",data
677         v, k = ast.literal_eval(data)
678         master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
679         print master_public_key
680         wallet_id = random_string(10)
681         w = Wallet( Direct_Interface() )
682         w.master_public_key = master_public_key.decode('hex')
683         w.synchronize()
684         wallets[wallet_id] = w
685         out = wallet_id
686         print "wallets", wallets
687
688     elif cmd == 'bccapi_getAccountInfo':
689         from wallet import int_to_hex
690         v, wallet_id = ast.literal_eval(data)
691         w = wallets.get(wallet_id)
692         if w is not None:
693             num = len(w.addresses)
694             c, u = w.get_balance()
695             out = int_to_hex(num,4) + int_to_hex(c,8) + int_to_hex( c+u, 8 )
696             out = out.decode('hex')
697         else:
698             print "error",data
699             out = "error"
700
701     elif cmd == 'bccapi_getAccountStatement':
702         from wallet import int_to_hex
703         v, wallet_id = ast.literal_eval(data)
704         w = wallets.get(wallet_id)
705         if w is not None:
706             num = len(w.addresses)
707             c, u = w.get_balance()
708             total_records = num_records = 0
709             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 )
710             out = out.decode('hex')
711         else:
712             print "error",data
713             out = "error"
714
715     elif cmd == 'bccapi_getSendCoinForm':
716         out = ''
717
718     elif cmd == 'bccapi_submitTransaction':
719         out = ''
720             
721     elif cmd=='poll': 
722         out = poll_session(data)
723
724     elif cmd == 'h': 
725         # history
726         address = data
727         out = repr( store.get_history( address ) )
728
729     elif cmd == 'load': 
730         out = cmd_load(data)
731
732     elif cmd =='tx':
733         out = send_tx(data)
734         print timestr(), "sent tx:", ipaddr, out
735
736     elif cmd == 'stop':
737         out = cmd_stop(data)
738
739     elif cmd == 'peers':
740         out = repr(peer_list.values())
741
742     else:
743         out = None
744
745     return out
746
747
748
749 ####################################################################
750
751 def tcp_server_thread():
752     thread.start_new_thread(process_input_queue, ())
753     thread.start_new_thread(process_output_queue, ())
754
755     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
756     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
757     s.bind((config.get('server','host'), 50001))
758     s.listen(1)
759     while not stopping:
760         conn, addr = s.accept()
761         try:
762             thread.start_new_thread(tcp_client_thread, (addr, conn,))
763         except:
764             # can't start new thread if there is no memory..
765             traceback.print_exc(file=sys.stdout)
766
767
768 def close_session(session_id):
769     #print "lost connection", session_id
770     sessions.pop(session_id)
771     if session_id in sessions_sub_numblocks:
772         sessions_sub_numblocks.pop(session_id)
773
774
775 # one thread per client. put requests in a queue.
776 def tcp_client_thread(ipaddr,conn):
777     """ use a persistent connection. put commands in a queue."""
778
779     print timestr(), "TCP session", ipaddr
780     global sessions
781
782     session_id = random_string(10)
783     sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown', 'type':'persistent' }
784
785     ipaddr = ipaddr[0]
786     msg = ''
787
788     while not stopping:
789         try:
790             d = conn.recv(1024)
791         except socket.error:
792             d = ''
793         if not d:
794             close_session(session_id)
795             break
796
797         msg += d
798         while True:
799             s = msg.find('\n')
800             if s ==-1:
801                 break
802             else:
803                 c = msg[0:s].strip()
804                 msg = msg[s+1:]
805                 if c == 'quit': 
806                     conn.close()
807                     close_session(session_id)
808                     return
809                 try:
810                     c = json.loads(c)
811                 except:
812                     print "json error", repr(c)
813                     continue
814                 try:
815                     message_id = c.get('id')
816                     method = c.get('method')
817                     params = c.get('params')
818                 except:
819                     print "syntax error", repr(c), ipaddr
820                     continue
821
822                 # add to queue
823                 input_queue.put((session_id, message_id, method, params))
824
825
826
827 # read commands from the input queue. perform requests, etc. this should be called from the main thread.
828 def process_input_queue():
829     while not stopping:
830         session_id, message_id, method, data = input_queue.get()
831         if session_id not in sessions.keys():
832             continue
833         out = None
834         if method == 'address.subscribe':
835             address = data[0]
836             subscribe_to_address(session_id,message_id,address)
837         elif method == 'numblocks.subscribe':
838             subscribe_to_numblocks(session_id,message_id)
839         elif method == 'client.version':
840             sessions[session_id]['version'] = data[0]
841         elif method == 'server.banner':
842             out = { 'result':config.get('server','banner').replace('\\n','\n') } 
843         elif method == 'server.peers':
844             out = { 'result':peer_list.values() } 
845         elif method == 'address.get_history':
846             address = data[0]
847             out = { 'result':store.get_history( address ) } 
848         elif method == 'transaction.broadcast':
849             postdata = dumps({"method": 'importtransaction', 'params': [data], 'id':'jsonrpc'})
850             txo = urllib.urlopen(bitcoind_url, postdata).read()
851             print "sent tx:", txo
852             out = json.loads(txo)
853         else:
854             print "unknown command", method
855         if out:
856             out['id'] = message_id
857             out = json.dumps( out )
858             output_queue.put((session_id, out))
859
860 # this is a separate thread
861 def process_output_queue():
862     while not stopping:
863         session_id, out = output_queue.get()
864         session = sessions.get(session_id)
865         if session: 
866             try:
867                 conn = session.get('conn')
868                 conn.send(out+'\n')
869             except:
870                 close_session(session_id)
871                 
872
873
874
875 ####################################################################
876
877
878 def memorypool_update(store):
879
880     ds = BCDataStream.BCDataStream()
881     previous_transactions = store.mempool_keys
882     store.mempool_keys = []
883
884     postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'})
885     respdata = urllib.urlopen(bitcoind_url, postdata).read()
886     r = loads(respdata)
887     if r['error'] != None:
888         return
889
890     v = r['result'].get('transactions')
891     for hextx in v:
892         ds.clear()
893         ds.write(hextx.decode('hex'))
894         tx = deserialize.parse_Transaction(ds)
895         tx['hash'] = util.double_sha256(tx['tx'])
896         tx_hash = store.hashin(tx['hash'])
897
898         store.mempool_keys.append(tx_hash)
899         if store.tx_find_id_and_value(tx):
900             pass
901         else:
902             tx_id = store.import_tx(tx, False)
903             store.update_tx_cache(tx_id)
904
905     store.commit()
906
907
908 def clean_session_thread():
909     while not stopping:
910         time.sleep(30)
911         t = time.time()
912         for k,s in sessions.items():
913             if s.get('type') == 'persistent': continue
914             t0 = s['last_time']
915             if t - t0 > 5*60:
916                 sessions.pop(k)
917                 print "lost session", k
918             
919
920 def irc_thread():
921     global peer_list
922     NICK = 'E_'+random_string(10)
923     while not stopping:
924         try:
925             s = socket.socket()
926             s.connect(('irc.freenode.net', 6667))
927             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
928             s.send('NICK '+NICK+'\n')
929             s.send('JOIN #electrum\n')
930             sf = s.makefile('r', 0)
931             t = 0
932             while not stopping:
933                 line = sf.readline()
934                 line = line.rstrip('\r\n')
935                 line = line.split()
936                 if line[0]=='PING': 
937                     s.send('PONG '+line[1]+'\n')
938                 elif '353' in line: # answer to /names
939                     k = line.index('353')
940                     for item in line[k+1:]:
941                         if item[0:2] == 'E_':
942                             s.send('WHO %s\n'%item)
943                 elif '352' in line: # answer to /who
944                     # warning: this is a horrible hack which apparently works
945                     k = line.index('352')
946                     ip = line[k+4]
947                     ip = socket.gethostbyname(ip)
948                     name = line[k+6]
949                     host = line[k+9]
950                     peer_list[name] = (ip,host)
951                 if time.time() - t > 5*60:
952                     s.send('NAMES #electrum\n')
953                     t = time.time()
954                     peer_list = {}
955         except:
956             traceback.print_exc(file=sys.stdout)
957         finally:
958             sf.close()
959             s.close()
960
961
962 def get_peers_json(_,__):
963     return peer_list.values()
964
965 def http_server_thread(store):
966     # see http://code.google.com/p/jsonrpclib/
967     from SocketServer import ThreadingMixIn
968     from StratumJSONRPCServer import StratumJSONRPCServer
969     class StratumThreadedJSONRPCServer(ThreadingMixIn, StratumJSONRPCServer): pass
970     server = StratumThreadedJSONRPCServer(( config.get('server','host'), 8081))
971     server.register_function(get_peers_json, 'server.peers')
972     server.register_function(cmd_stop, 'stop')
973     server.register_function(cmd_load, 'load')
974     server.register_function(clear_cache, 'clear_cache')
975     server.register_function(get_cache, 'get_cache')
976     server.register_function(get_banner, 'server.banner')
977     server.register_function(lambda a,b,c: send_tx(c), 'transaction.broadcast')
978     server.register_function(address_get_history_json, 'address.get_history')
979     server.register_function(add_address_to_session_json, 'address.subscribe')
980     server.register_function(subscribe_to_numblocks_json, 'numblocks.subscribe')
981     server.register_function(client_version_json, 'client.version')
982     server.register_function(create_session_json, 'session.create')   # internal message (not part of protocol)
983     server.register_function(poll_session_json, 'session.poll')       # internal message (not part of protocol)
984     server.serve_forever()
985
986
987 import traceback
988
989
990 if __name__ == '__main__':
991
992     if len(sys.argv)>1:
993         import jsonrpclib
994         server = jsonrpclib.Server('http://%s:8081'%config.get('server','host'))
995         cmd = sys.argv[1]
996         if cmd == 'load':
997             out = server.load(password)
998         elif cmd == 'peers':
999             out = server.server.peers()
1000         elif cmd == 'stop':
1001             out = server.stop(password)
1002         elif cmd == 'clear_cache':
1003             out = server.clear_cache(password)
1004         elif cmd == 'get_cache':
1005             out = server.get_cache(password,sys.argv[2])
1006         elif cmd == 'h':
1007             out = server.address.get_history(sys.argv[2])
1008         elif cmd == 'tx':
1009             out = server.transaction.broadcast(sys.argv[2])
1010         elif cmd == 'b':
1011             out = server.numblocks.subscribe()
1012         else:
1013             out = "Unknown command: '%s'" % cmd
1014         print out
1015         sys.exit(0)
1016
1017
1018     print "starting Electrum server"
1019
1020     conf = DataStore.CONFIG_DEFAULTS
1021     args, argv = readconf.parse_argv( [], conf)
1022     args.dbtype= config.get('database','type')
1023     if args.dbtype == 'sqlite3':
1024         args.connect_args = { 'database' : config.get('database','database') }
1025     elif args.dbtype == 'MySQLdb':
1026         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
1027     elif args.dbtype == 'psycopg2':
1028         args.connect_args = { 'database' : config.get('database','database') }
1029     store = MyStore(args)
1030     store.tx_cache = {}
1031     store.mempool_keys = {}
1032
1033     # supported protocols
1034     thread.start_new_thread(native_server_thread, ())
1035     thread.start_new_thread(tcp_server_thread, ())
1036     thread.start_new_thread(http_server_thread, (store,))
1037
1038     thread.start_new_thread(clean_session_thread, ())
1039
1040     if (config.get('server','irc') == 'yes' ):
1041         thread.start_new_thread(irc_thread, ())
1042
1043     while not stopping:
1044         try:
1045             dblock.acquire()
1046             store.catch_up()
1047             memorypool_update(store)
1048
1049             block_number = store.get_block_number(1)
1050             if block_number != old_block_number:
1051                 old_block_number = block_number
1052                 for session_id in sessions_sub_numblocks.keys():
1053                     send_numblocks(session_id)
1054
1055         except IOError:
1056             print "IOError: cannot reach bitcoind"
1057             block_number = 0
1058         except:
1059             traceback.print_exc(file=sys.stdout)
1060             block_number = 0
1061         finally:
1062             dblock.release()
1063
1064         # do addresses
1065         while True:
1066             try:
1067                 addr = address_queue.get(False)
1068             except:
1069                 break
1070             do_update_address(addr)
1071
1072         time.sleep(10)
1073
1074     print "server stopped"
1075