commit 87fa402c345f1b59daa4f85bc61517b9d80052ff
parent 2642b7e1265f1e0e4a1f18dba33601af3b8b8d75
Author: ThomasV <thomasv@gitorious>
Date: Wed, 7 May 2014 15:26:38 +0200
support for payment requests in the gui
Diffstat:
4 files changed, 142 insertions(+), 101 deletions(-)
diff --git a/gui/qt/__init__.py b/gui/qt/__init__.py
@@ -150,21 +150,38 @@ class ElectrumGui:
def set_url(self, url):
from electrum import util
from decimal import Decimal
+
try:
- address, amount, label, message, url = util.parse_url(url)
+ address, amount, label, message, request_url, url = util.parse_url(url)
except Exception:
QMessageBox.warning(self.main_window, _('Error'), _('Invalid bitcoin URL'), _('OK'))
return
- try:
- if amount and self.main_window.base_unit() == 'mBTC':
- amount = str( 1000* Decimal(amount))
- elif amount:
- amount = str(Decimal(amount))
- except Exception:
- amount = "0.0"
- QMessageBox.warning(self.main_window, _('Error'), _('Invalid Amount'), _('OK'))
-
+ if amount:
+ try:
+ if self.main_window.base_unit() == 'mBTC':
+ amount = str( 1000* Decimal(amount))
+ else:
+ amount = str(Decimal(amount))
+ except Exception:
+ amount = "0.0"
+ QMessageBox.warning(self.main_window, _('Error'), _('Invalid Amount'), _('OK'))
+
+ if request_url:
+ try:
+ from electrum import paymentrequest
+ except:
+ print "cannot import paymentrequest"
+ return
+ def payment_request():
+ pr = paymentrequest.PaymentRequest(request_url)
+ if pr.verify() or 1:
+ self.main_window.payment_request = pr
+ self.main_window.emit(SIGNAL('payment_request_ok'))
+ else:
+ self.main_window.emit(SIGNAL('payment_request_failed'))
+
+ threading.Thread(target=payment_request).start()
self.main_window.set_send(address, amount, label, message)
if self.lite_window:
diff --git a/gui/qt/main_window.py b/gui/qt/main_window.py
@@ -120,6 +120,7 @@ class ElectrumWindow(QMainWindow):
set_language(config.get('language'))
self.funds_error = False
+ self.payment_request = None
self.completions = QStringListModel()
self.tabs = tabs = QTabWidget(self)
@@ -155,6 +156,7 @@ class ElectrumWindow(QMainWindow):
self.connect(self, QtCore.SIGNAL('transaction_signal'), lambda: self.notify_transactions() )
self.connect(self, QtCore.SIGNAL('send_tx2'), self.send_tx2)
self.connect(self, QtCore.SIGNAL('send_tx3'), self.send_tx3)
+ self.connect(self, QtCore.SIGNAL('payment_request_ok'), self.payment_request_ok)
self.history_list.setFocus(True)
@@ -203,7 +205,7 @@ class ElectrumWindow(QMainWindow):
self.password_menu.setEnabled(not self.wallet.is_watching_only())
self.seed_menu.setEnabled(self.wallet.has_seed())
self.mpk_menu.setEnabled(self.wallet.is_deterministic())
- self.import_menu.setEnabled(self.wallet.can_create_accounts() or not self.wallet.is_deterministic())
+ self.import_menu.setEnabled(self.wallet.can_import())
self.update_lock_icon()
self.update_buttons_on_seed()
@@ -767,24 +769,31 @@ class ElectrumWindow(QMainWindow):
def do_send(self):
-
label = unicode( self.message_e.text() )
- r = unicode( self.payto_e.text() )
- r = r.strip()
- # label or alias, with address in brackets
- m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
- to_address = m.group(2) if m else r
+ if self.payment_request:
+ outputs = self.payment_request.outputs
+ amount = self.payment_request.get_amount()
- if not is_valid(to_address):
- QMessageBox.warning(self, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
- return
+ else:
+ r = unicode( self.payto_e.text() )
+ r = r.strip()
+
+ # label or alias, with address in brackets
+ m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
+ to_address = m.group(2) if m else r
+ if not is_valid(to_address):
+ QMessageBox.warning(self, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
+ return
+
+ try:
+ amount = self.read_amount(unicode( self.amount_e.text()))
+ except Exception:
+ QMessageBox.warning(self, _('Error'), _('Invalid Amount'), _('OK'))
+ return
+
+ outputs = [(to_address, amount)]
- try:
- amount = self.read_amount(unicode( self.amount_e.text()))
- except Exception:
- QMessageBox.warning(self, _('Error'), _('Invalid Amount'), _('OK'))
- return
try:
fee = self.read_amount(unicode( self.fee_e.text()))
except Exception:
@@ -801,7 +810,7 @@ class ElectrumWindow(QMainWindow):
if not self.question(_("The fee for this transaction seems unusually high.\nAre you really sure you want to pay %(fee)s in fees?")%{ 'fee' : self.format_amount(fee) + ' '+ self.base_unit()}):
return
- self.send_tx(to_address, amount, fee, label)
+ self.send_tx(outputs, fee, label)
def waiting_dialog(self, message):
@@ -815,11 +824,10 @@ class ElectrumWindow(QMainWindow):
@protected
- def send_tx(self, to_address, amount, fee, label, password):
+ def send_tx(self, outputs, fee, label, password):
# first, create an unsigned tx
domain = self.get_payment_sources()
- outputs = [(to_address, amount)]
try:
tx = self.wallet.make_unsigned_transaction(outputs, fee, None, domain)
tx.error = None
@@ -842,9 +850,6 @@ class ElectrumWindow(QMainWindow):
self.tx_wait_dialog = self.waiting_dialog('Signing..')
threading.Thread(target=sign_thread).start()
- # add recipient to addressbook
- if to_address not in self.wallet.addressbook and not self.wallet.is_mine(to_address):
- self.wallet.addressbook.append(to_address)
def send_tx2(self):
@@ -866,28 +871,36 @@ class ElectrumWindow(QMainWindow):
self.show_transaction(tx)
return
- # broadcast the tx
def broadcast_thread():
+ if self.payment_request:
+ refund_address = self.wallet.addresses()[0]
+ self.payment_request.send_ack(str(tx), refund_address)
+ self.payment_request = None
+ # note: BIP 70 recommends not broadcasting the tx to the network and letting the merchant do that
self.tx_broadcast_result = self.wallet.sendtx(tx)
self.emit(SIGNAL('send_tx3'))
+
self.tx_broadcast_dialog = self.waiting_dialog('Broadcasting..')
threading.Thread(target=broadcast_thread).start()
+
def send_tx3(self):
self.tx_broadcast_dialog.accept()
status, msg = self.tx_broadcast_result
if status:
QMessageBox.information(self, '', _('Payment sent.') + '\n' + msg, _('OK'))
self.do_clear()
- self.update_contacts_tab()
else:
QMessageBox.warning(self, _('Error'), msg, _('OK'))
-
-
+ def payment_request_ok(self):
+ self.payto_e.setText(self.payment_request.domain)
+ self.payto_e.setReadOnly(True)
+ self.amount_e.setText(self.format_amount(self.payment_request.get_amount()))
+ self.amount_e.setReadOnly(True)
def set_send(self, address, amount, label, message):
diff --git a/lib/paymentrequest.py b/lib/paymentrequest.py
@@ -12,7 +12,7 @@ try:
import paymentrequest_pb2
except:
print "protoc --proto_path=lib/ --python_out=lib/ lib/paymentrequest.proto"
- sys.exit(1)
+ raise Exception()
import urlparse
import requests
@@ -21,38 +21,47 @@ from M2Crypto import X509
from bitcoin import is_valid
import urlparse
+
+import util
import transaction
+
REQUEST_HEADERS = {'Accept': 'application/bitcoin-paymentrequest', 'User-Agent': 'Electrum'}
ACK_HEADERS = {'Content-Type':'application/bitcoin-payment','Accept':'application/bitcoin-paymentack','User-Agent':'Electrum'}
+ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
+ca_list = {}
+try:
+ with open(ca_path, 'r') as ca_f:
+ c = ""
+ for line in ca_f:
+ if line == "-----BEGIN CERTIFICATE-----\n":
+ c = line
+ else:
+ c += line
+ if line == "-----END CERTIFICATE-----\n":
+ x = X509.load_cert_string(c)
+ ca_list[x.get_fingerprint()] = x
+except Exception:
+ print "ERROR: Could not open %s"%ca_path
+ print "ca-bundle.crt file should be placed in ~/.electrum/ca/ca-bundle.crt"
+ print "Documentation on how to download or create the file here: http://curl.haxx.se/docs/caextract.html"
+ print "Payment will continue with manual verification."
+ raise Exception()
+
+
class PaymentRequest:
- def __init__(self):
- self.ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
- self.ca_list = {}
- try:
- with open(self.ca_path, 'r') as ca_f:
- c = ""
- for line in ca_f:
- if line == "-----BEGIN CERTIFICATE-----\n":
- c = line
- else:
- c += line
- if line == "-----END CERTIFICATE-----\n":
- x = X509.load_cert_string(c)
- self.ca_list[x.get_fingerprint()] = x
- except Exception:
- print "ERROR: Could not open %s"%self.ca_path
- print "ca-bundle.crt file should be placed in ~/.electrum/ca/ca-bundle.crt"
- print "Documentation on how to download or create the file here: http://curl.haxx.se/docs/caextract.html"
- print "Payment will continue with manual verification."
-
-
-
- def verify(self, url):
-
- u = urlparse.urlparse(urllib2.unquote(url))
+ def __init__(self, url):
+ self.url = url
+ self.outputs = []
+
+ def get_amount(self):
+ return sum(map(lambda x:x[1], self.outputs))
+
+
+ def verify(self):
+ u = urlparse.urlparse(self.url)
self.domain = u.netloc
connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
@@ -64,6 +73,9 @@ class PaymentRequest:
paymntreq.ParseFromString(r)
sig = paymntreq.signature
+ if not sig:
+ print "No signature"
+ return
cert = paymentrequest_pb2.X509Certificates()
cert.ParseFromString(paymntreq.pki_data)
@@ -116,7 +128,7 @@ class PaymentRequest:
supplied_CA_CN = x509[cert_num-2].get_subject().CN
CA_match = False
- x = self.ca_list.get(supplied_CA_fingerprint)
+ x = ca_list.get(supplied_CA_fingerprint)
if x:
CA_OU = x.get_subject().OU
CA_match = True
@@ -155,9 +167,8 @@ class PaymentRequest:
if pay_det.expires and pay_det.expires < int(time.time()):
print "ERROR: Payment Request has Expired."
- return False
+ #return False
- self.outputs = []
for o in pay_det.outputs:
addr = transaction.get_address_from_output_script(o.script)[1]
self.outputs.append( (addr, o.amount) )
@@ -165,7 +176,7 @@ class PaymentRequest:
if CA_match:
print 'Signed By Trusted CA: ', CA_OU
- return True
+ return pay_det
@@ -185,7 +196,7 @@ class PaymentRequest:
payurl = urlparse.urlparse(pay_det.payment_url)
try:
- r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=self.ca_path)
+ r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=ca_path)
except requests.exceptions.SSLError:
print "Payment Message/PaymentACK verify Failed"
try:
@@ -202,17 +213,20 @@ class PaymentRequest:
print "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
-uri = "bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D26c19879d44c3891214e7897797b9160&amount=1"
-url = "https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D26c19879d44c3891214e7897797b9160"
-
-#uri = "bitcoin:1m9Lw2pFCe6Hs7xUuo9fMJCzEwQNdCo5e?amount=0.0012&r=https%3A%2F%2Fbitpay.com%2Fi%2F8XNDiQU92H2whNG4j8hZ5M"
-#url = "https%3A%2F%2Fbitpay.com%2Fi%2F8XNDiQU92H2whNG4j8hZ5M"
if __name__ == "__main__":
- pr = PaymentRequest()
- if not pr.verify(url):
+ try:
+ uri = sys.argv[1]
+ except:
+ print "usage: %s url"%sys.argv[0]
+ print "example url: \"bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D2a828c05b8b80dc440c80a5d58890298&amount=1\""
+ sys.exit(1)
+
+ address, amount, label, message, request_url, url = util.parse_url(uri)
+ pr = PaymentRequest(request_url)
+ if not pr.verify():
sys.exit(1)
print 'Payment Request Verified Domain: ', pr.domain
@@ -220,5 +234,5 @@ if __name__ == "__main__":
print 'Payment Memo: ', pr.payment_details.memo
tx = "blah"
- pr.send_ack(tx, "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")
+ pr.send_ack(tx, refund_addr = "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")
diff --git a/lib/util.py b/lib/util.py
@@ -153,46 +153,43 @@ def age(from_date, since_date = None, target_tz=None, include_seconds=False):
return "over %d years ago" % (round(distance_in_minutes / 525600))
-
-
# URL decode
-_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
-urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
+#_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
+#urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
def parse_url(url):
+ import urlparse
from decimal import Decimal
- url = str(url)
- o = url[8:].split('?')
- address = o[0]
- if len(o)>1:
- params = o[1].split('&')
- else:
- params = []
- kv = {}
+ u = urlparse.urlparse(url)
+ assert u.scheme == 'bitcoin'
+
+ address = u.path
+ #assert bitcoin.is_address(address)
+
+ pq = urlparse.parse_qs(u.query)
+
+ for k, v in pq.items():
+ if len(v)!=1:
+ raise Exception('Duplicate Key', k)
amount = label = message = ''
- for p in params:
- k,v = p.split('=')
- uv = urldecode(v)
- if k in kv:
- raise Exception('Duplicate Keys')
- kv[k] = uv
-
- if 'amount' in kv:
- am = kv['amount']
+ if 'amount' in pq:
+ am = pq['amount'][0]
m = re.match('([0-9\.]+)X([0-9])', am)
if m:
k = int(m.group(2)) - 8
amount = Decimal(m.group(1)) * pow( Decimal(10) , k)
else:
amount = Decimal(am)
- if 'message' in kv:
- message = kv['message']
- if 'label' in kv:
- label = kv['label']
-
- return address, amount, label, message, url
+ if 'message' in pq:
+ message = pq['message'][0]
+ if 'label' in pq:
+ label = pq['label'][0]
+ if 'r' in pq:
+ request_url = pq['r'][0]
+
+ return address, amount, label, message, request_url, url
# Python bug (http://bugs.python.org/issue1927) causes raw_input