2 # Copyright(C) 2011 thomasv@gitorious
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.
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.
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>.
20 * server should check and return bitcoind status..
21 * improve txpoint sorting
22 * command to check cache
24 mempool transactions do not need to be added to the database; it slows it down
28 import time, socket, operator, thread, ast, sys,re
29 import psycopg2, binascii
32 from Abe.abe import hash_to_address, decode_check_address
33 from Abe.DataStore import DataStore as Datastore_class
34 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
38 config = ConfigParser.ConfigParser()
39 # set some defaults, which will be overwritten by the config file
40 config.add_section('server')
41 config.set('server','banner', 'Welcome to Electrum!')
42 config.set('server', 'host', 'localhost')
43 config.set('server', 'port', 50000)
44 config.set('server', 'password', '')
45 config.set('server', 'irc', 'yes')
46 config.set('server', 'cache', 'no')
47 config.set('server', 'ircname', 'Electrum server')
48 config.add_section('database')
49 config.set('database', 'type', 'psycopg2')
50 config.set('database', 'database', 'abe')
53 f = open('/etc/electrum.conf','r')
57 print "Could not read electrum.conf. I will use the default values."
62 dblock = thread.allocate_lock()
65 wallets = {} # for ultra-light clients such as bccapi
67 class MyStore(Datastore_class):
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)
73 def update_tx_cache(self, txid):
74 inrows = self.get_tx_inputs(txid, False)
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
80 self.tx_cache.pop(address)
81 outrows = self.get_tx_outputs(txid, False)
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
87 self.tx_cache.pop(address)
89 def safe_sql(self,sql, params=(), lock=True):
91 if lock: dblock.acquire()
92 ret = self.selectall(sql,params)
93 if lock: dblock.release()
96 print "sql error", sql
99 def get_tx_outputs(self, tx_id, lock=True):
100 return self.safe_sql("""SELECT
102 txout.txout_scriptPubKey,
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)
116 def get_tx_inputs(self, tx_id, lock=True):
117 return self.safe_sql(""" SELECT
121 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
123 COALESCE(txout.txout_pos, u.txout_pos),
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)
134 def get_address_out_rows(self, dbhash):
135 return self.safe_sql(""" SELECT
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,))
155 def get_address_out_rows_memorypool(self, dbhash):
156 return self.safe_sql(""" SELECT
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,))
168 def get_address_in_rows(self, dbhash):
169 return self.safe_sql(""" SELECT
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,))
188 def get_address_in_rows_memorypool(self, dbhash):
189 return self.safe_sql( """ SELECT
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,))
200 def get_history(self, addr):
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
207 version, binaddr = decode_check_address(addr)
211 dbhash = self.binin(binaddr)
213 rows += self.get_address_out_rows( dbhash )
214 rows += self.get_address_in_rows( dbhash )
221 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
223 print "cannot unpack row", row
225 tx_hash = self.hashout_hex(tx_hash)
228 #"chain_id": int(chain_id),
229 "height": int(height),
231 "blk_hash": self.hashout_hex(blk_hash),
238 txpoints.append(txpoint)
239 known_tx.append(self.hashout_hex(tx_hash))
242 # todo: sort them really...
243 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
247 rows += self.get_address_in_rows_memorypool( dbhash )
248 rows += self.get_address_out_rows_memorypool( dbhash )
249 address_has_mempool = False
252 is_in, tx_hash, tx_id, pos, value = row
253 tx_hash = self.hashout_hex(tx_hash)
254 if tx_hash in known_tx:
257 # this means that pending transactions were added to the db, even if they are not returned by getmemorypool
258 address_has_mempool = True
260 # this means pending transactions are returned by getmemorypool
261 if tx_hash not in self.mempool_keys:
264 #print "mempool", tx_hash
270 "blk_hash": 'mempool',
276 txpoints.append(txpoint)
279 for txpoint in txpoints:
280 tx_id = txpoint['tx_id']
283 inrows = self.get_tx_inputs(tx_id)
285 _hash = self.binout(row[6])
286 address = hash_to_address(chr(0), _hash)
287 txinputs.append(address)
288 txpoint['inputs'] = txinputs
290 outrows = self.get_tx_outputs(tx_id)
292 _hash = self.binout(row[6])
293 address = hash_to_address(chr(0), _hash)
294 txoutputs.append(address)
295 txpoint['outputs'] = txoutputs
297 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
298 if not txpoint['is_in']:
299 # detect if already redeemed...
301 if row[6] == dbhash: break
304 #row = self.get_tx_output(tx_id,dbhash)
305 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
306 # if not redeemed, we add the script
308 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
311 if config.get('server','cache') == 'yes' and not address_has_mempool:
312 self.tx_cache[addr] = txpoints
320 conn = bitcoinrpc.connect_to_local()
322 v = conn.importtransaction(tx)
324 v = "error: transaction rejected by memorypool"
328 def listen_thread(store):
329 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
330 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
331 s.bind((config.get('server','host'), config.getint('server','port')))
334 conn, addr = s.accept()
335 thread.start_new_thread(client_thread, (addr, conn,))
337 def random_string(N):
338 import random, string
339 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
341 def client_thread(ipaddr,conn):
342 #print "client thread", ipaddr
352 msg = msg.split('#', 1)[0]
355 cmd, data = ast.literal_eval(msg)
357 print "syntax error", repr(msg), ipaddr
362 out = "%d"%block_number
364 elif cmd in ['session','new_session']:
365 session_id = random_string(10)
368 addresses = ast.literal_eval(data)
371 version, addresses = ast.literal_eval(data)
372 if version[0]=="0": version = "v" + version
378 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version
380 sessions[session_id] = { 'addresses':{}, 'version':version, 'ip':ipaddr }
382 sessions[session_id]['addresses'][a] = ''
383 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
384 sessions[session_id]['last_time'] = time.time()
386 elif cmd=='update_session':
388 session_id, addresses = ast.literal_eval(data)
394 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses)
396 sessions[session_id]['addresses'] = {}
398 sessions[session_id]['addresses'][a] = ''
400 sessions[session_id]['last_time'] = time.time()
402 elif cmd == 'bccapi_login':
405 v, k = ast.literal_eval(data)
406 master_public_key = k.decode('hex') # todo: sanitize. no need to decode twice...
407 print master_public_key
408 wallet_id = random_string(10)
409 w = electrum.Wallet()
410 w.master_public_key = master_public_key.decode('hex')
412 wallets[wallet_id] = w
414 print "wallets", wallets
416 elif cmd == 'bccapi_getAccountInfo':
418 v, wallet_id = ast.literal_eval(data)
419 w = wallets.get(wallet_id)
421 num = len(w.addresses)
422 c, u = w.get_balance()
423 out = electrum.int_to_hex(num,4) + electrum.int_to_hex(c,8) + electrum.int_to_hex( c+u, 8 )
424 out = out.decode('hex')
431 session = sessions.get(session_id)
433 print time.asctime(), "session not found", session_id, ipaddr
434 out = repr( (-1, {}))
437 addresses = session['addresses']
438 session['last_time'] = time.time()
441 for addr in addresses:
442 if store.tx_cache.get( addr ) is not None: k += 1
444 # get addtess status, i.e. the last block for that address.
445 tx_points = store.get_history(addr)
449 lastpoint = tx_points[-1]
450 status = lastpoint['blk_hash']
451 # this is a temporary hack; move it up once old clients have disappeared
452 if status == 'mempool' and session['version'] != "old":
453 status = status + ':%d'% len(tx_points)
455 last_status = addresses.get( addr )
456 if last_status != status:
457 addresses[addr] = status
460 sessions[session_id]['addresses'] = addresses
461 out = repr( (block_number, ret ) )
462 t2 = time.time() - t1
464 print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2
469 out = repr( store.get_history( address ) )
472 if config.get('server','password') == data:
473 out = repr( len(sessions) )
475 out = 'wrong password'
479 print "sent tx:", out
481 elif cmd =='clear_cache':
482 if config.get('server','password') == data:
486 out = 'wrong password'
488 elif cmd =='get_cache':
494 if config.get('server','password') == pw:
495 out = store.tx_cache.get(addr)
498 out = 'wrong password'
500 out = "error: "+ repr(data)
504 if config.get('server','password') == data:
508 out = 'wrong password'
511 out = repr(peer_list.values())
517 #print ipaddr, cmd, len(out)
521 print "error, could not send"
531 def memorypool_update(store):
532 ds = BCDataStream.BCDataStream()
533 store.mempool_keys = []
534 conn = bitcoinrpc.connect_to_local()
536 v = conn.getmemorypool()
538 print "cannot contact bitcoin daemon"
540 v = v['transactions']
543 ds.write(hextx.decode('hex'))
544 tx = deserialize.parse_Transaction(ds)
545 tx['hash'] = util.double_sha256(tx['tx'])
546 tx_hash = tx['hash'][::-1].encode('hex')
547 store.mempool_keys.append(tx_hash)
548 if store.tx_find_id_and_value(tx):
551 store.import_tx(tx, False)
557 def clean_session_thread():
561 for k,s in sessions.items():
564 print time.strftime("[%d/%m/%Y-%H:%M:%S]"), "end session", s['ip']
570 NICK = 'E_'+random_string(10)
574 s.connect(('irc.freenode.net', 6667))
575 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
576 s.send('NICK '+NICK+'\n')
577 s.send('JOIN #electrum\n')
578 sf = s.makefile('r', 0)
582 line = line.rstrip('\r\n')
585 s.send('PONG '+line[1]+'\n')
586 elif '353' in line: # answer to /names
587 k = line.index('353')
588 for item in line[k+1:]:
589 if item[0:2] == 'E_':
590 s.send('WHO %s\n'%item)
591 elif '352' in line: # answer to /who
592 # warning: this is a horrible hack which apparently works
593 k = line.index('352')
595 ip = socket.gethostbyname(ip)
598 peer_list[name] = (ip,host)
599 if time.time() - t > 5*60:
600 s.send('NAMES #electrum\n')
604 traceback.print_exc(file=sys.stdout)
613 if __name__ == '__main__':
617 pw = config.get('server','password')
619 request = "('load','%s')#"%pw
621 request = "('peers','')#"
623 request = "('stop','%s')#"%pw
624 elif cmd == 'clear_cache':
625 request = "('clear_cache','%s')#"%pw
626 elif cmd == 'get_cache':
627 request = "('get_cache',('%s','%s'))#"%(pw,sys.argv[2])
629 request = "('h','%s')#"%sys.argv[2]
631 request = "('b','')#"
633 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
634 s.connect((config.get('server','host'), config.getint('server','port')))
646 print "starting Electrum server"
647 print "cache:", config.get('server', 'cache')
649 conf = DataStore.CONFIG_DEFAULTS
650 args, argv = readconf.parse_argv( [], conf)
651 args.dbtype= config.get('database','type')
652 if args.dbtype == 'sqlite3':
653 args.connect_args = { 'database' : config.get('database','database') }
654 elif args.dbtype == 'MySQLdb':
655 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
656 elif args.dbtype == 'psycopg2':
657 args.connect_args = { 'database' : config.get('database','database') }
658 store = MyStore(args)
660 store.mempool_keys = {}
662 thread.start_new_thread(listen_thread, (store,))
663 thread.start_new_thread(clean_session_thread, ())
664 if (config.get('server','irc') == 'yes' ):
665 thread.start_new_thread(irc_thread, ())
671 memorypool_update(store)
672 block_number = store.get_block_number(1)
675 traceback.print_exc(file=sys.stdout)
678 print "server stopped"