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, Interface
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')
37 my_password = config.get('main','password')
38 my_host = config.get('main','host')
39 my_port = config.getint('main','port')
41 cb_received = config.get('callback','received')
42 cb_expired = config.get('callback','expired')
43 cb_password = config.get('callback','password')
46 wallet.master_public_key = config.get('electrum','mpk')
52 def electrum_input_thread(in_queue):
54 addr, amount = in_queue.get(True,1000000000)
55 if addr in omg_addresses:
58 print "subscribing to ", addr
59 omg_addresses[addr] = amount
60 interface.send([('blockchain.address.subscribe',[addr])])
63 def electrum_output_thread(out_queue):
65 r = interface.responses.get(True, 100000000000)
66 method = r.get('method')
68 if method == 'blockchain.address.subscribe':
69 addr = r.get('params')[0]
70 interface.send([('blockchain.address.get_history',[addr])])
72 elif method == 'blockchain.address.get_history':
73 addr = r.get('params')[0]
74 #print "received history for", addr
75 confirmed = unconfirmed = 0
87 s = (confirmed+unconfirmed)/1.e8
88 print "balance for %s:"%addr, s
89 amount = float(omg_addresses.get(addr))
91 out_queue.put( ('payment',addr) )
103 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));")
106 def process_request(i, amount, confirmations, expires_in, password):
107 print "process_request", i, amount, confirmations, expires_in
108 if password!=my_password:
109 print "wrong password ", password
111 addr = wallet.get_new_address(i, 0)
112 out_queue.put( ('request',(i,addr,amount,expires_in) ))
116 return wallet.master_public_key
119 def server_thread(conn):
120 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
121 server = SimpleJSONRPCServer(( my_host, my_port))
122 server.register_function(process_request, 'request')
123 server.register_function(get_mpk, 'mpk')
124 server.register_function(do_stop, 'stop')
125 server.serve_forever()
128 def handle_command(cmd):
130 server = jsonrpclib.Server('http://%s:%d'%(my_host, my_port))
136 elif cmd == 'create':
137 conn = mdb.connect(db_instance, db_user, db_password, db_name);
141 out = "unknown command"
143 print "Server not running"
150 if __name__ == '__main__':
152 if len(sys.argv) > 1:
153 ret = handle_command(sys.argv[1])
156 print "using database", db_name
157 conn = mdb.connect(db_instance, db_user, db_password, db_name);
159 interface = Interface({'server':"%s:%d:t"%(electrum_server, 50001)})
162 verifier = WalletVerifier(interface, config)
166 # this process detects when addresses have paid
167 in_queue = Queue.Queue()
168 out_queue = Queue.Queue()
169 thread.start_new_thread(electrum_input_thread, (in_queue,))
170 thread.start_new_thread(electrum_output_thread, (out_queue,))
172 thread.start_new_thread(server_thread, (conn,))
178 # get a list of addresses to watch
179 cur.execute("SELECT address, amount FROM electrum_payments WHERE paid IS NULL;")
180 data = cur.fetchall()
185 cmd, params = out_queue.get(True, 10)
190 # set paid=1 for received payments
191 print "received payment from", addr
192 cur.execute("select id from electrum_payments where address='%s';"%addr)
193 id = cur.fetchone()[0]
194 cur.execute("update electrum_payments set paid=1 where id=%d;"%(id))
195 elif cmd == 'request':
196 i, addr, amount, hours = params
197 sql = "INSERT INTO electrum_payments (id, address, amount, received_at, expires_at, paid, processed)"\
198 + " VALUES (%d, '%s', %f, CURRENT_TIMESTAMP, ADDTIME(CURRENT_TIMESTAMP, '0 %d:0:0'), NULL, NULL);"%(i, addr, amount, hours)
202 # set paid=0 for expired requests
203 cur.execute("""UPDATE electrum_payments set paid=0 WHERE expires_at < CURRENT_TIMESTAMP and paid is NULL;""")
205 # do callback for addresses that received payment
206 cur.execute("""SELECT id, address, paid from electrum_payments WHERE paid is not NULL and processed is NULL;""")
207 data = cur.fetchall()
209 print "callback:", item
213 headers = {'content-type':'application/json'}
214 data_json = { 'id':id, 'address':address, 'btc_auth':cb_password }
215 data_json = json.dumps(data_json)
216 url = cb_received if paid else cb_expired
217 req = urllib2.Request(url, data_json, headers)
219 response_stream = urllib2.urlopen(req)
220 cur.execute("UPDATE electrum_payments SET processed=1 WHERE id=%d;"%(id))
221 except urllib2.HTTPError:
222 print "cannot do callback", data_json