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
25 import time, socket, operator, thread, ast, sys,re
26 import psycopg2, binascii
29 from Abe.abe import hash_to_address, decode_check_address
30 from Abe.DataStore import DataStore as Datastore_class
31 from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58
35 config = ConfigParser.ConfigParser()
36 # set some defaults, which will be overwritten by the config file
37 config.add_section('server')
38 config.set('server','banner', 'Welcome to Electrum!')
39 config.set('server', 'host', 'ecdsa.org')
40 config.set('server', 'port', 50000)
41 config.set('server', 'password', '')
42 config.set('server', 'irc', 'yes')
43 config.set('server', 'ircname', 'Electrum server')
44 config.add_section('database')
45 config.set('database', 'type', 'psycopg2')
46 config.set('database', 'database', 'abe')
49 f = open('/etc/electrum.conf','r')
53 print "Could not read electrum.conf. I will use the default values."
58 sessions_last_time = {}
59 dblock = thread.allocate_lock()
63 class MyStore(Datastore_class):
65 def safe_sql(self,sql, params=()):
68 ret = self.selectall(sql,params)
72 print "sql error", sql
75 def get_tx_outputs(self, tx_id):
76 return self.safe_sql("""SELECT
78 txout.txout_scriptPubKey,
85 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
86 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
87 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
88 WHERE txout.tx_id = %d
89 ORDER BY txout.txout_pos
92 def get_tx_inputs(self, tx_id):
93 return self.safe_sql(""" SELECT
97 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
99 COALESCE(txout.txout_pos, u.txout_pos),
102 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
103 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
104 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
105 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
106 WHERE txin.tx_id = %d
107 ORDER BY txin.txin_pos
110 def get_address_out_rows(self, dbhash):
111 return self.safe_sql(""" SELECT
121 FROM chain_candidate cc
122 JOIN block b ON (b.block_id = cc.block_id)
123 JOIN block_tx ON (block_tx.block_id = b.block_id)
124 JOIN tx ON (tx.tx_id = block_tx.tx_id)
125 JOIN txin ON (txin.tx_id = tx.tx_id)
126 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
127 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
128 WHERE pubkey.pubkey_hash = ?
129 AND cc.in_longest = 1""", (dbhash,))
131 def get_address_out_rows_memorypool(self, dbhash):
132 return self.safe_sql(""" SELECT
139 JOIN txin ON (txin.tx_id = tx.tx_id)
140 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
141 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
142 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
144 def get_address_in_rows(self, dbhash):
145 return self.safe_sql(""" SELECT
155 FROM chain_candidate cc
156 JOIN block b ON (b.block_id = cc.block_id)
157 JOIN block_tx ON (block_tx.block_id = b.block_id)
158 JOIN tx ON (tx.tx_id = block_tx.tx_id)
159 JOIN txout ON (txout.tx_id = tx.tx_id)
160 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
161 WHERE pubkey.pubkey_hash = ?
162 AND cc.in_longest = 1""", (dbhash,))
164 def get_address_in_rows_memorypool(self, dbhash):
165 return self.safe_sql( """ SELECT
172 JOIN txout ON (txout.tx_id = tx.tx_id)
173 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
174 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
176 def get_txpoints(self, addr):
177 version, binaddr = decode_check_address(addr)
180 dbhash = self.binin(binaddr)
182 rows += self.get_address_out_rows( dbhash )
183 rows += self.get_address_in_rows( dbhash )
190 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
192 print "cannot unpack row", row
194 tx_hash = self.hashout_hex(tx_hash)
197 #"chain_id": int(chain_id),
198 "height": int(height),
200 "blk_hash": self.hashout_hex(blk_hash),
207 txpoints.append(txpoint)
208 known_tx.append(self.hashout_hex(tx_hash))
211 # todo: sort them really...
212 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
216 rows += self.get_address_in_rows_memorypool( dbhash )
217 rows += self.get_address_out_rows_memorypool( dbhash )
219 is_in, tx_hash, tx_id, pos, value = row
220 tx_hash = self.hashout_hex(tx_hash)
221 if tx_hash in known_tx:
223 #print "mempool", tx_hash
229 "blk_hash": 'mempool',
235 txpoints.append(txpoint)
238 for txpoint in txpoints:
239 tx_id = txpoint['tx_id']
242 inrows = self.get_tx_inputs(tx_id)
244 _hash = self.binout(row[6])
245 address = hash_to_address(chr(0), _hash)
246 txinputs.append(address)
247 txpoint['inputs'] = txinputs
249 outrows = self.get_tx_outputs(tx_id)
251 _hash = self.binout(row[6])
252 address = hash_to_address(chr(0), _hash)
253 txoutputs.append(address)
254 txpoint['outputs'] = txoutputs
256 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
257 if not txpoint['is_in']:
258 # detect if already redeemed...
260 if row[6] == dbhash: break
263 #row = self.get_tx_output(tx_id,dbhash)
264 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
265 # if not redeemed, we add the script
267 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
273 def get_status(self, addr):
274 # last block for an address
275 tx_points = self.get_txpoints(addr)
279 return tx_points[-1]['blk_hash']
284 conn = bitcoinrpc.connect_to_local()
286 v = conn.importtransaction(tx)
288 v = "error: transaction rejected by memorypool"
292 def listen_thread(store):
293 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
294 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
295 s.bind((config.get('server','host'), config.getint('server','port')))
298 conn, addr = s.accept()
299 thread.start_new_thread(client_thread, (addr, conn,))
301 def random_string(N):
302 import random, string
303 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
305 def client_thread(ipaddr,conn):
306 #print "client thread", ipaddr
319 cmd, data = ast.literal_eval(msg[:-1])
321 print "syntax error", repr(msg)
326 out = "%d"%block_number
328 session_id = random_string(10)
330 addresses = ast.literal_eval(data)
336 print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
338 sessions[session_id] = {}
340 sessions[session_id][a] = ''
341 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
342 sessions_last_time[session_id] = time.time()
346 addresses = sessions.get(session_id)
348 print "session not found", ipaddr
349 out = repr( (-1, {}))
351 sessions_last_time[session_id] = time.time()
353 for addr in addresses:
354 status = store.get_status( addr )
355 last_status = sessions[session_id].get( addr )
356 if last_status != status:
357 sessions[session_id][addr] = status
359 out = repr( (block_number, ret ) )
364 h = store.get_txpoints( addr )
368 if config.get('server','password') == data:
369 out = repr( len(sessions) )
371 out = 'wrong password'
378 if config.get('server','password') == data:
382 out = 'wrong password'
385 out = repr(peer_list.values())
391 #print ipaddr, cmd, len(out)
395 print "error, could not send"
401 ds = BCDataStream.BCDataStream()
404 def memorypool_update(store):
406 conn = bitcoinrpc.connect_to_local()
408 v = conn.getmemorypool()
410 print "cannot contact bitcoin daemmon"
412 v = v['transactions']
415 ds.write(hextx.decode('hex'))
416 tx = deserialize.parse_Transaction(ds)
417 tx['hash'] = util.double_sha256(tx['tx'])
419 if store.tx_find_id_and_value(tx):
422 store.import_tx(tx, False)
423 #print tx['hash'][::-1].encode('hex')
429 def clean_session_thread():
433 for k,t0 in sessions_last_time.items():
435 print "lost session",k
437 sessions_last_time.pop(k)
442 NICK = 'E_'+random_string(10)
446 s.connect(('irc.freenode.net', 6667))
447 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
448 s.send('NICK '+NICK+'\n')
449 s.send('JOIN #electrum\n')
450 sf = s.makefile('r', 0)
454 line = line.rstrip('\r\n')
457 s.send('PONG '+line[1]+'\n')
458 elif '353' in line: # answer to /names
459 k = line.index('353')
460 for item in line[k+1:]:
461 if item[0:2] == 'E_':
462 s.send('WHO %s\n'%item)
463 elif '352' in line: # answer to /who
464 # warning: this is a horrible hack which apparently works
465 k = line.index('352')
467 ip = socket.gethostbyname(ip)
470 peer_list[name] = (ip,host)
471 elif time.time() - t > 5*60:
472 s.send('NAMES #electrum\n')
475 traceback.print_exc(file=sys.stdout)
484 if __name__ == '__main__':
489 request = "('load','%s')#"%config.get('server','password')
491 request = "('peers','')#"
493 request = "('stop','%s')#"%config.get('server','password')
495 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
496 s.connect((config.get('server','host'), config.getint('server','port')))
508 print "starting Electrum server"
509 conf = DataStore.CONFIG_DEFAULTS
510 args, argv = readconf.parse_argv( [], conf)
511 args.dbtype= config.get('database','type')
512 if args.dbtype == 'sqlite3':
513 args.connect_args = { 'database' : config.get('database','database') }
514 elif args.dbtype == 'MySQLdb':
515 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
516 elif args.dbtype == 'psycopg2':
517 args.connect_args = { 'database' : config.get('database','database') }
518 store = MyStore(args)
520 thread.start_new_thread(listen_thread, (store,))
521 thread.start_new_thread(clean_session_thread, ())
522 if (config.get('server','irc') == 'yes' ):
523 thread.start_new_thread(irc_thread, ())
529 memorypool_update(store)
530 block_number = store.get_block_number(1)
533 traceback.print_exc(file=sys.stdout)
536 print "server stopped"