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.add_section('database')
43 config.set('database', 'type', 'psycopg2')
44 config.set('database', 'database', 'abe')
47 f = open('/etc/electrum.conf','r')
51 print "Could not read electrum.conf. I will use the dafault values."
56 sessions_last_time = {}
57 dblock = thread.allocate_lock()
61 class MyStore(Datastore_class):
63 def safe_sql(self,sql, params=()):
66 ret = self.selectall(sql,params)
70 print "sql error", sql
73 def get_tx_outputs(self, tx_id):
74 return self.safe_sql("""SELECT
76 txout.txout_scriptPubKey,
83 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
84 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
85 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
86 WHERE txout.tx_id = %d
87 ORDER BY txout.txout_pos
90 def get_tx_inputs(self, tx_id):
91 return self.safe_sql(""" SELECT
95 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
97 COALESCE(txout.txout_pos, u.txout_pos),
100 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
101 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
102 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
103 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
104 WHERE txin.tx_id = %d
105 ORDER BY txin.txin_pos
108 def get_address_out_rows(self, dbhash):
109 return self.safe_sql(""" SELECT
119 FROM chain_candidate cc
120 JOIN block b ON (b.block_id = cc.block_id)
121 JOIN block_tx ON (block_tx.block_id = b.block_id)
122 JOIN tx ON (tx.tx_id = block_tx.tx_id)
123 JOIN txin ON (txin.tx_id = tx.tx_id)
124 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
125 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
126 WHERE pubkey.pubkey_hash = ?
127 AND cc.in_longest = 1""", (dbhash,))
129 def get_address_out_rows_memorypool(self, dbhash):
130 return self.safe_sql(""" SELECT
137 JOIN txin ON (txin.tx_id = tx.tx_id)
138 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
139 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
140 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
142 def get_address_in_rows(self, dbhash):
143 return self.safe_sql(""" SELECT
153 FROM chain_candidate cc
154 JOIN block b ON (b.block_id = cc.block_id)
155 JOIN block_tx ON (block_tx.block_id = b.block_id)
156 JOIN tx ON (tx.tx_id = block_tx.tx_id)
157 JOIN txout ON (txout.tx_id = tx.tx_id)
158 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
159 WHERE pubkey.pubkey_hash = ?
160 AND cc.in_longest = 1""", (dbhash,))
162 def get_address_in_rows_memorypool(self, dbhash):
163 return self.safe_sql( """ SELECT
170 JOIN txout ON (txout.tx_id = tx.tx_id)
171 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
172 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
174 def get_txpoints(self, addr):
175 version, binaddr = decode_check_address(addr)
178 dbhash = self.binin(binaddr)
180 rows += self.get_address_out_rows( dbhash )
181 rows += self.get_address_in_rows( dbhash )
188 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
190 print "cannot unpack row", row
192 tx_hash = self.hashout_hex(tx_hash)
195 #"chain_id": int(chain_id),
196 "height": int(height),
198 "blk_hash": self.hashout_hex(blk_hash),
205 txpoints.append(txpoint)
206 known_tx.append(self.hashout_hex(tx_hash))
209 # todo: sort them really...
210 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
214 rows += self.get_address_in_rows_memorypool( dbhash )
215 rows += self.get_address_out_rows_memorypool( dbhash )
217 is_in, tx_hash, tx_id, pos, value = row
218 tx_hash = self.hashout_hex(tx_hash)
219 if tx_hash in known_tx:
221 #print "mempool", tx_hash
227 "blk_hash": 'mempool',
233 txpoints.append(txpoint)
236 for txpoint in txpoints:
237 tx_id = txpoint['tx_id']
240 inrows = self.get_tx_inputs(tx_id)
242 _hash = self.binout(row[6])
243 address = hash_to_address(chr(0), _hash)
244 txinputs.append(address)
245 txpoint['inputs'] = txinputs
247 outrows = self.get_tx_outputs(tx_id)
249 _hash = self.binout(row[6])
250 address = hash_to_address(chr(0), _hash)
251 txoutputs.append(address)
252 txpoint['outputs'] = txoutputs
254 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
255 if not txpoint['is_in']:
256 # detect if already redeemed...
258 if row[6] == dbhash: break
261 #row = self.get_tx_output(tx_id,dbhash)
262 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
263 # if not redeemed, we add the script
265 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
271 def get_status(self, addr):
272 # last block for an address
273 tx_points = self.get_txpoints(addr)
277 return tx_points[-1]['blk_hash']
282 conn = bitcoinrpc.connect_to_local()
284 v = conn.importtransaction(tx)
286 v = "error: transaction rejected by memorypool"
290 def listen_thread(store):
291 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
292 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
293 s.bind((config.get('server','host'), config.getint('server','port')))
296 conn, addr = s.accept()
297 thread.start_new_thread(client_thread, (addr, conn,))
299 def random_string(N):
300 import random, string
301 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
303 def client_thread(ipaddr,conn):
304 #print "client thread", ipaddr
317 cmd, data = ast.literal_eval(msg[:-1])
319 print "syntax error", repr(msg)
324 out = "%d"%block_number
326 session_id = random_string(10)
328 addresses = ast.literal_eval(data)
334 print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
336 sessions[session_id] = {}
338 sessions[session_id][a] = ''
339 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
340 sessions_last_time[session_id] = time.time()
344 addresses = sessions.get(session_id)
346 print "session not found", ipaddr
347 out = repr( (-1, {}))
349 sessions_last_time[session_id] = time.time()
351 for addr in addresses:
352 status = store.get_status( addr )
353 last_status = sessions[session_id].get( addr )
354 if last_status != status:
355 sessions[session_id][addr] = status
357 out = repr( (block_number, ret ) )
362 h = store.get_txpoints( addr )
366 if config.get('server','password') == data:
367 out = repr( len(sessions) )
369 out = 'wrong password'
376 if config.get('server','password') == data:
380 out = 'wrong password'
383 out = repr(peer_list.values())
389 #print ipaddr, cmd, len(out)
393 print "error, could not send"
399 ds = BCDataStream.BCDataStream()
402 def memorypool_update(store):
404 conn = bitcoinrpc.connect_to_local()
406 v = conn.getmemorypool()
408 print "cannot contact bitcoin daemmon"
410 v = v['transactions']
413 ds.write(hextx.decode('hex'))
414 tx = deserialize.parse_Transaction(ds)
415 tx['hash'] = util.double_sha256(tx['tx'])
417 if store.tx_find_id_and_value(tx):
420 store.import_tx(tx, False)
421 #print tx['hash'][::-1].encode('hex')
427 def clean_session_thread():
431 for k,t0 in sessions_last_time.items():
433 print "lost session",k
435 sessions_last_time.pop(k)
440 NICK = 'E_'+random_string(10)
444 s.connect(('irc.freenode.net', 6667))
445 s.send('USER '+config.get('server','host')+' '+NICK+' bla :'+NICK+'\n')
446 s.send('NICK '+NICK+'\n')
447 s.send('JOIN #electrum\n')
451 line = line.rstrip('\r\n')
454 s.send('PONG '+line[1]+'\n')
455 elif '353' in line: # answer to /names
456 k = line.index('353')
458 k2 = line.index('366')
461 for item in line[k+1:k2]:
462 if item[0:2] == 'E_':
463 s.send('USERHOST %s\n'%item)
464 elif '302' in line: # answer to /userhost
465 k = line.index('302')
466 m = re.match( "^:(.*?)=\+~(.*?)@(.*?)$", line[k+2] )
471 peer_list[name] = (ip,host)
472 elif time.time() - t > 5*60:
473 s.send('NAMES #electrum\n')
476 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','user'), 'passwd' : config.get('database','pass') }
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 thread.start_new_thread(irc_thread, ())
528 memorypool_update(store)
529 block_number = store.get_block_number(1)
532 traceback.print_exc(file=sys.stdout)
535 print "server stopped"