updates for python3

This commit is contained in:
ThomasV 2017-03-15 12:13:20 +01:00
parent 65aeb0bd3c
commit ab15ff3a00
27 changed files with 50 additions and 51 deletions

View File

@ -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):

View File

@ -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

View File

@ -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)

View File

@ -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():

View File

@ -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)

View File

@ -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

View File

@ -217,4 +217,4 @@ class PasswordDialog(WindowModalDialog):
def run(self):
if not self.exec_():
return
return unicode(self.pw.text())
return self.pw.text()

View File

@ -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?")
])

View File

@ -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:

View File

@ -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()

View File

@ -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):

View File

@ -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

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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'

View File

@ -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):

View File

@ -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

View File

@ -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:

View File

@ -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:

View File

@ -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)

View File

@ -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

View File

@ -1,4 +1,4 @@
from labels import LabelsPlugin
from .labels import LabelsPlugin
from electrum.plugins import hook
class Plugin(LabelsPlugin):

View File

@ -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):

View File

@ -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):

View File

@ -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")]

View File

@ -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