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()
65 class MyStore(Datastore_class):
67 def import_tx(self, tx, is_coinbase):
68 tx_id = super(MyStore, self).import_tx(tx, is_coinbase)
69 self.update_tx_cache(tx_id)
71 def update_tx_cache(self, txid):
72 inrows = self.get_tx_inputs(txid, False)
74 _hash = store.binout(row[6])
75 address = hash_to_address(chr(0), _hash)
76 if self.tx_cache.has_key(address):
77 print "cache: popping", address
78 self.tx_cache.pop(address)
79 outrows = self.get_tx_outputs(txid, False)
81 _hash = store.binout(row[6])
82 address = hash_to_address(chr(0), _hash)
83 if self.tx_cache.has_key(address):
84 print "cache: popping", address
85 self.tx_cache.pop(address)
87 def safe_sql(self,sql, params=(), lock=True):
89 if lock: dblock.acquire()
90 ret = self.selectall(sql,params)
91 if lock: dblock.release()
94 print "sql error", sql
97 def get_tx_outputs(self, tx_id, lock=True):
98 return self.safe_sql("""SELECT
100 txout.txout_scriptPubKey,
107 LEFT JOIN txin ON (txin.txout_id = txout.txout_id)
108 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
109 LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id)
110 WHERE txout.tx_id = %d
111 ORDER BY txout.txout_pos
112 """%(tx_id), (), lock)
114 def get_tx_inputs(self, tx_id, lock=True):
115 return self.safe_sql(""" SELECT
119 COALESCE(prevtx.tx_hash, u.txout_tx_hash),
121 COALESCE(txout.txout_pos, u.txout_pos),
124 LEFT JOIN txout ON (txout.txout_id = txin.txout_id)
125 LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
126 LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id)
127 LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id)
128 WHERE txin.tx_id = %d
129 ORDER BY txin.txin_pos
130 """%(tx_id,), (), lock)
132 def get_address_out_rows(self, dbhash):
133 return self.safe_sql(""" SELECT
143 FROM chain_candidate cc
144 JOIN block b ON (b.block_id = cc.block_id)
145 JOIN block_tx ON (block_tx.block_id = b.block_id)
146 JOIN tx ON (tx.tx_id = block_tx.tx_id)
147 JOIN txin ON (txin.tx_id = tx.tx_id)
148 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
149 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
150 WHERE pubkey.pubkey_hash = ?
151 AND cc.in_longest = 1""", (dbhash,))
153 def get_address_out_rows_memorypool(self, dbhash):
154 return self.safe_sql(""" SELECT
161 JOIN txin ON (txin.tx_id = tx.tx_id)
162 JOIN txout prevout ON (txin.txout_id = prevout.txout_id)
163 JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id)
164 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
166 def get_address_in_rows(self, dbhash):
167 return self.safe_sql(""" SELECT
177 FROM chain_candidate cc
178 JOIN block b ON (b.block_id = cc.block_id)
179 JOIN block_tx ON (block_tx.block_id = b.block_id)
180 JOIN tx ON (tx.tx_id = block_tx.tx_id)
181 JOIN txout ON (txout.tx_id = tx.tx_id)
182 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
183 WHERE pubkey.pubkey_hash = ?
184 AND cc.in_longest = 1""", (dbhash,))
186 def get_address_in_rows_memorypool(self, dbhash):
187 return self.safe_sql( """ SELECT
194 JOIN txout ON (txout.tx_id = tx.tx_id)
195 JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id)
196 WHERE pubkey.pubkey_hash = ? """, (dbhash,))
198 def get_txpoints(self, addr):
200 cached_version = self.tx_cache.get( addr )
202 version, binaddr = decode_check_address(addr)
205 dbhash = self.binin(binaddr)
207 rows += self.get_address_out_rows( dbhash )
208 rows += self.get_address_in_rows( dbhash )
215 nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row
217 print "cannot unpack row", row
219 tx_hash = self.hashout_hex(tx_hash)
222 #"chain_id": int(chain_id),
223 "height": int(height),
225 "blk_hash": self.hashout_hex(blk_hash),
232 txpoints.append(txpoint)
233 known_tx.append(self.hashout_hex(tx_hash))
236 # todo: sort them really...
237 txpoints = sorted(txpoints, key=operator.itemgetter("nTime"))
241 rows += self.get_address_in_rows_memorypool( dbhash )
242 rows += self.get_address_out_rows_memorypool( dbhash )
244 is_in, tx_hash, tx_id, pos, value = row
245 tx_hash = self.hashout_hex(tx_hash)
246 if tx_hash in known_tx:
248 #print "mempool", tx_hash
254 "blk_hash": 'mempool',
260 txpoints.append(txpoint)
263 for txpoint in txpoints:
264 tx_id = txpoint['tx_id']
267 inrows = self.get_tx_inputs(tx_id)
269 _hash = self.binout(row[6])
270 address = hash_to_address(chr(0), _hash)
271 txinputs.append(address)
272 txpoint['inputs'] = txinputs
274 outrows = self.get_tx_outputs(tx_id)
276 _hash = self.binout(row[6])
277 address = hash_to_address(chr(0), _hash)
278 txoutputs.append(address)
279 txpoint['outputs'] = txoutputs
281 # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address)
282 if not txpoint['is_in']:
283 # detect if already redeemed...
285 if row[6] == dbhash: break
288 #row = self.get_tx_output(tx_id,dbhash)
289 # pos, script, value, o_hash, o_id, o_pos, binaddr = row
290 # if not redeemed, we add the script
292 if not row[4]: txpoint['raw_scriptPubKey'] = row[1]
295 if cached_version is None:
296 #print "cache: adding", addr
297 self.tx_cache[addr] = txpoints
300 if cached_version != txpoints:
301 print "cache error: ", addr
305 def get_status(self, addr):
306 # last block for an address.
307 tx_points = self.get_txpoints(addr)
311 return tx_points[-1]['blk_hash']
316 conn = bitcoinrpc.connect_to_local()
318 v = conn.importtransaction(tx)
320 v = "error: transaction rejected by memorypool"
324 def listen_thread(store):
325 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
326 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
327 s.bind((config.get('server','host'), config.getint('server','port')))
330 conn, addr = s.accept()
331 thread.start_new_thread(client_thread, (addr, conn,))
333 def random_string(N):
334 import random, string
335 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
337 def client_thread(ipaddr,conn):
338 #print "client thread", ipaddr
351 cmd, data = ast.literal_eval(msg[:-1])
353 print "syntax error", repr(msg)
358 out = "%d"%block_number
360 session_id = random_string(10)
362 addresses = ast.literal_eval(data)
368 print time.asctime(), "session", ipaddr, session_id, addresses[0], len(addresses)
370 sessions[session_id] = {}
372 sessions[session_id][a] = ''
373 out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) )
374 sessions_last_time[session_id] = time.time()
378 addresses = sessions.get(session_id)
380 print "session not found", ipaddr
381 out = repr( (-1, {}))
383 sessions_last_time[session_id] = time.time()
385 for addr in addresses:
386 status = store.get_status( addr )
387 last_status = sessions[session_id].get( addr )
388 if last_status != status:
389 sessions[session_id][addr] = status
391 out = repr( (block_number, ret ) )
396 out = repr( store.get_txpoints( address ) )
399 if config.get('server','password') == data:
400 out = repr( len(sessions) )
402 out = 'wrong password'
409 if config.get('server','password') == data:
413 out = 'wrong password'
416 out = repr(peer_list.values())
422 #print ipaddr, cmd, len(out)
426 print "error, could not send"
432 ds = BCDataStream.BCDataStream()
437 def memorypool_update(store):
438 conn = bitcoinrpc.connect_to_local()
440 v = conn.getmemorypool()
442 print "cannot contact bitcoin daemon"
444 v = v['transactions']
447 ds.write(hextx.decode('hex'))
448 tx = deserialize.parse_Transaction(ds)
451 tx['hash'] = util.double_sha256(tx['tx'])
453 if store.tx_find_id_and_value(tx):
456 store.import_tx(tx, False)
463 def clean_session_thread():
467 for k,t0 in sessions_last_time.items():
469 print "lost session",k
471 sessions_last_time.pop(k)
476 NICK = 'E_'+random_string(10)
480 s.connect(('irc.freenode.net', 6667))
481 s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n')
482 s.send('NICK '+NICK+'\n')
483 s.send('JOIN #electrum\n')
484 sf = s.makefile('r', 0)
488 line = line.rstrip('\r\n')
491 s.send('PONG '+line[1]+'\n')
492 elif '353' in line: # answer to /names
493 k = line.index('353')
494 for item in line[k+1:]:
495 if item[0:2] == 'E_':
496 s.send('WHO %s\n'%item)
497 elif '352' in line: # answer to /who
498 # warning: this is a horrible hack which apparently works
499 k = line.index('352')
501 ip = socket.gethostbyname(ip)
504 peer_list[name] = (ip,host)
505 elif time.time() - t > 5*60:
506 s.send('NAMES #electrum\n')
510 traceback.print_exc(file=sys.stdout)
519 if __name__ == '__main__':
524 request = "('load','%s')#"%config.get('server','password')
526 request = "('peers','')#"
528 request = "('stop','%s')#"%config.get('server','password')
530 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
531 s.connect((config.get('server','host'), config.getint('server','port')))
543 print "starting Electrum server"
544 conf = DataStore.CONFIG_DEFAULTS
545 args, argv = readconf.parse_argv( [], conf)
546 args.dbtype= config.get('database','type')
547 if args.dbtype == 'sqlite3':
548 args.connect_args = { 'database' : config.get('database','database') }
549 elif args.dbtype == 'MySQLdb':
550 args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') }
551 elif args.dbtype == 'psycopg2':
552 args.connect_args = { 'database' : config.get('database','database') }
553 store = MyStore(args)
556 thread.start_new_thread(listen_thread, (store,))
557 thread.start_new_thread(clean_session_thread, ())
558 if (config.get('server','irc') == 'yes' ):
559 thread.start_new_thread(irc_thread, ())
565 memorypool_update(store)
566 block_number = store.get_block_number(1)
569 traceback.print_exc(file=sys.stdout)
572 print "server stopped"