show request memo
[electrum-nvc.git] / lib / paymentrequest.py
1 import hashlib
2 import httplib
3 import os.path
4 import re
5 import sys
6 import threading
7 import time
8 import traceback
9 import urllib2
10
11 try:
12     import paymentrequest_pb2
13 except:
14     print "protoc --proto_path=lib/ --python_out=lib/ lib/paymentrequest.proto"
15     raise Exception()
16
17 import urlparse
18 import requests
19 from M2Crypto import X509
20
21 from bitcoin import is_valid
22 import urlparse
23
24
25 import util
26 import transaction
27
28
29 REQUEST_HEADERS = {'Accept': 'application/bitcoin-paymentrequest', 'User-Agent': 'Electrum'}
30 ACK_HEADERS = {'Content-Type':'application/bitcoin-payment','Accept':'application/bitcoin-paymentack','User-Agent':'Electrum'}
31
32 ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
33 ca_list = {}
34 try:
35     with open(ca_path, 'r') as ca_f:
36         c = ""
37         for line in ca_f:
38             if line == "-----BEGIN CERTIFICATE-----\n":
39                 c = line
40             else:
41                 c += line
42             if line == "-----END CERTIFICATE-----\n":
43                 x = X509.load_cert_string(c)
44                 ca_list[x.get_fingerprint()] = x
45 except Exception:
46     print "ERROR: Could not open %s"%ca_path
47     print "ca-bundle.crt file should be placed in ~/.electrum/ca/ca-bundle.crt"
48     print "Documentation on how to download or create the file here: http://curl.haxx.se/docs/caextract.html"
49     print "Payment will continue with manual verification."
50     raise Exception()
51
52
53 class PaymentRequest:
54
55     def __init__(self, url):
56         self.url = url
57         self.outputs = []
58         self.error = ""
59
60     def get_amount(self):
61         return sum(map(lambda x:x[1], self.outputs))
62
63
64     def verify(self):
65         u = urlparse.urlparse(self.url)
66         self.domain = u.netloc
67
68         try:
69             connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
70             connection.request("GET",u.geturl(), headers=REQUEST_HEADERS)
71             resp = connection.getresponse()
72         except:
73             self.error = "cannot read url"
74             return
75
76         paymntreq = paymentrequest_pb2.PaymentRequest()
77         try:
78             r = resp.read()
79             paymntreq.ParseFromString(r)
80         except:
81             self.error = "cannot parse payment request"
82             return
83
84         sig = paymntreq.signature
85         if not sig:
86             self.error = "No signature"
87             return 
88
89         cert = paymentrequest_pb2.X509Certificates()
90         cert.ParseFromString(paymntreq.pki_data)
91         cert_num = len(cert.certificate)
92
93         x509_1 = X509.load_cert_der_string(cert.certificate[0])
94         if self.domain != x509_1.get_subject().CN:
95             validcert = False
96             try:
97                 SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
98                 for s in SANs:
99                     s = s.strip()
100                     if s.startswith("DNS:") and s[4:] == self.domain:
101                         validcert = True
102                         print "Match SAN DNS"
103                     elif s.startswith("IP:") and s[3:] == self.domain:
104                         validcert = True
105                         print "Match SAN IP"
106                     elif s.startswith("email:") and s[6:] == self.domain:
107                         validcert = True
108                         print "Match SAN email"
109             except Exception, e:
110                 print "ERROR: No SAN data"
111             if not validcert:
112                 ###TODO: check for wildcards
113                 self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
114                 return
115
116         x509 = []
117         CA_OU = ''
118
119         if cert_num > 1:
120             for i in range(cert_num - 1):
121                 x509.append(X509.load_cert_der_string(cert.certificate[i+1]))
122                 if x509[i].check_ca() == 0:
123                     self.error = "ERROR: Supplied CA Certificate Error"
124                     return
125             for i in range(cert_num - 1):
126                 if i == 0:
127                     if x509_1.verify(x509[i].get_pubkey()) != 1:
128                         self.error = "ERROR: Certificate not Signed by Provided CA Certificate Chain"
129                         return
130                 else:
131                     if x509[i-1].verify(x509[i].get_pubkey()) != 1:
132                         self.error = "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
133                         return
134
135             supplied_CA_fingerprint = x509[cert_num-2].get_fingerprint()
136             supplied_CA_CN = x509[cert_num-2].get_subject().CN
137             CA_match = False
138
139             x = ca_list.get(supplied_CA_fingerprint)
140             if x:
141                 CA_OU = x.get_subject().OU
142                 CA_match = True
143                 if x.get_subject().CN != supplied_CA_CN:
144                     print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
145                     print "Payment will continue with manual verification."
146             else:
147                 print "ERROR: Supplied CA Not Found in Trusted CA Store."
148                 print "Payment will continue with manual verification."
149         else:
150             self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
151             return False
152
153         paymntreq.signature = ''
154         s = paymntreq.SerializeToString()
155         pubkey_1 = x509_1.get_pubkey()
156
157         if paymntreq.pki_type == "x509+sha256":
158             pubkey_1.reset_context(md="sha256")
159         elif paymntreq.pki_type == "x509+sha1":
160             pubkey_1.reset_context(md="sha1")
161         else:
162             self.error = "ERROR: Unsupported PKI Type for Message Signature"
163             return False
164
165         pubkey_1.verify_init()
166         pubkey_1.verify_update(s)
167         if pubkey_1.verify_final(sig) != 1:
168             self.error = "ERROR: Invalid Signature for Payment Request Data"
169             return False
170
171         ### SIG Verified
172
173         self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
174         pay_det.ParseFromString(paymntreq.serialized_payment_details)
175
176         if pay_det.expires and pay_det.expires < int(time.time()):
177             self.error = "ERROR: Payment Request has Expired."
178             return False
179
180         for o in pay_det.outputs:
181             addr = transaction.get_address_from_output_script(o.script)[1]
182             self.outputs.append( (addr, o.amount) )
183
184         self.memo = pay_det.memo
185
186         if CA_match:
187             print 'Signed By Trusted CA: ', CA_OU
188
189         print "payment url", pay_det.payment_url
190         return True
191
192
193
194     def send_ack(self, raw_tx, refund_addr):
195
196         pay_det = self.payment_details
197         if not pay_det.payment_url:
198             return False, "no url"
199
200         paymnt = paymentrequest_pb2.Payment()
201         paymnt.merchant_data = pay_det.merchant_data
202         paymnt.transactions.append(raw_tx)
203
204         ref_out = paymnt.refund_to.add()
205         ref_out.script = transaction.Transaction.pay_script(refund_addr)
206         paymnt.memo = "Paid using Electrum"
207         pm = paymnt.SerializeToString()
208
209         payurl = urlparse.urlparse(pay_det.payment_url)
210         try:
211             r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=ca_path)
212         except requests.exceptions.SSLError:
213             print "Payment Message/PaymentACK verify Failed"
214             try:
215                 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
216             except Exception as e:
217                 print e
218                 return False, "Payment Message/PaymentACK Failed"
219
220         if r.status_code >= 500:
221             return False, r.reason
222
223         try:
224             paymntack = paymentrequest_pb2.PaymentACK()
225             paymntack.ParseFromString(r.content)
226         except Exception:
227             return False, "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
228
229         print "PaymentACK message received: %s" % paymntack.memo
230         return True, paymntack.memo
231
232
233
234
235 if __name__ == "__main__":
236
237     try:
238         uri = sys.argv[1]
239     except:
240         print "usage: %s url"%sys.argv[0]
241         print "example url: \"bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D2a828c05b8b80dc440c80a5d58890298&amount=1\""
242         sys.exit(1)
243
244     address, amount, label, message, request_url, url = util.parse_url(uri)
245     pr = PaymentRequest(request_url)
246     if not pr.verify():
247         sys.exit(1)
248
249     print 'Payment Request Verified Domain: ', pr.domain
250     print 'outputs', pr.outputs
251     print 'Payment Memo: ', pr.payment_details.memo
252
253     tx = "blah"
254     pr.send_ack(tx, refund_addr = "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")
255