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