allow config to be None in constructor of Interface
[electrum-nvc.git] / scripts / merchant.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
5 #
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.
10 #
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.
15 #
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/>.
18
19
20 import time, thread, sys, socket, os
21 import urllib2,json
22 import MySQLdb as mdb
23 import Queue
24 from electrum import Wallet, Interface
25
26 import ConfigParser
27 config = ConfigParser.ConfigParser()
28 config.read("merchant.conf")
29
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')
34
35 electrum_server = config.get('electrum','server')
36 mpk = config.get('electrum','mpk')
37
38 my_password = config.get('main','password')
39 my_host = config.get('main','host')
40 my_port = config.getint('main','port')
41
42 cb_received = config.get('callback','received')
43 cb_expired = config.get('callback','expired')
44 cb_password = config.get('callback','password')
45
46 wallet = Wallet()
47 wallet.master_public_key = mpk.decode('hex')
48
49
50
51 omg_addresses = {}
52
53 def electrum_input_thread(in_queue, i):
54     while True:
55         addr, amount = in_queue.get(True,1000000000)
56         if addr in omg_addresses: 
57             continue
58         else:
59             print "subscribing to ", addr
60             omg_addresses[addr] = amount
61             i.send([('blockchain.address.subscribe',[addr])])
62
63
64 def electrum_output_thread(out_queue, i):
65     while True:
66         r = i.responses.get(True, 100000000000)
67         method = r.get('method') 
68
69         if method == 'blockchain.address.subscribe':
70             addr = r.get('params')[0]
71             i.send([('blockchain.address.get_history',[addr])])
72
73         elif method == 'blockchain.address.get_history':
74             addr = r.get('params')[0]
75             #print "received history for", addr
76             confirmed = unconfirmed = 0
77             h = r.get('result')
78             if h is None:
79                 continue
80             for item in h:
81                 v = item['value']
82                 if v<0: continue
83                 if item['height']:
84                     confirmed += v
85                 else:
86                     unconfirmed += v
87                 
88             s = (confirmed+unconfirmed)/1.e8
89             print "balance for %s:"%addr, s
90             amount = float(omg_addresses.get(addr))
91             if s>=amount:
92                 out_queue.put( ('payment',addr) )
93
94
95 stopping = False
96
97 def do_stop():
98     global stopping
99     stopping = True
100
101 def do_create(conn):
102     # creation
103     cur = conn.cursor()
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));")
105     conn.commit()
106
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
111         return
112     addr = wallet.get_new_address(i, 0)
113     out_queue.put( ('request',(i,addr,amount,expires_in) ))
114     return addr
115
116 def get_mpk():
117     return wallet.master_public_key.encode('hex')
118
119
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()
127     
128
129 def handle_command(cmd):
130     import jsonrpclib
131     server = jsonrpclib.Server('http://%s:%d'%(my_host, my_port))
132     try:
133         if cmd == 'mpk':
134             out = server.mpk()
135         elif cmd == 'stop':
136             out = server.stop()
137         elif cmd == 'create':
138             conn = mdb.connect(db_instance, db_user, db_password, db_name);
139             do_create(conn)
140             out = "ok"
141         else:
142             out = "unknown command"
143     except socket.error:
144         print "Server not running"
145         return 1
146
147     print out
148     return 0
149
150
151 if __name__ == '__main__':
152
153     if len(sys.argv) > 1:
154         ret = handle_command(sys.argv[1])
155         sys.exit(ret)
156
157     print "using database", db_name
158     conn = mdb.connect(db_instance, db_user, db_password, db_name);
159
160     i = Interface({'server':"%s:%d:t"%(electrum_server, 50001)})
161     i.start()
162     
163
164     # this process detects when addresses have paid
165     in_queue = Queue.Queue()
166     out_queue = Queue.Queue()
167     thread.start_new_thread(electrum_input_thread, (in_queue,i))
168     thread.start_new_thread(electrum_output_thread, (out_queue,i))
169
170     thread.start_new_thread(server_thread, (conn,))
171
172
173     while not stopping:
174         cur = conn.cursor()
175
176         # get a list of addresses to watch
177         cur.execute("SELECT address, amount FROM electrum_payments WHERE paid IS NULL;")
178         data = cur.fetchall()
179         for item in data: 
180             in_queue.put(item)
181
182         try:
183             cmd, params = out_queue.get(True, 10)
184         except Queue.Empty:
185             cmd = ''
186
187         if cmd == 'payment':
188             # set paid=1 for received payments
189             print "received payment from", addr
190             cur.execute("select id from electrum_payments where address='%s';"%addr)
191             id = cur.fetchone()[0]
192             cur.execute("update electrum_payments set paid=1 where id=%d;"%(id))
193         elif cmd == 'request':
194             i, addr, amount, hours = params
195             sql = "INSERT INTO electrum_payments (id, address, amount, received_at, expires_at, paid, processed)"\
196                 + " VALUES (%d, '%s', %f, CURRENT_TIMESTAMP, ADDTIME(CURRENT_TIMESTAMP, '0 %d:0:0'), NULL, NULL);"%(i, addr, amount, hours)
197             cur.execute(sql)
198
199
200         # set paid=0 for expired requests 
201         cur.execute("""UPDATE electrum_payments set paid=0 WHERE expires_at < CURRENT_TIMESTAMP and paid is NULL;""")
202
203         # do callback for addresses that received payment
204         cur.execute("""SELECT id, address, paid from electrum_payments WHERE paid is not NULL and processed is NULL;""")
205         data = cur.fetchall()
206         for item in data:
207             print "callback:", item
208             id = int(item[0])
209             address = item[1]
210             paid = int(item[2])
211             headers = {'content-type':'application/json'}
212             data_json = { 'id':id, 'address':address, 'btc_auth':cb_password }
213             data_json = json.dumps(data_json)
214             url = cb_received if paid else cb_expired
215             req = urllib2.Request(url, data_json, headers)
216             try:
217                 response_stream = urllib2.urlopen(req)
218                 cur.execute("UPDATE electrum_payments SET processed=1 WHERE id=%d;"%(id))
219             except urllib2.HTTPError:
220                 print "cannot do callback", data_json
221         
222         conn.commit()
223
224
225     conn.close()
226
227