commit ab15ff3a006caa23f34c89d47a0eb9930a75d780
parent 65aeb0bd3c40da82dd6f9a85eb8dc4889008f09f
Author: ThomasV <thomasv@electrum.org>
Date: Wed, 15 Mar 2017 12:13:20 +0100
updates for python3
Diffstat:
27 files changed, 50 insertions(+), 51 deletions(-)
diff --git a/gui/kivy/i18n.py b/gui/kivy/i18n.py
@@ -1,6 +1,6 @@
import gettext
-class _(unicode):
+class _(str):
observers = set()
lang = None
@@ -15,9 +15,7 @@ class _(unicode):
@staticmethod
def translate(s, *args, **kwargs):
- tr = _.lang(s).format(args, kwargs)
- tr = tr.decode('utf8')
- return tr
+ return _.lang(s).format(args, kwargs)
@staticmethod
def bind(label):
diff --git a/gui/qt/__init__.py b/gui/qt/__init__.py
@@ -57,6 +57,7 @@ except Exception as e:
from .util import * # * needed for plugins
from .main_window import ElectrumWindow
+from .network_dialog import NetworkDialog
class OpenFileEventFilter(QObject):
@@ -142,7 +143,6 @@ class ElectrumGui:
self.app.emit(SIGNAL('new_window'), path, uri)
def show_network_dialog(self, parent):
- from network_dialog import NetworkDialog
if not self.daemon.network:
parent.show_warning(_('You are using Electrum in offline mode; restart Electrum if you want to get connected'), title=_('Offline'))
return
diff --git a/gui/qt/contact_list.py b/gui/qt/contact_list.py
@@ -59,7 +59,7 @@ class ContactList(MyTreeWidget):
def import_contacts(self):
wallet_folder = self.parent.get_wallet_folder()
- filename = unicode(QFileDialog.getOpenFileName(self.parent, "Select your wallet file", wallet_folder))
+ filename = QFileDialog.getOpenFileName(self.parent, "Select your wallet file", wallet_folder)
if not filename:
return
self.parent.contacts.import_file(filename)
diff --git a/gui/qt/installwizard.py b/gui/qt/installwizard.py
@@ -181,8 +181,7 @@ class InstallWizard(QDialog, MessageBoxMixin, BaseWizard):
self.name_e.setText(path)
def on_filename(filename):
- filename = unicode(filename)
- path = os.path.join(wallet_folder, filename.encode('utf8'))
+ path = os.path.join(wallet_folder, filename)
try:
self.storage = WalletStorage(path)
except IOError:
@@ -213,7 +212,7 @@ class InstallWizard(QDialog, MessageBoxMixin, BaseWizard):
button.clicked.connect(on_choose)
self.name_e.textChanged.connect(on_filename)
n = os.path.basename(self.storage.path)
- self.name_e.setText(n.decode('utf8'))
+ self.name_e.setText(n)
while True:
if self.storage.file_exists() and not self.storage.is_encrypted():
diff --git a/gui/qt/invoice_list.py b/gui/qt/invoice_list.py
@@ -64,7 +64,7 @@ class InvoiceList(MyTreeWidget):
def import_invoices(self):
wallet_folder = self.parent.get_wallet_folder()
- filename = unicode(QFileDialog.getOpenFileName(self.parent, "Select your wallet file", wallet_folder))
+ filename = QFileDialog.getOpenFileName(self.parent, "Select your wallet file", wallet_folder)
if not filename:
return
self.parent.invoices.import_file(filename)
diff --git a/gui/qt/main_window.py b/gui/qt/main_window.py
@@ -356,7 +356,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
def watching_only_changed(self):
title = 'Electrum %s - %s' % (self.wallet.electrum_version,
- self.wallet.basename().decode('utf8'))
+ self.wallet.basename())
extra = [self.wallet.storage.get('wallet_type', '?')]
if self.wallet.is_watching_only():
self.warn_if_watching_only()
@@ -401,7 +401,6 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
self.show_critical(_("Electrum was unable to copy your wallet file to the specified location.") + "\n" + str(reason), title=_("Unable to create backup"))
def update_recently_visited(self, filename):
- filename = filename.decode('utf8')
recent = self.config.get('recently_open', [])
try:
sorted(recent)
@@ -416,7 +415,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
for i, k in enumerate(sorted(recent)):
b = os.path.basename(k)
def loader(k):
- return lambda: self.gui_object.new_window(k.encode('utf8'))
+ return lambda: self.gui_object.new_window(k)
self.recently_visited_menu.addAction(b, loader(k)).setShortcut(QKeySequence("Ctrl+%d"%(i+1)))
self.recently_visited_menu.setEnabled(len(recent))
@@ -702,7 +701,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
text = _("Not connected")
icon = QIcon(":icons/status_disconnected.png")
- self.tray.setToolTip("%s (%s)" % (text, self.wallet.basename().decode('utf8')))
+ self.tray.setToolTip("%s (%s)" % (text, self.wallet.basename()))
self.balance_label.setText(text)
self.status_button.setIcon( icon )
@@ -2009,7 +2008,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
d.exec_()
def password_dialog(self, msg=None, parent=None):
- from password_dialog import PasswordDialog
+ from .password_dialog import PasswordDialog
parent = parent or self
d = PasswordDialog(parent, msg)
return d.run()
@@ -2378,7 +2377,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
if not self.config.is_modifiable('language'):
for w in [lang_combo, lang_label]: w.setEnabled(False)
def on_lang(x):
- lang_request = languages.keys()[lang_combo.currentIndex()]
+ lang_request = list(languages.keys())[lang_combo.currentIndex()]
if lang_request != self.config.get('language'):
self.config.set_key("language", lang_request, True)
self.need_restart = True
diff --git a/gui/qt/password_dialog.py b/gui/qt/password_dialog.py
@@ -217,4 +217,4 @@ class PasswordDialog(WindowModalDialog):
def run(self):
if not self.exec_():
return
- return unicode(self.pw.text())
+ return self.pw.text()
diff --git a/lib/base_wizard.py b/lib/base_wizard.py
@@ -74,7 +74,7 @@ class BaseWizard(object):
def new(self):
name = os.path.basename(self.storage.path)
- title = _("Create") + ' ' + name.decode('utf8')
+ title = _("Create") + ' ' + name
message = '\n'.join([
_("What kind of wallet do you want to create?")
])
diff --git a/lib/blockchain.py b/lib/blockchain.py
@@ -39,7 +39,7 @@ def serialize_header(res):
return s
def deserialize_header(s, height):
- hex_to_int = lambda s: int('0x' + s[::-1].encode('hex'), 16)
+ hex_to_int = lambda s: int('0x' + bh2u(s[::-1]), 16)
h = {}
h['version'] = hex_to_int(s[0:4])
h['prev_block_hash'] = hash_encode(s[4:36])
@@ -55,7 +55,7 @@ def hash_header(header):
return '0' * 64
if header.get('prev_block_hash') is None:
header['prev_block_hash'] = '00'*32
- return hash_encode(Hash(serialize_header(header).decode('hex')))
+ return hash_encode(Hash(bfh(serialize_header(header))))
blockchains = {}
@@ -107,7 +107,7 @@ class Blockchain(util.PrintError):
return blockchains[self.parent_id]
def get_max_child(self):
- children = filter(lambda y: y.parent_id==self.checkpoint, blockchains.values())
+ children = list(filter(lambda y: y.parent_id==self.checkpoint, blockchains.values()))
return max([x.checkpoint for x in children]) if children else None
def get_checkpoint(self):
@@ -141,7 +141,7 @@ class Blockchain(util.PrintError):
def update_size(self):
p = self.path()
- self._size = os.path.getsize(p)/80 if os.path.exists(p) else 0
+ self._size = os.path.getsize(p)//80 if os.path.exists(p) else 0
def verify_header(self, header, prev_header, bits, target):
prev_hash = hash_header(prev_header)
@@ -230,7 +230,7 @@ class Blockchain(util.PrintError):
def save_header(self, header):
delta = header.get('block_height') - self.checkpoint
- data = serialize_header(header).decode('hex')
+ data = bfh(serialize_header(header))
assert delta == self.size()
assert len(data) == 80
self.write(data, delta*80)
@@ -309,7 +309,7 @@ class Blockchain(util.PrintError):
prev_hash = hash_header(previous_header)
if prev_hash != header.get('prev_block_hash'):
return False
- bits, target = self.get_target(height / 2016)
+ bits, target = self.get_target(height // 2016)
try:
self.verify_header(header, previous_header, bits, target)
except:
diff --git a/lib/commands.py b/lib/commands.py
@@ -232,7 +232,7 @@ class Commands:
elif txin.get('redeemScript'):
raise BaseException('Not implemented')
- outputs = map(lambda x: (TYPE_ADDRESS, x['address'], int(x['value'])), outputs)
+ outputs = [(TYPE_ADDRESS, x['address'], int(x['value'])) for x in outputs]
tx = Transaction.from_io(inputs, outputs, locktime=locktime)
tx.sign(keypairs)
return tx.as_dict()
diff --git a/lib/exchange_rate.py b/lib/exchange_rate.py
@@ -170,7 +170,7 @@ class BitStamp(ExchangeBase):
class Bitvalor(ExchangeBase):
def get_rates(self,ccy):
- json = self.get_json('api.bitvalor.com', '/v1/ticker.json')
+ json = self.get_json('api.bitvalor.com', '/v1/ticker.json')
return {'BRL': Decimal(json['ticker_1h']['total']['last'])}
@@ -253,7 +253,7 @@ class Coinsecure(ExchangeBase):
class Foxbit(ExchangeBase):
def get_rates(self,ccy):
- json = self.get_json('api.bitvalor.com', '/v1/ticker.json')
+ json = self.get_json('api.bitvalor.com', '/v1/ticker.json')
return {'BRL': Decimal(json['ticker_1h']['exchanges']['FOX']['last'])}
@@ -297,7 +297,7 @@ class MercadoBitcoin(ExchangeBase):
class NegocieCoins(ExchangeBase):
def get_rates(self,ccy):
- json = self.get_json('api.bitvalor.com', '/v1/ticker.json')
+ json = self.get_json('api.bitvalor.com', '/v1/ticker.json')
return {'BRL': Decimal(json['ticker_1h']['exchanges']['NEG']['last'])}
def history_ccys(self):
diff --git a/lib/keystore.py b/lib/keystore.py
@@ -544,7 +544,7 @@ class Hardware_KeyStore(KeyStore, Xpub):
def bip39_normalize_passphrase(passphrase):
- return normalize('NFKD', unicode(passphrase or ''))
+ return normalize('NFKD', passphrase or '')
def bip39_to_seed(mnemonic, passphrase):
import pbkdf2, hashlib, hmac
diff --git a/lib/network.py b/lib/network.py
@@ -517,7 +517,7 @@ class Network(util.DaemonThread):
if self.server_is_lagging() and self.auto_connect:
# switch to one that has the correct header (not height)
header = self.blockchain().read_header(self.get_local_height())
- filtered = map(lambda x:x[0], filter(lambda x: x[1].tip_header==header, self.interfaces.items()))
+ filtered = list(map(lambda x:x[0], filter(lambda x: x[1].tip_header==header, self.interfaces.items())))
if filtered:
choice = random.choice(filtered)
self.switch_to_interface(choice)
@@ -1047,7 +1047,7 @@ class Network(util.DaemonThread):
def get_blockchains(self):
out = {}
for k, b in self.blockchains.items():
- r = filter(lambda i: i.blockchain==b, self.interfaces.values())
+ r = list(filter(lambda i: i.blockchain==b, self.interfaces.values()))
if r:
out[k] = r
return out
diff --git a/lib/simple_config.py b/lib/simple_config.py
@@ -225,7 +225,7 @@ class SimpleConfig(PrintError):
def reverse_dynfee(self, fee_per_kb):
import operator
- l = self.fee_estimates.items() + [(1, self.dynfee(4))]
+ l = list(self.fee_estimates.items()) + [(1, self.dynfee(4))]
dist = map(lambda x: (x[0], abs(x[1] - fee_per_kb)), l)
min_target, min_value = min(dist, key=operator.itemgetter(1))
if fee_per_kb < self.fee_estimates.get(25)/2:
diff --git a/lib/storage.py b/lib/storage.py
@@ -39,7 +39,7 @@ from .i18n import _
from .util import NotEnoughFunds, PrintError, profiler
from .plugins import run_hook, plugin_loaders
from .keystore import bip44_derivation
-import .bitcoin
+from . import bitcoin
# seed_version is now used for the version of the wallet file
diff --git a/lib/transaction.py b/lib/transaction.py
@@ -286,7 +286,7 @@ def match_decoded(decoded, to_match):
def parse_sig(x_sig):
- return map(lambda x: None if x == NO_SIGNATURE else x, x_sig)
+ return [None if x == NO_SIGNATURE else x for x in x_sig]
def safe_parse_pubkey(x):
try:
@@ -488,7 +488,7 @@ def multisig_script(public_keys, m):
assert m <= n
op_m = format(opcodes.OP_1 + m - 1, 'x')
op_n = format(opcodes.OP_1 + n - 1, 'x')
- keylist = [op_push(len(k)/2) + k for k in public_keys]
+ keylist = [op_push(len(k)//2) + k for k in public_keys]
return op_m + ''.join(keylist) + op_n + 'ae'
diff --git a/lib/util.py b/lib/util.py
@@ -65,7 +65,7 @@ class UserCancelled(Exception):
class MyEncoder(json.JSONEncoder):
def default(self, obj):
- from transaction import Transaction
+ from .transaction import Transaction
if isinstance(obj, Transaction):
return obj.as_dict()
return super(MyEncoder, self).default(obj)
@@ -497,7 +497,7 @@ testnet_block_explorers = {
}
def block_explorer_info():
- import bitcoin
+ from . import bitcoin
return testnet_block_explorers if bitcoin.TESTNET else mainnet_block_explorers
def block_explorer(config):
diff --git a/lib/wallet.py b/lib/wallet.py
@@ -60,6 +60,8 @@ from .mnemonic import Mnemonic
from . import paymentrequest
from .paymentrequest import PR_PAID, PR_UNPAID, PR_UNKNOWN, PR_EXPIRED
+from .paymentrequest import InvoiceStore
+from .contacts import Contacts
from .storage import WalletStorage
diff --git a/plugins/cosigner_pool/qt.py b/plugins/cosigner_pool/qt.py
@@ -36,6 +36,7 @@ from electrum import transaction
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
from electrum.wallet import Multisig_Wallet
+from electrum.util import bh2u
from electrum_gui.qt.transaction_dialog import show_transaction
@@ -129,8 +130,8 @@ class Plugin(BasePlugin):
self.cosigner_list = []
for key, keystore in wallet.keystores.items():
xpub = keystore.get_master_public_key()
- K = bitcoin.deserialize_xpub(xpub)[-1].encode('hex')
- _hash = bitcoin.Hash(K).encode('hex')
+ K = bitcoin.deserialize_xpub(xpub)[-1]
+ _hash = bh2u(bitcoin.Hash(K))
if not keystore.is_watching_only():
self.keys.append((key, _hash, window))
else:
diff --git a/plugins/digitalbitbox/digitalbitbox.py b/plugins/digitalbitbox/digitalbitbox.py
@@ -504,7 +504,7 @@ class DigitalBitbox_KeyStore(Hardware_KeyStore):
dbb_signatures.extend(reply['sign'])
# Fill signatures
- if len(dbb_signatures) <> len(tx.inputs()):
+ if len(dbb_signatures) != len(tx.inputs()):
raise Exception("Incorrect number of transactions signed.") # Should never occur
for i, txin in enumerate(tx.inputs()):
num = txin['num_sig']
@@ -564,7 +564,7 @@ class DigitalBitboxPlugin(HW_PluginBase):
if device.interface_number == 0 or device.usage_page == 0xffff:
self.handler = handler
client = self.get_dbb_device(device)
- if client <> None:
+ if client is not None:
client = DigitalBitbox_Client(client)
return client
else:
diff --git a/plugins/hw_wallet/qt.py b/plugins/hw_wallet/qt.py
@@ -123,7 +123,7 @@ class QtHandlerBase(QObject, PrintError):
vbox.addWidget(pw)
vbox.addLayout(Buttons(CancelButton(d), OkButton(d)))
d.setLayout(vbox)
- passphrase = unicode(pw.text()) if d.exec_() else None
+ passphrase = pw.text() if d.exec_() else None
self.passphrase = passphrase
self.done.set()
@@ -137,7 +137,7 @@ class QtHandlerBase(QObject, PrintError):
hbox.addWidget(text)
hbox.addStretch(1)
dialog.exec_() # Firmware cannot handle cancellation
- self.word = unicode(text.text())
+ self.word = text.text()
self.done.set()
def message_dialog(self, msg, on_cancel):
@@ -180,7 +180,7 @@ class QtPluginBase(object):
@hook
def load_wallet(self, wallet, window):
for keystore in wallet.get_keystores():
- if type(keystore) != self.keystore_class:
+ if not isinstance(keystore, self.keystore_class):
continue
tooltip = self.device + '\n' + (keystore.label or 'unnamed')
cb = partial(self.show_settings_dialog, window, keystore)
diff --git a/plugins/keepkey/keepkey.py b/plugins/keepkey/keepkey.py
@@ -14,7 +14,7 @@ class KeepKeyPlugin(TrezorCompatiblePlugin):
def __init__(self, *args):
try:
- import client
+ from . import client
import keepkeylib
import keepkeylib.ckd_public
import keepkeylib.transport_hid
diff --git a/plugins/labels/kivy.py b/plugins/labels/kivy.py
@@ -1,4 +1,4 @@
-from labels import LabelsPlugin
+from .labels import LabelsPlugin
from electrum.plugins import hook
class Plugin(LabelsPlugin):
diff --git a/plugins/trezor/client.py b/plugins/trezor/client.py
@@ -1,5 +1,5 @@
from trezorlib.client import proto, BaseClient, ProtocolMixin
-from clientbase import TrezorClientBase
+from .clientbase import TrezorClientBase
class TrezorClient(TrezorClientBase, ProtocolMixin, BaseClient):
def __init__(self, transport, handler, plugin):
diff --git a/plugins/trezor/clientbase.py b/plugins/trezor/clientbase.py
@@ -209,7 +209,7 @@ class TrezorClientBase(GuiMixin, PrintError):
return (f.major_version, f.minor_version, f.patch_version)
def atleast_version(self, major, minor=0, patch=0):
- return cmp(self.firmware_version(), (major, minor, patch)) >= 0
+ return self.firmware_version() >= (major, minor, patch)
@staticmethod
def wrapper(func):
diff --git a/plugins/trezor/qt_generic.py b/plugins/trezor/qt_generic.py
@@ -10,7 +10,7 @@ from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from electrum.i18n import _
from electrum.plugins import hook, DeviceMgr
-from electrum.util import PrintError, UserCancelled
+from electrum.util import PrintError, UserCancelled, bh2u
from electrum.wallet import Wallet, Standard_Wallet
PASSPHRASE_HELP_SHORT =_(
@@ -320,7 +320,7 @@ class SettingsDialog(WindowModalDialog):
def update(features):
self.features = features
set_label_enabled()
- bl_hash = features.bootloader_hash.encode('hex')
+ bl_hash = bh2u(features.bootloader_hash)
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
diff --git a/plugins/trezor/trezor.py b/plugins/trezor/trezor.py
@@ -13,7 +13,7 @@ class TrezorPlugin(TrezorCompatiblePlugin):
def __init__(self, *args):
try:
- import client
+ from . import client
import trezorlib
import trezorlib.ckd_public
import trezorlib.transport_hid