adding initial bip70 script (wozz)
[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     sys.exit(1)
16
17 import urlparse
18 import requests
19 from M2Crypto import X509
20
21 from bitcoin import is_valid
22 import urlparse
23
24 import transaction
25
26 REQUEST_HEADERS = {'Accept': 'application/bitcoin-paymentrequest', 'User-Agent': 'Electrum'}
27 ACK_HEADERS = {'Content-Type':'application/bitcoin-payment','Accept':'application/bitcoin-paymentack','User-Agent':'Electrum'}
28
29 class PaymentRequest:
30
31     def __init__(self):
32         self.ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
33         self.ca_list = {}
34         try:
35             with open(self.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                         self.ca_list[x.get_fingerprint()] = x
45         except Exception:
46             print "ERROR: Could not open %s"%self.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
51
52
53     def verify(self, url):
54
55         u = urlparse.urlparse(urllib2.unquote(url))
56         self.domain = u.netloc
57
58         connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
59         connection.request("GET",u.geturl(), headers=REQUEST_HEADERS)
60         resp = connection.getresponse()
61
62         r = resp.read()
63         paymntreq = paymentrequest_pb2.PaymentRequest()
64         paymntreq.ParseFromString(r)
65
66         sig = paymntreq.signature
67
68         cert = paymentrequest_pb2.X509Certificates()
69         cert.ParseFromString(paymntreq.pki_data)
70         cert_num = len(cert.certificate)
71
72         x509_1 = X509.load_cert_der_string(cert.certificate[0])
73         if self.domain != x509_1.get_subject().CN:
74             ###TODO: check for subject alt names
75             ###       check for wildcards
76             print "ERROR: Certificate Subject Domain Mismatch"
77             print self.domain, x509_1.get_subject().CN
78             #return
79
80         x509 = []
81         CA_OU = ''
82
83         if cert_num > 1:
84             for i in range(cert_num - 1):
85                 x509.append(X509.load_cert_der_string(cert.certificate[i+1]))
86                 if x509[i].check_ca() == 0:
87                     print "ERROR: Supplied CA Certificate Error"
88                     return
89             for i in range(cert_num - 1):
90                 if i == 0:
91                     if x509_1.verify(x509[i].get_pubkey()) != 1:
92                         print "ERROR: Certificate not Signed by Provided CA Certificate Chain"
93                         return
94                 else:
95                     if x509[i-1].verify(x509[i].get_pubkey()) != 1:
96                         print "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
97                         return
98
99             supplied_CA_fingerprint = x509[cert_num-2].get_fingerprint()
100             supplied_CA_CN = x509[cert_num-2].get_subject().CN
101             CA_match = False
102
103             x = self.ca_list.get(supplied_CA_fingerprint)
104             if x:
105                 CA_OU = x.get_subject().OU
106                 CA_match = True
107                 if x.get_subject().CN != supplied_CA_CN:
108                     print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
109                     print "Payment will continue with manual verification."
110             else:
111                 print "ERROR: Supplied CA Not Found in Trusted CA Store."
112                 print "Payment will continue with manual verification."
113         else:
114             print "ERROR: CA Certificate Chain Not Provided by Payment Processor"
115             return False
116
117         paymntreq.signature = ''
118         s = paymntreq.SerializeToString()
119         pubkey_1 = x509_1.get_pubkey()
120
121         if paymntreq.pki_type == "x509+sha256":
122             pubkey_1.reset_context(md="sha256")
123         elif paymntreq.pki_type == "x509+sha1":
124             pubkey_1.reset_context(md="sha1")
125         else:
126             print "ERROR: Unsupported PKI Type for Message Signature"
127             return False
128
129         pubkey_1.verify_init()
130         pubkey_1.verify_update(s)
131         if pubkey_1.verify_final(sig) != 1:
132             print "ERROR: Invalid Signature for Payment Request Data"
133             return False
134
135         ### SIG Verified
136
137         self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
138         pay_det.ParseFromString(paymntreq.serialized_payment_details)
139
140         if pay_det.expires and pay_det.expires < int(time.time()):
141             print "ERROR: Payment Request has Expired."
142             return False
143
144         self.outputs = []
145         for o in pay_det.outputs:
146             addr = transaction.get_address_from_output_script(o.script)[1]
147             self.outputs.append( (addr, o.amount) )
148
149         if CA_match:
150             print 'Signed By Trusted CA: ', CA_OU
151
152         return True
153
154
155
156     def send_ack(self, raw_tx, refund_addr):
157
158         pay_det = self.payment_details
159         if pay_det.payment_url:
160             paymnt = paymentrequest_pb2.Payment()
161
162             paymnt.merchant_data = pay_det.merchant_data
163             paymnt.transactions.append(raw_tx)
164
165             ref_out = paymnt.refund_to.add()
166             ref_out.script = transaction.Transaction.pay_script(refund_addr)
167             paymnt.memo = "Paid using Electrum"
168             pm = paymnt.SerializeToString()
169
170             payurl = urlparse.urlparse(pay_det.payment_url)
171             try:
172                 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=self.ca_path)
173             except requests.exceptions.SSLError:
174                 print "Payment Message/PaymentACK verify Failed"
175                 try:
176                     r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
177                 except Exception as e:
178                     print "Payment Message/PaymentACK Failed"
179                     print e
180                     return
181             try:
182                 paymntack = paymentrequest_pb2.PaymentACK()
183                 paymntack.ParseFromString(r.content)
184                 print "PaymentACK message received: %s" % paymntack.memo
185             except Exception:
186                 print "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
187
188
189 uri = "bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D26c19879d44c3891214e7897797b9160&amount=1"
190 url = "https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D26c19879d44c3891214e7897797b9160"
191
192 #uri = "bitcoin:1m9Lw2pFCe6Hs7xUuo9fMJCzEwQNdCo5e?amount=0.0012&r=https%3A%2F%2Fbitpay.com%2Fi%2F8XNDiQU92H2whNG4j8hZ5M"
193 #url = "https%3A%2F%2Fbitpay.com%2Fi%2F8XNDiQU92H2whNG4j8hZ5M"
194
195
196 if __name__ == "__main__":
197
198     pr = PaymentRequest()
199     if not pr.verify(url):
200         sys.exit(1)
201
202     print 'Payment Request Verified Domain: ', pr.domain
203     print 'outputs', pr.outputs
204     print 'Payment Memo: ', pr.payment_details.memo
205
206     tx = "blah"
207     pr.send_ack(tx, "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")
208