2014-06-10 05:32:17 -07:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# Electrum - lightweight Bitcoin client
|
|
|
|
# Copyright (C) 2014 Thomas Voegtlin
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
|
2014-05-05 08:31:39 -07:00
|
|
|
import hashlib
|
|
|
|
import httplib
|
|
|
|
import os.path
|
|
|
|
import re
|
|
|
|
import sys
|
|
|
|
import threading
|
|
|
|
import time
|
|
|
|
import traceback
|
|
|
|
import urllib2
|
2014-06-07 10:53:54 -07:00
|
|
|
import urlparse
|
2015-01-26 05:14:16 -08:00
|
|
|
import requests
|
2014-05-05 08:31:39 -07:00
|
|
|
|
|
|
|
try:
|
2015-04-05 09:57:00 -07:00
|
|
|
import paymentrequest_pb2 as pb2
|
2015-01-27 01:01:40 -08:00
|
|
|
except ImportError:
|
2014-06-07 10:53:54 -07:00
|
|
|
sys.exit("Error: could not find paymentrequest_pb2.py. Create it with 'protoc --proto_path=lib/ --python_out=lib/ lib/paymentrequest.proto'")
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-06-07 02:11:49 -07:00
|
|
|
import bitcoin
|
2014-05-07 06:26:38 -07:00
|
|
|
import util
|
2014-05-05 08:31:39 -07:00
|
|
|
import transaction
|
2014-06-10 05:32:17 -07:00
|
|
|
import x509
|
2014-11-11 02:08:25 -08:00
|
|
|
from util import print_error
|
2014-05-07 06:26:38 -07:00
|
|
|
|
2014-05-05 08:31:39 -07:00
|
|
|
REQUEST_HEADERS = {'Accept': 'application/bitcoin-paymentrequest', 'User-Agent': 'Electrum'}
|
|
|
|
ACK_HEADERS = {'Content-Type':'application/bitcoin-payment','Accept':'application/bitcoin-paymentack','User-Agent':'Electrum'}
|
|
|
|
|
2014-06-26 10:52:09 -07:00
|
|
|
ca_path = requests.certs.where()
|
2015-02-15 12:27:11 -08:00
|
|
|
ca_list = x509.load_certificates(ca_path)
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-06-10 05:32:17 -07:00
|
|
|
|
2014-11-11 02:08:25 -08:00
|
|
|
# status of payment requests
|
|
|
|
PR_UNPAID = 0
|
|
|
|
PR_EXPIRED = 1
|
|
|
|
PR_SENT = 2 # sent but not propagated
|
|
|
|
PR_PAID = 3 # send and propagated
|
|
|
|
PR_ERROR = 4 # could not parse
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-11-11 02:08:25 -08:00
|
|
|
import json
|
2014-06-07 10:53:54 -07:00
|
|
|
|
|
|
|
|
2014-11-11 02:08:25 -08:00
|
|
|
def get_payment_request(url):
|
|
|
|
u = urlparse.urlparse(url)
|
2015-04-13 08:54:28 -07:00
|
|
|
if u.scheme in ['http', 'https']:
|
|
|
|
connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
|
|
|
|
connection.request("GET", u.geturl(), headers=REQUEST_HEADERS)
|
|
|
|
response = connection.getresponse()
|
|
|
|
data = response.read()
|
|
|
|
elif u.scheme == 'file':
|
|
|
|
with open(u.path, 'r') as f:
|
|
|
|
data = f.read()
|
|
|
|
else:
|
|
|
|
raise BaseException("unknown scheme", url)
|
2014-11-11 02:08:25 -08:00
|
|
|
pr = PaymentRequest(data)
|
|
|
|
return pr
|
2014-06-07 10:53:54 -07:00
|
|
|
|
|
|
|
|
2014-11-11 02:08:25 -08:00
|
|
|
class PaymentRequest:
|
2014-06-07 10:53:54 -07:00
|
|
|
|
2014-11-11 02:08:25 -08:00
|
|
|
def __init__(self, data):
|
|
|
|
self.raw = data
|
|
|
|
self.parse(data)
|
|
|
|
self.domain = None # known after verify
|
|
|
|
self.tx = None
|
2014-06-07 10:53:54 -07:00
|
|
|
|
2014-11-11 02:08:25 -08:00
|
|
|
def __str__(self):
|
|
|
|
return self.raw
|
2014-06-07 10:53:54 -07:00
|
|
|
|
2014-11-11 02:08:25 -08:00
|
|
|
def get_status(self):
|
|
|
|
if self.tx is not None:
|
|
|
|
return PR_PAID
|
|
|
|
if self.has_expired():
|
|
|
|
return PR_EXPIRED
|
|
|
|
return PR_UNPAID
|
2014-06-07 10:53:54 -07:00
|
|
|
|
|
|
|
def parse(self, r):
|
2014-11-11 02:08:25 -08:00
|
|
|
self.id = bitcoin.sha256(r)[0:16].encode('hex')
|
2014-06-06 07:16:14 -07:00
|
|
|
try:
|
2015-04-05 09:57:00 -07:00
|
|
|
self.data = pb2.PaymentRequest()
|
2014-06-06 07:16:14 -07:00
|
|
|
self.data.ParseFromString(r)
|
2014-05-07 09:20:17 -07:00
|
|
|
except:
|
|
|
|
self.error = "cannot parse payment request"
|
|
|
|
return
|
2015-04-10 07:32:16 -07:00
|
|
|
self.details = pb2.PaymentDetails()
|
|
|
|
self.details.ParseFromString(self.data.serialized_payment_details)
|
2014-11-11 02:08:25 -08:00
|
|
|
self.outputs = []
|
2015-04-10 07:32:16 -07:00
|
|
|
for o in self.details.outputs:
|
|
|
|
addr = transaction.get_address_from_output_script(o.script)[1]
|
|
|
|
self.outputs.append(('address', addr, o.amount))
|
|
|
|
self.memo = self.details.memo
|
|
|
|
self.payment_url = self.details.payment_url
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-06-06 07:16:14 -07:00
|
|
|
def verify(self):
|
2014-06-07 02:11:49 -07:00
|
|
|
if not ca_list:
|
|
|
|
self.error = "Trusted certificate authorities list not found"
|
|
|
|
return False
|
2014-06-06 07:16:14 -07:00
|
|
|
paymntreq = self.data
|
2014-06-10 05:32:17 -07:00
|
|
|
if not paymntreq.signature:
|
2014-05-07 09:10:14 -07:00
|
|
|
self.error = "No signature"
|
2014-10-21 10:05:51 -07:00
|
|
|
return
|
2015-04-05 09:57:00 -07:00
|
|
|
cert = pb2.X509Certificates()
|
2014-05-05 08:31:39 -07:00
|
|
|
cert.ParseFromString(paymntreq.pki_data)
|
|
|
|
cert_num = len(cert.certificate)
|
2014-06-10 05:32:17 -07:00
|
|
|
x509_chain = []
|
|
|
|
for i in range(cert_num):
|
|
|
|
x = x509.X509()
|
|
|
|
x.parseBinary(bytearray(cert.certificate[i]))
|
|
|
|
x509_chain.append(x)
|
|
|
|
if i == 0:
|
2014-06-27 02:36:51 -07:00
|
|
|
try:
|
|
|
|
x.check_date()
|
|
|
|
except Exception as e:
|
|
|
|
self.error = str(e)
|
2014-06-10 05:32:17 -07:00
|
|
|
return
|
2014-11-11 02:08:25 -08:00
|
|
|
self.domain = x.get_common_name()
|
2015-04-13 08:54:28 -07:00
|
|
|
if self.domain.startswith('*.'):
|
|
|
|
self.domain = self.domain[2:]
|
2014-06-10 05:32:17 -07:00
|
|
|
else:
|
|
|
|
if not x.check_ca():
|
2014-05-07 09:10:14 -07:00
|
|
|
self.error = "ERROR: Supplied CA Certificate Error"
|
2014-05-05 08:31:39 -07:00
|
|
|
return
|
2014-06-10 05:32:17 -07:00
|
|
|
if not cert_num > 1:
|
2014-05-07 09:10:14 -07:00
|
|
|
self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
|
2014-05-05 08:31:39 -07:00
|
|
|
return False
|
2015-04-10 07:32:16 -07:00
|
|
|
# if the root CA is not supplied, add it to the chain
|
|
|
|
ca = x509_chain[cert_num-1]
|
2015-04-14 06:04:04 -07:00
|
|
|
if ca.get_common_name() not in ca_list:
|
|
|
|
x = ca_list.get(ca.get_issuer())
|
|
|
|
if x:
|
|
|
|
x509_chain.append(x)
|
2015-04-10 07:32:16 -07:00
|
|
|
else:
|
|
|
|
self.error = "Supplied CA Not Found in Trusted CA Store."
|
|
|
|
return False
|
|
|
|
# verify the chain of signatures
|
|
|
|
cert_num = len(cert.certificate)
|
2014-06-10 05:32:17 -07:00
|
|
|
for i in range(1, cert_num):
|
|
|
|
x = x509_chain[i]
|
|
|
|
prev_x = x509_chain[i-1]
|
2015-04-14 06:04:04 -07:00
|
|
|
algo, sig, data = prev_x.get_signature()
|
|
|
|
sig = bytearray(sig)
|
2014-06-10 05:32:17 -07:00
|
|
|
pubkey = x.publicKey
|
2015-04-14 06:04:04 -07:00
|
|
|
if algo == x509.ALGO_RSA_SHA1:
|
2014-06-30 11:19:18 -07:00
|
|
|
verify = pubkey.hashAndVerify(sig, data)
|
2015-04-14 06:04:04 -07:00
|
|
|
elif algo == x509.ALGO_RSA_SHA256:
|
2014-06-30 11:19:18 -07:00
|
|
|
hashBytes = bytearray(hashlib.sha256(data).digest())
|
2015-02-08 11:04:42 -08:00
|
|
|
verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA256 + hashBytes)
|
2015-04-14 06:04:04 -07:00
|
|
|
elif algo == x509.ALGO_RSA_SHA384:
|
2015-02-08 11:04:42 -08:00
|
|
|
hashBytes = bytearray(hashlib.sha384(data).digest())
|
|
|
|
verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA384 + hashBytes)
|
2015-04-14 06:04:04 -07:00
|
|
|
elif algo == x509.ALGO_RSA_SHA512:
|
2015-02-08 11:04:42 -08:00
|
|
|
hashBytes = bytearray(hashlib.sha512(data).digest())
|
|
|
|
verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA512 + hashBytes)
|
2014-06-30 11:19:18 -07:00
|
|
|
else:
|
2014-10-21 10:05:51 -07:00
|
|
|
self.error = "Algorithm not supported"
|
2014-06-30 11:19:18 -07:00
|
|
|
util.print_error(self.error, algo.getComponentByName('algorithm'))
|
2015-04-10 07:32:16 -07:00
|
|
|
return False
|
2014-06-10 05:32:17 -07:00
|
|
|
if not verify:
|
|
|
|
self.error = "Certificate not Signed by Provided CA Certificate Chain"
|
2015-04-10 07:32:16 -07:00
|
|
|
return False
|
|
|
|
# verify the BIP70 signature
|
2014-06-10 05:32:17 -07:00
|
|
|
pubkey0 = x509_chain[0].publicKey
|
|
|
|
sig = paymntreq.signature
|
2014-05-05 08:31:39 -07:00
|
|
|
paymntreq.signature = ''
|
|
|
|
s = paymntreq.SerializeToString()
|
2014-06-10 05:32:17 -07:00
|
|
|
sigBytes = bytearray(sig)
|
|
|
|
msgBytes = bytearray(s)
|
2014-05-05 08:31:39 -07:00
|
|
|
if paymntreq.pki_type == "x509+sha256":
|
2014-06-10 05:32:17 -07:00
|
|
|
hashBytes = bytearray(hashlib.sha256(msgBytes).digest())
|
2015-02-08 11:04:42 -08:00
|
|
|
verify = pubkey0.verify(sigBytes, x509.PREFIX_RSA_SHA256 + hashBytes)
|
2014-05-05 08:31:39 -07:00
|
|
|
elif paymntreq.pki_type == "x509+sha1":
|
2014-06-10 05:32:17 -07:00
|
|
|
verify = pubkey0.hashAndVerify(sigBytes, msgBytes)
|
2014-05-05 08:31:39 -07:00
|
|
|
else:
|
2014-05-07 09:10:14 -07:00
|
|
|
self.error = "ERROR: Unsupported PKI Type for Message Signature"
|
2014-05-05 08:31:39 -07:00
|
|
|
return False
|
2014-06-10 05:32:17 -07:00
|
|
|
if not verify:
|
2014-05-07 09:10:14 -07:00
|
|
|
self.error = "ERROR: Invalid Signature for Payment Request Data"
|
2014-05-05 08:31:39 -07:00
|
|
|
return False
|
|
|
|
### SIG Verified
|
2015-04-13 08:54:28 -07:00
|
|
|
self.error = 'Signed by Trusted CA: ' + ca.get_common_name()
|
2014-05-07 09:10:14 -07:00
|
|
|
return True
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-06-07 10:53:54 -07:00
|
|
|
def has_expired(self):
|
|
|
|
return self.details.expires and self.details.expires < int(time.time())
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-06-13 07:53:43 -07:00
|
|
|
def get_expiration_date(self):
|
|
|
|
return self.details.expires
|
|
|
|
|
2014-06-06 07:16:14 -07:00
|
|
|
def get_amount(self):
|
2014-07-09 12:21:47 -07:00
|
|
|
return sum(map(lambda x:x[2], self.outputs))
|
2014-06-06 07:16:14 -07:00
|
|
|
|
|
|
|
def get_domain(self):
|
2014-11-11 02:08:25 -08:00
|
|
|
return self.domain if self.domain else 'unknown'
|
|
|
|
|
|
|
|
def get_verify_status(self):
|
|
|
|
return self.error
|
2014-06-06 07:16:14 -07:00
|
|
|
|
2014-06-12 01:20:06 -07:00
|
|
|
def get_memo(self):
|
|
|
|
return self.memo
|
|
|
|
|
2014-06-06 07:16:14 -07:00
|
|
|
def get_id(self):
|
|
|
|
return self.id
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-06-07 10:53:54 -07:00
|
|
|
def get_outputs(self):
|
2014-06-12 02:27:18 -07:00
|
|
|
return self.outputs[:]
|
2014-06-07 10:53:54 -07:00
|
|
|
|
2014-05-05 08:31:39 -07:00
|
|
|
def send_ack(self, raw_tx, refund_addr):
|
|
|
|
|
2014-06-07 10:53:54 -07:00
|
|
|
pay_det = self.details
|
|
|
|
if not self.details.payment_url:
|
2014-05-10 11:35:00 -07:00
|
|
|
return False, "no url"
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-05-07 09:59:51 -07:00
|
|
|
paymnt = paymentrequest_pb2.Payment()
|
|
|
|
paymnt.merchant_data = pay_det.merchant_data
|
|
|
|
paymnt.transactions.append(raw_tx)
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-05-07 09:59:51 -07:00
|
|
|
ref_out = paymnt.refund_to.add()
|
2014-07-09 12:21:47 -07:00
|
|
|
ref_out.script = transaction.Transaction.pay_script('address', refund_addr)
|
2014-05-07 09:59:51 -07:00
|
|
|
paymnt.memo = "Paid using Electrum"
|
|
|
|
pm = paymnt.SerializeToString()
|
2014-05-05 08:31:39 -07:00
|
|
|
|
2014-05-07 09:59:51 -07:00
|
|
|
payurl = urlparse.urlparse(pay_det.payment_url)
|
|
|
|
try:
|
|
|
|
r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=ca_path)
|
|
|
|
except requests.exceptions.SSLError:
|
|
|
|
print "Payment Message/PaymentACK verify Failed"
|
2014-05-05 08:31:39 -07:00
|
|
|
try:
|
2014-05-07 09:59:51 -07:00
|
|
|
r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
|
|
|
|
except Exception as e:
|
|
|
|
print e
|
2014-05-10 11:35:00 -07:00
|
|
|
return False, "Payment Message/PaymentACK Failed"
|
|
|
|
|
|
|
|
if r.status_code >= 500:
|
|
|
|
return False, r.reason
|
|
|
|
|
2014-05-07 09:59:51 -07:00
|
|
|
try:
|
2015-04-05 09:57:00 -07:00
|
|
|
paymntack = pb2.PaymentACK()
|
2014-05-07 09:59:51 -07:00
|
|
|
paymntack.ParseFromString(r.content)
|
|
|
|
except Exception:
|
2014-05-10 11:35:00 -07:00
|
|
|
return False, "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
|
2014-05-07 09:59:51 -07:00
|
|
|
|
|
|
|
print "PaymentACK message received: %s" % paymntack.memo
|
2014-05-10 11:35:00 -07:00
|
|
|
return True, paymntack.memo
|
2014-05-05 08:31:39 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
2015-04-05 09:57:00 -07:00
|
|
|
def make_payment_request(amount, script, memo, rsakey=None):
|
|
|
|
"""Generates a http PaymentRequest object"""
|
|
|
|
pd = pb2.PaymentDetails()
|
|
|
|
pd.outputs.add(amount=amount, script=script)
|
|
|
|
now = int(time.time())
|
|
|
|
pd.time = now
|
|
|
|
pd.expires = now + 15*60
|
|
|
|
pd.memo = memo
|
|
|
|
#pd.payment_url = 'http://payment_ack.url'
|
|
|
|
pr = pb2.PaymentRequest()
|
|
|
|
pr.serialized_payment_details = pd.SerializeToString()
|
|
|
|
pr.signature = ''
|
|
|
|
if rsakey:
|
|
|
|
pr.pki_type = 'x509+sha256'
|
|
|
|
pr.pki_data = certificates.SerializeToString()
|
|
|
|
msgBytes = bytearray(pr.SerializeToString())
|
|
|
|
hashBytes = bytearray(hashlib.sha256(msgBytes).digest())
|
|
|
|
sig = rsakey.sign(x509.PREFIX_RSA_SHA256 + hashBytes)
|
|
|
|
pr.signature = bytes(sig)
|
|
|
|
return pr.SerializeToString()
|
|
|
|
|
|
|
|
|
|
|
|
|
2014-11-11 02:08:25 -08:00
|
|
|
|
|
|
|
class InvoiceStore(object):
|
|
|
|
|
|
|
|
def __init__(self, config):
|
|
|
|
self.config = config
|
|
|
|
self.invoices = {}
|
|
|
|
self.load_invoices()
|
|
|
|
|
|
|
|
def load_invoices(self):
|
|
|
|
path = os.path.join(self.config.path, 'invoices')
|
|
|
|
try:
|
|
|
|
with open(path, 'r') as f:
|
|
|
|
d = json.loads(f.read())
|
|
|
|
except:
|
|
|
|
return
|
|
|
|
for k, v in d.items():
|
|
|
|
ser, domain, tx = v
|
|
|
|
try:
|
|
|
|
pr = PaymentRequest(ser.decode('hex'))
|
|
|
|
pr.tx = tx
|
|
|
|
pr.domain = domain
|
|
|
|
self.invoices[k] = pr
|
|
|
|
except:
|
|
|
|
continue
|
|
|
|
|
|
|
|
def save(self):
|
|
|
|
l = {}
|
|
|
|
for k, pr in self.invoices.items():
|
|
|
|
l[k] = str(pr).encode('hex'), pr.domain, pr.tx
|
|
|
|
path = os.path.join(self.config.path, 'invoices')
|
|
|
|
with open(path, 'w') as f:
|
|
|
|
r = f.write(json.dumps(l))
|
|
|
|
|
|
|
|
def add(self, pr):
|
|
|
|
key = pr.get_id()
|
|
|
|
if key in self.invoices:
|
|
|
|
print_error('invoice already in list')
|
|
|
|
return False
|
|
|
|
self.invoices[key] = pr
|
|
|
|
self.save()
|
|
|
|
return key
|
|
|
|
|
|
|
|
def remove(self, key):
|
|
|
|
self.invoices.pop(key)
|
|
|
|
self.save()
|
|
|
|
|
|
|
|
def get(self, k):
|
|
|
|
return self.invoices.get(k)
|
|
|
|
|
|
|
|
def set_paid(self, key, tx_hash):
|
|
|
|
self.invoices[key].tx = tx_hash
|
|
|
|
self.save()
|
|
|
|
|
|
|
|
def sorted_list(self):
|
|
|
|
# sort
|
|
|
|
return self.invoices.values()
|
|
|
|
|
|
|
|
|
|
|
|
|
2014-05-05 08:31:39 -07:00
|
|
|
if __name__ == "__main__":
|
|
|
|
|
2014-08-11 04:22:53 -07:00
|
|
|
util.set_verbosity(True)
|
|
|
|
|
2014-05-07 06:26:38 -07:00
|
|
|
try:
|
|
|
|
uri = sys.argv[1]
|
|
|
|
except:
|
|
|
|
print "usage: %s url"%sys.argv[0]
|
2014-06-26 10:52:09 -07:00
|
|
|
print "example url: \"bitcoin:17KjQgnXC96jakzJe9yo8zxqerhqNptmhq?amount=0.0018&r=https%3A%2F%2Fbitpay.com%2Fi%2FMXc7qTM5f87EC62SWiS94z\""
|
2014-05-07 06:26:38 -07:00
|
|
|
sys.exit(1)
|
|
|
|
|
2014-06-26 10:52:09 -07:00
|
|
|
address, amount, label, message, request_url = util.parse_URI(uri)
|
|
|
|
from simple_config import SimpleConfig
|
|
|
|
config = SimpleConfig()
|
|
|
|
pr = PaymentRequest(config)
|
|
|
|
pr.read(request_url)
|
2014-05-07 06:26:38 -07:00
|
|
|
if not pr.verify():
|
2014-06-26 10:52:09 -07:00
|
|
|
print 'verify failed'
|
|
|
|
print pr.error
|
2014-05-05 08:31:39 -07:00
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
print 'Payment Request Verified Domain: ', pr.domain
|
|
|
|
print 'outputs', pr.outputs
|
2014-06-07 10:53:54 -07:00
|
|
|
print 'Payment Memo: ', pr.details.memo
|
2014-05-05 08:31:39 -07:00
|
|
|
|
|
|
|
tx = "blah"
|
2014-05-07 06:26:38 -07:00
|
|
|
pr.send_ack(tx, refund_addr = "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")
|