readme for merchant script
[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
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             for item in h:
80                 v = item['value']
81                 if v<0: continue
82                 if item['height']:
83                     confirmed += v
84                 else:
85                     unconfirmed += v
86                 
87             s = (confirmed+unconfirmed)/1.e8
88             print "balance for %s:"%addr, s
89             amount = float(omg_addresses.get(addr))
90             if s>=amount:
91                 out_queue.put( ('payment',addr) )
92
93
94 stopping = False
95
96 def do_stop():
97     global stopping
98     stopping = True
99
100 def do_create(conn):
101     # creation
102     cur = conn.cursor()
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));")
104     conn.commit()
105
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
110         return
111     addr = wallet.get_new_address(i, 0)
112     out_queue.put( ('request',(i,addr,amount,expires_in) ))
113     return addr
114
115 def get_mpk():
116     return wallet.master_public_key
117
118
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()
126     
127
128 def handle_command(cmd):
129     import jsonrpclib
130     server = jsonrpclib.Server('http://%s:%d'%(my_host, my_port))
131     try:
132         if cmd == 'mpk':
133             out = server.mpk()
134         elif cmd == 'stop':
135             out = server.stop()
136         elif cmd == 'create':
137             conn = mdb.connect(db_instance, db_user, db_password, db_name);
138             do_create(conn)
139             out = "ok"
140         else:
141             out = "unknown command"
142     except socket.error:
143         print "Server not running"
144         return 1
145
146     print out
147     return 0
148
149
150 if __name__ == '__main__':
151
152     if len(sys.argv) > 1:
153         ret = handle_command(sys.argv[1])
154         sys.exit(ret)
155
156     print "using database", db_name
157     conn = mdb.connect(db_instance, db_user, db_password, db_name);
158
159     interface = Interface({'server':"%s:%d:t"%(electrum_server, 50001)})
160     interface.start()
161
162     verifier = WalletVerifier(interface, config)
163     verifier.start()
164     
165
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,))
171
172     thread.start_new_thread(server_thread, (conn,))
173
174
175     while not stopping:
176         cur = conn.cursor()
177
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()
181         for item in data: 
182             in_queue.put(item)
183
184         try:
185             cmd, params = out_queue.get(True, 10)
186         except Queue.Empty:
187             cmd = ''
188
189         if cmd == 'payment':
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)
199             cur.execute(sql)
200
201
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;""")
204
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()
208         for item in data:
209             print "callback:", item
210             id = int(item[0])
211             address = item[1]
212             paid = int(item[2])
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)
218             try:
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
223         
224         conn.commit()
225
226
227     conn.close()
228
229