retrieve peers list from IRC
[electrum-server.git] / server.py
index 3271a89..272cb37 100644 (file)
--- a/server.py
+++ b/server.py
@@ -21,21 +21,8 @@ Todo:
    * improve txpoint sorting
 """
 
-SERVER_MESSAGE = """
-Welcome to ecdsa.org.
-
-This service is free. Support this node: 
-19mP9FKrXqL46Si58pHdhGKow88SUPy1V8
-
-The server code is free software; you may 
-download it and operate your own Electrum 
-node. See http://ecdsa.org/electrum
-"""
-
-
 
 import time, socket, operator, thread, ast, sys
-
 import psycopg2, binascii
 import bitcoinrpc
 
@@ -43,10 +30,26 @@ from Abe.abe import hash_to_address, decode_check_address
 from Abe.DataStore import DataStore as Datastore_class
 from Abe import DataStore, readconf, BCDataStream,  deserialize, util, base58
 
+try:
+    f = open('/etc/electrum.conf','r')
+    data = f.read()
+    f.close()
+    HOST, PORT, PASSWORD, SERVER_MESSAGE = ast.literal_eval(data)
+except:
+    print "could not read /etc/electrum.conf"
+    SERVER_MESSAGE = "Welcome to Electrum"
+    HOST = 'ecdsa.org'
+    PORT = 50000
+    PASSWORD = ''
+
+
+stopping = False
 
 sessions = {}
+sessions_last_time = {}
 dblock = thread.allocate_lock()
 
+peer_list = {}
 
 class MyStore(Datastore_class):
 
@@ -278,18 +281,20 @@ def send_tx(tx):
 
 
 def listen_thread(store):
-
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-    s.bind(('ecdsa.org', 50000))
+    s.bind((HOST, PORT))
     s.listen(1)
-    while True:
+    while not stopping:
         conn, addr = s.accept()
         thread.start_new_thread(client_thread, (addr, conn,))
 
+def random_string(N):
+    import random, string
+    return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
 
 def client_thread(ipaddr,conn):
-    print "client thread", ipaddr
+    #print "client thread", ipaddr
     try:
         ipaddr = ipaddr[0]
         msg = ''
@@ -299,7 +304,7 @@ def client_thread(ipaddr,conn):
             if d[-1]=='#':
                 break
 
-        print msg
+        #print msg
 
         try:
             cmd, data = ast.literal_eval(msg[:-1])
@@ -312,15 +317,21 @@ def client_thread(ipaddr,conn):
             out = "%d"%store.get_block_number(1)
 
         elif cmd=='session':
-            import random, string
-            session_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
-            print "new session", ipaddr, session_id
+            session_id = random_string(10)
+            try:
+                addresses = ast.literal_eval(data)
+            except:
+                print "error"
+                conn.close()
+                return
+
+            print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
 
-            addresses = ast.literal_eval(data)
             sessions[session_id] = {}
             for a in addresses:
                 sessions[session_id][a] = ''
             out = repr( (session_id, SERVER_MESSAGE) )
+            sessions_last_time[session_id] = time.time()
 
         elif cmd=='poll': 
             session_id = data
@@ -329,6 +340,7 @@ def client_thread(ipaddr,conn):
                 print "session not found", ipaddr
                 out = repr( (-1, {}))
             else:
+                sessions_last_time[session_id] = time.time()
                 ret = {}
                 for addr in addresses:
                     status = store.get_status( addr )
@@ -344,9 +356,26 @@ def client_thread(ipaddr,conn):
             h = store.get_txpoints( addr )
             out = repr(h)
 
+        elif cmd == 'load': 
+            if PASSWORD == data:
+                out = repr( len(sessions) )
+            else:
+                out = 'wrong password'
+
         elif cmd =='tx':        
-            # transaction
             out = send_tx(data)
+
+        elif cmd == 'stop':
+            global stopping
+            if PASSWORD == data:
+                stopping = True
+                out = 'ok'
+            else:
+                out = 'wrong password'
+
+        elif cmd == 'peers':
+            out = repr(peer_list.values())
+
         else:
             out = None
 
@@ -383,14 +412,88 @@ def memorypool_update(store):
             pass
         else:
             store.import_tx(tx, False)
-            print tx['hash'][::-1].encode('hex')
+            #print tx['hash'][::-1].encode('hex')
     store.commit()
 
+
+
+
+def clean_session_thread():
+    while not stopping:
+        time.sleep(30)
+        t = time.time()
+        for k,t0 in sessions_last_time.items():
+            if t - t0 > 60:
+                print "lost session",k
+                sessions.pop(k)
+                sessions_last_time.pop(k)
+            
+
+def irc_thread():
+    global peer_list
+    NICK = 'E_'+random_string(10)
+    while not stopping:
+        try:
+            s = socket.socket()
+            s.connect(('irc.freenode.net', 6667))
+            s.send('USER '+NICK+' '+NICK+' bla :'+NICK+'\n') 
+            s.send('NICK '+NICK+'\n') 
+            s.send('JOIN #electrum\n')
+            t = 0
+            while not stopping:
+                line = s.recv(2048)
+                line = line.rstrip('\r\n')
+                line = line.split()
+                if line[0]=='PING': 
+                    s.send('PONG '+line[1]+'\n')
+                elif '353' in line: # answer to /names
+                    k = line.index('353')
+                    k2 = line.index('366')
+                    for item in line[k+1:k2]:
+                        if item[0:2] == 'E_':
+                            s.send('USERHOST %s\n'%item)
+                elif '302' in line: # answer to /userhost
+                    k = line.index('302')
+                    name = line[k+1]
+                    host = line[k+2].split('@')[1]
+                    peer_list[name] = host
+                elif time.time() - t > 5*60:
+                    s.send('NAMES #electrum\n')
+                    t = time.time()
+        except:
+            traceback.print_exc(file=sys.stdout)
+        finally:
+            s.close()
+
+
 import traceback
 
 
 if __name__ == '__main__':
 
+    if len(sys.argv)>1:
+        cmd = sys.argv[1]
+        if cmd == 'load':
+            request = "('load','%s')#"%PASSWORD
+        elif cmd == 'peers':
+            request = "('peers','')#"
+        elif cmd == 'stop':
+            request = "('stop','%s')#"%PASSWORD
+
+        s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
+        s.connect(( HOST, PORT))
+        s.send( request )
+        out = ''
+        while 1:
+            msg = s.recv(1024)
+            if msg: out += msg
+            else: break
+        s.close()
+        print out
+        sys.exit(0)
+
+
+    print "starting Electrum server"
     conf = DataStore.CONFIG_DEFAULTS
     args, argv = readconf.parse_argv( [], conf)
     args.dbtype='psycopg2'
@@ -398,8 +501,10 @@ if __name__ == '__main__':
     store = MyStore(args)
 
     thread.start_new_thread(listen_thread, (store,))
+    thread.start_new_thread(clean_session_thread, ())
+    thread.start_new_thread(irc_thread, ())
 
-    while True:
+    while not stopping:
         try:
             dblock.acquire()
             store.catch_up()
@@ -409,3 +514,5 @@ if __name__ == '__main__':
             traceback.print_exc(file=sys.stdout)
         time.sleep(10)
 
+    print "server stopped"
+