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
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'}
32 ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
35 with open(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 ca_list[x.get_fingerprint()] = x
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."
55 def __init__(self, url):
62 u = urlparse.urlparse(self.url)
63 self.domain = u.netloc
66 connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
67 connection.request("GET",u.geturl(), headers=REQUEST_HEADERS)
68 resp = connection.getresponse()
70 self.error = "cannot read url"
73 paymntreq = paymentrequest_pb2.PaymentRequest()
76 paymntreq.ParseFromString(r)
78 self.error = "cannot parse payment request"
81 sig = paymntreq.signature
83 self.error = "No signature"
86 cert = paymentrequest_pb2.X509Certificates()
87 cert.ParseFromString(paymntreq.pki_data)
88 cert_num = len(cert.certificate)
90 x509_1 = X509.load_cert_der_string(cert.certificate[0])
91 if self.domain != x509_1.get_subject().CN:
94 SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
97 if s.startswith("DNS:") and s[4:] == self.domain:
100 elif s.startswith("IP:") and s[3:] == self.domain:
103 elif s.startswith("email:") and s[6:] == self.domain:
105 print "Match SAN email"
107 print "ERROR: No SAN data"
109 ###TODO: check for wildcards
110 self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
117 for i in range(cert_num - 1):
118 x509.append(X509.load_cert_der_string(cert.certificate[i+1]))
119 if x509[i].check_ca() == 0:
120 self.error = "ERROR: Supplied CA Certificate Error"
122 for i in range(cert_num - 1):
124 if x509_1.verify(x509[i].get_pubkey()) != 1:
125 self.error = "ERROR: Certificate not Signed by Provided CA Certificate Chain"
128 if x509[i-1].verify(x509[i].get_pubkey()) != 1:
129 self.error = "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
132 supplied_CA_fingerprint = x509[cert_num-2].get_fingerprint()
133 supplied_CA_CN = x509[cert_num-2].get_subject().CN
136 x = ca_list.get(supplied_CA_fingerprint)
138 CA_OU = x.get_subject().OU
140 if x.get_subject().CN != supplied_CA_CN:
141 print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
142 print "Payment will continue with manual verification."
144 print "ERROR: Supplied CA Not Found in Trusted CA Store."
145 print "Payment will continue with manual verification."
147 self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
150 paymntreq.signature = ''
151 s = paymntreq.SerializeToString()
152 pubkey_1 = x509_1.get_pubkey()
154 if paymntreq.pki_type == "x509+sha256":
155 pubkey_1.reset_context(md="sha256")
156 elif paymntreq.pki_type == "x509+sha1":
157 pubkey_1.reset_context(md="sha1")
159 self.error = "ERROR: Unsupported PKI Type for Message Signature"
162 pubkey_1.verify_init()
163 pubkey_1.verify_update(s)
164 if pubkey_1.verify_final(sig) != 1:
165 self.error = "ERROR: Invalid Signature for Payment Request Data"
170 self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
171 pay_det.ParseFromString(paymntreq.serialized_payment_details)
173 if pay_det.expires and pay_det.expires < int(time.time()):
174 self.error = "ERROR: Payment Request has Expired."
177 for o in pay_det.outputs:
178 addr = transaction.get_address_from_output_script(o.script)[1]
179 self.outputs.append( (addr, o.amount) )
181 self.memo = pay_det.memo
184 self.status = 'Signed by Trusted CA:\n' + CA_OU
186 print "payment url", pay_det.payment_url
191 def send_ack(self, raw_tx, refund_addr):
193 pay_det = self.payment_details
194 if not pay_det.payment_url:
195 return False, "no url"
197 paymnt = paymentrequest_pb2.Payment()
198 paymnt.merchant_data = pay_det.merchant_data
199 paymnt.transactions.append(raw_tx)
201 ref_out = paymnt.refund_to.add()
202 ref_out.script = transaction.Transaction.pay_script(refund_addr)
203 paymnt.memo = "Paid using Electrum"
204 pm = paymnt.SerializeToString()
206 payurl = urlparse.urlparse(pay_det.payment_url)
208 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=ca_path)
209 except requests.exceptions.SSLError:
210 print "Payment Message/PaymentACK verify Failed"
212 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
213 except Exception as e:
215 return False, "Payment Message/PaymentACK Failed"
217 if r.status_code >= 500:
218 return False, r.reason
221 paymntack = paymentrequest_pb2.PaymentACK()
222 paymntack.ParseFromString(r.content)
224 return False, "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
226 print "PaymentACK message received: %s" % paymntack.memo
227 return True, paymntack.memo
232 if __name__ == "__main__":
237 print "usage: %s url"%sys.argv[0]
238 print "example url: \"bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D2a828c05b8b80dc440c80a5d58890298&amount=1\""
241 address, amount, label, message, request_url, url = util.parse_url(uri)
242 pr = PaymentRequest(request_url)
246 print 'Payment Request Verified Domain: ', pr.domain
247 print 'outputs', pr.outputs
248 print 'Payment Memo: ', pr.payment_details.memo
251 pr.send_ack(tx, refund_addr = "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")