Browse Source

Merge branch 'master' into tray_tip_wallet

283
Neil Booth 10 years ago
parent
commit
506ed8ee74
  1. 2
      gui/qt/amountedit.py
  2. 2
      gui/qt/history_widget.py
  3. 2
      gui/qt/history_widget_lite.py
  4. 19
      gui/qt/main_window.py
  5. 12
      gui/qt/util.py
  6. 2
      lib/commands.py
  7. 36
      lib/util.py
  8. 320
      plugins/exchange_rate.py
  9. 6
      plugins/labels.py

2
gui/qt/amountedit.py

@ -18,6 +18,8 @@ class AmountEdit(MyLineEdit):
def __init__(self, base_unit, is_int = False, parent=None): def __init__(self, base_unit, is_int = False, parent=None):
QLineEdit.__init__(self, parent) QLineEdit.__init__(self, parent)
# This seems sufficient for hundred-BTC amounts with 8 decimals
self.setFixedWidth(140)
self.base_unit = base_unit self.base_unit = base_unit
self.textChanged.connect(self.numbify) self.textChanged.connect(self.numbify)
self.is_int = is_int self.is_int = is_int

2
gui/qt/history_widget.py

@ -28,7 +28,7 @@ from electrum.plugins import run_hook
class HistoryWidget(MyTreeWidget): class HistoryWidget(MyTreeWidget):
def __init__(self, parent=None): 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.config = self.parent.config
self.setSortingEnabled(False) self.setSortingEnabled(False)

2
gui/qt/history_widget_lite.py

@ -20,6 +20,6 @@ class HistoryWidget(QTreeWidget):
if date is None: if date is None:
date = _("Unknown") date = _("Unknown")
item = QTreeWidgetItem([amount, address, date]) item = QTreeWidgetItem([amount, address, date])
if float(amount) < 0: if amount.find('-') != -1:
item.setForeground(0, QBrush(QColor("#BC1E1E"))) item.setForeground(0, QBrush(QColor("#BC1E1E")))
self.insertTopLevelItem(0, item) self.insertTopLevelItem(0, item)

19
gui/qt/main_window.py

@ -633,7 +633,7 @@ class ElectrumWindow(QMainWindow):
buttons.addWidget(self.new_request_button) buttons.addWidget(self.new_request_button)
self.receive_requests_label = QLabel(_('My Requests')) 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.currentItemChanged.connect(self.receive_item_changed)
self.receive_list.itemClicked.connect(self.receive_item_changed) self.receive_list.itemClicked.connect(self.receive_item_changed)
self.receive_list.setSortingEnabled(True) self.receive_list.setSortingEnabled(True)
@ -905,7 +905,7 @@ class ElectrumWindow(QMainWindow):
self.from_label = QLabel(_('From')) self.from_label = QLabel(_('From'))
grid.addWidget(self.from_label, 3, 0) 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.setHeaderHidden(True)
self.from_list.setMaximumHeight(80) self.from_list.setMaximumHeight(80)
grid.addWidget(self.from_list, 3, 1, 1, 3) grid.addWidget(self.from_list, 3, 1, 1, 3)
@ -972,12 +972,11 @@ class ElectrumWindow(QMainWindow):
self.fee_e.textChanged.connect(entry_changed) self.fee_e.textChanged.connect(entry_changed)
self.invoices_label = QLabel(_('Invoices')) self.invoices_label = QLabel(_('Invoices'))
self.invoices_list = MyTreeWidget( self.invoices_list = MyTreeWidget(self, self.create_invoice_menu,
self, [_('Date'), _('Requestor'), _('Description'), _('Amount'), _('Status')], 2)
self.create_invoice_menu, self.invoices_list.header().setResizeMode(1, QHeaderView.Interactive)
[_('Date'), _('Requestor'), _('Description'), _('Amount'), _('Status')], self.invoices_list.setColumnWidth(1, 200)
[150, 150, None, 150, 100]
)
vbox0 = QVBoxLayout() vbox0 = QVBoxLayout()
vbox0.addLayout(grid) vbox0.addLayout(grid)
vbox0.addLayout(buttons) vbox0.addLayout(buttons)
@ -1313,14 +1312,14 @@ class ElectrumWindow(QMainWindow):
return w return w
def create_addresses_tab(self): 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.setSelectionMode(QAbstractItemView.ExtendedSelection)
l.setSortingEnabled(False) l.setSortingEnabled(False)
self.address_list = l self.address_list = l
return self.create_list_tab(l) return self.create_list_tab(l)
def create_contacts_tab(self): 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 self.contacts_list = l
return self.create_list_tab(l) return self.create_list_tab(l)

12
gui/qt/util.py

@ -260,7 +260,7 @@ def filename_field(parent, config, defaultname, select_msg):
class MyTreeWidget(QTreeWidget): 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) QTreeWidget.__init__(self, parent)
self.parent = parent self.parent = parent
self.setColumnCount(len(headers)) self.setColumnCount(len(headers))
@ -277,13 +277,9 @@ class MyTreeWidget(QTreeWidget):
self.edit_column = None self.edit_column = None
self.itemDoubleClicked.connect(self.edit_label) self.itemDoubleClicked.connect(self.edit_label)
self.itemChanged.connect(self.label_changed) self.itemChanged.connect(self.label_changed)
# set column width # stretch
for i, width in enumerate(column_width): for i in range(len(headers)):
if width is None: self.header().setResizeMode(i, QHeaderView.Stretch if i == stretch_column else QHeaderView.ResizeToContents)
self.header().setResizeMode(i, QHeaderView.Stretch)
self.edit_column = i
else:
self.setColumnWidth(i, width)
self.setSortingEnabled(True) self.setSortingEnabled(True)
def on_activated(self, item): def on_activated(self, item):

2
lib/commands.py

@ -343,7 +343,7 @@ class Commands:
balance = 0 balance = 0
out = [] out = []
for item in self.wallet.get_history(): 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: try:
time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3] time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
except Exception: except Exception:

36
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): def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespaces=False):
from decimal import Decimal from locale import localeconv
if x is None: x = int(x) # Some callers pass Decimal
return 'unknown' scale_factor = pow (10, decimal_point)
s = Decimal(x) integer_part = "{:n}".format(int(abs(x) / float(scale_factor)))
sign, digits, exp = s.as_tuple() if x < 0:
digits = map(str, digits) integer_part = '-' + integer_part
while len(digits) < decimal_point + 1:
digits.insert(0,'0')
digits.insert(-decimal_point,'.')
s = ''.join(digits).rstrip('0')
if sign:
s = '-' + s
elif is_diff: elif is_diff:
s = "+" + s integer_part = '+' + integer_part
dp = localeconv()['decimal_point']
p = s.find('.') fract_part = ("{:0" + str(decimal_point) + "}").format(abs(x) % scale_factor)
s += "0"*( 1 + num_zeros - ( len(s) - p )) 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: if whitespaces:
s += " "*( 1 + decimal_point - ( len(s) - p )) result += " " * (decimal_point - len(fract_part))
s = " "*( 13 - decimal_point - ( p )) + s result = " " * (15 - len(result)) + result
return s return result
def format_time(timestamp): def format_time(timestamp):
import datetime import datetime

320
plugins/exchange_rate.py

@ -3,7 +3,7 @@ from PyQt4.QtCore import *
import datetime import datetime
import decimal import decimal
import httplib import requests
import json import json
import threading import threading
import time import time
@ -53,41 +53,9 @@ class Exchanger(threading.Thread):
self.is_running = False self.is_running = False
def get_json(self, site, get_string): def get_json(self, site, get_string):
try: resp = requests.request('GET', 'https://' + site + get_string, headers={"User-Agent":"Electrum"})
connection = httplib.HTTPSConnection(site) return resp.json()
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 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): def exchange(self, btc_amount, quote_currency):
with self.lock: with self.lock:
if self.quote_currencies is None: if self.quote_currencies is None:
@ -95,7 +63,7 @@ class Exchanger(threading.Thread):
quote_currencies = self.quote_currencies.copy() quote_currencies = self.quote_currencies.copy()
if quote_currency not in quote_currencies: if quote_currency not in quote_currencies:
return None return None
return btc_amount * decimal.Decimal(str(quote_currencies[quote_currency])) return btc_amount * Decimal(str(quote_currencies[quote_currency]))
def stop(self): def stop(self):
self.is_running = False self.is_running = False
@ -119,9 +87,13 @@ class Exchanger(threading.Thread):
"Winkdex": self.update_wd, "Winkdex": self.update_wd,
} }
try: try:
update_rates[self.use_exchange]() rates = update_rates[self.use_exchange]()
except KeyError: except Exception as e:
return self.parent.print_error(e)
rates = {}
with self.lock:
self.quote_currencies = rates
self.parent.set_currencies(rates)
def run(self): def run(self):
self.is_running = True self.is_running = True
@ -132,28 +104,15 @@ class Exchanger(threading.Thread):
def update_cd(self): def update_cd(self):
try: resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json")
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
quote_currencies = {} quote_currencies = {}
for cur in resp_currencies: for cur in resp_currencies:
quote_currencies[str(cur["currency"])] = 0.0 quote_currencies[str(cur["currency"])] = 0.0
current_cur = self.parent.config.get("currency", "EUR") current_cur = self.parent.config.get("currency", "EUR")
if current_cur in quote_currencies: if current_cur in quote_currencies:
try: resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(current_cur) + ".json")
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"]))
quote_currencies[str(current_cur)] = decimal.Decimal(str(resp_rate["bpi"][str(current_cur)]["rate_float"])) return quote_currencies
except Exception:
return
with self.lock:
self.quote_currencies = quote_currencies
self.parent.set_currencies(quote_currencies)
def update_ib(self): def update_ib(self):
available_currencies = ["USD", "EUR", "SGD"] available_currencies = ["USD", "EUR", "SGD"]
@ -162,254 +121,61 @@ class Exchanger(threading.Thread):
quote_currencies[cur] = 0.0 quote_currencies[cur] = 0.0
current_cur = self.parent.config.get("currency", "EUR") current_cur = self.parent.config.get("currency", "EUR")
if current_cur in available_currencies: if current_cur in available_currencies:
try: resp_rate = self.get_json('api.itbit.com', "/v1/markets/XBT" + str(current_cur) + "/ticker")
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"]))
quote_currencies[str(current_cur)] = decimal.Decimal(str(resp_rate["lastPrice"])) return quote_currencies
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)
def update_wd(self): def update_wd(self):
try: winkresp = self.get_json('winkdex.com', "/api/v0/price")
winkresp = self.get_json('winkdex.com', "/api/v0/price") return {"USD": Decimal(str(winkresp["price"]))/Decimal("100.0")}
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)
def update_cv(self): def update_cv(self):
try: jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json")
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}
cadprice = jsonresp["last"] cadprice = jsonresp["last"]
try: return {"CAD": Decimal(str(cadprice))}
quote_currencies["CAD"] = decimal.Decimal(str(cadprice))
with self.lock:
self.quote_currencies = quote_currencies
except KeyError:
pass
self.parent.set_currencies(quote_currencies)
def update_bm(self): def update_bm(self):
try: jsonresp = self.get_json('www.bitmarket.pl', "/json/BTCPLN/ticker.json")
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}
pln_price = jsonresp["last"] pln_price = jsonresp["last"]
try: return {"PLN": Decimal(str(pln_price))}
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)
def update_bx(self): def update_bx(self):
try: jsonresp = self.get_json('pln.bitcurex.com', "/data/ticker.json")
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}
pln_price = jsonresp["last"] pln_price = jsonresp["last"]
try: return {"PLN": Decimal(str(pln_price))}
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)
def update_CNY(self): def update_CNY(self):
try: jsonresp = self.get_json('data.btcchina.com', "/data/ticker")
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}
cnyprice = jsonresp["ticker"]["last"] cnyprice = jsonresp["ticker"]["last"]
try: return {"CNY": Decimal(str(cnyprice))}
quote_currencies["CNY"] = decimal.Decimal(str(cnyprice))
with self.lock:
self.quote_currencies = quote_currencies
except KeyError:
pass
self.parent.set_currencies(quote_currencies)
def update_bp(self): def update_bp(self):
try: jsonresp = self.get_json('bitpay.com', "/api/rates")
jsonresp = self.get_json('bitpay.com', "/api/rates") return dict([(str(r["code"]), Decimal(r["rate"])) for r in jsonresp])
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)
def update_cb(self): def update_cb(self):
try: jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates")
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_")])
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)
def update_bc(self): def update_bc(self):
try: jsonresp = self.get_json('blockchain.info', "/ticker")
jsonresp = self.get_json('blockchain.info', "/ticker") return dict([(r, Decimal(str(jsonresp[r]["15m"]))) for r in jsonresp])
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)
def update_lb(self): def update_lb(self):
try: jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/")
jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/") return dict([(r, Decimal(jsonresp[r]["rates"]["last"])) for r in jsonresp])
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)
def update_bv(self): def update_bv(self):
try: jsonresp = self.get_json('api.bitcoinvenezuela.com', "/")
jsonresp = self.get_json_insecure('api.bitcoinvenezuela.com', "/") return dict([(r, Decimal(jsonresp["BTC"][r])) for r in jsonresp["BTC"]])
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)
def update_bpl(self): def update_bpl(self):
try: jsonresp = self.get_json('btcparalelo.com', "/api/price")
jsonresp = self.get_json_insecure('btcparalelo.com', "/api/price") return {"VEF": Decimal(jsonresp["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)
def update_ba(self): def update_ba(self):
try: jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all")
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"])
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"])
class Plugin(BasePlugin): class Plugin(BasePlugin):

6
plugins/labels.py

@ -25,7 +25,7 @@ from electrum_gui.qt.util import ThreadedButton, Buttons, CancelButton, OkButton
class Plugin(BasePlugin): class Plugin(BasePlugin):
target_host = 'sync.bysh.me:8080' target_host = 'sync.bysh.me:9090'
encode_password = None encode_password = None
def fullname(self): def fullname(self):
@ -140,8 +140,8 @@ class Plugin(BasePlugin):
QMessageBox.information(None, _("Labels synchronised"), _("Your labels have been synchronised.")) QMessageBox.information(None, _("Labels synchronised"), _("Your labels have been synchronised."))
def do_request(self, method, url = "/labels", is_batch=False, data=None): def do_request(self, method, url = "/labels", is_batch=False, data=None):
url = 'http://' + self.target_host + url url = 'https://' + self.target_host + url
kwargs = {'headers': {}} kwargs = {'headers': {}, 'verify': False}
if method == 'GET' and data: if method == 'GET' and data:
kwargs['params'] = data kwargs['params'] = data
elif method == 'POST' and data: elif method == 'POST' and data:

Loading…
Cancel
Save