12 import paymentrequest_pb2
14 print "protoc --proto_path=lib/ --python_out=lib/ lib/paymentrequest.proto"
19 from M2Crypto import X509
22 from bitcoin import is_valid
30 REQUEST_HEADERS = {'Accept': 'application/bitcoin-paymentrequest', 'User-Agent': 'Electrum'}
31 ACK_HEADERS = {'Content-Type':'application/bitcoin-payment','Accept':'application/bitcoin-paymentack','User-Agent':'Electrum'}
36 PR_SENT = 2 # sent but not propagated
37 PR_PAID = 3 # send and propagated
42 ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
45 with open(ca_path, 'r') as ca_f:
48 if line == "-----BEGIN CERTIFICATE-----\n":
52 if line == "-----END CERTIFICATE-----\n":
53 x = X509.load_cert_string(c)
54 ca_list[x.get_fingerprint()] = x
56 print "ERROR: Could not open %s"%ca_path
57 print "ca-bundle.crt file should be placed in ~/.electrum/ca/ca-bundle.crt"
58 print "Documentation on how to download or create the file here: http://curl.haxx.se/docs/caextract.html"
59 print "Payment will continue with manual verification."
65 def __init__(self, config):
73 u = urlparse.urlparse(url)
74 self.domain = u.netloc
77 connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
78 connection.request("GET",u.geturl(), headers=REQUEST_HEADERS)
79 response = connection.getresponse()
81 self.error = "cannot read url"
87 self.error = "cannot read"
91 self.data = paymentrequest_pb2.PaymentRequest()
92 self.data.ParseFromString(r)
94 self.error = "cannot parse payment request"
97 self.id = bitcoin.sha256(r)[0:16].encode('hex')
100 dir_path = os.path.join( self.config.path, 'requests')
101 if not os.path.exists(dir_path):
103 filename = os.path.join(dir_path, self.id)
104 with open(filename,'w') as f:
110 paymntreq = self.data
111 sig = paymntreq.signature
113 self.error = "No signature"
116 cert = paymentrequest_pb2.X509Certificates()
117 cert.ParseFromString(paymntreq.pki_data)
118 cert_num = len(cert.certificate)
120 x509_1 = X509.load_cert_der_string(cert.certificate[0])
121 if self.domain != x509_1.get_subject().CN:
124 SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
127 if s.startswith("DNS:") and s[4:] == self.domain:
129 print "Match SAN DNS"
130 elif s.startswith("IP:") and s[3:] == self.domain:
133 elif s.startswith("email:") and s[6:] == self.domain:
135 print "Match SAN email"
137 print "ERROR: No SAN data"
139 ###TODO: check for wildcards
140 self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
147 for i in range(cert_num - 1):
148 x509.append(X509.load_cert_der_string(cert.certificate[i+1]))
149 if x509[i].check_ca() == 0:
150 self.error = "ERROR: Supplied CA Certificate Error"
152 for i in range(cert_num - 1):
154 if x509_1.verify(x509[i].get_pubkey()) != 1:
155 self.error = "ERROR: Certificate not Signed by Provided CA Certificate Chain"
158 if x509[i-1].verify(x509[i].get_pubkey()) != 1:
159 self.error = "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
162 supplied_CA_fingerprint = x509[cert_num-2].get_fingerprint()
163 supplied_CA_CN = x509[cert_num-2].get_subject().CN
166 x = ca_list.get(supplied_CA_fingerprint)
168 CA_OU = x.get_subject().OU
170 if x.get_subject().CN != supplied_CA_CN:
171 print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
172 print "Payment will continue with manual verification."
174 print "ERROR: Supplied CA Not Found in Trusted CA Store."
175 print "Payment will continue with manual verification."
177 self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
180 paymntreq.signature = ''
181 s = paymntreq.SerializeToString()
182 pubkey_1 = x509_1.get_pubkey()
184 if paymntreq.pki_type == "x509+sha256":
185 pubkey_1.reset_context(md="sha256")
186 elif paymntreq.pki_type == "x509+sha1":
187 pubkey_1.reset_context(md="sha1")
189 self.error = "ERROR: Unsupported PKI Type for Message Signature"
192 pubkey_1.verify_init()
193 pubkey_1.verify_update(s)
194 if pubkey_1.verify_final(sig) != 1:
195 self.error = "ERROR: Invalid Signature for Payment Request Data"
200 self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
201 pay_det.ParseFromString(paymntreq.serialized_payment_details)
203 if pay_det.expires and pay_det.expires < int(time.time()):
204 self.error = "ERROR: Payment Request has Expired."
207 for o in pay_det.outputs:
208 addr = transaction.get_address_from_output_script(o.script)[1]
209 self.outputs.append( (addr, o.amount) )
211 self.memo = pay_det.memo
214 self.status = 'Signed by Trusted CA:\n' + CA_OU
216 print "payment url", pay_det.payment_url
220 def get_amount(self):
221 return sum(map(lambda x:x[1], self.outputs))
223 def get_domain(self):
229 def send_ack(self, raw_tx, refund_addr):
231 pay_det = self.payment_details
232 if not pay_det.payment_url:
233 return False, "no url"
235 paymnt = paymentrequest_pb2.Payment()
236 paymnt.merchant_data = pay_det.merchant_data
237 paymnt.transactions.append(raw_tx)
239 ref_out = paymnt.refund_to.add()
240 ref_out.script = transaction.Transaction.pay_script(refund_addr)
241 paymnt.memo = "Paid using Electrum"
242 pm = paymnt.SerializeToString()
244 payurl = urlparse.urlparse(pay_det.payment_url)
246 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=ca_path)
247 except requests.exceptions.SSLError:
248 print "Payment Message/PaymentACK verify Failed"
250 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
251 except Exception as e:
253 return False, "Payment Message/PaymentACK Failed"
255 if r.status_code >= 500:
256 return False, r.reason
259 paymntack = paymentrequest_pb2.PaymentACK()
260 paymntack.ParseFromString(r.content)
262 return False, "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
264 print "PaymentACK message received: %s" % paymntack.memo
265 return True, paymntack.memo
269 if __name__ == "__main__":
274 print "usage: %s url"%sys.argv[0]
275 print "example url: \"bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D2a828c05b8b80dc440c80a5d58890298&amount=1\""
278 address, amount, label, message, request_url, url = util.parse_url(uri)
279 pr = PaymentRequest(request_url)
283 print 'Payment Request Verified Domain: ', pr.domain
284 print 'outputs', pr.outputs
285 print 'Payment Memo: ', pr.payment_details.memo
288 pr.send_ack(tx, refund_addr = "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")