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