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