support for payment requests in the gui
[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
59     def get_amount(self):
60         return sum(map(lambda x:x[1], self.outputs))
61
62
63     def verify(self):
64         u = urlparse.urlparse(self.url)
65         self.domain = u.netloc
66
67         connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
68         connection.request("GET",u.geturl(), headers=REQUEST_HEADERS)
69         resp = connection.getresponse()
70
71         r = resp.read()
72         paymntreq = paymentrequest_pb2.PaymentRequest()
73         paymntreq.ParseFromString(r)
74
75         sig = paymntreq.signature
76         if not sig:
77             print "No signature"
78             return 
79
80         cert = paymentrequest_pb2.X509Certificates()
81         cert.ParseFromString(paymntreq.pki_data)
82         cert_num = len(cert.certificate)
83
84         x509_1 = X509.load_cert_der_string(cert.certificate[0])
85         if self.domain != x509_1.get_subject().CN:
86             validcert = False
87             try:
88                 SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
89                 for s in SANs:
90                     s = s.strip()
91                     if s.startswith("DNS:") and s[4:] == self.domain:
92                         validcert = True
93                         print "Match SAN DNS"
94                     elif s.startswith("IP:") and s[3:] == self.domain:
95                         validcert = True
96                         print "Match SAN IP"
97                     elif s.startswith("email:") and s[6:] == self.domain:
98                         validcert = True
99                         print "Match SAN email"
100             except Exception, e:
101                 print "ERROR: No SAN data"
102             if not validcert:
103                 ###TODO: check for wildcards
104                 print "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
105                 print self.domain, x509_1.get_subject().CN
106                 return
107
108         x509 = []
109         CA_OU = ''
110
111         if cert_num > 1:
112             for i in range(cert_num - 1):
113                 x509.append(X509.load_cert_der_string(cert.certificate[i+1]))
114                 if x509[i].check_ca() == 0:
115                     print "ERROR: Supplied CA Certificate Error"
116                     return
117             for i in range(cert_num - 1):
118                 if i == 0:
119                     if x509_1.verify(x509[i].get_pubkey()) != 1:
120                         print "ERROR: Certificate not Signed by Provided CA Certificate Chain"
121                         return
122                 else:
123                     if x509[i-1].verify(x509[i].get_pubkey()) != 1:
124                         print "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
125                         return
126
127             supplied_CA_fingerprint = x509[cert_num-2].get_fingerprint()
128             supplied_CA_CN = x509[cert_num-2].get_subject().CN
129             CA_match = False
130
131             x = ca_list.get(supplied_CA_fingerprint)
132             if x:
133                 CA_OU = x.get_subject().OU
134                 CA_match = True
135                 if x.get_subject().CN != supplied_CA_CN:
136                     print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
137                     print "Payment will continue with manual verification."
138             else:
139                 print "ERROR: Supplied CA Not Found in Trusted CA Store."
140                 print "Payment will continue with manual verification."
141         else:
142             print "ERROR: CA Certificate Chain Not Provided by Payment Processor"
143             return False
144
145         paymntreq.signature = ''
146         s = paymntreq.SerializeToString()
147         pubkey_1 = x509_1.get_pubkey()
148
149         if paymntreq.pki_type == "x509+sha256":
150             pubkey_1.reset_context(md="sha256")
151         elif paymntreq.pki_type == "x509+sha1":
152             pubkey_1.reset_context(md="sha1")
153         else:
154             print "ERROR: Unsupported PKI Type for Message Signature"
155             return False
156
157         pubkey_1.verify_init()
158         pubkey_1.verify_update(s)
159         if pubkey_1.verify_final(sig) != 1:
160             print "ERROR: Invalid Signature for Payment Request Data"
161             return False
162
163         ### SIG Verified
164
165         self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
166         pay_det.ParseFromString(paymntreq.serialized_payment_details)
167
168         if pay_det.expires and pay_det.expires < int(time.time()):
169             print "ERROR: Payment Request has Expired."
170             #return False
171
172         for o in pay_det.outputs:
173             addr = transaction.get_address_from_output_script(o.script)[1]
174             self.outputs.append( (addr, o.amount) )
175
176         if CA_match:
177             print 'Signed By Trusted CA: ', CA_OU
178
179         return pay_det
180
181
182
183     def send_ack(self, raw_tx, refund_addr):
184
185         pay_det = self.payment_details
186         if pay_det.payment_url:
187             paymnt = paymentrequest_pb2.Payment()
188
189             paymnt.merchant_data = pay_det.merchant_data
190             paymnt.transactions.append(raw_tx)
191
192             ref_out = paymnt.refund_to.add()
193             ref_out.script = transaction.Transaction.pay_script(refund_addr)
194             paymnt.memo = "Paid using Electrum"
195             pm = paymnt.SerializeToString()
196
197             payurl = urlparse.urlparse(pay_det.payment_url)
198             try:
199                 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=ca_path)
200             except requests.exceptions.SSLError:
201                 print "Payment Message/PaymentACK verify Failed"
202                 try:
203                     r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
204                 except Exception as e:
205                     print "Payment Message/PaymentACK Failed"
206                     print e
207                     return
208             try:
209                 paymntack = paymentrequest_pb2.PaymentACK()
210                 paymntack.ParseFromString(r.content)
211                 print "PaymentACK message received: %s" % paymntack.memo
212             except Exception:
213                 print "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
214
215
216
217
218 if __name__ == "__main__":
219
220     try:
221         uri = sys.argv[1]
222     except:
223         print "usage: %s url"%sys.argv[0]
224         print "example url: \"bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D2a828c05b8b80dc440c80a5d58890298&amount=1\""
225         sys.exit(1)
226
227     address, amount, label, message, request_url, url = util.parse_url(uri)
228     pr = PaymentRequest(request_url)
229     if not pr.verify():
230         sys.exit(1)
231
232     print 'Payment Request Verified Domain: ', pr.domain
233     print 'outputs', pr.outputs
234     print 'Payment Memo: ', pr.payment_details.memo
235
236     tx = "blah"
237     pr.send_ack(tx, refund_addr = "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")
238