Browse Source

Minor style changes

patch-4
Benoit Verret 4 years ago
parent
commit
f731c38293
No known key found for this signature in database GPG Key ID: 54D95F51ED0FD5AF
  1. 4
      contrib/build-wine/deterministic.spec
  2. 5
      contrib/sign_packages
  3. 2
      electrum/coinchooser.py
  4. 4
      electrum/crypto.py
  5. 2
      electrum/currencies.json
  6. 2
      electrum/exchange_rate.py
  7. 2
      electrum/gui/kivy/main_window.py
  8. 2
      electrum/gui/kivy/uix/dialogs/qr_scanner.py
  9. 4
      electrum/gui/kivy/uix/drawer.py
  10. 4
      electrum/gui/qt/invoice_list.py
  11. 14
      electrum/gui/qt/main_window.py
  12. 12
      electrum/gui/qt/network_dialog.py
  13. 2
      electrum/gui/qt/password_dialog.py
  14. 2
      electrum/gui/qt/qrcodewidget.py
  15. 2
      electrum/gui/qt/request_list.py
  16. 6
      electrum/gui/qt/util.py
  17. 12
      electrum/gui/stdio.py
  18. 38
      electrum/gui/text.py
  19. 2
      electrum/keystore.py
  20. 6
      electrum/lnonion.py
  21. 4
      electrum/lnworker.py
  22. 2
      electrum/mnemonic.py
  23. 2
      electrum/network.py
  24. 6
      electrum/old_mnemonic.py
  25. 2
      electrum/plot.py
  26. 6
      electrum/plugins/coldcard/coldcard.py
  27. 2
      electrum/plugins/coldcard/qt.py
  28. 2
      electrum/plugins/hw_wallet/cmdline.py
  29. 4
      electrum/plugins/hw_wallet/plugin.py
  30. 8
      electrum/plugins/keepkey/keepkey.py
  31. 4
      electrum/plugins/ledger/auth2fa.py
  32. 6
      electrum/plugins/ledger/ledger.py
  33. 8
      electrum/plugins/revealer/qt.py
  34. 8
      electrum/plugins/safe_t/safe_t.py
  35. 10
      electrum/plugins/trezor/trezor.py
  36. 4
      electrum/tests/test_bitcoin.py
  37. 6
      electrum/tests/test_commands.py
  38. 8
      electrum/tests/test_lnchannel.py
  39. 2
      electrum/tests/test_transaction.py
  40. 2
      electrum/tests/test_wallet_vertical.py
  41. 4
      electrum/trampoline.py
  42. 2
      electrum/transaction.py
  43. 2
      electrum/util.py
  44. 2
      electrum/wallet_db.py
  45. 2
      run_electrum

4
contrib/build-wine/deterministic.spec

@ -92,7 +92,7 @@ for x in a.binaries.copy():
a.binaries.remove(x)
print('----> Removed x =', x)
qt_data2remove=(r'pyqt5\qt\translations\qtwebengine_locales', )
qt_data2remove=(r'pyqt5\qt\translations\qtwebengine_locales',)
print("Removing Qt datas:", *qt_data2remove)
for x in a.datas.copy():
for r in qt_data2remove:
@ -126,7 +126,7 @@ exe_portable = EXE(
pyz,
a.scripts,
a.binaries,
a.datas + [ ('is_portable', 'README.md', 'DATA' ) ],
a.datas + [('is_portable', 'README.md', 'DATA')],
name=os.path.join('build\\pyi.win32\\electrum', cmdline_name + "-portable.exe"),
debug=False,
strip=None,

5
contrib/sign_packages

@ -9,9 +9,6 @@ if __name__ == '__main__':
for f in os.listdir('.'):
if f.endswith('asc'):
continue
os.system( "gpg --sign --armor --detach --passphrase \"%s\" %s"%(password, f) )
os.system("gpg --sign --armor --detach --passphrase \"%s\" %s"%(password, f))
os.chdir("..")

2
electrum/coinchooser.py

@ -358,7 +358,7 @@ class CoinChooserRandom(CoinChooserBase):
# Add all singletons
for n, bucket in enumerate(buckets):
if sufficient_funds([bucket], bucket_value_sum=bucket.value):
candidates.add((n, ))
candidates.add((n,))
# And now some random ones
attempts = min(100, (len(buckets) - 1) * 10 + 1)

4
electrum/crypto.py

@ -172,8 +172,8 @@ def DecodeAES_bytes(secret: bytes, ciphertext: bytes) -> bytes:
PW_HASH_VERSION_LATEST = 1
KNOWN_PW_HASH_VERSIONS = (1, 2, )
SUPPORTED_PW_HASH_VERSIONS = (1, )
KNOWN_PW_HASH_VERSIONS = (1, 2,)
SUPPORTED_PW_HASH_VERSIONS = (1,)
assert PW_HASH_VERSION_LATEST in KNOWN_PW_HASH_VERSIONS
assert PW_HASH_VERSION_LATEST in SUPPORTED_PW_HASH_VERSIONS

2
electrum/currencies.json

@ -352,7 +352,7 @@
],
"Bitcointoyou": [
"BRL"
],
],
"Bitso": [
"MXN"
],

2
electrum/exchange_rate.py

@ -288,7 +288,7 @@ class CoinDesk(ExchangeBase):
return result
def history_starts(self):
return { 'USD': '2012-11-30', 'EUR': '2013-09-01' }
return {'USD': '2012-11-30', 'EUR': '2013-09-01'}
def history_ccys(self):
return self.history_starts().keys()

2
electrum/gui/kivy/main_window.py

@ -1028,7 +1028,7 @@ class ElectrumWindow(App, Logger):
modal=False):
''' Show an error Message Bubble.
'''
self.show_info_bubble( text=error, icon=icon, width=width,
self.show_info_bubble(text=error, icon=icon, width=width,
pos=pos or Window.center, arrow_pos=arrow_pos, exit=exit,
duration=duration, modal=modal)

2
electrum/gui/kivy/uix/dialogs/qr_scanner.py

@ -6,7 +6,7 @@ Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner')
class QrScannerDialog(Factory.AnimatedPopup):
__events__ = ('on_complete', )
__events__ = ('on_complete',)
def on_symbols(self, instance, value):
instance.stop()

4
electrum/gui/kivy/uix/drawer.py

@ -188,7 +188,7 @@ class Drawer(Factory.RelativeLayout):
if app.ui_mode[0] == 't':
return super(Drawer, self).on_touch_up(touch)
self.old_x = [1, ] * 10
self.old_x = [1,] * 10
self.speed = sum((
(self.old_x[x + 1] - self.old_x[x]) for x in range(9))) / 9.
@ -255,4 +255,4 @@ if __name__ == '__main__':
Drawer:
Button:
Button
'''))
'''))

4
electrum/gui/qt/invoice_list.py

@ -136,8 +136,8 @@ class InvoiceList(MyTreeView):
wallet = self.parent.wallet
items = self.selected_in_column(0)
if len(items)>1:
keys = [ item.data(ROLE_REQUEST_ID) for item in items]
invoices = [ wallet.invoices.get(key) for key in keys]
keys = [item.data(ROLE_REQUEST_ID) for item in items]
invoices = [wallet.invoices.get(key) for key in keys]
can_batch_pay = all([i.type == PR_TYPE_ONCHAIN and wallet.get_invoice_status(i) == PR_UNPAID for i in invoices])
menu = QMenu(self)
if can_batch_pay:

14
electrum/gui/qt/main_window.py

@ -129,7 +129,7 @@ class StatusBarButton(QToolButton):
self.func()
def keyPressEvent(self, e):
if e.key() in [ Qt.Key_Return, Qt.Key_Enter ]:
if e.key() in [Qt.Key_Return, Qt.Key_Enter]:
self.func()
@ -967,7 +967,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
icon = read_QIcon("status_lagging%s.png"%fork_str)
else:
c, u, x = self.wallet.get_balance()
text = _("Balance" ) + ": %s "%(self.format_amount_and_units(c))
text = _("Balance") + ": %s "%(self.format_amount_and_units(c))
if u:
text += " [%s unconfirmed]"%(self.format_amount(u, is_diff=True).strip())
if x:
@ -993,7 +993,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
self.tray.setToolTip("%s (%s)" % (text, self.wallet.basename()))
self.balance_label.setText(text)
if self.status_button:
self.status_button.setIcon( icon )
self.status_button.setIcon(icon)
def update_wallet(self):
self.update_status()
@ -2220,11 +2220,11 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
self.update_check_button.hide()
sb.addPermanentWidget(self.update_check_button)
self.password_button = StatusBarButton(QIcon(), _("Password"), self.change_password_dialog )
self.password_button = StatusBarButton(QIcon(), _("Password"), self.change_password_dialog)
sb.addPermanentWidget(self.password_button)
sb.addPermanentWidget(StatusBarButton(read_QIcon("preferences.png"), _("Preferences"), self.settings_dialog ) )
self.seed_button = StatusBarButton(read_QIcon("seed.png"), _("Seed"), self.show_seed_dialog )
sb.addPermanentWidget(StatusBarButton(read_QIcon("preferences.png"), _("Preferences"), self.settings_dialog))
self.seed_button = StatusBarButton(read_QIcon("seed.png"), _("Seed"), self.show_seed_dialog)
sb.addPermanentWidget(self.seed_button)
self.lightning_button = None
if self.wallet.has_lightning():
@ -2906,7 +2906,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
self.show_privkeys_signal.emit()
def show_privkeys():
s = "\n".join( map( lambda x: x[0] + "\t"+ x[1], private_keys.items()))
s = "\n".join(map(lambda x: x[0] + "\t"+ x[1], private_keys.items()))
e.setText(s)
b.setEnabled(True)
self.show_privkeys_signal.disconnect()

12
electrum/gui/qt/network_dialog.py

@ -117,7 +117,7 @@ class NodesListWidget(QTreeWidget):
menu.exec_(self.viewport().mapToGlobal(position))
def keyPressEvent(self, event):
if event.key() in [ Qt.Key_F2, Qt.Key_Return, Qt.Key_Enter ]:
if event.key() in [Qt.Key_F2, Qt.Key_Return, Qt.Key_Enter]:
self.on_activated(self.currentItem(), self.currentColumn())
else:
QTreeWidget.keyPressEvent(self, event)
@ -396,11 +396,11 @@ class NetworkChoiceLayout(object):
def set_proxy(self):
net_params = self.network.get_parameters()
if self.proxy_cb.isChecked():
proxy = { 'mode':str(self.proxy_mode.currentText()).lower(),
'host':str(self.proxy_host.text()),
'port':str(self.proxy_port.text()),
'user':str(self.proxy_user.text()),
'password':str(self.proxy_password.text())}
proxy = {'mode':str(self.proxy_mode.currentText()).lower(),
'host':str(self.proxy_host.text()),
'port':str(self.proxy_port.text()),
'user':str(self.proxy_user.text()),
'password':str(self.proxy_password.text())}
else:
proxy = None
self.tor_cb.setChecked(False)

2
electrum/gui/qt/password_dialog.py

@ -50,7 +50,7 @@ def check_password_strength(password):
num = re.search("[0-9]", password) is not None and re.match("^[0-9]*$", password) is None
caps = password != password.upper() and password != password.lower()
extra = re.match("^[a-zA-Z0-9]*$", password) is None
score = len(password)*( n + caps + num + extra)/20
score = len(password)*(n + caps + num + extra)/20
password_strength = {0:"Weak",1:"Medium",2:"Strong",3:"Very Strong"}
return password_strength[min(3, int(score))]

2
electrum/gui/qt/qrcodewidget.py

@ -72,7 +72,7 @@ class QRCodeWidget(QWidget):
margin = 10
framesize = min(r.width(), r.height())
boxsize = int( (framesize - 2*margin)/k )
boxsize = int((framesize - 2*margin)/k)
size = k*boxsize
left = (framesize - size)/2
top = (framesize - size)/2

2
electrum/gui/qt/request_list.py

@ -189,7 +189,7 @@ class RequestList(MyTreeView):
def create_menu(self, position):
items = self.selected_in_column(0)
if len(items)>1:
keys = [ item.data(ROLE_KEY) for item in items]
keys = [item.data(ROLE_KEY) for item in items]
menu = QMenu(self)
menu.addAction(_("Delete requests"), lambda: self.parent.delete_requests(keys))
menu.exec_(self.viewport().mapToGlobal(position))

6
electrum/gui/qt/util.py

@ -72,7 +72,7 @@ class EnterButton(QPushButton):
self.clicked.connect(func)
def keyPressEvent(self, e):
if e.key() in [ Qt.Key_Return, Qt.Key_Enter ]:
if e.key() in [Qt.Key_Return, Qt.Key_Enter]:
self.func()
@ -458,7 +458,7 @@ def filename_field(parent, config, defaultname, select_msg):
hbox = QHBoxLayout()
directory = config.get('io_dir', os.path.expanduser('~'))
path = os.path.join( directory, defaultname )
path = os.path.join(directory, defaultname)
filename_e = QLineEdit()
filename_e.setText(path)
@ -609,7 +609,7 @@ class MyTreeView(QTreeView):
def keyPressEvent(self, event):
if self.itemDelegate().opened:
return
if event.key() in [ Qt.Key_F2, Qt.Key_Return, Qt.Key_Enter ]:
if event.key() in [Qt.Key_F2, Qt.Key_Return, Qt.Key_Enter]:
self.on_activated(self.selectionModel().currentIndex())
return
super().keyPressEvent(event)

12
electrum/gui/stdio.py

@ -56,7 +56,7 @@ class ElectrumGui:
_("[r] - show own receipt addresses"), \
_("[c] - display contacts"), \
_("[b] - print server banner"), \
_("[q] - quit") ]
_("[q] - quit")]
self.num_commands = len(self.commands)
def on_network(self, event, *args):
@ -112,7 +112,7 @@ class ElectrumGui:
messages.append(format_str % (time_str, label, format_satoshis(delta, whitespaces=True),
format_satoshis(hist_item.balance, whitespaces=True)))
self.print_list(messages[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance")))
self.print_list(messages[::-1], format_str%(_("Date"), _("Description"), _("Amount"), _("Balance")))
def print_balance(self):
@ -121,7 +121,7 @@ class ElectrumGui:
def get_balance(self):
if self.wallet.network.is_connected():
if not self.wallet.up_to_date:
msg = _( "Synchronizing..." )
msg = _("Synchronizing...")
else:
c, u, x = self.wallet.get_balance()
msg = _("Balance")+": %f "%(Decimal(c) / COIN)
@ -130,7 +130,7 @@ class ElectrumGui:
if x:
msg += " [%f unmatured]"%(Decimal(x) / COIN)
else:
msg = _( "Not connected" )
msg = _("Not connected")
return(msg)
@ -157,8 +157,8 @@ class ElectrumGui:
self.do_send()
def print_banner(self):
for i, x in enumerate( self.wallet.network.banner.split('\n') ):
print( x )
for i, x in enumerate(self.wallet.network.banner.split('\n')):
print(x)
def print_list(self, lst, firstline):
lst = list(lst)

38
electrum/gui/text.py

@ -96,7 +96,7 @@ class ElectrumGui:
def get_string(self, y, x):
self.set_cursor(1)
curses.echo()
self.stdscr.addstr( y, x, " "*20, curses.A_REVERSE)
self.stdscr.addstr(y, x, " "*20, curses.A_REVERSE)
s = self.stdscr.getstr(y,x)
curses.noecho()
self.set_cursor(0)
@ -117,7 +117,7 @@ class ElectrumGui:
if self.history is None:
self.update_history()
self.print_list(self.history[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance")))
self.print_list(self.history[::-1], format_str%(_("Date"), _("Description"), _("Amount"), _("Balance")))
def update_history(self):
width = [20, 40, 14, 14]
@ -159,10 +159,10 @@ class ElectrumGui:
else:
msg = _("Not connected")
self.stdscr.addstr( self.maxy -1, 3, msg)
self.stdscr.addstr(self.maxy -1, 3, msg)
for i in range(self.num_tabs):
self.stdscr.addstr( 0, 2 + 2*i + len(''.join(self.tab_names[0:i])), ' '+self.tab_names[i]+' ', curses.A_BOLD if self.tab == i else 0)
self.stdscr.addstr(0, 2 + 2*i + len(''.join(self.tab_names[0:i])), ' '+self.tab_names[i]+' ', curses.A_BOLD if self.tab == i else 0)
self.stdscr.addstr(self.maxy -1, self.maxx-30, ' '.join([_("Settings"), _("Network"), _("Quit")]))
@ -181,9 +181,9 @@ class ElectrumGui:
self.print_list(messages, fmt % ("Address", "Label"))
def print_edit_line(self, y, label, text, index, size):
text += " "*(size - len(text) )
self.stdscr.addstr( y, 2, label)
self.stdscr.addstr( y, 15, text, curses.A_REVERSE if self.pos%6==index else curses.color_pair(1))
text += " "*(size - len(text))
self.stdscr.addstr(y, 2, label)
self.stdscr.addstr(y, 15, text, curses.A_REVERSE if self.pos%6==index else curses.color_pair(1))
def print_send_tab(self):
self.stdscr.clear()
@ -191,8 +191,8 @@ class ElectrumGui:
self.print_edit_line(5, _("Description"), self.str_description, 1, 40)
self.print_edit_line(7, _("Amount"), self.str_amount, 2, 15)
self.print_edit_line(9, _("Fee"), self.str_fee, 3, 15)
self.stdscr.addstr( 12, 15, _("[Send]"), curses.A_REVERSE if self.pos%6==4 else curses.color_pair(2))
self.stdscr.addstr( 12, 25, _("[Clear]"), curses.A_REVERSE if self.pos%6==5 else curses.color_pair(2))
self.stdscr.addstr(12, 15, _("[Send]"), curses.A_REVERSE if self.pos%6==4 else curses.color_pair(2))
self.stdscr.addstr(12, 25, _("[Clear]"), curses.A_REVERSE if self.pos%6==5 else curses.color_pair(2))
self.maxpos = 6
def print_banner(self):
@ -230,13 +230,13 @@ class ElectrumGui:
if not self.maxpos: return
if firstline:
firstline += " "*(self.maxx -2 - len(firstline))
self.stdscr.addstr( 1, 1, firstline )
self.stdscr.addstr(1, 1, firstline)
for i in range(self.maxy-4):
msg = lst[i] if i < len(lst) else ""
msg += " "*(self.maxx - 2 - len(msg))
m = msg[0:self.maxx - 2]
m = m.encode(self.encoding)
self.stdscr.addstr( i+2, 1, m, curses.A_REVERSE if i == (self.pos % self.maxpos) else 0)
self.stdscr.addstr(i+2, 1, m, curses.A_REVERSE if i == (self.pos % self.maxpos) else 0)
def refresh(self):
if self.tab == -1: return
@ -438,7 +438,7 @@ class ElectrumGui:
def settings_dialog(self):
fee = str(Decimal(self.config.fee_per_kb()) / COIN)
out = self.run_dialog('Settings', [
{'label':'Default fee', 'type':'satoshis', 'value': fee }
{'label':'Default fee', 'type':'satoshis', 'value': fee}
], buttons = 1)
if out:
if out.get('Default fee'):
@ -456,13 +456,13 @@ class ElectrumGui:
def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3):
self.popup_pos = 0
self.w = curses.newwin( 5 + len(list(items))*interval + (2 if buttons else 0), 50, y_pos, 5)
self.w = curses.newwin(5 + len(list(items))*interval + (2 if buttons else 0), 50, y_pos, 5)
w = self.w
out = {}
while True:
w.clear()
w.border(0)
w.addstr( 0, 2, title)
w.addstr(0, 2, title)
num = len(list(items))
@ -488,14 +488,14 @@ class ElectrumGui:
value += ' '*(20-len(value))
if 'value' in item:
w.addstr( 2+interval*i, 2, label)
w.addstr( 2+interval*i, 15, value, curses.A_REVERSE if self.popup_pos%numpos==i else curses.color_pair(1) )
w.addstr(2+interval*i, 2, label)
w.addstr(2+interval*i, 15, value, curses.A_REVERSE if self.popup_pos%numpos==i else curses.color_pair(1))
else:
w.addstr( 2+interval*i, 2, label, curses.A_REVERSE if self.popup_pos%numpos==i else 0)
w.addstr(2+interval*i, 2, label, curses.A_REVERSE if self.popup_pos%numpos==i else 0)
if buttons:
w.addstr( 5+interval*i, 10, "[ ok ]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-2) else curses.color_pair(2))
w.addstr( 5+interval*i, 25, "[cancel]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-1) else curses.color_pair(2))
w.addstr(5+interval*i, 10, "[ ok ]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-2) else curses.color_pair(2))
w.addstr(5+interval*i, 25, "[cancel]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-1) else curses.color_pair(2))
w.refresh()

2
electrum/keystore.py

@ -864,7 +864,7 @@ def bip39_is_checksum_valid(mnemonic: str) -> Tuple[bool, bool]:
"""Test checksum of bip39 mnemonic assuming English wordlist.
Returns tuple (is_checksum_valid, is_wordlist_valid)
"""
words = [ normalize('NFKD', word) for word in mnemonic.split() ]
words = [normalize('NFKD', word) for word in mnemonic.split()]
words_len = len(words)
wordlist = Wordlist.from_file("english.txt")
n = len(wordlist)

6
electrum/lnonion.py

@ -170,7 +170,7 @@ class OnionPacket:
def __init__(self, public_key: bytes, hops_data: bytes, hmac: bytes):
assert len(public_key) == 33
assert len(hops_data) in [ HOPS_DATA_SIZE, TRAMPOLINE_HOPS_DATA_SIZE ]
assert len(hops_data) in [HOPS_DATA_SIZE, TRAMPOLINE_HOPS_DATA_SIZE]
assert len(hmac) == PER_HOP_HMAC_SIZE
self.version = 0
self.public_key = public_key
@ -184,13 +184,13 @@ class OnionPacket:
ret += self.public_key
ret += self.hops_data
ret += self.hmac
if len(ret) - 66 not in [ HOPS_DATA_SIZE, TRAMPOLINE_HOPS_DATA_SIZE ]:
if len(ret) - 66 not in [HOPS_DATA_SIZE, TRAMPOLINE_HOPS_DATA_SIZE]:
raise Exception('unexpected length {}'.format(len(ret)))
return ret
@classmethod
def from_bytes(cls, b: bytes):
if len(b) - 66 not in [ HOPS_DATA_SIZE, TRAMPOLINE_HOPS_DATA_SIZE ]:
if len(b) - 66 not in [HOPS_DATA_SIZE, TRAMPOLINE_HOPS_DATA_SIZE]:
raise Exception('unexpected length {}'.format(len(b)))
version = b[0]
if version != 0:

4
electrum/lnworker.py

@ -396,9 +396,9 @@ class LNWorker(Logger, NetworkRetryManager[LNPeerAddr]):
return [peer]
# getting desperate... let's try hardcoded fallback list of peers
if constants.net in (constants.BitcoinTestnet, ):
if constants.net in (constants.BitcoinTestnet,):
fallback_list = FALLBACK_NODE_LIST_TESTNET
elif constants.net in (constants.BitcoinMainnet, ):
elif constants.net in (constants.BitcoinMainnet,):
fallback_list = FALLBACK_NODE_LIST_MAINNET
else:
return [] # regtest??

2
electrum/mnemonic.py

@ -45,7 +45,7 @@ CJK_INTERVALS = [
(0x2B740, 0x2B81F, 'CJK Unified Ideographs Extension D'),
(0xF900, 0xFAFF, 'CJK Compatibility Ideographs'),
(0x2F800, 0x2FA1D, 'CJK Compatibility Ideographs Supplement'),
(0x3190, 0x319F , 'Kanbun'),
(0x3190, 0x319F, 'Kanbun'),
(0x2E80, 0x2EFF, 'CJK Radicals Supplement'),
(0x2F00, 0x2FDF, 'CJK Radicals'),
(0x31C0, 0x31EF, 'CJK Strokes'),

2
electrum/network.py

@ -167,7 +167,7 @@ def deserialize_proxy(s: str) -> Optional[dict]:
return None
if s.lower() == 'none':
return None
proxy = { "mode":"socks5", "host":"localhost" }
proxy = {"mode":"socks5", "host":"localhost"}
# FIXME raw IPv6 address fails here
args = s.split(':')
n = 0

6
electrum/old_mnemonic.py

@ -1666,7 +1666,7 @@ assert n == 1626
# Note about US patent no 5892470: Here each word does not represent a given digit.
# Instead, the digit represented by a word is variable, it depends on the previous word.
def mn_encode( message ):
def mn_encode(message):
assert len(message) % 8 == 0
out = []
for i in range(len(message)//8):
@ -1675,11 +1675,11 @@ def mn_encode( message ):
w1 = (x%n)
w2 = ((x//n) + w1)%n
w3 = ((x//n//n) + w2)%n
out += [ wordlist[w1], wordlist[w2], wordlist[w3] ]
out += [wordlist[w1], wordlist[w2], wordlist[w3]]
return out
def mn_decode( wlist ):
def mn_decode(wlist):
out = ''
for i in range(len(wlist)//3):
word1, word2, word3 = wlist[3*i:3*i+3]

2
electrum/plot.py

@ -35,7 +35,7 @@ def plot_history(history):
f, axarr = plt.subplots(2, sharex=True)
plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation=25 )
plt.xticks(rotation=25)
ax = plt.gca()
plt.ylabel('BTC')
plt.xlabel('Month')

6
electrum/plugins/coldcard/coldcard.py

@ -97,7 +97,7 @@ class CKCCClient(HardwareClientBase):
if expected_xpub is None:
expected_xpub = self.dev.master_xpub
if ( (self._expected_device is not None)
if ((self._expected_device is not None)
or (self.dev.master_fingerprint != expected_xfp)
or (self.dev.master_xpub != expected_xpub)):
# probably indicating programing error, not hacking
@ -569,14 +569,14 @@ class ColdcardPlugin(HW_PluginBase):
print('# Exported from Electrum', file=fp)
print(f'Name: {name:.20s}', file=fp)
print(f'Policy: {wallet.m} of {wallet.n}', file=fp)
print(f'Format: {wallet.txin_type.upper()}' , file=fp)
print(f'Format: {wallet.txin_type.upper()}', file=fp)
xpubs = []
for xpub, ks in zip(wallet.get_master_public_keys(), wallet.get_keystores()): # type: str, KeyStoreWithMPK
fp_bytes, der_full = ks.get_fp_and_derivation_to_be_used_in_partial_tx(der_suffix=[], only_der_suffix=False)
fp_hex = fp_bytes.hex().upper()
der_prefix_str = bip32.convert_bip32_intpath_to_strpath(der_full)
xpubs.append( (fp_hex, xpub, der_prefix_str) )
xpubs.append((fp_hex, xpub, der_prefix_str))
# Before v3.2.1 derivation didn't matter too much to the Coldcard, since it
# could use key path data from PSBT or USB request as needed. However,

2
electrum/plugins/coldcard/qt.py

@ -136,7 +136,7 @@ class CKCCSettingsDialog(WindowModalDialog):
<br><a href="https://coldcardwallet.com">coldcardwallet.com</a>''')
title.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
grid.addWidget(title , 0,0, 1,2, Qt.AlignHCenter)
grid.addWidget(title, 0,0, 1,2, Qt.AlignHCenter)
y = 3
rows = [

2
electrum/plugins/hw_wallet/cmdline.py

@ -15,7 +15,7 @@ class CmdLineHandler(HardwareHandlerBase):
return getpass.getpass('')
def get_pin(self, msg, *, show_strength=True):
t = { 'a':'7', 'b':'8', 'c':'9', 'd':'4', 'e':'5', 'f':'6', 'g':'1', 'h':'2', 'i':'3'}
t = {'a':'7', 'b':'8', 'c':'9', 'd':'4', 'e':'5', 'f':'6', 'g':'1', 'h':'2', 'i':'3'}
print_stderr(msg)
print_stderr("a b c\nd e f\ng h i\n-----")
o = raw_input()

4
electrum/plugins/hw_wallet/plugin.py

@ -48,8 +48,8 @@ class HW_PluginBase(BasePlugin):
libraries_available: bool
# define supported library versions: minimum_library <= x < maximum_library
minimum_library = (0, )
maximum_library = (float('inf'), )
minimum_library = (0,)
maximum_library = (float('inf'),)
DEVICE_IDS: Iterable[Any]

8
electrum/plugins/keepkey/keepkey.py

@ -308,9 +308,9 @@ class KeepKeyPlugin(HW_PluginBase):
return self.types.SPENDWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return self.types.SPENDP2SHWITNESS
if electrum_txin_type in ('p2pkh', ):
if electrum_txin_type in ('p2pkh',):
return self.types.SPENDADDRESS
if electrum_txin_type in ('p2sh', ):
if electrum_txin_type in ('p2sh',):
return self.types.SPENDMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
@ -319,9 +319,9 @@ class KeepKeyPlugin(HW_PluginBase):
return self.types.PAYTOWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return self.types.PAYTOP2SHWITNESS
if electrum_txin_type in ('p2pkh', ):
if electrum_txin_type in ('p2pkh',):
return self.types.PAYTOADDRESS
if electrum_txin_type in ('p2sh', ):
if electrum_txin_type in ('p2sh',):
return self.types.PAYTOMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))

4
electrum/plugins/ledger/auth2fa.py

@ -26,7 +26,7 @@ helpTxt = [_("Your Ledger Wallet wants to tell you a one-time PIN code.<br><br>"
"put your cursor into it, and plug your device into that computer. " \
"It will output a summary of the transaction being signed and a one-time PIN.<br><br>" \
"Verify the transaction summary and type the PIN code here.<br><br>" \
"Before pressing enter, plug the device back into this computer.<br>" ),
"Before pressing enter, plug the device back into this computer.<br>"),
_("Verify the address below.<br>Type the character from your security card corresponding to the <u><b>BOLD</b></u> character."),
]
@ -161,7 +161,7 @@ class LedgerAuthDialog(QDialog):
def getDevice2FAMode(self):
apdu = [0xe0, 0x24, 0x01, 0x00, 0x00, 0x01] # get 2fa mode
try:
mode = self.dongle.exchange( bytearray(apdu) )
mode = self.dongle.exchange(bytearray(apdu))
return mode
except BTChipException as e:
_logger.debug('Device getMode Failed')

6
electrum/plugins/ledger/ledger.py

@ -193,7 +193,7 @@ class Ledger_Client(HardwareClientBase):
except BTChipException as e:
if (e.sw == 0x6985):
self.close()
self.handler.get_setup( )
self.handler.get_setup()
# Acquire the new client on the next run
else:
raise e
@ -493,7 +493,7 @@ class Ledger_KeyStore(Hardware_KeyStore):
raise UserWarning()
self.handler.show_message(_("Confirmed. Signing Transaction..."))
while inputIndex < len(inputs):
singleInput = [ chipInputs[inputIndex] ]
singleInput = [chipInputs[inputIndex]]
client_ledger.startUntrustedTransaction(False, 0,
singleInput, redeemScripts[inputIndex], version=tx.version)
inputSignature = client_ledger.untrustedHashSign(inputsPaths[inputIndex], pin, lockTime=tx.locktime)
@ -595,7 +595,7 @@ class LedgerPlugin(HW_PluginBase):
(0x2c97, 0x0009), # RFU
(0x2c97, 0x000a) # RFU
]
VENDOR_IDS = (0x2c97, )
VENDOR_IDS = (0x2c97,)
LEDGER_MODEL_IDS = {
0x10: "Ledger Nano S",
0x40: "Ledger Nano X",

8
electrum/plugins/revealer/qt.py

@ -299,7 +299,7 @@ class Plugin(RevealerPlugin):
bitmap.fill(Qt.white)
painter = QPainter()
painter.begin(bitmap)
QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf') )
QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf'))
if len(txt) < 102 :
fontsize = 15
linespace = 15
@ -325,7 +325,7 @@ class Plugin(RevealerPlugin):
while len(' '.join(map(str, temp_seed))) > max_letters:
nwords = nwords - 1
temp_seed = seed_array[:nwords]
painter.drawText(QRect(0, linespace*n , self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed)))
painter.drawText(QRect(0, linespace*n, self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed)))
del seed_array[:nwords]
painter.end()
@ -463,7 +463,7 @@ class Plugin(RevealerPlugin):
painter.end()
def pixelcode_2x2(self, img):
result = QImage(img.width()*2, img.height()*2, QImage.Format_ARGB32 )
result = QImage(img.width()*2, img.height()*2, QImage.Format_ARGB32)
white = qRgba(255,255,255,0)
black = qRgba(0,0,0,255)
@ -625,7 +625,7 @@ class Plugin(RevealerPlugin):
+ self.versioned_seed.checksum)
target = QRectF(base_img.width()-65-qr_size,
base_img.height()-65-qr_size,
qr_size, qr_size )
qr_size, qr_size)
painter.drawImage(target, qr_qt)
painter.setPen(QPen(Qt.black, 4))
painter.drawLine(base_img.width()-65-qr_size,

8
electrum/plugins/safe_t/safe_t.py

@ -278,9 +278,9 @@ class SafeTPlugin(HW_PluginBase):
return self.types.InputScriptType.SPENDWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return self.types.InputScriptType.SPENDP2SHWITNESS
if electrum_txin_type in ('p2pkh', ):
if electrum_txin_type in ('p2pkh',):
return self.types.InputScriptType.SPENDADDRESS
if electrum_txin_type in ('p2sh', ):
if electrum_txin_type in ('p2sh',):
return self.types.InputScriptType.SPENDMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
@ -289,9 +289,9 @@ class SafeTPlugin(HW_PluginBase):
return self.types.OutputScriptType.PAYTOWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return self.types.OutputScriptType.PAYTOP2SHWITNESS
if electrum_txin_type in ('p2pkh', ):
if electrum_txin_type in ('p2pkh',):
return self.types.OutputScriptType.PAYTOADDRESS
if electrum_txin_type in ('p2sh', ):
if electrum_txin_type in ('p2sh',):
return self.types.OutputScriptType.PAYTOMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))

10
electrum/plugins/trezor/trezor.py

@ -322,9 +322,9 @@ class TrezorPlugin(HW_PluginBase):
return InputScriptType.SPENDWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return InputScriptType.SPENDP2SHWITNESS
if electrum_txin_type in ('p2pkh', ):
if electrum_txin_type in ('p2pkh',):
return InputScriptType.SPENDADDRESS
if electrum_txin_type in ('p2sh', ):
if electrum_txin_type in ('p2sh',):
return InputScriptType.SPENDMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
@ -333,15 +333,15 @@ class TrezorPlugin(HW_PluginBase):
return OutputScriptType.PAYTOWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return OutputScriptType.PAYTOP2SHWITNESS
if electrum_txin_type in ('p2pkh', ):
if electrum_txin_type in ('p2pkh',):
return OutputScriptType.PAYTOADDRESS
if electrum_txin_type in ('p2sh', ):
if electrum_txin_type in ('p2sh',):
return OutputScriptType.PAYTOMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
@runs_in_hwd_thread
def sign_transaction(self, keystore, tx: PartialTransaction, prev_tx):
prev_tx = { bfh(txhash): self.electrum_tx_to_txtype(tx) for txhash, tx in prev_tx.items() }
prev_tx = {bfh(txhash): self.electrum_tx_to_txtype(tx) for txhash, tx in prev_tx.items()}
client = self.get_client(keystore)
inputs = self.tx_inputs(tx, for_sig=True, keystore=keystore)
outputs = self.tx_outputs(tx, keystore=keystore)

4
electrum/tests/test_bitcoin.py

@ -347,7 +347,7 @@ class Test_bitcoin(ElectrumTestCase):
def test_var_int(self):
for i in range(0xfd):
self.assertEqual(var_int(i), "{:02x}".format(i) )
self.assertEqual(var_int(i), "{:02x}".format(i))
self.assertEqual(var_int(0xfd), "fdfd00")
self.assertEqual(var_int(0xfe), "fdfe00")
@ -422,7 +422,7 @@ class Test_bitcoin(ElectrumTestCase):
self.assertEqual(add_number_to_script(32768), bfh('03008000'))
self.assertEqual(add_number_to_script(8388607), bfh('03ffff7f'))
self.assertEqual(add_number_to_script(-2147483647), bfh('04ffffffff'))
self.assertEqual(add_number_to_script(-8388608 ), bfh('0400008080'))
self.assertEqual(add_number_to_script(-8388608), bfh('0400008080'))
self.assertEqual(add_number_to_script(8388608), bfh('0400008000'))
self.assertEqual(add_number_to_script(2147483647), bfh('04ffffff7f'))

6
electrum/tests/test_commands.py

@ -103,9 +103,9 @@ class TestCommands(ElectrumTestCase):
cmds._run('getprivatekeys', ("bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw",), wallet=wallet))
# list of addresses tests
with self.assertRaises(Exception):
cmds._run('getprivatekeys', (['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'asd'], ), wallet=wallet)
cmds._run('getprivatekeys', (['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'asd'],), wallet=wallet)
self.assertEqual(['p2wpkh:L4jkdiXszG26SUYvwwJhzGwg37H2nLhrbip7u6crmgNeJysv5FHL', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'],
cmds._run('getprivatekeys', (['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'], ), wallet=wallet))
cmds._run('getprivatekeys', (['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'],), wallet=wallet))
@mock.patch.object(wallet.Abstract_Wallet, 'save_db')
def test_export_private_key_deterministic(self, mock_save_db):
@ -125,7 +125,7 @@ class TestCommands(ElectrumTestCase):
with self.assertRaises(Exception):
cmds._run('getprivatekeys', (['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'asd'],), wallet=wallet)
self.assertEqual(['p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'],
cmds._run('getprivatekeys', (['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'], ), wallet=wallet))
cmds._run('getprivatekeys', (['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'],), wallet=wallet))
class TestCommandsTestnet(TestCaseForTestnet):

8
electrum/tests/test_lnchannel.py

@ -126,8 +126,8 @@ def create_test_channels(*, feerate=6000, local_msat=None, remote_msat=None,
funding_sat = ((local_msat + remote_msat) // 1000) if local_msat is not None and remote_msat is not None else (bitcoin.COIN * 10)
local_amount = local_msat if local_msat is not None else (funding_sat * 1000 // 2)
remote_amount = remote_msat if remote_msat is not None else (funding_sat * 1000 // 2)
alice_raw = [ bip32("m/" + str(i)) for i in range(5) ]
bob_raw = [ bip32("m/" + str(i)) for i in range(5,11) ]
alice_raw = [bip32("m/" + str(i)) for i in range(5)]
bob_raw = [bip32("m/" + str(i)) for i in range(5,11)]
alice_privkeys = [lnutil.Keypair(lnutil.privkey_to_pubkey(x), x) for x in alice_raw]
bob_privkeys = [lnutil.Keypair(lnutil.privkey_to_pubkey(x), x) for x in bob_raw]
alice_pubkeys = [lnutil.OnlyPubkeyKeypair(x.pubkey) for x in alice_privkeys]
@ -853,13 +853,13 @@ class TestDust(ElectrumTestCase):
'timestamp' : 0,
}
old_values = [x.value for x in bob_channel.get_latest_commitment(LOCAL).outputs() ]
old_values = [x.value for x in bob_channel.get_latest_commitment(LOCAL).outputs()]
aliceHtlcIndex = alice_channel.add_htlc(htlc).htlc_id
bobHtlcIndex = bob_channel.receive_htlc(htlc).htlc_id
force_state_transition(alice_channel, bob_channel)
alice_ctx = alice_channel.get_latest_commitment(LOCAL)
bob_ctx = bob_channel.get_latest_commitment(LOCAL)
new_values = [x.value for x in bob_ctx.outputs() ]
new_values = [x.value for x in bob_ctx.outputs()]
self.assertNotEqual(old_values, new_values)
self.assertEqual(len(alice_ctx.outputs()), 3)
self.assertEqual(len(bob_ctx.outputs()), 2)

2
electrum/tests/test_transaction.py

@ -15,7 +15,7 @@ signed_blob = '01000000012a5c9a94fcde98f5581cd00162c60a13936ceb75389ea65bf38633b
v2_blob = "0200000001191601a44a81e061502b7bfbc6eaa1cef6d1e6af5308ef96c9342f71dbf4b9b5000000006b483045022100a6d44d0a651790a477e75334adfb8aae94d6612d01187b2c02526e340a7fd6c8022028bdf7a64a54906b13b145cd5dab21a26bd4b85d6044e9b97bceab5be44c2a9201210253e8e0254b0c95776786e40984c1aa32a7d03efa6bdacdea5f421b774917d346feffffff026b20fa04000000001976a914024db2e87dd7cfd0e5f266c5f212e21a31d805a588aca0860100000000001976a91421919b94ae5cefcdf0271191459157cdb41c4cbf88aca6240700"
signed_segwit_blob = "01000000000101b66d722484f2db63e827ebf41d02684fed0c6550e85015a6c9d41ef216a8a6f00000000000fdffffff0280c3c90100000000160014b65ce60857f7e7892b983851c2a8e3526d09e4ab64bac30400000000160014c478ebbc0ab2097706a98e10db7cf101839931c4024730440220789c7d47f876638c58d98733c30ae9821c8fa82b470285dcdf6db5994210bf9f02204163418bbc44af701212ad42d884cc613f3d3d831d2d0cc886f767cca6e0235e012103083a6dc250816d771faa60737bfe78b23ad619f6b458e0a1f1688e3a0605e79c00000000"
signed_blob_signatures = ['3046022100a82bbc57a0136751e5433f41cf000b3f1a99c6744775e76ec764fb78c54ee100022100f9e80b7de89de861dc6fb0c1429d5da72c2b6b2ee2406bc9bfb1beedd729d98501', ]
signed_blob_signatures = ['3046022100a82bbc57a0136751e5433f41cf000b3f1a99c6744775e76ec764fb78c54ee100022100f9e80b7de89de861dc6fb0c1429d5da72c2b6b2ee2406bc9bfb1beedd729d98501',]
class TestBCDataStream(ElectrumTestCase):

2
electrum/tests/test_wallet_vertical.py

@ -1716,7 +1716,7 @@ class TestWalletSending(TestCaseForTestnet):
else:
raise Exception("unexpected txid")
privkeys = ['93NQ7CFbwTPyKDJLXe97jczw33fiLijam2SCZL3Uinz1NSbHrTu', ]
privkeys = ['93NQ7CFbwTPyKDJLXe97jczw33fiLijam2SCZL3Uinz1NSbHrTu',]
network = NetworkMock()
dest_addr = 'tb1q3ws2p0qjk5vrravv065xqlnkckvzcpclk79eu2'
sweep_coro = sweep(privkeys, network=network, config=self.config, to_address=dest_addr, fee=5000, locktime=1325785, tx_version=1)

4
electrum/trampoline.py

@ -62,9 +62,9 @@ TRAMPOLINE_NODES_TESTNET = {
}
def hardcoded_trampoline_nodes():
if constants.net in (constants.BitcoinMainnet, ):
if constants.net in (constants.BitcoinMainnet,):
return TRAMPOLINE_NODES_MAINNET
if constants.net in (constants.BitcoinTestnet, ):
if constants.net in (constants.BitcoinTestnet,):
return TRAMPOLINE_NODES_TESTNET
return {}

2
electrum/transaction.py

@ -642,7 +642,7 @@ class Transaction:
# We assume low S (as that is a bitcoin standardness rule).
# We do not assume low R (even though the sigs we create conform), as external sigs,
# e.g. from a hw signer cannot be expected to have a low R.
sig_list = [ "00" * 72 ] * num_sig
sig_list = ["00" * 72] * num_sig
else:
pk_list = [pubkey.hex() for pubkey in txin.pubkeys]
sig_list = [txin.part_sigs.get(pubkey, b'').hex() for pubkey in txin.pubkeys]

2
electrum/util.py

@ -917,7 +917,7 @@ def parse_URI(uri: str, on_pr: Callable = None, *, loop=None) -> dict:
m = re.match(r'([0-9.]+)X([0-9])', am)
if m:
k = int(m.group(2)) - 8
amount = Decimal(m.group(1)) * pow( Decimal(10) , k)
amount = Decimal(m.group(1)) * pow(Decimal(10), k)
else:
amount = Decimal(am) * COIN
out['amount'] = int(amount)

2
electrum/wallet_db.py

@ -528,7 +528,7 @@ class WalletDB(JsonDB):
r['buckets'] = d
c['revocation_store'] = r
# convert channels to dict
self.data['channels'] = { x['channel_id']: x for x in channels }
self.data['channels'] = {x['channel_id']: x for x in channels}
# convert txi & txo
txi = self.get('txi', {})
for tx_hash, d in list(txi.items()):

2
run_electrum

@ -149,7 +149,7 @@ def init_cmdline(config_options, wallet_path, server, *, config: 'SimpleConfig')
use_encryption = True
# commands needing password
if ( (cmd.requires_wallet and storage.is_encrypted() and server is False)\
if ((cmd.requires_wallet and storage.is_encrypted() and server is False)\
or (cmdname == 'load_wallet' and storage.is_encrypted())\
or (cmd.requires_password and use_encryption)):
if storage.is_encrypted_with_hw_device():

Loading…
Cancel
Save