diff --git a/gui/qt/amountedit.py b/gui/qt/amountedit.py index f9e939b02..dcb14aad7 100644 --- a/gui/qt/amountedit.py +++ b/gui/qt/amountedit.py @@ -18,6 +18,8 @@ class AmountEdit(MyLineEdit): def __init__(self, base_unit, is_int = False, parent=None): QLineEdit.__init__(self, parent) + # This seems sufficient for hundred-BTC amounts with 8 decimals + self.setFixedWidth(140) self.base_unit = base_unit self.textChanged.connect(self.numbify) self.is_int = is_int diff --git a/gui/qt/history_widget.py b/gui/qt/history_widget.py index 6449cc65b..94acd43ea 100644 --- a/gui/qt/history_widget.py +++ b/gui/qt/history_widget.py @@ -28,7 +28,7 @@ from electrum.plugins import run_hook class HistoryWidget(MyTreeWidget): def __init__(self, parent=None): - MyTreeWidget.__init__(self, parent, self.create_menu, [ '', _('Date'), _('Description') , _('Amount'), _('Balance')], [40, 140, None, 140, 140]) + MyTreeWidget.__init__(self, parent, self.create_menu, [ '', _('Date'), _('Description') , _('Amount'), _('Balance')], 2) self.config = self.parent.config self.setSortingEnabled(False) diff --git a/gui/qt/history_widget_lite.py b/gui/qt/history_widget_lite.py index a08f8d1c7..d202ff7ff 100644 --- a/gui/qt/history_widget_lite.py +++ b/gui/qt/history_widget_lite.py @@ -20,6 +20,6 @@ class HistoryWidget(QTreeWidget): if date is None: date = _("Unknown") item = QTreeWidgetItem([amount, address, date]) - if float(amount) < 0: + if amount.find('-') != -1: item.setForeground(0, QBrush(QColor("#BC1E1E"))) self.insertTopLevelItem(0, item) diff --git a/gui/qt/main_window.py b/gui/qt/main_window.py index 2d59e9fde..90c9c9e5c 100644 --- a/gui/qt/main_window.py +++ b/gui/qt/main_window.py @@ -633,7 +633,7 @@ class ElectrumWindow(QMainWindow): buttons.addWidget(self.new_request_button) self.receive_requests_label = QLabel(_('My Requests')) - self.receive_list = MyTreeWidget(self, self.receive_list_menu, [_('Date'), _('Account'), _('Address'), _('Description'), _('Amount'), _('Status')], []) + self.receive_list = MyTreeWidget(self, self.receive_list_menu, [_('Date'), _('Account'), _('Address'), _('Description'), _('Amount'), _('Status')], 3) self.receive_list.currentItemChanged.connect(self.receive_item_changed) self.receive_list.itemClicked.connect(self.receive_item_changed) self.receive_list.setSortingEnabled(True) @@ -905,7 +905,7 @@ class ElectrumWindow(QMainWindow): self.from_label = QLabel(_('From')) grid.addWidget(self.from_label, 3, 0) - self.from_list = MyTreeWidget(self, self.from_list_menu, ['',''], [350, 50]) + self.from_list = MyTreeWidget(self, self.from_list_menu, ['','']) self.from_list.setHeaderHidden(True) self.from_list.setMaximumHeight(80) grid.addWidget(self.from_list, 3, 1, 1, 3) @@ -972,12 +972,11 @@ class ElectrumWindow(QMainWindow): self.fee_e.textChanged.connect(entry_changed) self.invoices_label = QLabel(_('Invoices')) - self.invoices_list = MyTreeWidget( - self, - self.create_invoice_menu, - [_('Date'), _('Requestor'), _('Description'), _('Amount'), _('Status')], - [150, 150, None, 150, 100] - ) + self.invoices_list = MyTreeWidget(self, self.create_invoice_menu, + [_('Date'), _('Requestor'), _('Description'), _('Amount'), _('Status')], 2) + self.invoices_list.header().setResizeMode(1, QHeaderView.Interactive) + self.invoices_list.setColumnWidth(1, 200) + vbox0 = QVBoxLayout() vbox0.addLayout(grid) vbox0.addLayout(buttons) @@ -1313,14 +1312,14 @@ class ElectrumWindow(QMainWindow): return w def create_addresses_tab(self): - l = MyTreeWidget(self, self.create_receive_menu, [ _('Address'), _('Label'), _('Balance'), _('Tx')], [370, None, 130]) + l = MyTreeWidget(self, self.create_receive_menu, [ _('Address'), _('Label'), _('Balance'), _('Tx')], 1) l.setSelectionMode(QAbstractItemView.ExtendedSelection) l.setSortingEnabled(False) self.address_list = l return self.create_list_tab(l) def create_contacts_tab(self): - l = MyTreeWidget(self, self.create_contact_menu, [_('Key'), _('Value'), _('Type')], [250, None, 130]) + l = MyTreeWidget(self, self.create_contact_menu, [_('Key'), _('Value'), _('Type')], 1) self.contacts_list = l return self.create_list_tab(l) diff --git a/gui/qt/util.py b/gui/qt/util.py index 2a3ff28e6..0babb0e2d 100644 --- a/gui/qt/util.py +++ b/gui/qt/util.py @@ -260,7 +260,7 @@ def filename_field(parent, config, defaultname, select_msg): class MyTreeWidget(QTreeWidget): - def __init__(self, parent, create_menu, headers, column_width): + def __init__(self, parent, create_menu, headers, stretch_column=0): QTreeWidget.__init__(self, parent) self.parent = parent self.setColumnCount(len(headers)) @@ -277,13 +277,9 @@ class MyTreeWidget(QTreeWidget): self.edit_column = None self.itemDoubleClicked.connect(self.edit_label) self.itemChanged.connect(self.label_changed) - # set column width - for i, width in enumerate(column_width): - if width is None: - self.header().setResizeMode(i, QHeaderView.Stretch) - self.edit_column = i - else: - self.setColumnWidth(i, width) + # stretch + for i in range(len(headers)): + self.header().setResizeMode(i, QHeaderView.Stretch if i == stretch_column else QHeaderView.ResizeToContents) self.setSortingEnabled(True) def on_activated(self, item): diff --git a/lib/commands.py b/lib/commands.py index 478cebb82..0136cf805 100644 --- a/lib/commands.py +++ b/lib/commands.py @@ -343,7 +343,7 @@ class Commands: balance = 0 out = [] for item in self.wallet.get_history(): - tx_hash, conf, is_mine, value, fee, balance, timestamp = item + tx_hash, conf, value, timestamp, balance = item try: time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3] except Exception: diff --git a/lib/util.py b/lib/util.py index 62fec50a5..72685fff2 100644 --- a/lib/util.py +++ b/lib/util.py @@ -108,28 +108,24 @@ def user_dir(): def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespaces=False): - from decimal import Decimal - if x is None: - return 'unknown' - s = Decimal(x) - sign, digits, exp = s.as_tuple() - digits = map(str, digits) - while len(digits) < decimal_point + 1: - digits.insert(0,'0') - digits.insert(-decimal_point,'.') - s = ''.join(digits).rstrip('0') - if sign: - s = '-' + s + from locale import localeconv + x = int(x) # Some callers pass Decimal + scale_factor = pow (10, decimal_point) + integer_part = "{:n}".format(int(abs(x) / float(scale_factor))) + if x < 0: + integer_part = '-' + integer_part elif is_diff: - s = "+" + s - - p = s.find('.') - s += "0"*( 1 + num_zeros - ( len(s) - p )) + integer_part = '+' + integer_part + dp = localeconv()['decimal_point'] + fract_part = ("{:0" + str(decimal_point) + "}").format(abs(x) % scale_factor) + fract_part = fract_part.rstrip('0') + if len(fract_part) < num_zeros: + fract_part += "0" * (num_zeros - len(fract_part)) + result = integer_part + dp + fract_part if whitespaces: - s += " "*( 1 + decimal_point - ( len(s) - p )) - s = " "*( 13 - decimal_point - ( p )) + s - return s - + result += " " * (decimal_point - len(fract_part)) + result = " " * (15 - len(result)) + result + return result def format_time(timestamp): import datetime diff --git a/plugins/exchange_rate.py b/plugins/exchange_rate.py index 8ab3fd81b..ff21c10c6 100644 --- a/plugins/exchange_rate.py +++ b/plugins/exchange_rate.py @@ -3,7 +3,7 @@ from PyQt4.QtCore import * import datetime import decimal -import httplib +import requests import json import threading import time @@ -53,41 +53,9 @@ class Exchanger(threading.Thread): self.is_running = False def get_json(self, site, get_string): - try: - connection = httplib.HTTPSConnection(site) - connection.request("GET", get_string, headers={"User-Agent":"Electrum"}) - except Exception: - raise - resp = connection.getresponse() - if resp.reason == httplib.responses[httplib.NOT_FOUND]: - raise - try: - json_resp = json.loads(resp.read()) - except Exception: - raise - return json_resp + resp = requests.request('GET', 'https://' + site + get_string, headers={"User-Agent":"Electrum"}) + return resp.json() - def get_json_insecure(self, site, get_string): - """ get_json_insecure shouldn't be used in production releases - It doesn't use SSL, and so prices could be manipulated by a middle man - This should be used ONLY when developing plugins when you don't have a - SSL certificate that validates against HTTPSConnection - """ - try: - connection = httplib.HTTPConnection(site) - connection.request("GET", get_string, headers={"User-Agent":"Electrum"}) - except Exception: - raise - resp = connection.getresponse() - if resp.reason == httplib.responses[httplib.NOT_FOUND]: - raise - try: - json_resp = json.loads(resp.read()) - except Exception: - raise - return json_resp - - def exchange(self, btc_amount, quote_currency): with self.lock: if self.quote_currencies is None: @@ -95,7 +63,7 @@ class Exchanger(threading.Thread): quote_currencies = self.quote_currencies.copy() if quote_currency not in quote_currencies: return None - return btc_amount * decimal.Decimal(str(quote_currencies[quote_currency])) + return btc_amount * Decimal(str(quote_currencies[quote_currency])) def stop(self): self.is_running = False @@ -119,9 +87,13 @@ class Exchanger(threading.Thread): "Winkdex": self.update_wd, } try: - update_rates[self.use_exchange]() - except KeyError: - return + rates = update_rates[self.use_exchange]() + except Exception as e: + self.parent.print_error(e) + rates = {} + with self.lock: + self.quote_currencies = rates + self.parent.set_currencies(rates) def run(self): self.is_running = True @@ -132,28 +104,15 @@ class Exchanger(threading.Thread): def update_cd(self): - try: - resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json") - except SSLError: - print("SSL Error when accesing coindesk") - return - except Exception: - return - + resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json") quote_currencies = {} for cur in resp_currencies: quote_currencies[str(cur["currency"])] = 0.0 - current_cur = self.parent.config.get("currency", "EUR") if current_cur in quote_currencies: - try: - resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(current_cur) + ".json") - quote_currencies[str(current_cur)] = decimal.Decimal(str(resp_rate["bpi"][str(current_cur)]["rate_float"])) - except Exception: - return - with self.lock: - self.quote_currencies = quote_currencies - self.parent.set_currencies(quote_currencies) + resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(current_cur) + ".json") + quote_currencies[str(current_cur)] = Decimal(str(resp_rate["bpi"][str(current_cur)]["rate_float"])) + return quote_currencies def update_ib(self): available_currencies = ["USD", "EUR", "SGD"] @@ -162,254 +121,61 @@ class Exchanger(threading.Thread): quote_currencies[cur] = 0.0 current_cur = self.parent.config.get("currency", "EUR") if current_cur in available_currencies: - try: - resp_rate = self.get_json('api.itbit.com', "/v1/markets/XBT" + str(current_cur) + "/ticker") - quote_currencies[str(current_cur)] = decimal.Decimal(str(resp_rate["lastPrice"])) - except SSLError: - print("SSL Error when accesing itbit") - return - except Exception: - return - with self.lock: - self.quote_currencies = quote_currencies - self.parent.set_currencies(quote_currencies) + resp_rate = self.get_json('api.itbit.com', "/v1/markets/XBT" + str(current_cur) + "/ticker") + quote_currencies[str(current_cur)] = Decimal(str(resp_rate["lastPrice"])) + return quote_currencies def update_wd(self): - try: - winkresp = self.get_json('winkdex.com', "/api/v0/price") - except SSLError: - print("SSL Error when accesing winkdex") - return - except Exception: - return - quote_currencies = {"USD": 0.0} - usdprice = decimal.Decimal(str(winkresp["price"]))/decimal.Decimal("100.0") - try: - quote_currencies["USD"] = usdprice - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) + winkresp = self.get_json('winkdex.com', "/api/v0/price") + return {"USD": Decimal(str(winkresp["price"]))/Decimal("100.0")} def update_cv(self): - try: - jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json") - except SSLError: - print("SSL Error when accesing cavirtex") - return - except Exception: - return - quote_currencies = {"CAD": 0.0} + jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json") cadprice = jsonresp["last"] - try: - quote_currencies["CAD"] = decimal.Decimal(str(cadprice)) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) + return {"CAD": Decimal(str(cadprice))} def update_bm(self): - try: - jsonresp = self.get_json('www.bitmarket.pl', "/json/BTCPLN/ticker.json") - except SSLError: - print("SSL Error when accesing bitmarket") - return - except Exception: - return - quote_currencies = {"PLN": 0.0} + jsonresp = self.get_json('www.bitmarket.pl', "/json/BTCPLN/ticker.json") pln_price = jsonresp["last"] - try: - quote_currencies["PLN"] = decimal.Decimal(str(pln_price)) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) + return {"PLN": Decimal(str(pln_price))} def update_bx(self): - try: - jsonresp = self.get_json('pln.bitcurex.com', "/data/ticker.json") - except SSLError: - print("SSL Error when accesing bitcurex") - return - except Exception: - return - quote_currencies = {"PLN": 0.0} + jsonresp = self.get_json('pln.bitcurex.com', "/data/ticker.json") pln_price = jsonresp["last"] - try: - quote_currencies["PLN"] = decimal.Decimal(str(pln_price)) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) + return {"PLN": Decimal(str(pln_price))} def update_CNY(self): - try: - jsonresp = self.get_json('data.btcchina.com', "/data/ticker") - except SSLError: - print("SSL Error when accesing btcchina") - return - except Exception: - return - quote_currencies = {"CNY": 0.0} + jsonresp = self.get_json('data.btcchina.com', "/data/ticker") cnyprice = jsonresp["ticker"]["last"] - try: - quote_currencies["CNY"] = decimal.Decimal(str(cnyprice)) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) + return {"CNY": Decimal(str(cnyprice))} def update_bp(self): - try: - jsonresp = self.get_json('bitpay.com', "/api/rates") - except SSLError: - print("SSL Error when accesing bitpay") - return - except Exception: - return - quote_currencies = {} - try: - for r in jsonresp: - quote_currencies[str(r["code"])] = decimal.Decimal(r["rate"]) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) + jsonresp = self.get_json('bitpay.com', "/api/rates") + return dict([(str(r["code"]), Decimal(r["rate"])) for r in jsonresp]) def update_cb(self): - try: - jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates") - except SSLError: - print("SSL Error when accesing coinbase") - return - except Exception: - return - - quote_currencies = {} - try: - for r in jsonresp: - if r[:7] == "btc_to_": - quote_currencies[r[7:].upper()] = self._lookup_rate_cb(jsonresp, r) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) - + jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates") + return dict([(r[7:].upper(), Decimal(str(jsonresp[r]))) for r in jsonresp if r.startswith("btc_to_")]) def update_bc(self): - try: - jsonresp = self.get_json('blockchain.info', "/ticker") - except SSLError: - print("SSL Error when accesing blockchain") - return - except Exception: - return - quote_currencies = {} - try: - for r in jsonresp: - quote_currencies[r] = self._lookup_rate(jsonresp, r) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) + jsonresp = self.get_json('blockchain.info', "/ticker") + return dict([(r, Decimal(str(jsonresp[r]["15m"]))) for r in jsonresp]) def update_lb(self): - try: - jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/") - except SSLError: - print("SSL Error when accesing localbitcoins") - return - except Exception: - return - quote_currencies = {} - try: - for r in jsonresp: - quote_currencies[r] = self._lookup_rate_lb(jsonresp, r) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) - + jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/") + return dict([(r, Decimal(jsonresp[r]["rates"]["last"])) for r in jsonresp]) def update_bv(self): - try: - jsonresp = self.get_json_insecure('api.bitcoinvenezuela.com', "/") - print("**WARNING**: update_bv is using an insecure connection, shouldn't be used on production") - except SSLError: - print("SSL Error when accesing bitcoinvenezuela") - return - except Exception: - return - - quote_currencies = {} - try: - for r in jsonresp["BTC"]: - quote_currencies[r] = Decimal(jsonresp["BTC"][r]) - - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - print ("KeyError") - self.parent.set_currencies(quote_currencies) + jsonresp = self.get_json('api.bitcoinvenezuela.com', "/") + return dict([(r, Decimal(jsonresp["BTC"][r])) for r in jsonresp["BTC"]]) - def update_bpl(self): - try: - jsonresp = self.get_json_insecure('btcparalelo.com', "/api/price") - print("**WARNING**: update_bpl is using an insecure connection, shouldn't be used on production") - except SSLError: - print("SSL Error when accesing btcparalelo") - return - except Exception: - return - - - quote_currencies = {} - try: - quote_currencies = {"VEF": Decimal(jsonresp["price"])} - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - print ("KeyError") - self.parent.set_currencies(quote_currencies) - + jsonresp = self.get_json('btcparalelo.com', "/api/price") + return {"VEF": Decimal(jsonresp["price"])} + def update_ba(self): - try: - jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all") - except SSLError: - print("SSL Error when accesing bitcoinaverage") - return - except Exception: - return - quote_currencies = {} - try: - for r in jsonresp: - if not r == "timestamp": - quote_currencies[r] = self._lookup_rate_ba(jsonresp, r) - with self.lock: - self.quote_currencies = quote_currencies - except KeyError: - pass - self.parent.set_currencies(quote_currencies) - - - def _lookup_rate(self, response, quote_id): - return decimal.Decimal(str(response[str(quote_id)]["15m"])) - def _lookup_rate_cb(self, response, quote_id): - return decimal.Decimal(str(response[str(quote_id)])) - def _lookup_rate_ba(self, response, quote_id): - return decimal.Decimal(response[str(quote_id)]["last"]) - def _lookup_rate_lb(self, response, quote_id): - return decimal.Decimal(response[str(quote_id)]["rates"]["last"]) + jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all") + return dict([(r, Decimal(jsonresp[r]["last"])) for r in jsonresp if not r == "timestamp"]) class Plugin(BasePlugin): diff --git a/plugins/labels.py b/plugins/labels.py index fcdef4c3b..0bde56447 100644 --- a/plugins/labels.py +++ b/plugins/labels.py @@ -25,7 +25,7 @@ from electrum_gui.qt.util import ThreadedButton, Buttons, CancelButton, OkButton class Plugin(BasePlugin): - target_host = 'sync.bysh.me:8080' + target_host = 'sync.bysh.me:9090' encode_password = None def fullname(self): @@ -140,8 +140,8 @@ class Plugin(BasePlugin): QMessageBox.information(None, _("Labels synchronised"), _("Your labels have been synchronised.")) def do_request(self, method, url = "/labels", is_batch=False, data=None): - url = 'http://' + self.target_host + url - kwargs = {'headers': {}} + url = 'https://' + self.target_host + url + kwargs = {'headers': {}, 'verify': False} if method == 'GET' and data: kwargs['params'] = data elif method == 'POST' and data: