12 import paymentrequest_pb2
14 print "protoc --proto_path=lib/ --python_out=lib/ lib/paymentrequest.proto"
19 from M2Crypto import X509
21 from bitcoin import is_valid
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'}
32 self.ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
35 with open(self.ca_path, 'r') as ca_f:
38 if line == "-----BEGIN CERTIFICATE-----\n":
42 if line == "-----END CERTIFICATE-----\n":
43 x = X509.load_cert_string(c)
44 self.ca_list[x.get_fingerprint()] = x
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."
53 def verify(self, url):
55 u = urlparse.urlparse(urllib2.unquote(url))
56 self.domain = u.netloc
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()
63 paymntreq = paymentrequest_pb2.PaymentRequest()
64 paymntreq.ParseFromString(r)
66 sig = paymntreq.signature
68 cert = paymentrequest_pb2.X509Certificates()
69 cert.ParseFromString(paymntreq.pki_data)
70 cert_num = len(cert.certificate)
72 x509_1 = X509.load_cert_der_string(cert.certificate[0])
73 if self.domain != x509_1.get_subject().CN:
76 SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
79 if s.startswith("DNS:") and s[4:] == self.domain:
82 elif s.startswith("IP:") and s[3:] == self.domain:
85 elif s.startswith("email:") and s[6:] == self.domain:
87 print "Match SAN email"
89 print "ERROR: No SAN data"
91 ###TODO: check for wildcards
92 print "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
93 print self.domain, x509_1.get_subject().CN
100 for i in range(cert_num - 1):
101 x509.append(X509.load_cert_der_string(cert.certificate[i+1]))
102 if x509[i].check_ca() == 0:
103 print "ERROR: Supplied CA Certificate Error"
105 for i in range(cert_num - 1):
107 if x509_1.verify(x509[i].get_pubkey()) != 1:
108 print "ERROR: Certificate not Signed by Provided CA Certificate Chain"
111 if x509[i-1].verify(x509[i].get_pubkey()) != 1:
112 print "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
115 supplied_CA_fingerprint = x509[cert_num-2].get_fingerprint()
116 supplied_CA_CN = x509[cert_num-2].get_subject().CN
119 x = self.ca_list.get(supplied_CA_fingerprint)
121 CA_OU = x.get_subject().OU
123 if x.get_subject().CN != supplied_CA_CN:
124 print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
125 print "Payment will continue with manual verification."
127 print "ERROR: Supplied CA Not Found in Trusted CA Store."
128 print "Payment will continue with manual verification."
130 print "ERROR: CA Certificate Chain Not Provided by Payment Processor"
133 paymntreq.signature = ''
134 s = paymntreq.SerializeToString()
135 pubkey_1 = x509_1.get_pubkey()
137 if paymntreq.pki_type == "x509+sha256":
138 pubkey_1.reset_context(md="sha256")
139 elif paymntreq.pki_type == "x509+sha1":
140 pubkey_1.reset_context(md="sha1")
142 print "ERROR: Unsupported PKI Type for Message Signature"
145 pubkey_1.verify_init()
146 pubkey_1.verify_update(s)
147 if pubkey_1.verify_final(sig) != 1:
148 print "ERROR: Invalid Signature for Payment Request Data"
153 self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
154 pay_det.ParseFromString(paymntreq.serialized_payment_details)
156 if pay_det.expires and pay_det.expires < int(time.time()):
157 print "ERROR: Payment Request has Expired."
161 for o in pay_det.outputs:
162 addr = transaction.get_address_from_output_script(o.script)[1]
163 self.outputs.append( (addr, o.amount) )
166 print 'Signed By Trusted CA: ', CA_OU
172 def send_ack(self, raw_tx, refund_addr):
174 pay_det = self.payment_details
175 if pay_det.payment_url:
176 paymnt = paymentrequest_pb2.Payment()
178 paymnt.merchant_data = pay_det.merchant_data
179 paymnt.transactions.append(raw_tx)
181 ref_out = paymnt.refund_to.add()
182 ref_out.script = transaction.Transaction.pay_script(refund_addr)
183 paymnt.memo = "Paid using Electrum"
184 pm = paymnt.SerializeToString()
186 payurl = urlparse.urlparse(pay_det.payment_url)
188 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=self.ca_path)
189 except requests.exceptions.SSLError:
190 print "Payment Message/PaymentACK verify Failed"
192 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
193 except Exception as e:
194 print "Payment Message/PaymentACK Failed"
198 paymntack = paymentrequest_pb2.PaymentACK()
199 paymntack.ParseFromString(r.content)
200 print "PaymentACK message received: %s" % paymntack.memo
202 print "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
205 uri = "bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D26c19879d44c3891214e7897797b9160&amount=1"
206 url = "https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D26c19879d44c3891214e7897797b9160"
208 #uri = "bitcoin:1m9Lw2pFCe6Hs7xUuo9fMJCzEwQNdCo5e?amount=0.0012&r=https%3A%2F%2Fbitpay.com%2Fi%2F8XNDiQU92H2whNG4j8hZ5M"
209 #url = "https%3A%2F%2Fbitpay.com%2Fi%2F8XNDiQU92H2whNG4j8hZ5M"
212 if __name__ == "__main__":
214 pr = PaymentRequest()
215 if not pr.verify(url):
218 print 'Payment Request Verified Domain: ', pr.domain
219 print 'outputs', pr.outputs
220 print 'Payment Memo: ', pr.payment_details.memo
223 pr.send_ack(tx, "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")