Browse Source

Merge pull request #7125 from verretor/2021-03-style

Minor style changes
patch-4
ThomasV 4 years ago
committed by GitHub
parent
commit
22e6fe09c1
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  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) a.binaries.remove(x)
print('----> Removed x =', 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) print("Removing Qt datas:", *qt_data2remove)
for x in a.datas.copy(): for x in a.datas.copy():
for r in qt_data2remove: for r in qt_data2remove:
@ -126,7 +126,7 @@ exe_portable = EXE(
pyz, pyz,
a.scripts, a.scripts,
a.binaries, 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"), name=os.path.join('build\\pyi.win32\\electrum', cmdline_name + "-portable.exe"),
debug=False, debug=False,
strip=None, strip=None,

5
contrib/sign_packages

@ -9,9 +9,6 @@ if __name__ == '__main__':
for f in os.listdir('.'): for f in os.listdir('.'):
if f.endswith('asc'): if f.endswith('asc'):
continue 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("..") os.chdir("..")

2
electrum/coinchooser.py

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

2
electrum/currencies.json

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

2
electrum/exchange_rate.py

@ -288,7 +288,7 @@ class CoinDesk(ExchangeBase):
return result return result
def history_starts(self): 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): def history_ccys(self):
return self.history_starts().keys() return self.history_starts().keys()

2
electrum/gui/kivy/main_window.py

@ -1028,7 +1028,7 @@ class ElectrumWindow(App, Logger):
modal=False): modal=False):
''' Show an error Message Bubble. ''' 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, pos=pos or Window.center, arrow_pos=arrow_pos, exit=exit,
duration=duration, modal=modal) 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): class QrScannerDialog(Factory.AnimatedPopup):
__events__ = ('on_complete', ) __events__ = ('on_complete',)
def on_symbols(self, instance, value): def on_symbols(self, instance, value):
instance.stop() instance.stop()

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

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

4
electrum/gui/qt/invoice_list.py

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

14
electrum/gui/qt/main_window.py

@ -129,7 +129,7 @@ class StatusBarButton(QToolButton):
self.func() self.func()
def keyPressEvent(self, e): 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() self.func()
@ -967,7 +967,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
icon = read_QIcon("status_lagging%s.png"%fork_str) icon = read_QIcon("status_lagging%s.png"%fork_str)
else: else:
c, u, x = self.wallet.get_balance() 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: if u:
text += " [%s unconfirmed]"%(self.format_amount(u, is_diff=True).strip()) text += " [%s unconfirmed]"%(self.format_amount(u, is_diff=True).strip())
if x: if x:
@ -993,7 +993,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
self.tray.setToolTip("%s (%s)" % (text, self.wallet.basename())) self.tray.setToolTip("%s (%s)" % (text, self.wallet.basename()))
self.balance_label.setText(text) self.balance_label.setText(text)
if self.status_button: if self.status_button:
self.status_button.setIcon( icon ) self.status_button.setIcon(icon)
def update_wallet(self): def update_wallet(self):
self.update_status() self.update_status()
@ -2220,11 +2220,11 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
self.update_check_button.hide() self.update_check_button.hide()
sb.addPermanentWidget(self.update_check_button) 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(self.password_button)
sb.addPermanentWidget(StatusBarButton(read_QIcon("preferences.png"), _("Preferences"), self.settings_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 ) self.seed_button = StatusBarButton(read_QIcon("seed.png"), _("Seed"), self.show_seed_dialog)
sb.addPermanentWidget(self.seed_button) sb.addPermanentWidget(self.seed_button)
self.lightning_button = None self.lightning_button = None
if self.wallet.has_lightning(): if self.wallet.has_lightning():
@ -2906,7 +2906,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
self.show_privkeys_signal.emit() self.show_privkeys_signal.emit()
def show_privkeys(): 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) e.setText(s)
b.setEnabled(True) b.setEnabled(True)
self.show_privkeys_signal.disconnect() 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)) menu.exec_(self.viewport().mapToGlobal(position))
def keyPressEvent(self, event): 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()) self.on_activated(self.currentItem(), self.currentColumn())
else: else:
QTreeWidget.keyPressEvent(self, event) QTreeWidget.keyPressEvent(self, event)
@ -396,11 +396,11 @@ class NetworkChoiceLayout(object):
def set_proxy(self): def set_proxy(self):
net_params = self.network.get_parameters() net_params = self.network.get_parameters()
if self.proxy_cb.isChecked(): if self.proxy_cb.isChecked():
proxy = { 'mode':str(self.proxy_mode.currentText()).lower(), proxy = {'mode':str(self.proxy_mode.currentText()).lower(),
'host':str(self.proxy_host.text()), 'host':str(self.proxy_host.text()),
'port':str(self.proxy_port.text()), 'port':str(self.proxy_port.text()),
'user':str(self.proxy_user.text()), 'user':str(self.proxy_user.text()),
'password':str(self.proxy_password.text())} 'password':str(self.proxy_password.text())}
else: else:
proxy = None proxy = None
self.tor_cb.setChecked(False) 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 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() caps = password != password.upper() and password != password.lower()
extra = re.match("^[a-zA-Z0-9]*$", password) is None 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"} password_strength = {0:"Weak",1:"Medium",2:"Strong",3:"Very Strong"}
return password_strength[min(3, int(score))] return password_strength[min(3, int(score))]

2
electrum/gui/qt/qrcodewidget.py

@ -72,7 +72,7 @@ class QRCodeWidget(QWidget):
margin = 10 margin = 10
framesize = min(r.width(), r.height()) framesize = min(r.width(), r.height())
boxsize = int( (framesize - 2*margin)/k ) boxsize = int((framesize - 2*margin)/k)
size = k*boxsize size = k*boxsize
left = (framesize - size)/2 left = (framesize - size)/2
top = (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): def create_menu(self, position):
items = self.selected_in_column(0) items = self.selected_in_column(0)
if len(items)>1: 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 = QMenu(self)
menu.addAction(_("Delete requests"), lambda: self.parent.delete_requests(keys)) menu.addAction(_("Delete requests"), lambda: self.parent.delete_requests(keys))
menu.exec_(self.viewport().mapToGlobal(position)) menu.exec_(self.viewport().mapToGlobal(position))

6
electrum/gui/qt/util.py

@ -72,7 +72,7 @@ class EnterButton(QPushButton):
self.clicked.connect(func) self.clicked.connect(func)
def keyPressEvent(self, e): 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() self.func()
@ -458,7 +458,7 @@ def filename_field(parent, config, defaultname, select_msg):
hbox = QHBoxLayout() hbox = QHBoxLayout()
directory = config.get('io_dir', os.path.expanduser('~')) 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 = QLineEdit()
filename_e.setText(path) filename_e.setText(path)
@ -609,7 +609,7 @@ class MyTreeView(QTreeView):
def keyPressEvent(self, event): def keyPressEvent(self, event):
if self.itemDelegate().opened: if self.itemDelegate().opened:
return 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()) self.on_activated(self.selectionModel().currentIndex())
return return
super().keyPressEvent(event) super().keyPressEvent(event)

12
electrum/gui/stdio.py

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

38
electrum/gui/text.py

@ -96,7 +96,7 @@ class ElectrumGui:
def get_string(self, y, x): def get_string(self, y, x):
self.set_cursor(1) self.set_cursor(1)
curses.echo() 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) s = self.stdscr.getstr(y,x)
curses.noecho() curses.noecho()
self.set_cursor(0) self.set_cursor(0)
@ -117,7 +117,7 @@ class ElectrumGui:
if self.history is None: if self.history is None:
self.update_history() 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): def update_history(self):
width = [20, 40, 14, 14] width = [20, 40, 14, 14]
@ -159,10 +159,10 @@ class ElectrumGui:
else: else:
msg = _("Not connected") 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): 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")])) 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")) self.print_list(messages, fmt % ("Address", "Label"))
def print_edit_line(self, y, label, text, index, size): def print_edit_line(self, y, label, text, index, size):
text += " "*(size - len(text) ) text += " "*(size - len(text))
self.stdscr.addstr( y, 2, label) 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)) self.stdscr.addstr(y, 15, text, curses.A_REVERSE if self.pos%6==index else curses.color_pair(1))
def print_send_tab(self): def print_send_tab(self):
self.stdscr.clear() self.stdscr.clear()
@ -191,8 +191,8 @@ class ElectrumGui:
self.print_edit_line(5, _("Description"), self.str_description, 1, 40) 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(7, _("Amount"), self.str_amount, 2, 15)
self.print_edit_line(9, _("Fee"), self.str_fee, 3, 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, 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, 25, _("[Clear]"), curses.A_REVERSE if self.pos%6==5 else curses.color_pair(2))
self.maxpos = 6 self.maxpos = 6
def print_banner(self): def print_banner(self):
@ -230,13 +230,13 @@ class ElectrumGui:
if not self.maxpos: return if not self.maxpos: return
if firstline: if firstline:
firstline += " "*(self.maxx -2 - len(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): for i in range(self.maxy-4):
msg = lst[i] if i < len(lst) else "" msg = lst[i] if i < len(lst) else ""
msg += " "*(self.maxx - 2 - len(msg)) msg += " "*(self.maxx - 2 - len(msg))
m = msg[0:self.maxx - 2] m = msg[0:self.maxx - 2]
m = m.encode(self.encoding) 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): def refresh(self):
if self.tab == -1: return if self.tab == -1: return
@ -438,7 +438,7 @@ class ElectrumGui:
def settings_dialog(self): def settings_dialog(self):
fee = str(Decimal(self.config.fee_per_kb()) / COIN) fee = str(Decimal(self.config.fee_per_kb()) / COIN)
out = self.run_dialog('Settings', [ out = self.run_dialog('Settings', [
{'label':'Default fee', 'type':'satoshis', 'value': fee } {'label':'Default fee', 'type':'satoshis', 'value': fee}
], buttons = 1) ], buttons = 1)
if out: if out:
if out.get('Default fee'): if out.get('Default fee'):
@ -456,13 +456,13 @@ class ElectrumGui:
def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3): def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3):
self.popup_pos = 0 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 w = self.w
out = {} out = {}
while True: while True:
w.clear() w.clear()
w.border(0) w.border(0)
w.addstr( 0, 2, title) w.addstr(0, 2, title)
num = len(list(items)) num = len(list(items))
@ -488,14 +488,14 @@ class ElectrumGui:
value += ' '*(20-len(value)) value += ' '*(20-len(value))
if 'value' in item: if 'value' in item:
w.addstr( 2+interval*i, 2, label) 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, 15, value, curses.A_REVERSE if self.popup_pos%numpos==i else curses.color_pair(1))
else: 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: 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, 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, 25, "[cancel]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-1) else curses.color_pair(2))
w.refresh() 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. """Test checksum of bip39 mnemonic assuming English wordlist.
Returns tuple (is_checksum_valid, is_wordlist_valid) 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) words_len = len(words)
wordlist = Wordlist.from_file("english.txt") wordlist = Wordlist.from_file("english.txt")
n = len(wordlist) n = len(wordlist)

6
electrum/lnonion.py

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

4
electrum/lnworker.py

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

2
electrum/mnemonic.py

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

2
electrum/network.py

@ -167,7 +167,7 @@ def deserialize_proxy(s: str) -> Optional[dict]:
return None return None
if s.lower() == 'none': if s.lower() == 'none':
return None return None
proxy = { "mode":"socks5", "host":"localhost" } proxy = {"mode":"socks5", "host":"localhost"}
# FIXME raw IPv6 address fails here # FIXME raw IPv6 address fails here
args = s.split(':') args = s.split(':')
n = 0 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. # 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. # 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 assert len(message) % 8 == 0
out = [] out = []
for i in range(len(message)//8): for i in range(len(message)//8):
@ -1675,11 +1675,11 @@ def mn_encode( message ):
w1 = (x%n) w1 = (x%n)
w2 = ((x//n) + w1)%n w2 = ((x//n) + w1)%n
w3 = ((x//n//n) + w2)%n w3 = ((x//n//n) + w2)%n
out += [ wordlist[w1], wordlist[w2], wordlist[w3] ] out += [wordlist[w1], wordlist[w2], wordlist[w3]]
return out return out
def mn_decode( wlist ): def mn_decode(wlist):
out = '' out = ''
for i in range(len(wlist)//3): for i in range(len(wlist)//3):
word1, word2, word3 = wlist[3*i:3*i+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) f, axarr = plt.subplots(2, sharex=True)
plt.subplots_adjust(bottom=0.2) plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation=25 ) plt.xticks(rotation=25)
ax = plt.gca() ax = plt.gca()
plt.ylabel('BTC') plt.ylabel('BTC')
plt.xlabel('Month') plt.xlabel('Month')

6
electrum/plugins/coldcard/coldcard.py

@ -97,7 +97,7 @@ class CKCCClient(HardwareClientBase):
if expected_xpub is None: if expected_xpub is None:
expected_xpub = self.dev.master_xpub 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_fingerprint != expected_xfp)
or (self.dev.master_xpub != expected_xpub)): or (self.dev.master_xpub != expected_xpub)):
# probably indicating programing error, not hacking # probably indicating programing error, not hacking
@ -569,14 +569,14 @@ class ColdcardPlugin(HW_PluginBase):
print('# Exported from Electrum', file=fp) print('# Exported from Electrum', file=fp)
print(f'Name: {name:.20s}', file=fp) print(f'Name: {name:.20s}', file=fp)
print(f'Policy: {wallet.m} of {wallet.n}', 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 = [] xpubs = []
for xpub, ks in zip(wallet.get_master_public_keys(), wallet.get_keystores()): # type: str, KeyStoreWithMPK 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_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() fp_hex = fp_bytes.hex().upper()
der_prefix_str = bip32.convert_bip32_intpath_to_strpath(der_full) 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 # 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, # 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>''') <br><a href="https://coldcardwallet.com">coldcardwallet.com</a>''')
title.setTextInteractionFlags(Qt.LinksAccessibleByMouse) title.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
grid.addWidget(title , 0,0, 1,2, Qt.AlignHCenter) grid.addWidget(title, 0,0, 1,2, Qt.AlignHCenter)
y = 3 y = 3
rows = [ rows = [

2
electrum/plugins/hw_wallet/cmdline.py

@ -15,7 +15,7 @@ class CmdLineHandler(HardwareHandlerBase):
return getpass.getpass('') return getpass.getpass('')
def get_pin(self, msg, *, show_strength=True): 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(msg)
print_stderr("a b c\nd e f\ng h i\n-----") print_stderr("a b c\nd e f\ng h i\n-----")
o = raw_input() o = raw_input()

4
electrum/plugins/hw_wallet/plugin.py

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

8
electrum/plugins/keepkey/keepkey.py

@ -308,9 +308,9 @@ class KeepKeyPlugin(HW_PluginBase):
return self.types.SPENDWITNESS return self.types.SPENDWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'): if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return self.types.SPENDP2SHWITNESS return self.types.SPENDP2SHWITNESS
if electrum_txin_type in ('p2pkh', ): if electrum_txin_type in ('p2pkh',):
return self.types.SPENDADDRESS return self.types.SPENDADDRESS
if electrum_txin_type in ('p2sh', ): if electrum_txin_type in ('p2sh',):
return self.types.SPENDMULTISIG return self.types.SPENDMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type)) raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
@ -319,9 +319,9 @@ class KeepKeyPlugin(HW_PluginBase):
return self.types.PAYTOWITNESS return self.types.PAYTOWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'): if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return self.types.PAYTOP2SHWITNESS return self.types.PAYTOP2SHWITNESS
if electrum_txin_type in ('p2pkh', ): if electrum_txin_type in ('p2pkh',):
return self.types.PAYTOADDRESS return self.types.PAYTOADDRESS
if electrum_txin_type in ('p2sh', ): if electrum_txin_type in ('p2sh',):
return self.types.PAYTOMULTISIG return self.types.PAYTOMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type)) 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. " \ "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>" \ "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>" \ "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."), _("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): def getDevice2FAMode(self):
apdu = [0xe0, 0x24, 0x01, 0x00, 0x00, 0x01] # get 2fa mode apdu = [0xe0, 0x24, 0x01, 0x00, 0x00, 0x01] # get 2fa mode
try: try:
mode = self.dongle.exchange( bytearray(apdu) ) mode = self.dongle.exchange(bytearray(apdu))
return mode return mode
except BTChipException as e: except BTChipException as e:
_logger.debug('Device getMode Failed') _logger.debug('Device getMode Failed')

6
electrum/plugins/ledger/ledger.py

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

8
electrum/plugins/revealer/qt.py

@ -299,7 +299,7 @@ class Plugin(RevealerPlugin):
bitmap.fill(Qt.white) bitmap.fill(Qt.white)
painter = QPainter() painter = QPainter()
painter.begin(bitmap) 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 : if len(txt) < 102 :
fontsize = 15 fontsize = 15
linespace = 15 linespace = 15
@ -325,7 +325,7 @@ class Plugin(RevealerPlugin):
while len(' '.join(map(str, temp_seed))) > max_letters: while len(' '.join(map(str, temp_seed))) > max_letters:
nwords = nwords - 1 nwords = nwords - 1
temp_seed = seed_array[:nwords] 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] del seed_array[:nwords]
painter.end() painter.end()
@ -463,7 +463,7 @@ class Plugin(RevealerPlugin):
painter.end() painter.end()
def pixelcode_2x2(self, img): 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) white = qRgba(255,255,255,0)
black = qRgba(0,0,0,255) black = qRgba(0,0,0,255)
@ -625,7 +625,7 @@ class Plugin(RevealerPlugin):
+ self.versioned_seed.checksum) + self.versioned_seed.checksum)
target = QRectF(base_img.width()-65-qr_size, target = QRectF(base_img.width()-65-qr_size,
base_img.height()-65-qr_size, base_img.height()-65-qr_size,
qr_size, qr_size ) qr_size, qr_size)
painter.drawImage(target, qr_qt) painter.drawImage(target, qr_qt)
painter.setPen(QPen(Qt.black, 4)) painter.setPen(QPen(Qt.black, 4))
painter.drawLine(base_img.width()-65-qr_size, 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 return self.types.InputScriptType.SPENDWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'): if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return self.types.InputScriptType.SPENDP2SHWITNESS return self.types.InputScriptType.SPENDP2SHWITNESS
if electrum_txin_type in ('p2pkh', ): if electrum_txin_type in ('p2pkh',):
return self.types.InputScriptType.SPENDADDRESS return self.types.InputScriptType.SPENDADDRESS
if electrum_txin_type in ('p2sh', ): if electrum_txin_type in ('p2sh',):
return self.types.InputScriptType.SPENDMULTISIG return self.types.InputScriptType.SPENDMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type)) raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
@ -289,9 +289,9 @@ class SafeTPlugin(HW_PluginBase):
return self.types.OutputScriptType.PAYTOWITNESS return self.types.OutputScriptType.PAYTOWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'): if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return self.types.OutputScriptType.PAYTOP2SHWITNESS return self.types.OutputScriptType.PAYTOP2SHWITNESS
if electrum_txin_type in ('p2pkh', ): if electrum_txin_type in ('p2pkh',):
return self.types.OutputScriptType.PAYTOADDRESS return self.types.OutputScriptType.PAYTOADDRESS
if electrum_txin_type in ('p2sh', ): if electrum_txin_type in ('p2sh',):
return self.types.OutputScriptType.PAYTOMULTISIG return self.types.OutputScriptType.PAYTOMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type)) 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 return InputScriptType.SPENDWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'): if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return InputScriptType.SPENDP2SHWITNESS return InputScriptType.SPENDP2SHWITNESS
if electrum_txin_type in ('p2pkh', ): if electrum_txin_type in ('p2pkh',):
return InputScriptType.SPENDADDRESS return InputScriptType.SPENDADDRESS
if electrum_txin_type in ('p2sh', ): if electrum_txin_type in ('p2sh',):
return InputScriptType.SPENDMULTISIG return InputScriptType.SPENDMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type)) raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
@ -333,15 +333,15 @@ class TrezorPlugin(HW_PluginBase):
return OutputScriptType.PAYTOWITNESS return OutputScriptType.PAYTOWITNESS
if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'): if electrum_txin_type in ('p2wpkh-p2sh', 'p2wsh-p2sh'):
return OutputScriptType.PAYTOP2SHWITNESS return OutputScriptType.PAYTOP2SHWITNESS
if electrum_txin_type in ('p2pkh', ): if electrum_txin_type in ('p2pkh',):
return OutputScriptType.PAYTOADDRESS return OutputScriptType.PAYTOADDRESS
if electrum_txin_type in ('p2sh', ): if electrum_txin_type in ('p2sh',):
return OutputScriptType.PAYTOMULTISIG return OutputScriptType.PAYTOMULTISIG
raise ValueError('unexpected txin type: {}'.format(electrum_txin_type)) raise ValueError('unexpected txin type: {}'.format(electrum_txin_type))
@runs_in_hwd_thread @runs_in_hwd_thread
def sign_transaction(self, keystore, tx: PartialTransaction, prev_tx): 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) client = self.get_client(keystore)
inputs = self.tx_inputs(tx, for_sig=True, keystore=keystore) inputs = self.tx_inputs(tx, for_sig=True, keystore=keystore)
outputs = self.tx_outputs(tx, 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): def test_var_int(self):
for i in range(0xfd): 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(0xfd), "fdfd00")
self.assertEqual(var_int(0xfe), "fdfe00") 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(32768), bfh('03008000'))
self.assertEqual(add_number_to_script(8388607), bfh('03ffff7f')) self.assertEqual(add_number_to_script(8388607), bfh('03ffff7f'))
self.assertEqual(add_number_to_script(-2147483647), bfh('04ffffffff')) 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(8388608), bfh('0400008000'))
self.assertEqual(add_number_to_script(2147483647), bfh('04ffffff7f')) 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)) cmds._run('getprivatekeys', ("bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw",), wallet=wallet))
# list of addresses tests # list of addresses tests
with self.assertRaises(Exception): with self.assertRaises(Exception):
cmds._run('getprivatekeys', (['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'asd'], ), wallet=wallet) cmds._run('getprivatekeys', (['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'asd'],), wallet=wallet)
self.assertEqual(['p2wpkh:L4jkdiXszG26SUYvwwJhzGwg37H2nLhrbip7u6crmgNeJysv5FHL', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'], 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') @mock.patch.object(wallet.Abstract_Wallet, 'save_db')
def test_export_private_key_deterministic(self, mock_save_db): def test_export_private_key_deterministic(self, mock_save_db):
@ -125,7 +125,7 @@ class TestCommands(ElectrumTestCase):
with self.assertRaises(Exception): with self.assertRaises(Exception):
cmds._run('getprivatekeys', (['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'asd'],), wallet=wallet) cmds._run('getprivatekeys', (['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'asd'],), wallet=wallet)
self.assertEqual(['p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'], self.assertEqual(['p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'],
cmds._run('getprivatekeys', (['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'], ), wallet=wallet)) cmds._run('getprivatekeys', (['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'],), wallet=wallet))
class TestCommandsTestnet(TestCaseForTestnet): 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) 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) 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) 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) ] alice_raw = [bip32("m/" + str(i)) for i in range(5)]
bob_raw = [ bip32("m/" + str(i)) for i in range(5,11) ] 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] 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] 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] alice_pubkeys = [lnutil.OnlyPubkeyKeypair(x.pubkey) for x in alice_privkeys]
@ -853,13 +853,13 @@ class TestDust(ElectrumTestCase):
'timestamp' : 0, '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 aliceHtlcIndex = alice_channel.add_htlc(htlc).htlc_id
bobHtlcIndex = bob_channel.receive_htlc(htlc).htlc_id bobHtlcIndex = bob_channel.receive_htlc(htlc).htlc_id
force_state_transition(alice_channel, bob_channel) force_state_transition(alice_channel, bob_channel)
alice_ctx = alice_channel.get_latest_commitment(LOCAL) alice_ctx = alice_channel.get_latest_commitment(LOCAL)
bob_ctx = bob_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.assertNotEqual(old_values, new_values)
self.assertEqual(len(alice_ctx.outputs()), 3) self.assertEqual(len(alice_ctx.outputs()), 3)
self.assertEqual(len(bob_ctx.outputs()), 2) self.assertEqual(len(bob_ctx.outputs()), 2)

2
electrum/tests/test_transaction.py

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

2
electrum/tests/test_wallet_vertical.py

@ -1716,7 +1716,7 @@ class TestWalletSending(TestCaseForTestnet):
else: else:
raise Exception("unexpected txid") raise Exception("unexpected txid")
privkeys = ['93NQ7CFbwTPyKDJLXe97jczw33fiLijam2SCZL3Uinz1NSbHrTu', ] privkeys = ['93NQ7CFbwTPyKDJLXe97jczw33fiLijam2SCZL3Uinz1NSbHrTu',]
network = NetworkMock() network = NetworkMock()
dest_addr = 'tb1q3ws2p0qjk5vrravv065xqlnkckvzcpclk79eu2' dest_addr = 'tb1q3ws2p0qjk5vrravv065xqlnkckvzcpclk79eu2'
sweep_coro = sweep(privkeys, network=network, config=self.config, to_address=dest_addr, fee=5000, locktime=1325785, tx_version=1) 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(): def hardcoded_trampoline_nodes():
if constants.net in (constants.BitcoinMainnet, ): if constants.net in (constants.BitcoinMainnet,):
return TRAMPOLINE_NODES_MAINNET return TRAMPOLINE_NODES_MAINNET
if constants.net in (constants.BitcoinTestnet, ): if constants.net in (constants.BitcoinTestnet,):
return TRAMPOLINE_NODES_TESTNET return TRAMPOLINE_NODES_TESTNET
return {} return {}

2
electrum/transaction.py

@ -642,7 +642,7 @@ class Transaction:
# We assume low S (as that is a bitcoin standardness rule). # 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, # 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. # 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: else:
pk_list = [pubkey.hex() for pubkey in txin.pubkeys] pk_list = [pubkey.hex() for pubkey in txin.pubkeys]
sig_list = [txin.part_sigs.get(pubkey, b'').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) m = re.match(r'([0-9.]+)X([0-9])', am)
if m: if m:
k = int(m.group(2)) - 8 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: else:
amount = Decimal(am) * COIN amount = Decimal(am) * COIN
out['amount'] = int(amount) out['amount'] = int(amount)

2
electrum/wallet_db.py

@ -528,7 +528,7 @@ class WalletDB(JsonDB):
r['buckets'] = d r['buckets'] = d
c['revocation_store'] = r c['revocation_store'] = r
# convert channels to dict # 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 # convert txi & txo
txi = self.get('txi', {}) txi = self.get('txi', {})
for tx_hash, d in list(txi.items()): 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 use_encryption = True
# commands needing password # 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 (cmdname == 'load_wallet' and storage.is_encrypted())\
or (cmd.requires_password and use_encryption)): or (cmd.requires_password and use_encryption)):
if storage.is_encrypted_with_hw_device(): if storage.is_encrypted_with_hw_device():

Loading…
Cancel
Save