default to localhost
[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
25
26 import time, socket, operator, thread, ast, sys,re
27 import psycopg2, binascii
28 import bitcoinrpc
29
30 from Abe.abe import hash_to_address, decode_check_address
31 from Abe.DataStore import DataStore as Datastore_class
32 from Abe import DataStore, readconf, BCDataStream,  deserialize, util, base58
33
34 import ConfigParser
35
36 config = ConfigParser.ConfigParser()
37 # set some defaults, which will be overwritten by the config file
38 config.add_section('server')
39 config.set('server','banner', 'Welcome to Electrum!')
40 config.set('server', 'host', 'localhost')
41 config.set('server', 'port', 50000)
42 config.set('server', 'password', '')
43 config.set('server', 'irc', 'yes')
44 config.set('server', 'cache', 'no') 
45 config.set('server', 'ircname', 'Electrum server')
46 config.add_section('database')
47 config.set('database', 'type', 'psycopg2')
48 config.set('database', 'database', 'abe')
49
50 try:
51     f = open('/etc/electrum.conf','r')
52     config.readfp(f)
53     f.close()
54 except:
55     print "Could not read electrum.conf. I will use the default values."
56
57 stopping = False
58 block_number = -1
59 sessions = {}
60 sessions_last_time = {}
61 dblock = thread.allocate_lock()
62
63 peer_list = {}
64
65
66
67 class MyStore(Datastore_class):
68
69     def import_tx(self, tx, is_coinbase):
70         tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
71         if config.get('server', 'cache') == 'yes': self.update_tx_cache(tx_id)
72
73     def update_tx_cache(self, txid):
74         inrows = self.get_tx_inputs(txid, False)
75         for row in inrows:
76             _hash = store.binout(row[6])
77             address = hash_to_address(chr(0), _hash)
78             if self.tx_cache.has_key(address):
79                 #print "cache: invalidating", address, self.ismempool
80                 self.tx_cache.pop(address)
81         outrows = self.get_tx_outputs(txid, False)
82         for row in outrows:
83             _hash = store.binout(row[6])
84             address = hash_to_address(chr(0), _hash)
85             if self.tx_cache.has_key(address):
86                 #print "cache: invalidating", address, self.ismempool
87                 self.tx_cache.pop(address)
88
89     def safe_sql(self,sql, params=(), lock=True):
90         try:
91             if lock: dblock.acquire()
92             ret = self.selectall(sql,params)
93             if lock: dblock.release()
94             return ret
95         except:
96             print "sql error", sql
97             return []
98
99     def get_tx_outputs(self, tx_id, lock=True):
100         return self.safe_sql("""SELECT
101                 txout.txout_pos,
102                 txout.txout_scriptPubKey,
103                 txout.txout_value,
104                 nexttx.tx_hash,
105                 nexttx.tx_id,
106                 txin.txin_pos,
107                 pubkey.pubkey_hash
108               FROM txout
109               LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
110               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
111               LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
112              WHERE txout.tx_id = %d 
113              ORDER BY txout.txout_pos
114         """%(tx_id), (), lock)
115
116     def get_tx_inputs(self, tx_id, lock=True):
117         return self.safe_sql(""" SELECT
118                 txin.txin_pos,
119                 txin.txin_scriptSig,
120                 txout.txout_value,
121                 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
122                 prevtx.tx_id,
123                 COALESCE(txout.txout_pos, u.txout_pos),
124                 pubkey.pubkey_hash
125               FROM txin
126               LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
127               LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
128               LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
129               LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
130              WHERE txin.tx_id = %d
131              ORDER BY txin.txin_pos
132              """%(tx_id,), (), lock)
133
134     def get_address_out_rows(self, dbhash):
135         return self.safe_sql(""" SELECT
136                 b.block_nTime,
137                 cc.chain_id,
138                 b.block_height,
139                 1,
140                 b.block_hash,
141                 tx.tx_hash,
142                 tx.tx_id,
143                 txin.txin_pos,
144                 -prevout.txout_value
145               FROM chain_candidate cc
146               JOIN block b ON (b.block_id = cc.block_id)
147               JOIN block_tx ON (block_tx.block_id = b.block_id)
148               JOIN tx ON (tx.tx_id = block_tx.tx_id)
149               JOIN txin ON (txin.tx_id = tx.tx_id)
150               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
151               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
152              WHERE pubkey.pubkey_hash = ?
153                AND cc.in_longest = 1""", (dbhash,))
154
155     def get_address_out_rows_memorypool(self, dbhash):
156         return self.safe_sql(""" SELECT
157                 1,
158                 tx.tx_hash,
159                 tx.tx_id,
160                 txin.txin_pos,
161                 -prevout.txout_value
162               FROM tx 
163               JOIN txin ON (txin.tx_id = tx.tx_id)
164               JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
165               JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
166              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
167
168     def get_address_in_rows(self, dbhash):
169         return self.safe_sql(""" SELECT
170                 b.block_nTime,
171                 cc.chain_id,
172                 b.block_height,
173                 0,
174                 b.block_hash,
175                 tx.tx_hash,
176                 tx.tx_id,
177                 txout.txout_pos,
178                 txout.txout_value
179               FROM chain_candidate cc
180               JOIN block b ON (b.block_id = cc.block_id)
181               JOIN block_tx ON (block_tx.block_id = b.block_id)
182               JOIN tx ON (tx.tx_id = block_tx.tx_id)
183               JOIN txout ON (txout.tx_id = tx.tx_id)
184               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
185              WHERE pubkey.pubkey_hash = ?
186                AND cc.in_longest = 1""", (dbhash,))
187
188     def get_address_in_rows_memorypool(self, dbhash):
189         return self.safe_sql( """ SELECT
190                 0,
191                 tx.tx_hash,
192                 tx.tx_id,
193                 txout.txout_pos,
194                 txout.txout_value
195               FROM tx
196               JOIN txout ON (txout.tx_id = tx.tx_id)
197               JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
198              WHERE pubkey.pubkey_hash = ? """, (dbhash,))
199
200     def get_txpoints(self, addr):
201         
202         if config.get('server','cache') == 'yes':
203             cached_version = self.tx_cache.get( addr ) 
204             if cached_version is not None: 
205                 return cached_version
206
207         version, binaddr = decode_check_address(addr)
208         if binaddr is None:
209             return "err"
210         dbhash = self.binin(binaddr)
211         rows = []
212         rows += self.get_address_out_rows( dbhash )
213         rows += self.get_address_in_rows( dbhash )
214
215         txpoints = []
216         known_tx = []
217
218         for row in rows:
219             try:
220                 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
221             except:
222                 print "cannot unpack row", row
223                 break
224             tx_hash = self.hashout_hex(tx_hash)
225             txpoint = {
226                     "nTime":    int(nTime),
227                     #"chain_id": int(chain_id),
228                     "height":   int(height),
229                     "is_in":    int(is_in),
230                     "blk_hash": self.hashout_hex(blk_hash),
231                     "tx_hash":  tx_hash,
232                     "tx_id":    int(tx_id),
233                     "pos":      int(pos),
234                     "value":    int(value),
235                     }
236
237             txpoints.append(txpoint)
238             known_tx.append(self.hashout_hex(tx_hash))
239
240
241         # todo: sort them really...
242         txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
243
244         # read memory pool
245         rows = []
246         rows += self.get_address_in_rows_memorypool( dbhash )
247         rows += self.get_address_out_rows_memorypool( dbhash )
248         address_has_no_mempool = (rows == [])
249         for row in rows:
250             is_in, tx_hash, tx_id, pos, value = row
251             tx_hash = self.hashout_hex(tx_hash)
252             if tx_hash in known_tx:
253                 continue
254             #print "mempool", tx_hash
255             txpoint = {
256                     "nTime":    0,
257                     #"chain_id": 1,
258                     "height":   0,
259                     "is_in":    int(is_in),
260                     "blk_hash": 'mempool',
261                     "tx_hash":  tx_hash,
262                     "tx_id":    int(tx_id),
263                     "pos":      int(pos),
264                     "value":    int(value),
265                     }
266             txpoints.append(txpoint)
267
268
269         for txpoint in txpoints:
270             tx_id = txpoint['tx_id']
271             
272             txinputs = []
273             inrows = self.get_tx_inputs(tx_id)
274             for row in inrows:
275                 _hash = self.binout(row[6])
276                 address = hash_to_address(chr(0), _hash)
277                 txinputs.append(address)
278             txpoint['inputs'] = txinputs
279             txoutputs = []
280             outrows = self.get_tx_outputs(tx_id)
281             for row in outrows:
282                 _hash = self.binout(row[6])
283                 address = hash_to_address(chr(0), _hash)
284                 txoutputs.append(address)
285             txpoint['outputs'] = txoutputs
286
287             # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
288             if not txpoint['is_in']:
289                 # detect if already redeemed...
290                 for row in outrows:
291                     if row[6] == dbhash: break
292                 else:
293                     raise
294                 #row = self.get_tx_output(tx_id,dbhash)
295                 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
296                 # if not redeemed, we add the script
297                 if row:
298                     if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
299
300         # cache result
301         if config.get('server','cache') == 'yes' and address_has_no_mempool:
302             self.tx_cache[addr] = txpoints
303         
304         return txpoints
305
306
307     def get_status(self, addr):
308         # last block for an address.
309         tx_points = self.get_txpoints(addr)
310         if not tx_points:
311             return None
312         else:
313             return tx_points[-1]['blk_hash']
314
315
316 def send_tx(tx):
317     import bitcoinrpc
318     conn = bitcoinrpc.connect_to_local()
319     try:
320         v = conn.importtransaction(tx)
321     except:
322         v = "error: transaction rejected by memorypool"
323     return v
324
325
326 def listen_thread(store):
327     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
328     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
329     s.bind((config.get('server','host'), config.getint('server','port')))
330     s.listen(1)
331     while not stopping:
332         conn, addr = s.accept()
333         thread.start_new_thread(client_thread, (addr, conn,))
334
335 def random_string(N):
336     import random, string
337     return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
338
339 def client_thread(ipaddr,conn):
340     #print "client thread", ipaddr
341     try:
342         ipaddr = ipaddr[0]
343         msg = ''
344         while 1:
345             d = conn.recv(1024)
346             msg += d
347             if d[-1]=='#':
348                 break
349
350         #print msg
351
352         try:
353             cmd, data = ast.literal_eval(msg[:-1])
354         except:
355             print "syntax error", repr(msg)
356             conn.close()
357             return
358
359         if cmd=='b':
360             out = "%d"%block_number
361         elif cmd=='session':
362             session_id = random_string(10)
363             try:
364                 addresses = ast.literal_eval(data)
365             except:
366                 print "error"
367                 conn.close()
368                 return
369
370             print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
371
372             sessions[session_id] = {}
373             for a in addresses:
374                 sessions[session_id][a] = ''
375             out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
376             sessions_last_time[session_id] = time.time()
377
378         elif cmd=='poll': 
379             session_id = data
380             addresses = sessions.get(session_id)
381             if not addresses:
382                 print "session not found", ipaddr
383                 out = repr( (-1, {}))
384             else:
385                 sessions_last_time[session_id] = time.time()
386                 ret = {}
387                 for addr in addresses:
388                     status = store.get_status( addr )
389                     last_status = sessions[session_id].get( addr )
390                     if last_status != status:
391                         sessions[session_id][addr] = status
392                         ret[addr] = status
393                 out = repr( (block_number, ret ) )
394
395         elif cmd == 'h': 
396             # history
397             address = data
398             out = repr( store.get_txpoints( address ) )
399
400         elif cmd == 'load': 
401             if config.get('server','password') == data:
402                 out = repr( len(sessions) )
403             else:
404                 out = 'wrong password'
405
406         elif cmd =='tx':        
407             out = send_tx(data)
408
409         elif cmd == 'stop':
410             global stopping
411             if config.get('server','password') == data:
412                 stopping = True
413                 out = 'ok'
414             else:
415                 out = 'wrong password'
416
417         elif cmd == 'peers':
418             out = repr(peer_list.values())
419
420         else:
421             out = None
422
423         if out:
424             #print ipaddr, cmd, len(out)
425             try:
426                 conn.send(out)
427             except:
428                 print "error, could not send"
429
430     finally:
431         conn.close()
432     
433
434 ds = BCDataStream.BCDataStream()
435
436
437
438
439 def memorypool_update(store):
440     conn = bitcoinrpc.connect_to_local()
441     try:
442         v = conn.getmemorypool()
443     except:
444         print "cannot contact bitcoin daemon"
445         return
446     v = v['transactions']
447     for hextx in v:
448         ds.clear()
449         ds.write(hextx.decode('hex'))
450         tx = deserialize.parse_Transaction(ds)
451         #print "new tx",tx
452
453         tx['hash'] = util.double_sha256(tx['tx'])
454             
455         if store.tx_find_id_and_value(tx):
456             pass
457         else:
458             store.import_tx(tx, False)
459
460     store.commit()
461
462
463
464
465 def clean_session_thread():
466     while not stopping:
467         time.sleep(30)
468         t = time.time()
469         for k,t0 in sessions_last_time.items():
470             if t - t0 > 60:
471                 print "lost session",k
472                 sessions.pop(k)
473                 sessions_last_time.pop(k)
474             
475
476 def irc_thread():
477     global peer_list
478     NICK = 'E_'+random_string(10)
479     while not stopping:
480         try:
481             s = socket.socket()
482             s.connect(('irc.freenode.net', 6667))
483             s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
484             s.send('NICK '+NICK+'\n')
485             s.send('JOIN #electrum\n')
486             sf = s.makefile('r', 0)
487             t = 0
488             while not stopping:
489                 line = sf.readline()
490                 line = line.rstrip('\r\n')
491                 line = line.split()
492                 if line[0]=='PING': 
493                     s.send('PONG '+line[1]+'\n')
494                 elif '353' in line: # answer to /names
495                     k = line.index('353')
496                     for item in line[k+1:]:
497                         if item[0:2] == 'E_':
498                             s.send('WHO %s\n'%item)
499                 elif '352' in line: # answer to /who
500                     # warning: this is a horrible hack which apparently works
501                     k = line.index('352')
502                     ip = line[k+4]
503                     ip = socket.gethostbyname(ip)
504                     name = line[k+6]
505                     host = line[k+9]
506                     peer_list[name] = (ip,host)
507                 elif time.time() - t > 5*60:
508                     s.send('NAMES #electrum\n')
509                     t = time.time()
510                     peer_list = {}
511         except:
512             traceback.print_exc(file=sys.stdout)
513         finally:
514             sf.close()
515             s.close()
516
517
518 import traceback
519
520
521 if __name__ == '__main__':
522
523     if len(sys.argv)>1:
524         cmd = sys.argv[1]
525         if cmd == 'load':
526             request = "('load','%s')#"%config.get('server','password')
527         elif cmd == 'peers':
528             request = "('peers','')#"
529         elif cmd == 'stop':
530             request = "('stop','%s')#"%config.get('server','password')
531         elif cmd == 'h':
532             request = "('h','%s')#"%sys.argv[2]
533
534         s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
535         s.connect((config.get('server','host'), config.getint('server','port')))
536         s.send( request )
537         out = ''
538         while 1:
539             msg = s.recv(1024)
540             if msg: out += msg
541             else: break
542         s.close()
543         print out
544         sys.exit(0)
545
546
547     print "starting Electrum server"
548     conf = DataStore.CONFIG_DEFAULTS
549     args, argv = readconf.parse_argv( [], conf)
550     args.dbtype= config.get('database','type')
551     if args.dbtype == 'sqlite3':
552         args.connect_args = { 'database' : config.get('database','database') }
553     elif args.dbtype == 'MySQLdb':
554         args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
555     elif args.dbtype == 'psycopg2':
556         args.connect_args = { 'database' : config.get('database','database') }
557     store = MyStore(args)
558     store.tx_cache = {}
559     store.ismempool = False
560
561     thread.start_new_thread(listen_thread, (store,))
562     thread.start_new_thread(clean_session_thread, ())
563     if (config.get('server','irc') == 'yes' ):
564         thread.start_new_thread(irc_thread, ())
565
566     while not stopping:
567         try:
568             dblock.acquire()
569             store.catch_up()
570             store.ismempool = True
571             memorypool_update(store)
572             store.ismempool = False
573             block_number = store.get_block_number(1)
574             dblock.release()
575         except:
576             traceback.print_exc(file=sys.stdout)
577         time.sleep(10)
578
579     print "server stopped"
580