3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 import time, thread, sys, socket, os
24 from electrum import Wallet, TcpStratumInterface
27 config = ConfigParser.ConfigParser()
28 config.read("merchant.conf")
30 db_instance = config.get('db','instance')
31 db_user = config.get('db','user')
32 db_password = config.get('db','password')
33 db_name = config.get('db','name')
35 electrum_server = config.get('electrum','server')
36 mpk = config.get('electrum','mpk')
38 my_password = config.get('main','password')
39 my_host = config.get('main','host')
40 my_port = config.getint('main','port')
42 cb_received = config.get('callback','received')
43 cb_expired = config.get('callback','expired')
44 cb_password = config.get('callback','password')
47 wallet.master_public_key = mpk.decode('hex')
53 def electrum_input_thread(in_queue, i):
55 addr, amount = in_queue.get(True,1000000000)
56 if addr in omg_addresses:
59 print "subscribing to ", addr
60 omg_addresses[addr] = amount
61 i.send([('blockchain.address.subscribe',[addr])])
64 def electrum_output_thread(out_queue, i):
66 r = i.responses.get(True, 100000000000)
67 method = r.get('method')
69 if method == 'blockchain.address.subscribe':
70 addr = r.get('params')[0]
71 i.send([('blockchain.address.get_history',[addr])])
73 elif method == 'blockchain.address.get_history':
74 addr = r.get('params')[0]
75 #print "received history for", addr
76 confirmed = unconfirmed = 0
88 s = (confirmed+unconfirmed)/1.e8
89 print "balance for %s:"%addr, s
90 amount = float(omg_addresses.get(addr))
92 out_queue.put( ('payment',addr) )
104 cur.execute("CREATE TABLE electrum_payments (id INT PRIMARY KEY, address VARCHAR(40), amount FLOAT, received_at TIMESTAMP, expires_at TIMESTAMP, paid INT(1), processed INT(1));")
107 def process_request(i, amount, confirmations, expires_in, password):
108 print "process_request", i, amount, confirmations, expires_in
109 if password!=my_password:
110 print "wrong password ", password
112 addr = wallet.get_new_address(i, 0)
113 out_queue.put( ('request',(i,addr,amount,expires_in) ))
117 return wallet.master_public_key.encode('hex')
120 def server_thread(conn):
121 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
122 server = SimpleJSONRPCServer(( my_host, my_port))
123 server.register_function(process_request, 'request')
124 server.register_function(get_mpk, 'mpk')
125 server.register_function(do_stop, 'stop')
126 server.serve_forever()
129 def handle_command(cmd):
131 server = jsonrpclib.Server('http://%s:%d'%(my_host, my_port))
137 elif cmd == 'create':
138 conn = mdb.connect(db_instance, db_user, db_password, db_name);
142 out = "unknown command"
144 print "Server not running"
151 if __name__ == '__main__':
153 if len(sys.argv) > 1:
154 ret = handle_command(sys.argv[1])
157 print "using database", db_name
158 conn = mdb.connect(db_instance, db_user, db_password, db_name);
160 i = TcpStratumInterface(electrum_server, 50001)
165 # this process detects when addresses have paid
166 in_queue = Queue.Queue()
167 out_queue = Queue.Queue()
168 thread.start_new_thread(electrum_input_thread, (in_queue,i))
169 thread.start_new_thread(electrum_output_thread, (out_queue,i))
171 thread.start_new_thread(server_thread, (conn,))
177 # get a list of addresses to watch
178 cur.execute("SELECT address, amount FROM electrum_payments WHERE paid IS NULL;")
179 data = cur.fetchall()
184 cmd, params = out_queue.get(True, 10)
189 # set paid=1 for received payments
190 print "received payment from", addr
191 cur.execute("select id from electrum_payments where address='%s';"%addr)
192 id = cur.fetchone()[0]
193 cur.execute("update electrum_payments set paid=1 where id=%d;"%(id))
194 elif cmd == 'request':
195 i, addr, amount, hours = params
196 sql = "INSERT INTO electrum_payments (id, address, amount, received_at, expires_at, paid, processed)"\
197 + " VALUES (%d, '%s', %f, CURRENT_TIMESTAMP, ADDTIME(CURRENT_TIMESTAMP, '0 %d:0:0'), NULL, NULL);"%(i, addr, amount, hours)
201 # set paid=0 for expired requests
202 cur.execute("""UPDATE electrum_payments set paid=0 WHERE expires_at < CURRENT_TIMESTAMP and paid is NULL;""")
204 # do callback for addresses that received payment
205 cur.execute("""SELECT id, address, paid from electrum_payments WHERE paid is not NULL and processed is NULL;""")
206 data = cur.fetchall()
208 print "callback:", item
212 headers = {'content-type':'application/json'}
213 data_json = { 'id':id, 'address':address, 'btc_auth':cb_password }
214 data_json = json.dumps(data_json)
215 url = cb_received if paid else cb_expired
216 req = urllib2.Request(url, data_json, headers)
218 response_stream = urllib2.urlopen(req)
219 cur.execute("UPDATE electrum_payments SET processed=1 WHERE id=%d;"%(id))
220 except urllib2.HTTPError:
221 print "cannot do callback", data_json