Browse Source

Merge pull request #8337 from SomberNight/202304_flake8_bugbear

CI: flake8-bugbear
master
ghost43 3 years ago committed by GitHub
parent
commit
8ef395f4f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 11
      .cirrus.yml
  2. 2
      electrum/base_crash_reporter.py
  3. 2
      electrum/base_wizard.py
  4. 6
      electrum/bip32.py
  5. 16
      electrum/blockchain.py
  6. 2
      electrum/channel_db.py
  7. 6
      electrum/coinchooser.py
  8. 6
      electrum/commands.py
  9. 2
      electrum/constants.py
  10. 2
      electrum/contacts.py
  11. 6
      electrum/crypto.py
  12. 5
      electrum/daemon.py
  13. 2
      electrum/ecc.py
  14. 6
      electrum/exchange_rate.py
  15. 6
      electrum/gui/kivy/i18n.py
  16. 8
      electrum/gui/kivy/main_window.py
  17. 2
      electrum/gui/kivy/uix/dialogs/amount_dialog.py
  18. 4
      electrum/gui/kivy/uix/dialogs/installwizard.py
  19. 4
      electrum/gui/kivy/uix/screens.py
  20. 2
      electrum/gui/qml/qeapp.py
  21. 2
      electrum/gui/qml/qebitcoin.py
  22. 2
      electrum/gui/qml/qeconfig.py
  23. 8
      electrum/gui/qml/qefx.py
  24. 2
      electrum/gui/qml/qeinvoice.py
  25. 4
      electrum/gui/qml/qetxdetails.py
  26. 2
      electrum/gui/qml/qewallet.py
  27. 4
      electrum/gui/qt/amountedit.py
  28. 6
      electrum/gui/qt/history_list.py
  29. 8
      electrum/gui/qt/locktimeedit.py
  30. 12
      electrum/gui/qt/main_window.py
  31. 2
      electrum/gui/qt/my_treeview.py
  32. 2
      electrum/gui/qt/settings_dialog.py
  33. 2
      electrum/gui/qt/util.py
  34. 6
      electrum/gui/text.py
  35. 4
      electrum/interface.py
  36. 2
      electrum/json_db.py
  37. 4
      electrum/keystore.py
  38. 16
      electrum/lnpeer.py
  39. 4
      electrum/lnutil.py
  40. 6
      electrum/lnworker.py
  41. 12
      electrum/network.py
  42. 4
      electrum/paymentrequest.py
  43. 8
      electrum/plugins/bitbox02/bitbox02.py
  44. 4
      electrum/plugins/coldcard/coldcard.py
  45. 2
      electrum/plugins/digitalbitbox/digitalbitbox.py
  46. 2
      electrum/plugins/jade/jade.py
  47. 2
      electrum/plugins/keepkey/qt.py
  48. 6
      electrum/plugins/labels/labels.py
  49. 4
      electrum/plugins/ledger/ledger.py
  50. 2
      electrum/plugins/revealer/revealer.py
  51. 6
      electrum/plugins/trustedcoin/trustedcoin.py
  52. 2
      electrum/ripemd.py
  53. 2
      electrum/scripts/txbroadcast.py
  54. 2
      electrum/scripts/txradar.py
  55. 4
      electrum/simple_config.py
  56. 2
      electrum/storage.py
  57. 2
      electrum/submarine_swaps.py
  58. 16
      electrum/tests/test_blockchain.py
  59. 13
      electrum/tests/test_commands.py
  60. 6
      electrum/transaction.py
  61. 8
      electrum/util.py
  62. 2
      electrum/verifier.py
  63. 18
      electrum/wallet.py
  64. 4
      electrum/wallet_db.py

11
.cirrus.yml

@ -132,9 +132,9 @@ task:
folder: ~/.cache/pip
fingerprint_script: echo Flake8 && echo $ELECTRUM_IMAGE && cat $ELECTRUM_REQUIREMENTS
install_script:
- pip install flake8
- pip install flake8 flake8-bugbear
flake8_script:
- flake8 . --count --select=$ELECTRUM_LINTERS --show-source --statistics --exclude "*_pb2.py"
- flake8 . --count --select="$ELECTRUM_LINTERS" --ignore="$ELECTRUM_LINTERS_IGNORE" --show-source --statistics --exclude "*_pb2.py,electrum/_vendor/"
env:
ELECTRUM_IMAGE: python:3.8
ELECTRUM_REQUIREMENTS: contrib/requirements/requirements.txt
@ -144,10 +144,13 @@ task:
# list of error codes:
# - https://flake8.pycqa.org/en/latest/user/error-codes.html
# - https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes
ELECTRUM_LINTERS: E9,E101,E129,E273,E274,E703,E71,F63,F7,F82,W191,W29
# - https://github.com/PyCQA/flake8-bugbear/tree/8c0e7eb04217494d48d0ab093bf5b31db0921989#list-of-warnings
ELECTRUM_LINTERS: E9,E101,E129,E273,E274,E703,E71,F63,F7,F82,W191,W29,B
ELECTRUM_LINTERS_IGNORE: B007,B009,B010,B019
- name: Flake8 Non-Mandatory
env:
ELECTRUM_LINTERS: E,F,W,C90
ELECTRUM_LINTERS: E,F,W,C90,B
ELECTRUM_LINTERS_IGNORE: ""
allow_failures: true
task:

2
electrum/base_crash_reporter.py

@ -130,7 +130,7 @@ class BaseCrashReporter(Logger):
}
try:
args["wallet_type"] = self.get_wallet_type()
except:
except Exception:
# Maybe the wallet isn't loaded yet
pass
return args

2
electrum/base_wizard.py

@ -351,7 +351,7 @@ class BaseWizard(Logger):
state = _("initialized") if info.initialized else _("wiped")
label = info.label or _("An unnamed {}").format(name)
try: transport_str = info.device.transport_ui_string[:20]
except: transport_str = 'unknown transport'
except Exception: transport_str = 'unknown transport'
descr = f"{label} [{info.model_name or name}, {state}, {transport_str}]"
choices.append(((name, info), descr))
msg = _('Select a device') + ':'

6
electrum/bip32.py

@ -297,7 +297,7 @@ def is_xpub(text):
try:
node = BIP32Node.from_xkey(text)
return not node.is_private()
except:
except Exception:
return False
@ -305,7 +305,7 @@ def is_xprv(text):
try:
node = BIP32Node.from_xkey(text)
return node.is_private()
except:
except Exception:
return False
@ -374,7 +374,7 @@ def is_bip32_derivation(s: str) -> bool:
if not (s == 'm' or s.startswith('m/')):
return False
convert_bip32_strpath_to_intpath(s)
except:
except Exception:
return False
else:
return True

16
electrum/blockchain.py

@ -296,17 +296,17 @@ class Blockchain(Logger):
def verify_header(cls, header: dict, prev_hash: str, target: int, expected_header_hash: str=None) -> None:
_hash = hash_header(header)
if expected_header_hash and expected_header_hash != _hash:
raise Exception("hash mismatches with expected: {} vs {}".format(expected_header_hash, _hash))
raise InvalidHeader("hash mismatches with expected: {} vs {}".format(expected_header_hash, _hash))
if prev_hash != header.get('prev_block_hash'):
raise Exception("prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash')))
raise InvalidHeader("prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash')))
if constants.net.TESTNET:
return
bits = cls.target_to_bits(target)
if bits != header.get('bits'):
raise Exception("bits mismatch: %s vs %s" % (bits, header.get('bits')))
raise InvalidHeader("bits mismatch: %s vs %s" % (bits, header.get('bits')))
block_hash_as_num = int.from_bytes(bfh(_hash), byteorder='big')
if block_hash_as_num > target:
raise Exception(f"insufficient proof of work: {block_hash_as_num} vs target {target}")
raise InvalidHeader(f"insufficient proof of work: {block_hash_as_num} vs target {target}")
def verify_chunk(self, index: int, data: bytes) -> None:
num = len(data) // HEADER_SIZE
@ -544,7 +544,7 @@ class Blockchain(Logger):
def bits_to_target(cls, bits: int) -> int:
# arith_uint256::SetCompact in Bitcoin Core
if not (0 <= bits < (1 << 32)):
raise Exception(f"bits should be uint32. got {bits!r}")
raise InvalidHeader(f"bits should be uint32. got {bits!r}")
bitsN = (bits >> 24) & 0xff
bitsBase = bits & 0x7fffff
if bitsN <= 3:
@ -553,12 +553,12 @@ class Blockchain(Logger):
target = bitsBase << (8 * (bitsN-3))
if target != 0 and bits & 0x800000 != 0:
# Bit number 24 (0x800000) represents the sign of N
raise Exception("target cannot be negative")
raise InvalidHeader("target cannot be negative")
if (target != 0 and
(bitsN > 34 or
(bitsN > 33 and bitsBase > 0xff) or
(bitsN > 32 and bitsBase > 0xffff))):
raise Exception("target has overflown")
raise InvalidHeader("target has overflown")
return target
@classmethod
@ -622,7 +622,7 @@ class Blockchain(Logger):
return hash_header(header) == constants.net.GENESIS
try:
prev_hash = self.get_hash(height - 1)
except:
except Exception:
return False
if prev_hash != header.get('prev_block_hash'):
return False

2
electrum/channel_db.py

@ -175,7 +175,7 @@ class NodeInfo(NamedTuple):
alias = payload['alias'].rstrip(b'\x00')
try:
alias = alias.decode('utf8')
except:
except Exception:
alias = ''
timestamp = payload['timestamp']
node_info = NodeInfo(node_id=node_id, features=features, timestamp=timestamp, alias=alias)

6
electrum/coinchooser.py

@ -410,7 +410,11 @@ class CoinChooserRandom(CoinChooserBase):
for bkts_choose_from in bucket_sets:
try:
def sfunds(bkts, *, bucket_value_sum):
def sfunds(
bkts, *, bucket_value_sum,
already_selected_buckets_value_sum=already_selected_buckets_value_sum,
already_selected_buckets=already_selected_buckets,
):
bucket_value_sum += already_selected_buckets_value_sum
return sufficient_funds(already_selected_buckets + bkts,
bucket_value_sum=bucket_value_sum)

6
electrum/commands.py

@ -313,7 +313,7 @@ class Commands:
# call literal_eval for backward compatibility (see #4225)
try:
value = ast.literal_eval(value)
except:
except Exception:
pass
return value
@ -631,7 +631,7 @@ class Commands:
"""Convert xtype of a master key. e.g. xpub -> ypub"""
try:
node = BIP32Node.from_xkey(xkey)
except:
except Exception:
raise Exception('xkey should be a master public/private key')
return node._replace(xtype=xtype).to_xkey()
@ -1376,7 +1376,7 @@ def eval_bool(x: str) -> bool:
if x == 'true': return True
try:
return bool(ast.literal_eval(x))
except:
except Exception:
return bool(x)
param_descriptions = {

2
electrum/constants.py

@ -35,7 +35,7 @@ def read_json(filename, default):
try:
with open(path, 'r') as f:
r = json.loads(f.read())
except:
except Exception:
r = default
return r

2
electrum/contacts.py

@ -41,7 +41,7 @@ class Contacts(dict, Logger):
d = self.db.get('contacts', {})
try:
self.update(d)
except:
except Exception:
return
# backward compatibility
for k, v in self.items():

6
electrum/crypto.py

@ -42,7 +42,7 @@ _logger = get_logger(__name__)
HAS_PYAES = False
try:
import pyaes
except:
except Exception:
pass
else:
HAS_PYAES = True
@ -57,7 +57,7 @@ try:
from Cryptodome.Cipher import ChaCha20_Poly1305 as CD_ChaCha20_Poly1305
from Cryptodome.Cipher import ChaCha20 as CD_ChaCha20
from Cryptodome.Cipher import AES as CD_AES
except:
except Exception:
pass
else:
HAS_CRYPTODOME = True
@ -75,7 +75,7 @@ try:
from cryptography.hazmat.primitives.ciphers import modes as CG_modes
from cryptography.hazmat.backends import default_backend as CG_default_backend
import cryptography.hazmat.primitives.ciphers.aead as CG_aead
except:
except Exception:
pass
else:
HAS_CRYPTOGRAPHY = True

5
electrum/daemon.py

@ -110,6 +110,7 @@ def request(config: SimpleConfig, endpoint, args=(), timeout=60):
lockfile = get_lockfile(config)
while True:
create_time = None
path = None
try:
with open(lockfile) as f:
socktype, address, create_time = ast.literal_eval(f.read())
@ -127,7 +128,9 @@ def request(config: SimpleConfig, endpoint, args=(), timeout=60):
server_url = 'http://%s:%d' % (host, port)
auth = aiohttp.BasicAuth(login=rpc_user, password=rpc_password)
loop = util.get_asyncio_loop()
async def request_coroutine():
async def request_coroutine(
*, socktype=socktype, path=path, auth=auth, server_url=server_url, endpoint=endpoint,
):
if socktype == 'unix':
connector = aiohttp.UnixConnector(path=path)
elif socktype == 'tcp':

2
electrum/ecc.py

@ -370,7 +370,7 @@ class ECPubkey(object):
try:
ECPubkey(b)
return True
except:
except Exception:
return False

6
electrum/exchange_rate.py

@ -104,7 +104,7 @@ class ExchangeBase(Logger):
try:
with open(filename, 'r', encoding='utf-8') as f:
h = json.loads(f.read())
except:
except Exception:
return None
if not h: # e.g. empty dict
return None
@ -469,7 +469,7 @@ def get_exchanges_and_currencies():
try:
with open(path, 'r', encoding='utf-8') as f:
return json.loads(f.read())
except:
except Exception:
pass
# or if not present, generate it now.
print("cannot find currencies.json. will regenerate it now.")
@ -483,7 +483,7 @@ def get_exchanges_and_currencies():
try:
d[name] = await exchange.get_currencies()
print(name, "ok")
except:
except Exception:
print(name, "error")
async def query_all_exchanges_for_their_ccys_over_network():

6
electrum/gui/kivy/i18n.py

@ -22,14 +22,14 @@ class _(str):
def bind(label):
try:
_.observers.add(label)
except:
except Exception:
pass
# garbage collection
new = set()
for label in _.observers:
try:
new.add(label)
except:
except Exception:
pass
_.observers = new
@ -42,7 +42,7 @@ class _(str):
for label in _.observers:
try:
label.text = _(label.text.source_text)
except:
except Exception:
pass
# Note that all invocations of _() inside the core electrum library
# use electrum.i18n instead of electrum.gui.kivy.i18n, so we should update the

8
electrum/gui/kivy/main_window.py

@ -358,7 +358,7 @@ class ElectrumWindow(App, Logger, EventListener):
assert u == self.base_unit
try:
x = Decimal(a)
except:
except Exception:
return None
p = pow(10, self.decimal_point())
return int(p * x)
@ -487,7 +487,7 @@ class ElectrumWindow(App, Logger, EventListener):
from electrum.transaction import tx_from_any
try:
tx = tx_from_any(data)
except:
except Exception:
tx = None
if tx:
self.tx_dialog(tx)
@ -1119,7 +1119,7 @@ class ElectrumWindow(App, Logger, EventListener):
arrow_pos=arrow_pos)
@scheduled_in_gui_thread
def show_info_bubble(self, text=_('Hello World'), pos=None, duration=0,
def show_info_bubble(self, text=None, pos=None, duration=0,
arrow_pos='bottom_mid', width=None, icon='', modal=False, exit=False):
'''Method to show an Information Bubble
@ -1130,6 +1130,8 @@ class ElectrumWindow(App, Logger, EventListener):
width: width of the Bubble
arrow_pos: arrow position for the bubble
'''
if text is None:
text = _('Hello World')
text = str(text) # so that we also handle e.g. Exception
info_bubble = self.info_bubble
if not info_bubble:

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

@ -145,7 +145,7 @@ class AmountDialog(Factory.Popup):
try:
Decimal(amount+c)
amount += c
except:
except Exception:
pass
# truncate btc amounts to max precision:
if not kb.is_fiat and '.' in amount:

4
electrum/gui/kivy/uix/dialogs/installwizard.py

@ -665,7 +665,7 @@ class WizardOTPDialogBase(WizardDialog):
return
try:
return int(otp)
except:
except Exception:
return
def on_text(self, dt):
@ -1037,7 +1037,7 @@ class AddXpubDialog(WizardDialog):
def is_valid(x):
try:
return kwargs['is_valid'](x)
except:
except Exception:
return False
self.is_valid = is_valid
self.title = kwargs['title']

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

@ -341,7 +341,7 @@ class SendScreen(CScreen, Logger):
else:
try:
amount_sat = self.app.get_amount(self.amount)
except:
except Exception:
self.app.show_error(_('Invalid amount') + ':\n' + self.amount)
return
message = self.message
@ -384,7 +384,7 @@ class SendScreen(CScreen, Logger):
assert self.lnurl_data
try:
amount = self.app.get_amount(self.amount)
except:
except Exception:
self.app.show_error(_('Invalid amount') + ':\n' + self.amount)
return
if not (self.lnurl_data.min_sendable_sat <= amount <= self.lnurl_data.max_sendable_sat):

2
electrum/gui/qml/qeapp.py

@ -108,7 +108,7 @@ class QEAppController(BaseCrashReporter, QObject):
# connect only once
try:
qewallet.userNotify.disconnect(self.on_wallet_usernotify)
except:
except Exception:
pass
qewallet.userNotify.connect(self.on_wallet_usernotify)

2
electrum/gui/qml/qebitcoin.py

@ -158,7 +158,7 @@ class QEBitcoin(QObject):
try:
tx_from_any(rawtx)
return True
except:
except Exception:
return False
@pyqtSlot(str, result=bool)

2
electrum/gui/qml/qeconfig.py

@ -248,7 +248,7 @@ class QEConfig(AuthMixin, QObject):
self._amount = QEAmount()
try:
x = Decimal(unitAmount)
except:
except Exception:
return self._amount
# scale it to max allowed precision, make it an int

8
electrum/gui/qml/qefx.py

@ -105,7 +105,7 @@ class QEFX(QObject, QtEventListener):
else:
try:
sd = Decimal(satoshis)
except:
except Exception:
return ''
if plain:
return self.fx.ccy_amount_str(self.fx.fiat_value(satoshis, rate), add_thousands_sep=False)
@ -122,14 +122,14 @@ class QEFX(QObject, QtEventListener):
else:
try:
sd = Decimal(satoshis)
except:
except Exception:
return ''
try:
td = Decimal(timestamp)
if td == 0:
return ''
except:
except Exception:
return ''
dt = datetime.fromtimestamp(int(td))
if plain:
@ -143,7 +143,7 @@ class QEFX(QObject, QtEventListener):
rate = self.fx.exchange_rate()
try:
fd = Decimal(fiat)
except:
except Exception:
return ''
v = fd / Decimal(rate) * COIN
if v.is_nan():

2
electrum/gui/qml/qeinvoice.py

@ -617,7 +617,7 @@ class QEInvoiceParser(QEInvoice):
try:
assert amount >= self.lnurlData['min_sendable_sat']
assert amount <= self.lnurlData['max_sendable_sat']
except:
except Exception:
self.lnurlError.emit('amount', _('Amount out of bounds'))
return

4
electrum/gui/qml/qetxdetails.py

@ -323,7 +323,7 @@ class QETxDetails(QObject, QtEventListener):
if broadcast:
self._wallet.broadcastSucceeded.disconnect(self.onBroadcastSucceeded)
self._wallet.broadcastfailed.disconnect(self.onBroadcastFailed)
except:
except Exception:
pass
if broadcast:
@ -344,7 +344,7 @@ class QETxDetails(QObject, QtEventListener):
try:
self._wallet.broadcastfailed.disconnect(self.onBroadcastFailed)
except:
except Exception:
pass
self._wallet.broadcastFailed.connect(self.onBroadcastFailed)

2
electrum/gui/qml/qewallet.py

@ -739,7 +739,7 @@ class QEWallet(AuthMixin, QObject, QtEventListener):
try:
self._seed = self.wallet.get_seed(self.password)
self.seedRetrieved.emit()
except:
except Exception:
self._seed = ''
self.dataChanged.emit()

4
electrum/gui/qt/amountedit.py

@ -97,7 +97,7 @@ class AmountEdit(SizedFreezableLineEdit):
try:
text = text.replace(DECIMAL_POINT, '.')
return (int if self.is_int else Decimal)(text)
except:
except Exception:
return None
def get_amount(self) -> Union[None, Decimal, int]:
@ -130,7 +130,7 @@ class BTCAmountEdit(AmountEdit):
try:
text = text.replace(DECIMAL_POINT, '.')
x = Decimal(text)
except:
except Exception:
return None
# scale it to max allowed precision, make it an int
power = pow(10, self.max_precision())

6
electrum/gui/qt/history_list.py

@ -92,7 +92,7 @@ class HistorySortModel(QSortFilterProxyModel):
if v2 is None or isinstance(v2, Decimal) and v2.is_nan(): v2 = -float("inf")
try:
return v1 < v2
except:
except Exception:
return False
def get_item_key(tx_item):
@ -538,7 +538,7 @@ class HistoryList(MyTreeView, AcceptFileDragDrop):
else:
try:
year = int(s)
except:
except Exception:
return
self.start_date = datetime.datetime(year, 1, 1)
self.end_date = datetime.datetime(year+1, 1, 1)
@ -709,7 +709,7 @@ class HistoryList(MyTreeView, AcceptFileDragDrop):
if value is not None:
self.hm.update_fiat(index)
else:
assert False
raise Exception(f"did not expect {column=!r} to get edited")
def on_double_click(self, idx):
tx_item = idx.internalPointer().get_data()

8
electrum/gui/qt/locktimeedit.py

@ -93,7 +93,7 @@ class _LockTimeEditor:
return True
try:
x = int(x)
except:
except Exception:
return False
return cls.min_allowed_value <= x <= cls.max_allowed_value
@ -120,13 +120,13 @@ class LockTimeRawEdit(QLineEdit, _LockTimeEditor):
def get_locktime(self) -> Optional[int]:
try:
return int(str(self.text()))
except:
except Exception:
return None
def set_locktime(self, x: Any) -> None:
try:
x = int(x)
except:
except Exception:
self.setText('')
return
x = max(x, self.min_allowed_value)
@ -185,7 +185,7 @@ class LockTimeDateEdit(QDateTimeEdit, _LockTimeEditor):
return
try:
x = int(x)
except:
except Exception:
self.setDateTime(QDateTime.currentDateTime())
return
dt = datetime.fromtimestamp(x)

12
electrum/gui/qt/main_window.py

@ -515,7 +515,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger, QtEventListener):
screen = self.app.desktop().screenGeometry()
assert screen.contains(QRect(*winpos))
self.setGeometry(*winpos)
except:
except Exception:
self.logger.info("using default geometry")
self.setGeometry(100, 100, 840, 400)
@ -631,7 +631,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger, QtEventListener):
recent = self.config.get('recently_open', [])
try:
sorted(recent)
except:
except Exception:
recent = []
if filename in recent:
recent.remove(filename)
@ -1294,8 +1294,10 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger, QtEventListener):
else:
self.show_message(message)
def query_choice(self, msg, choices, title=_('Question'), default_choice=None):
def query_choice(self, msg, choices, title=None, default_choice=None):
# Needed by QtHandler for hardware wallets
if title is None:
title = _('Question')
dialog = WindowModalDialog(self.top_level_window(), title=title)
dialog.setMinimumWidth(400)
clayout = ChoicesLayout(msg, choices, checked_index=default_choice)
@ -1918,10 +1920,12 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger, QtEventListener):
d = SeedDialog(self, seed, passphrase, config=self.config)
d.exec_()
def show_qrcode(self, data, title = _("QR code"), parent=None, *,
def show_qrcode(self, data, title=None, parent=None, *,
help_text=None, show_copy_text_btn=False):
if not data:
return
if title is None:
title = _("QR code")
d = QRDialog(
data=data,
parent=parent or self,

2
electrum/gui/qt/my_treeview.py

@ -125,7 +125,7 @@ class MySortModel(QSortFilterProxyModel):
v2 = item2.text()
try:
return Decimal(v1) < Decimal(v2)
except:
except Exception:
return v1 < v2
class ElectrumItemDelegate(QStyledItemDelegate):

2
electrum/gui/qt/settings_dialog.py

@ -287,7 +287,7 @@ class SettingsDialog(QDialog, QtEventListener):
val = block_ex_custom_e.text()
try:
val = ast.literal_eval(val) # to also accept tuples
except:
except Exception:
pass
self.config.set_key('block_explorer_custom', val)
block_ex_custom_e.editingFinished.connect(on_be_edit)

2
electrum/gui/qt/util.py

@ -727,7 +727,7 @@ class OverlayControlMixin(GenericInputHandler):
from .qrcodewidget import QRDialog
try:
s = str(self.text())
except:
except Exception:
s = self.text()
if not s:
return

6
electrum/gui/text.py

@ -35,14 +35,14 @@ _ = lambda x:x # i18n
def parse_bip21(text):
try:
return util.parse_URI(text)
except:
except Exception:
return
def parse_bolt11(text):
from electrum.lnaddr import lndecode
try:
return lndecode(text)
except:
except Exception:
return
@ -594,7 +594,7 @@ class ElectrumGui(BaseElectrumGui, EventListener):
def parse_amount(self, text):
try:
x = Decimal(text)
except:
except Exception:
return None
power = pow(10, self.config.get_decimal_point())
return int(power * x)

4
electrum/interface.py

@ -1153,14 +1153,14 @@ def check_cert(host, cert):
try:
b = pem.dePem(cert, 'CERTIFICATE')
x = x509.X509(b)
except:
except Exception:
traceback.print_exc(file=sys.stdout)
return
try:
x.check_date()
expired = False
except:
except Exception:
expired = True
m = "host: %s\n"%host

2
electrum/json_db.py

@ -155,7 +155,7 @@ class JsonDB(Logger):
try:
json.dumps(key, cls=JsonDBJsonEncoder)
json.dumps(value, cls=JsonDBJsonEncoder)
except:
except Exception:
self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})")
return False
if value is not None:

4
electrum/keystore.py

@ -1084,13 +1084,13 @@ def load_keystore(db: 'WalletDB', name: str) -> KeyStore:
def is_old_mpk(mpk: str) -> bool:
try:
int(mpk, 16) # test if hex string
except:
except Exception:
return False
if len(mpk) != 128:
return False
try:
ecc.ECPubkey(bfh('04' + mpk))
except:
except Exception:
return False
return True

16
electrum/lnpeer.py

@ -602,7 +602,7 @@ class Peer(Logger):
try:
if self.transport:
self.transport.close()
except:
except Exception:
pass
self.lnworker.peer_closed(self)
self.got_disconnected.set()
@ -1594,7 +1594,7 @@ class Peer(Logger):
raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'')
try:
next_chan_scid = processed_onion.hop_data.payload["short_channel_id"]["short_channel_id"]
except:
except Exception:
raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00')
next_chan = self.lnworker.get_channel_by_short_id(next_chan_scid)
local_height = chain.height()
@ -1610,14 +1610,14 @@ class Peer(Logger):
raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message)
try:
next_amount_msat_htlc = processed_onion.hop_data.payload["amt_to_forward"]["amt_to_forward"]
except:
except Exception:
raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00')
if not next_chan.can_pay(next_amount_msat_htlc):
self.logger.info(f"cannot forward htlc due to transient errors (likely due to insufficient funds)")
raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message)
try:
next_cltv_expiry = processed_onion.hop_data.payload["outgoing_cltv_value"]["outgoing_cltv_value"]
except:
except Exception:
raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00')
if htlc.cltv_expiry - next_cltv_expiry < next_chan.forwarding_cltv_expiry_delta:
data = htlc.cltv_expiry.to_bytes(4, byteorder="big") + outgoing_chan_upd_message
@ -1746,7 +1746,7 @@ class Peer(Logger):
try:
amt_to_forward = processed_onion.hop_data.payload["amt_to_forward"]["amt_to_forward"]
except:
except Exception:
log_fail_reason(f"'amt_to_forward' missing from onion")
raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00')
@ -1766,7 +1766,7 @@ class Peer(Logger):
raise exc_incorrect_or_unknown_pd
try:
cltv_from_onion = processed_onion.hop_data.payload["outgoing_cltv_value"]["outgoing_cltv_value"]
except:
except Exception:
log_fail_reason(f"'outgoing_cltv_value' missing from onion")
raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00')
@ -1778,7 +1778,7 @@ class Peer(Logger):
data=htlc.cltv_expiry.to_bytes(4, byteorder="big"))
try:
total_msat = processed_onion.hop_data.payload["payment_data"]["total_msat"]
except:
except Exception:
total_msat = amt_to_forward # fall back to "amt_to_forward"
if not is_trampoline and amt_to_forward != htlc.amount_msat:
@ -1789,7 +1789,7 @@ class Peer(Logger):
try:
payment_secret_from_onion = processed_onion.hop_data.payload["payment_data"]["payment_secret"]
except:
except Exception:
if total_msat > amt_to_forward:
# payment_secret is required for MPP
log_fail_reason(f"'payment_secret' missing from onion")

4
electrum/lnutil.py

@ -1470,7 +1470,7 @@ def extract_nodeid(connect_contents: str) -> Tuple[bytes, Optional[str]]:
invoice = lndecode(connect_contents)
nodeid_bytes = invoice.pubkey.serialize()
nodeid_hex = nodeid_bytes.hex()
except:
except Exception:
# node id as hex?
nodeid_hex = connect_contents
if rest == '':
@ -1479,7 +1479,7 @@ def extract_nodeid(connect_contents: str) -> Tuple[bytes, Optional[str]]:
node_id = bfh(nodeid_hex)
if len(node_id) != 33:
raise Exception()
except:
except Exception:
raise ConnStringFormatError(_('Invalid node ID, must be 33 bytes and hexadecimal'))
return node_id, rest

6
electrum/lnworker.py

@ -1072,7 +1072,7 @@ class LNWallet(LNWorker):
self.wallet.set_reserved_state_of_address(addr, reserved=True)
try:
self.save_channel(chan)
except:
except Exception:
chan.set_state(ChannelState.REDEEMED)
self.remove_channel(chan.channel_id)
raise
@ -1516,13 +1516,13 @@ class LNWallet(LNWorker):
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_typed
return payload
except: # FIXME: too broad
except Exception: # FIXME: too broad
try:
message_type, payload = decode_msg(channel_update_as_received)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_as_received
return payload
except:
except Exception:
return None
@staticmethod

12
electrum/network.py

@ -403,7 +403,7 @@ class Network(Logger, NetworkRetryManager[ServerAddr]):
data = f.read()
servers_list = json.loads(data)
return [ServerAddr.from_str(s) for s in servers_list]
except:
except Exception:
return []
@with_recent_servers_lock
@ -415,7 +415,7 @@ class Network(Logger, NetworkRetryManager[ServerAddr]):
try:
with open(path, "w", encoding='utf-8') as f:
f.write(s)
except:
except Exception:
pass
async def _server_is_lagging(self) -> bool:
@ -516,7 +516,7 @@ class Network(Logger, NetworkRetryManager[ServerAddr]):
for n in FEE_ETA_TARGETS:
try:
out[n] = int(median(filter(None, [i.fee_estimates_eta.get(n) for i in self.interfaces.values()])))
except:
except Exception:
continue
return out
else:
@ -595,7 +595,7 @@ class Network(Logger, NetworkRetryManager[ServerAddr]):
if server:
try:
self.default_server = ServerAddr.from_str(server)
except:
except Exception:
self.logger.warning(f'failed to parse server-string ({server!r}); falling back to localhost:1:s.')
self.default_server = ServerAddr.from_str("localhost:1:s")
else:
@ -626,7 +626,7 @@ class Network(Logger, NetworkRetryManager[ServerAddr]):
if proxy:
proxy_modes.index(proxy['mode']) + 1
int(proxy['port'])
except:
except Exception:
return
self.config.set_key('auto_connect', net_params.auto_connect, False)
self.config.set_key('oneserver', net_params.oneserver, False)
@ -1362,7 +1362,7 @@ class Network(Logger, NetworkRetryManager[ServerAddr]):
async with session.post(url, json=json, headers=headers) as resp:
return await on_finish(resp)
else:
assert False
raise Exception(f"unexpected {method=!r}")
@classmethod
def send_http_on_proxy(cls, method, url, **kwargs):

4
electrum/paymentrequest.py

@ -126,7 +126,7 @@ class PaymentRequest:
try:
self.data = pb2.PaymentRequest()
self.data.ParseFromString(r)
except:
except Exception:
self.error = "cannot parse payment request"
return
self.details = pb2.PaymentDetails()
@ -157,7 +157,7 @@ class PaymentRequest:
pr = pb2.PaymentRequest()
try:
pr.ParseFromString(self.raw)
except:
except Exception:
self.error = "Error: Cannot parse payment request"
return False
if not pr.signature:

8
electrum/plugins/bitbox02/bitbox02.py

@ -79,7 +79,7 @@ class BitBox02Client(HardwareClientBase):
def close(self):
try:
self.bitbox02_device.close()
except:
except Exception:
pass
def has_usable_connection_with_device(self) -> bool:
@ -104,7 +104,7 @@ class BitBox02Client(HardwareClientBase):
self.handler.show_message(msg)
try:
res = device_response()
except:
except Exception:
# Close the hid device on exception
hid_device.close()
raise
@ -327,7 +327,7 @@ class BitBox02Client(HardwareClientBase):
)
except bitbox02.DuplicateEntryException:
raise
except:
except Exception:
raise UserFacingException("Failed to register multisig\naccount configuration on BitBox02")
return multisig_config
@ -648,7 +648,7 @@ class BitBox02Plugin(HW_PluginBase):
try:
from bitbox02 import bitbox02
version = bitbox02.__version__
except:
except Exception:
version = "unknown"
if requirements_ok:
return version

4
electrum/plugins/coldcard/coldcard.py

@ -160,7 +160,7 @@ class CKCCClient(HardwareClientBase):
try:
self.ping_check()
return True
except:
except Exception:
return False
@runs_in_hwd_thread
@ -187,7 +187,7 @@ class CKCCClient(HardwareClientBase):
try:
echo = self.dev.send_recv(CCProtocolPacker.ping(req))
assert echo == req
except:
except Exception:
raise RuntimeError("Communication trouble with Coldcard")
@runs_in_hwd_thread

2
electrum/plugins/digitalbitbox/digitalbitbox.py

@ -81,7 +81,7 @@ class DigitalBitbox_Client(HardwareClientBase):
if self.opened:
try:
self.dbb_hid.close()
except:
except Exception:
pass
self.opened = False

2
electrum/plugins/jade/jade.py

@ -411,7 +411,7 @@ class JadePlugin(HW_PluginBase):
version = jadepy.__version__
except ImportError:
raise
except:
except Exception:
version = "unknown"
return version

2
electrum/plugins/keepkey/qt.py

@ -201,7 +201,7 @@ class QtPlugin(QtPluginBase):
return
for keystore in wallet.get_keystores():
if type(keystore) == self.keystore_class:
def show_address():
def show_address(keystore=keystore):
keystore.thread.add(partial(self.show_address, wallet, addrs[0], keystore))
device_name = "{} ({})".format(self.device, keystore.label)
menu.addAction(_("Show on {}").format(device_name), show_address)

6
electrum/plugins/labels/labels.py

@ -116,7 +116,7 @@ class LabelsPlugin(BasePlugin):
try:
encoded_key = self.encode(wallet, key)
encoded_value = self.encode(wallet, value)
except:
except Exception:
self.logger.info(f'cannot encode {repr(key)} {repr(value)}')
continue
bundle["labels"].append({'encryptedLabel': encoded_value,
@ -142,12 +142,12 @@ class LabelsPlugin(BasePlugin):
try:
key = self.decode(wallet, label["externalId"])
value = self.decode(wallet, label["encryptedLabel"])
except:
except Exception:
continue
try:
json.dumps(key)
json.dumps(value)
except:
except Exception:
self.logger.info(f'error: no json {key}')
continue
if value:

4
electrum/plugins/ledger/ledger.py

@ -1171,7 +1171,7 @@ class Ledger_Client_New(Ledger_Client):
registered_hmac,
)
else:
def process_origin(origin: KeyOriginInfo) -> None:
def process_origin(origin: KeyOriginInfo, *, script_addrtype=script_addrtype) -> None:
if is_standard_path(origin.path, script_addrtype, get_chain()):
# these policies do not need to be registered
policy = self.get_singlesig_default_wallet_policy(script_addrtype, origin.path[2])
@ -1355,7 +1355,7 @@ class LedgerPlugin(HW_PluginBase):
version = ledger_bitcoin.__version__
except ImportError:
raise
except:
except Exception:
version = "unknown"
if LEDGER_BITCOIN:
return version

2
electrum/plugins/revealer/revealer.py

@ -47,7 +47,7 @@ class RevealerPlugin(BasePlugin):
return None
try:
int(txt, 16)
except:
except Exception:
return None
version = txt[0]
if version not in cls.KNOWN_VERSIONS:

6
electrum/plugins/trustedcoin/trustedcoin.py

@ -133,12 +133,12 @@ class TrustedCoinCosignerClient(Logger):
try:
r = await resp.json()
message = r['message']
except:
except Exception:
message = await resp.text()
raise TrustedCoinException(message, resp.status)
try:
return await resp.json()
except:
except Exception:
return await resp.text()
def send_request(self, method, relative_url, data=None, *, timeout=None):
@ -165,7 +165,7 @@ class TrustedCoinCosignerClient(Logger):
on_finish=self.handle_response,
timeout=timeout)
else:
assert False
raise Exception(f"unexpected {method=!r}")
except TrustedCoinException:
raise
except Exception as e:

2
electrum/ripemd.py

@ -151,7 +151,7 @@ def RMD160Transform(state, block): #uint32 state[5], uchar block[64]
if sys.byteorder == 'little':
x = struct.unpack('<16L', bytes([x for x in block[0:64]]))
else:
raise "Error!!"
raise Exception(f"unsupported {sys.byteorder=!r}")
a = state[0]
b = state[1]
c = state[2]

2
electrum/scripts/txbroadcast.py

@ -12,7 +12,7 @@ from electrum.simple_config import SimpleConfig
try:
rawtx = sys.argv[1]
except:
except Exception:
print("usage: txbroadcast rawtx")
sys.exit(1)

2
electrum/scripts/txradar.py

@ -9,7 +9,7 @@ from electrum.simple_config import SimpleConfig
try:
txid = sys.argv[1]
except:
except Exception:
print("usage: txradar txid")
sys.exit(1)

4
electrum/simple_config.py

@ -165,7 +165,7 @@ class SimpleConfig(Logger):
try:
json.dumps(key)
json.dumps(value)
except:
except Exception:
self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})")
return
self._set_key_in_user_config(key, value, save)
@ -674,7 +674,7 @@ class SimpleConfig(Logger):
if text:
try:
return NetAddress.from_string(text)
except:
except Exception:
pass
def format_amount(

2
electrum/storage.py

@ -142,7 +142,7 @@ class WalletStorage(Logger):
return StorageEncryptionVersion.XPUB_PASSWORD
else:
return StorageEncryptionVersion.PLAINTEXT
except:
except Exception:
return StorageEncryptionVersion.PLAINTEXT
@staticmethod

2
electrum/submarine_swaps.py

@ -501,7 +501,7 @@ class SwapManager(Logger):
limits = pairs['pairs']['BTC/BTC']['limits']
self._min_amount = limits['minimal']
self._max_amount = limits['maximal']
except:
except Exception:
self._min_amount = 10000
self._max_amount = 10000000

16
electrum/tests/test_blockchain.py

@ -4,7 +4,7 @@ import os
from electrum import constants, blockchain
from electrum.simple_config import SimpleConfig
from electrum.blockchain import Blockchain, deserialize_header, hash_header
from electrum.blockchain import Blockchain, deserialize_header, hash_header, InvalidHeader
from electrum.util import bfh, make_dir
from . import ElectrumTestCase
@ -418,11 +418,11 @@ class TestBlockchain(ElectrumTestCase):
# Make sure that we don't generate compacts with the 0x00800000 bit set
self.assertEqual(0x02008000, Blockchain.target_to_bits(0x80))
with self.assertRaises(Exception): # target cannot be negative
with self.assertRaises(InvalidHeader): # target cannot be negative
Blockchain.bits_to_target(0x01fedcba)
with self.assertRaises(Exception): # target cannot be negative
with self.assertRaises(InvalidHeader): # target cannot be negative
Blockchain.bits_to_target(0x04923456)
with self.assertRaises(Exception): # overflow
with self.assertRaises(InvalidHeader): # overflow
Blockchain.bits_to_target(0xff123456)
@ -441,20 +441,20 @@ class TestVerifyHeader(ElectrumTestCase):
Blockchain.verify_header(self.header, self.prev_hash, self.target)
def test_expected_hash_mismatch(self):
with self.assertRaises(Exception):
with self.assertRaises(InvalidHeader):
Blockchain.verify_header(self.header, self.prev_hash, self.target,
expected_header_hash="foo")
def test_prev_hash_mismatch(self):
with self.assertRaises(Exception):
with self.assertRaises(InvalidHeader):
Blockchain.verify_header(self.header, "foo", self.target)
def test_target_mismatch(self):
with self.assertRaises(Exception):
with self.assertRaises(InvalidHeader):
other_target = Blockchain.bits_to_target(0x1d00eeee)
Blockchain.verify_header(self.header, self.prev_hash, other_target)
def test_insufficient_pow(self):
with self.assertRaises(Exception):
with self.assertRaises(InvalidHeader):
self.header["nonce"] = 42
Blockchain.verify_header(self.header, self.prev_hash, self.target)

13
electrum/tests/test_commands.py

@ -8,6 +8,7 @@ from electrum.wallet import restore_wallet_from_text
from electrum.address_synchronizer import TX_HEIGHT_UNCONFIRMED
from electrum.simple_config import SimpleConfig
from electrum.transaction import Transaction, TxOutput, tx_from_any
from electrum.util import UserFacingException
from . import ElectrumTestCase
from .test_wallet_vertical import WalletIntegrityHelper
@ -91,14 +92,14 @@ class TestCommands(ElectrumTestCase):
config=self.config)['wallet']
cmds = Commands(config=self.config)
# single address tests
with self.assertRaises(Exception):
with self.assertRaises(UserFacingException):
await cmds.getprivatekeys("asdasd", wallet=wallet) # invalid addr, though might raise "not in wallet"
with self.assertRaises(Exception):
with self.assertRaises(UserFacingException):
await cmds.getprivatekeys("bc1qgfam82qk7uwh5j2xxmcd8cmklpe0zackyj6r23", wallet=wallet) # not in wallet
self.assertEqual("p2wpkh:L4jkdiXszG26SUYvwwJhzGwg37H2nLhrbip7u6crmgNeJysv5FHL",
await cmds.getprivatekeys("bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw", wallet=wallet))
# list of addresses tests
with self.assertRaises(Exception):
with self.assertRaises(UserFacingException):
await cmds.getprivatekeys(['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'asd'], wallet=wallet)
self.assertEqual(['p2wpkh:L4jkdiXszG26SUYvwwJhzGwg37H2nLhrbip7u6crmgNeJysv5FHL', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'],
await cmds.getprivatekeys(['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'], wallet=wallet))
@ -111,14 +112,14 @@ class TestCommands(ElectrumTestCase):
config=self.config)['wallet']
cmds = Commands(config=self.config)
# single address tests
with self.assertRaises(Exception):
with self.assertRaises(UserFacingException):
await cmds.getprivatekeys("asdasd", wallet=wallet) # invalid addr, though might raise "not in wallet"
with self.assertRaises(Exception):
with self.assertRaises(UserFacingException):
await cmds.getprivatekeys("bc1qgfam82qk7uwh5j2xxmcd8cmklpe0zackyj6r23", wallet=wallet) # not in wallet
self.assertEqual("p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2",
await cmds.getprivatekeys("bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af", wallet=wallet))
# list of addresses tests
with self.assertRaises(Exception):
with self.assertRaises(UserFacingException):
await cmds.getprivatekeys(['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'asd'], wallet=wallet)
self.assertEqual(['p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'],
await cmds.getprivatekeys(['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'], wallet=wallet))

6
electrum/transaction.py

@ -1195,18 +1195,18 @@ def convert_raw_tx_to_hex(raw: Union[str, bytes]) -> str:
# try hex
try:
return binascii.unhexlify(raw).hex()
except:
except Exception:
pass
# try base43
try:
return base_decode(raw, base=43).hex()
except:
except Exception:
pass
# try base64
if raw[0:6] in ('cHNidP', b'cHNidP'): # base64 psbt
try:
return base64.b64decode(raw).hex()
except:
except Exception:
pass
# raw bytes (do not strip whitespaces in this case)
if isinstance(raw_unstripped, bytes):

8
electrum/util.py

@ -432,7 +432,7 @@ def json_encode(obj):
def json_decode(x):
try:
return json.loads(x, parse_float=Decimal)
except:
except Exception:
return x
def json_normalize(x):
@ -562,7 +562,7 @@ def assert_bytes(*args):
try:
for x in args:
assert isinstance(x, (bytes, bytearray))
except:
except Exception:
print('assert bytes failed', list(map(type, args)))
raise
@ -646,7 +646,7 @@ def is_hex_str(text: Any) -> bool:
if not isinstance(text, str): return False
try:
b = bytes.fromhex(text)
except:
except Exception:
return False
# forbid whitespaces in text:
if len(text) != 2 * len(b):
@ -1191,7 +1191,7 @@ def parse_json(message):
return None, message
try:
j = json.loads(message[0:n].decode('utf8'))
except:
except Exception:
j = None
return j, message[n+1:]

2
electrum/verifier.py

@ -169,7 +169,7 @@ class SPV(NetworkJobOnDefaultServer):
tx = Transaction(raw_tx)
try:
tx.deserialize()
except:
except Exception:
pass
else:
raise InnerNodeOfSpvProofIsValidTx()

18
electrum/wallet.py

@ -653,7 +653,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
text_dec = Decimal(text)
text_dec_rounded = Decimal(fx.ccy_amount_str(text_dec, add_thousands_sep=False))
reset = text_dec_rounded == def_fiat_rounded
except:
except Exception:
# garbage. not resetting, but not saving either
return False
if reset:
@ -673,7 +673,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
fiat_value = self.fiat_value.get(ccy, {}).get(txid)
try:
return Decimal(fiat_value)
except:
except Exception:
return
def is_mine(self, address) -> bool:
@ -721,11 +721,11 @@ class Abstract_Wallet(ABC, Logger, EventListener):
def export_private_key(self, address: str, password: Optional[str]) -> str:
if self.is_watching_only():
raise Exception(_("This is a watching-only wallet"))
raise UserFacingException(_("This is a watching-only wallet"))
if not is_address(address):
raise Exception(f"Invalid bitcoin address: {address}")
raise UserFacingException(f"Invalid bitcoin address: {address}")
if not self.is_mine(address):
raise Exception(_('Address not in wallet.') + f' {address}')
raise UserFacingException(_('Address not in wallet.') + f' {address}')
index = self.get_address_index(address)
pk, compressed = self.keystore.get_private_key(index, password)
txin_type = self.get_txin_type(address)
@ -840,7 +840,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
try:
self.cpfp(tx, 0)
can_cpfp = True
except:
except Exception:
can_cpfp = False
else:
status = _('Local')
@ -1107,7 +1107,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
for x in data:
try:
req = Request(**x)
except:
except Exception:
raise FileImportFailed(_("Invalid invoice format"))
self.add_payment_request(req, write_to_disk=False)
self.save_db()
@ -1121,7 +1121,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
for x in data:
try:
invoice = Invoice(**x)
except:
except Exception:
raise FileImportFailed(_("Invalid invoice format"))
self.save_invoice(invoice, write_to_disk=False)
self.save_db()
@ -3460,7 +3460,7 @@ class Simple_Deterministic_Wallet(Simple_Wallet, Deterministic_Wallet):
self.keystore = load_keystore(self.db, 'keystore') # type: KeyStoreWithMPK
try:
xtype = bip32.xpub_type(self.keystore.xpub)
except:
except Exception:
xtype = 'standard'
self.txin_type = 'p2pkh' if xtype == 'standard' else xtype

4
electrum/wallet_db.py

@ -98,7 +98,7 @@ class WalletDB(JsonDB):
def load_data(self, s):
try:
self.data = json.loads(s)
except:
except Exception:
try:
d = ast.literal_eval(s)
labels = d.get('labels', {})
@ -109,7 +109,7 @@ class WalletDB(JsonDB):
try:
json.dumps(key)
json.dumps(value)
except:
except Exception:
self.logger.info(f'Failed to convert label to json format: {key}')
continue
self.data[key] = value

Loading…
Cancel
Save