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
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
34 f = open('/etc/electrum.conf','r')
37 HOST, PORT, PASSWORD, SERVER_MESSAGE = ast.literal_eval(data)
39 print "could not read /etc/electrum.conf"
40 SERVER_MESSAGE = "Welcome to Electrum"
49 sessions_last_time = {}
50 dblock = thread.allocate_lock()
54 class MyStore(Datastore_class):
56 def safe_sql(self,sql):
59 ret = self.selectall(sql)
63 print "sql error", sql
66 def get_tx_outputs(self, tx_id):
67 return self.safe_sql("""SELECT
69 txout.txout_scriptPubKey,
76 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
77 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
78 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
79 WHERE txout.tx_id = %d
80 ORDER BY txout.txout_pos
83 def get_tx_inputs(self, tx_id):
84 return self.safe_sql(""" SELECT
88 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
90 COALESCE(txout.txout_pos, u.txout_pos),
93 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
94 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
95 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
96 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
98 ORDER BY txin.txin_pos
101 def get_address_out_rows(self, dbhash):
102 return self.safe_sql(""" SELECT
112 FROM chain_candidate cc
113 JOIN block b ON (b.block_id = cc.block_id)
114 JOIN block_tx ON (block_tx.block_id = b.block_id)
115 JOIN tx ON (tx.tx_id = block_tx.tx_id)
116 JOIN txin ON (txin.tx_id = tx.tx_id)
117 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
118 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
119 WHERE pubkey.pubkey_hash = '%s'
120 AND cc.in_longest = 1"""%dbhash)
122 def get_address_out_rows_memorypool(self, dbhash):
123 return self.safe_sql(""" SELECT
130 JOIN txin ON (txin.tx_id = tx.tx_id)
131 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
132 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
133 WHERE pubkey.pubkey_hash ='%s' """%(dbhash))
135 def get_address_in_rows(self, dbhash):
136 return self.safe_sql(""" SELECT
146 FROM chain_candidate cc
147 JOIN block b ON (b.block_id = cc.block_id)
148 JOIN block_tx ON (block_tx.block_id = b.block_id)
149 JOIN tx ON (tx.tx_id = block_tx.tx_id)
150 JOIN txout ON (txout.tx_id = tx.tx_id)
151 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
152 WHERE pubkey.pubkey_hash = '%s'
153 AND cc.in_longest = 1"""%(dbhash))
155 def get_address_in_rows_memorypool(self, dbhash):
156 return self.safe_sql( """ SELECT
163 JOIN txout ON (txout.tx_id = tx.tx_id)
164 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
165 WHERE pubkey.pubkey_hash = '%s' """%(dbhash))
167 def get_txpoints(self, addr):
168 version, binaddr = decode_check_address(addr)
171 dbhash = self.binin(binaddr)
173 rows += self.get_address_out_rows( dbhash )
174 rows += self.get_address_in_rows( dbhash )
181 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
183 print "cannot unpack row", row
185 tx_hash = self.hashout_hex(tx_hash)
188 #"chain_id": int(chain_id),
189 "height": int(height),
191 "blk_hash": self.hashout_hex(blk_hash),
198 txpoints.append(txpoint)
199 known_tx.append(self.hashout_hex(tx_hash))
202 # todo: sort them really...
203 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
207 rows += self.get_address_in_rows_memorypool( dbhash )
208 rows += self.get_address_out_rows_memorypool( dbhash )
210 is_in, tx_hash, tx_id, pos, value = row
211 tx_hash = self.hashout_hex(tx_hash)
212 if tx_hash in known_tx:
214 #print "mempool", tx_hash
220 "blk_hash": 'mempool',
226 txpoints.append(txpoint)
229 for txpoint in txpoints:
230 tx_id = txpoint['tx_id']
233 inrows = self.get_tx_inputs(tx_id)
235 _hash = self.binout(row[6])
236 address = hash_to_address(chr(0), _hash)
237 txinputs.append(address)
238 txpoint['inputs'] = txinputs
240 outrows = self.get_tx_outputs(tx_id)
242 _hash = self.binout(row[6])
243 address = hash_to_address(chr(0), _hash)
244 txoutputs.append(address)
245 txpoint['outputs'] = txoutputs
247 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
248 if not txpoint['is_in']:
249 # detect if already redeemed...
251 if row[6] == dbhash: break
254 #row = self.get_tx_output(tx_id,dbhash)
255 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
256 # if not redeemed, we add the script
258 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
264 def get_status(self, addr):
265 # last block for an address
266 tx_points = self.get_txpoints(addr)
270 return tx_points[-1]['blk_hash']
275 conn = bitcoinrpc.connect_to_local()
277 v = conn.importtransaction(tx)
279 v = "error: transaction rejected by memorypool"
283 def listen_thread(store):
284 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
285 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
289 conn, addr = s.accept()
290 thread.start_new_thread(client_thread, (addr, conn,))
292 def random_string(N):
293 import random, string
294 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
296 def client_thread(ipaddr,conn):
297 #print "client thread", ipaddr
310 cmd, data = ast.literal_eval(msg[:-1])
312 print "syntax error", repr(msg)
317 out = "%d"%store.get_block_number(1)
320 session_id = random_string(10)
322 addresses = ast.literal_eval(data)
328 print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
330 sessions[session_id] = {}
332 sessions[session_id][a] = ''
333 out = repr( (session_id, SERVER_MESSAGE) )
334 sessions_last_time[session_id] = time.time()
338 addresses = sessions.get(session_id)
340 print "session not found", ipaddr
341 out = repr( (-1, {}))
343 sessions_last_time[session_id] = time.time()
345 for addr in addresses:
346 status = store.get_status( addr )
347 last_status = sessions[session_id].get( addr )
348 if last_status != status:
349 sessions[session_id][addr] = status
351 out = repr( (store.get_block_number(1), ret ) )
356 h = store.get_txpoints( addr )
361 out = repr( len(sessions) )
363 out = 'wrong password'
374 out = 'wrong password'
377 out = repr(peer_list.values())
383 #print ipaddr, cmd, len(out)
387 print "error, could not send"
393 ds = BCDataStream.BCDataStream()
396 def memorypool_update(store):
398 conn = bitcoinrpc.connect_to_local()
400 v = conn.getmemorypool()
402 print "cannot contact bitcoin daemmon"
404 v = v['transactions']
407 ds.write(hextx.decode('hex'))
408 tx = deserialize.parse_Transaction(ds)
409 tx['hash'] = util.double_sha256(tx['tx'])
411 if store.tx_find_id_and_value(tx):
414 store.import_tx(tx, False)
415 #print tx['hash'][::-1].encode('hex')
421 def clean_session_thread():
425 for k,t0 in sessions_last_time.items():
427 print "lost session",k
429 sessions_last_time.pop(k)
434 NICK = 'E_'+random_string(10)
438 s.connect(('irc.freenode.net', 6667))
439 s.send('USER '+NICK+' '+NICK+' bla :'+NICK+'\n')
440 s.send('NICK '+NICK+'\n')
441 s.send('JOIN #electrum\n')
445 line = line.rstrip('\r\n')
448 s.send('PONG '+line[1]+'\n')
449 elif '353' in line: # answer to /names
450 k = line.index('353')
451 k2 = line.index('366')
452 for item in line[k+1:k2]:
453 if item[0:2] == 'E_':
454 s.send('USERHOST %s\n'%item)
455 elif '302' in line: # answer to /userhost
456 k = line.index('302')
458 host = line[k+2].split('@')[1]
459 peer_list[name] = host
460 elif time.time() - t > 5*60:
461 s.send('NAMES #electrum\n')
464 traceback.print_exc(file=sys.stdout)
472 if __name__ == '__main__':
477 request = "('load','%s')#"%PASSWORD
479 request = "('peers','')#"
481 request = "('stop','%s')#"%PASSWORD
483 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
484 s.connect(( HOST, PORT))
496 print "starting Electrum server"
497 conf = DataStore.CONFIG_DEFAULTS
498 args, argv = readconf.parse_argv( [], conf)
499 args.dbtype='psycopg2'
500 args.connect_args = {"database":"abe"}
501 store = MyStore(args)
503 thread.start_new_thread(listen_thread, (store,))
504 thread.start_new_thread(clean_session_thread, ())
505 thread.start_new_thread(irc_thread, ())
511 memorypool_update(store)
514 traceback.print_exc(file=sys.stdout)
517 print "server stopped"