reset peer list before update
[electrum-server.git] / server.py
index 7ccee47..500a17b 100755 (executable)
--- a/server.py
+++ b/server.py
@@ -24,7 +24,7 @@ Todo:
 
 import time, socket, operator, thread, ast, sys,re
 import psycopg2, binascii
-import bitcoin
+import bitcoinrpc
 
 from Abe.abe import hash_to_address, decode_check_address
 from Abe.DataStore import DataStore as Datastore_class
@@ -39,6 +39,8 @@ config.set('server','banner', 'Welcome to Electrum!')
 config.set('server', 'host', 'ecdsa.org')
 config.set('server', 'port', 50000)
 config.set('server', 'password', '')
+config.set('server', 'irc', 'yes')
+config.set('server', 'ircname', 'Electrum server')
 config.add_section('database')
 config.set('database', 'type', 'psycopg2')
 config.set('database', 'database', 'abe')
@@ -48,7 +50,7 @@ try:
     config.readfp(f)
     f.close()
 except:
-    print "Could not read electrum.conf. I will use the dafault values."
+    print "Could not read electrum.conf. I will use the default values."
 
 stopping = False
 block_number = -1
@@ -60,10 +62,10 @@ peer_list = {}
 
 class MyStore(Datastore_class):
 
-    def safe_sql(self,sql):
+    def safe_sql(self,sql, params=()):
         try:
             dblock.acquire()
-            ret = self.selectall(sql)
+            ret = self.selectall(sql,params)
             dblock.release()
             return ret
         except:
@@ -123,8 +125,8 @@ class MyStore(Datastore_class):
               JOIN txin ON (txin.tx_id = tx.tx_id)
               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
-             WHERE pubkey.pubkey_hash = '%s'
-               AND cc.in_longest = 1"""%dbhash)
+             WHERE pubkey.pubkey_hash = ?
+               AND cc.in_longest = 1""", (dbhash,))
 
     def get_address_out_rows_memorypool(self, dbhash):
         return self.safe_sql(""" SELECT
@@ -137,7 +139,7 @@ class MyStore(Datastore_class):
               JOIN txin ON (txin.tx_id = tx.tx_id)
               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
-             WHERE pubkey.pubkey_hash ='%s' """%(dbhash))
+             WHERE pubkey.pubkey_hash = ? """, (dbhash,))
 
     def get_address_in_rows(self, dbhash):
         return self.safe_sql(""" SELECT
@@ -156,8 +158,8 @@ class MyStore(Datastore_class):
               JOIN tx ON (tx.tx_id = block_tx.tx_id)
               JOIN txout ON (txout.tx_id = tx.tx_id)
               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
-             WHERE pubkey.pubkey_hash = '%s'
-               AND cc.in_longest = 1"""%(dbhash))
+             WHERE pubkey.pubkey_hash = ?
+               AND cc.in_longest = 1""", (dbhash,))
 
     def get_address_in_rows_memorypool(self, dbhash):
         return self.safe_sql( """ SELECT
@@ -169,7 +171,7 @@ class MyStore(Datastore_class):
               FROM tx
               JOIN txout ON (txout.tx_id = tx.tx_id)
               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
-             WHERE pubkey.pubkey_hash = '%s' """%(dbhash))
+             WHERE pubkey.pubkey_hash = ? """, (dbhash,))
 
     def get_txpoints(self, addr):
         version, binaddr = decode_check_address(addr)
@@ -278,8 +280,8 @@ class MyStore(Datastore_class):
 
 
 def send_tx(tx):
-    import bitcoin
-    conn = bitcoin.connect_to_local()
+    import bitcoinrpc
+    conn = bitcoinrpc.connect_to_local()
     try:
         v = conn.importtransaction(tx)
     except:
@@ -401,7 +403,7 @@ ds = BCDataStream.BCDataStream()
 
 def memorypool_update(store):
 
-    conn = bitcoin.connect_to_local()
+    conn = bitcoinrpc.connect_to_local()
     try:
         v = conn.getmemorypool()
     except:
@@ -442,39 +444,38 @@ def irc_thread():
         try:
             s = socket.socket()
             s.connect(('irc.freenode.net', 6667))
-            s.send('USER '+config.get('server','host')+' '+NICK+' bla :'+NICK+'\n') 
+            s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
             s.send('NICK '+NICK+'\n')
             s.send('JOIN #electrum\n')
+            sf = s.makefile('r', 0)
             t = 0
             while not stopping:
-                line = s.recv(2048)
+                line = sf.readline()
                 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')
-                    try:
-                        k2 = line.index('366')
-                    except:
-                        continue
-                    for item in line[k+1:k2]:
+                    for item in line[k+1:]:
                         if item[0:2] == 'E_':
-                            s.send('USERHOST %s\n'%item)
-                elif '302' in line: # answer to /userhost
-                    k = line.index('302')
-                    m = re.match( "^:(.*?)=\+~(.*?)@(.*?)$", line[k+2] )
-                    if m:
-                        name = m.group(1)
-                        host = m.group(2)
-                        ip = m.group(3)
-                        peer_list[name] = (ip,host)
+                            s.send('WHO %s\n'%item)
+                elif '352' in line: # answer to /who
+                   # warning: this is a horrible hack which apparently works
+                   k = line.index('352')
+                    ip = line[k+4]
+                    ip = socket.gethostbyname(ip)
+                    name = line[k+6]
+                    host = line[k+9]
+                    peer_list[name] = (ip,host)
                 elif time.time() - t > 5*60:
                     s.send('NAMES #electrum\n')
                     t = time.time()
+                    peer_list = {}
         except:
             traceback.print_exc(file=sys.stdout)
         finally:
+           sf.close()
             s.close()
 
 
@@ -509,12 +510,18 @@ if __name__ == '__main__':
     conf = DataStore.CONFIG_DEFAULTS
     args, argv = readconf.parse_argv( [], conf)
     args.dbtype= config.get('database','type')
-    args.connect_args = {'database' : config.get('database','database') }
+    if args.dbtype == 'sqlite3':
+       args.connect_args = { 'database' : config.get('database','database') }
+    elif args.dbtype == 'MySQLdb':
+       args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
+    elif args.dbtype == 'psycopg2':
+       args.connect_args = { 'database' : config.get('database','database') }
     store = MyStore(args)
 
     thread.start_new_thread(listen_thread, (store,))
     thread.start_new_thread(clean_session_thread, ())
-    thread.start_new_thread(irc_thread, ())
+    if (config.get('server','irc') == 'yes' ):
+       thread.start_new_thread(irc_thread, ())
 
     while not stopping:
         try: