32e68acd66de31d0c852bca564daabf8d37c6062
[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, TcpStratumInterface
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 = TcpStratumInterface(electrum_server, 50001)
161     i.init_socket()
162     i.start()
163     
164
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))
170
171     thread.start_new_thread(server_thread, (conn,))
172
173
174     while not stopping:
175         cur = conn.cursor()
176
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()
180         for item in data: 
181             in_queue.put(item)
182
183         try:
184             cmd, params = out_queue.get(True, 10)
185         except Queue.Empty:
186             cmd = ''
187
188         if cmd == 'payment':
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)
198             cur.execute(sql)
199
200
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;""")
203
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()
207         for item in data:
208             print "callback:", item
209             id = int(item[0])
210             address = item[1]
211             paid = int(item[2])
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)
217             try:
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
222         
223         conn.commit()
224
225
226     conn.close()
227
228