compute merkle root from reduced list
[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, i):
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             i.send([('blockchain.address.subscribe',[addr])])
61
62
63 def electrum_output_thread(out_queue, i):
64     while True:
65         r = i.responses.get(True, 100000000000)
66         method = r.get('method') 
67
68         if method == 'blockchain.address.subscribe':
69             addr = r.get('params')[0]
70             i.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     i = Interface({'server':"%s:%d:t"%(electrum_server, 50001)})
160     i.start()
161     
162
163     # this process detects when addresses have paid
164     in_queue = Queue.Queue()
165     out_queue = Queue.Queue()
166     thread.start_new_thread(electrum_input_thread, (in_queue,i))
167     thread.start_new_thread(electrum_output_thread, (out_queue,i))
168
169     thread.start_new_thread(server_thread, (conn,))
170
171
172     while not stopping:
173         cur = conn.cursor()
174
175         # get a list of addresses to watch
176         cur.execute("SELECT address, amount FROM electrum_payments WHERE paid IS NULL;")
177         data = cur.fetchall()
178         for item in data: 
179             in_queue.put(item)
180
181         try:
182             cmd, params = out_queue.get(True, 10)
183         except Queue.Empty:
184             cmd = ''
185
186         if cmd == 'payment':
187             # set paid=1 for received payments
188             print "received payment from", addr
189             cur.execute("select id from electrum_payments where address='%s';"%addr)
190             id = cur.fetchone()[0]
191             cur.execute("update electrum_payments set paid=1 where id=%d;"%(id))
192         elif cmd == 'request':
193             i, addr, amount, hours = params
194             sql = "INSERT INTO electrum_payments (id, address, amount, received_at, expires_at, paid, processed)"\
195                 + " VALUES (%d, '%s', %f, CURRENT_TIMESTAMP, ADDTIME(CURRENT_TIMESTAMP, '0 %d:0:0'), NULL, NULL);"%(i, addr, amount, hours)
196             cur.execute(sql)
197
198
199         # set paid=0 for expired requests 
200         cur.execute("""UPDATE electrum_payments set paid=0 WHERE expires_at < CURRENT_TIMESTAMP and paid is NULL;""")
201
202         # do callback for addresses that received payment
203         cur.execute("""SELECT id, address, paid from electrum_payments WHERE paid is not NULL and processed is NULL;""")
204         data = cur.fetchall()
205         for item in data:
206             print "callback:", item
207             id = int(item[0])
208             address = item[1]
209             paid = int(item[2])
210             headers = {'content-type':'application/json'}
211             data_json = { 'id':id, 'address':address, 'btc_auth':cb_password }
212             data_json = json.dumps(data_json)
213             url = cb_received if paid else cb_expired
214             req = urllib2.Request(url, data_json, headers)
215             try:
216                 response_stream = urllib2.urlopen(req)
217                 cur.execute("UPDATE electrum_payments SET processed=1 WHERE id=%d;"%(id))
218             except urllib2.HTTPError:
219                 print "cannot do callback", data_json
220         
221         conn.commit()
222
223
224     conn.close()
225
226