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 folder: ~/.cache/pip
fingerprint_script: echo Flake8 && echo $ELECTRUM_IMAGE && cat $ELECTRUM_REQUIREMENTS fingerprint_script: echo Flake8 && echo $ELECTRUM_IMAGE && cat $ELECTRUM_REQUIREMENTS
install_script: install_script:
- pip install flake8 - pip install flake8 flake8-bugbear
flake8_script: 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: env:
ELECTRUM_IMAGE: python:3.8 ELECTRUM_IMAGE: python:3.8
ELECTRUM_REQUIREMENTS: contrib/requirements/requirements.txt ELECTRUM_REQUIREMENTS: contrib/requirements/requirements.txt
@ -144,10 +144,13 @@ task:
# list of error codes: # list of error codes:
# - https://flake8.pycqa.org/en/latest/user/error-codes.html # - https://flake8.pycqa.org/en/latest/user/error-codes.html
# - https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes # - 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 - name: Flake8 Non-Mandatory
env: env:
ELECTRUM_LINTERS: E,F,W,C90 ELECTRUM_LINTERS: E,F,W,C90,B
ELECTRUM_LINTERS_IGNORE: ""
allow_failures: true allow_failures: true
task: task:

2
electrum/base_crash_reporter.py

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

2
electrum/base_wizard.py

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

6
electrum/bip32.py

@ -297,7 +297,7 @@ def is_xpub(text):
try: try:
node = BIP32Node.from_xkey(text) node = BIP32Node.from_xkey(text)
return not node.is_private() return not node.is_private()
except: except Exception:
return False return False
@ -305,7 +305,7 @@ def is_xprv(text):
try: try:
node = BIP32Node.from_xkey(text) node = BIP32Node.from_xkey(text)
return node.is_private() return node.is_private()
except: except Exception:
return False return False
@ -374,7 +374,7 @@ def is_bip32_derivation(s: str) -> bool:
if not (s == 'm' or s.startswith('m/')): if not (s == 'm' or s.startswith('m/')):
return False return False
convert_bip32_strpath_to_intpath(s) convert_bip32_strpath_to_intpath(s)
except: except Exception:
return False return False
else: else:
return True 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: def verify_header(cls, header: dict, prev_hash: str, target: int, expected_header_hash: str=None) -> None:
_hash = hash_header(header) _hash = hash_header(header)
if expected_header_hash and expected_header_hash != _hash: 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'): 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: if constants.net.TESTNET:
return return
bits = cls.target_to_bits(target) bits = cls.target_to_bits(target)
if bits != header.get('bits'): 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') block_hash_as_num = int.from_bytes(bfh(_hash), byteorder='big')
if block_hash_as_num > target: 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: def verify_chunk(self, index: int, data: bytes) -> None:
num = len(data) // HEADER_SIZE num = len(data) // HEADER_SIZE
@ -544,7 +544,7 @@ class Blockchain(Logger):
def bits_to_target(cls, bits: int) -> int: def bits_to_target(cls, bits: int) -> int:
# arith_uint256::SetCompact in Bitcoin Core # arith_uint256::SetCompact in Bitcoin Core
if not (0 <= bits < (1 << 32)): 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 bitsN = (bits >> 24) & 0xff
bitsBase = bits & 0x7fffff bitsBase = bits & 0x7fffff
if bitsN <= 3: if bitsN <= 3:
@ -553,12 +553,12 @@ class Blockchain(Logger):
target = bitsBase << (8 * (bitsN-3)) target = bitsBase << (8 * (bitsN-3))
if target != 0 and bits & 0x800000 != 0: if target != 0 and bits & 0x800000 != 0:
# Bit number 24 (0x800000) represents the sign of N # 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 if (target != 0 and
(bitsN > 34 or (bitsN > 34 or
(bitsN > 33 and bitsBase > 0xff) or (bitsN > 33 and bitsBase > 0xff) or
(bitsN > 32 and bitsBase > 0xffff))): (bitsN > 32 and bitsBase > 0xffff))):
raise Exception("target has overflown") raise InvalidHeader("target has overflown")
return target return target
@classmethod @classmethod
@ -622,7 +622,7 @@ class Blockchain(Logger):
return hash_header(header) == constants.net.GENESIS return hash_header(header) == constants.net.GENESIS
try: try:
prev_hash = self.get_hash(height - 1) prev_hash = self.get_hash(height - 1)
except: except Exception:
return False return False
if prev_hash != header.get('prev_block_hash'): if prev_hash != header.get('prev_block_hash'):
return False return False

2
electrum/channel_db.py

@ -175,7 +175,7 @@ class NodeInfo(NamedTuple):
alias = payload['alias'].rstrip(b'\x00') alias = payload['alias'].rstrip(b'\x00')
try: try:
alias = alias.decode('utf8') alias = alias.decode('utf8')
except: except Exception:
alias = '' alias = ''
timestamp = payload['timestamp'] timestamp = payload['timestamp']
node_info = NodeInfo(node_id=node_id, features=features, timestamp=timestamp, alias=alias) 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: for bkts_choose_from in bucket_sets:
try: 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 bucket_value_sum += already_selected_buckets_value_sum
return sufficient_funds(already_selected_buckets + bkts, return sufficient_funds(already_selected_buckets + bkts,
bucket_value_sum=bucket_value_sum) bucket_value_sum=bucket_value_sum)

6
electrum/commands.py

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

2
electrum/constants.py

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

2
electrum/contacts.py

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

6
electrum/crypto.py

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

5
electrum/daemon.py

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

2
electrum/ecc.py

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

6
electrum/exchange_rate.py

@ -104,7 +104,7 @@ class ExchangeBase(Logger):
try: try:
with open(filename, 'r', encoding='utf-8') as f: with open(filename, 'r', encoding='utf-8') as f:
h = json.loads(f.read()) h = json.loads(f.read())
except: except Exception:
return None return None
if not h: # e.g. empty dict if not h: # e.g. empty dict
return None return None
@ -469,7 +469,7 @@ def get_exchanges_and_currencies():
try: try:
with open(path, 'r', encoding='utf-8') as f: with open(path, 'r', encoding='utf-8') as f:
return json.loads(f.read()) return json.loads(f.read())
except: except Exception:
pass pass
# or if not present, generate it now. # or if not present, generate it now.
print("cannot find currencies.json. will regenerate it now.") print("cannot find currencies.json. will regenerate it now.")
@ -483,7 +483,7 @@ def get_exchanges_and_currencies():
try: try:
d[name] = await exchange.get_currencies() d[name] = await exchange.get_currencies()
print(name, "ok") print(name, "ok")
except: except Exception:
print(name, "error") print(name, "error")
async def query_all_exchanges_for_their_ccys_over_network(): 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): def bind(label):
try: try:
_.observers.add(label) _.observers.add(label)
except: except Exception:
pass pass
# garbage collection # garbage collection
new = set() new = set()
for label in _.observers: for label in _.observers:
try: try:
new.add(label) new.add(label)
except: except Exception:
pass pass
_.observers = new _.observers = new
@ -42,7 +42,7 @@ class _(str):
for label in _.observers: for label in _.observers:
try: try:
label.text = _(label.text.source_text) label.text = _(label.text.source_text)
except: except Exception:
pass pass
# Note that all invocations of _() inside the core electrum library # Note that all invocations of _() inside the core electrum library
# use electrum.i18n instead of electrum.gui.kivy.i18n, so we should update the # 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 assert u == self.base_unit
try: try:
x = Decimal(a) x = Decimal(a)
except: except Exception:
return None return None
p = pow(10, self.decimal_point()) p = pow(10, self.decimal_point())
return int(p * x) return int(p * x)
@ -487,7 +487,7 @@ class ElectrumWindow(App, Logger, EventListener):
from electrum.transaction import tx_from_any from electrum.transaction import tx_from_any
try: try:
tx = tx_from_any(data) tx = tx_from_any(data)
except: except Exception:
tx = None tx = None
if tx: if tx:
self.tx_dialog(tx) self.tx_dialog(tx)
@ -1119,7 +1119,7 @@ class ElectrumWindow(App, Logger, EventListener):
arrow_pos=arrow_pos) arrow_pos=arrow_pos)
@scheduled_in_gui_thread @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): arrow_pos='bottom_mid', width=None, icon='', modal=False, exit=False):
'''Method to show an Information Bubble '''Method to show an Information Bubble
@ -1130,6 +1130,8 @@ class ElectrumWindow(App, Logger, EventListener):
width: width of the Bubble width: width of the Bubble
arrow_pos: arrow position for 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 text = str(text) # so that we also handle e.g. Exception
info_bubble = self.info_bubble info_bubble = self.info_bubble
if not info_bubble: if not info_bubble:

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

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

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

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

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

@ -341,7 +341,7 @@ class SendScreen(CScreen, Logger):
else: else:
try: try:
amount_sat = self.app.get_amount(self.amount) amount_sat = self.app.get_amount(self.amount)
except: except Exception:
self.app.show_error(_('Invalid amount') + ':\n' + self.amount) self.app.show_error(_('Invalid amount') + ':\n' + self.amount)
return return
message = self.message message = self.message
@ -384,7 +384,7 @@ class SendScreen(CScreen, Logger):
assert self.lnurl_data assert self.lnurl_data
try: try:
amount = self.app.get_amount(self.amount) amount = self.app.get_amount(self.amount)
except: except Exception:
self.app.show_error(_('Invalid amount') + ':\n' + self.amount) self.app.show_error(_('Invalid amount') + ':\n' + self.amount)
return return
if not (self.lnurl_data.min_sendable_sat <= amount <= self.lnurl_data.max_sendable_sat): 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 # connect only once
try: try:
qewallet.userNotify.disconnect(self.on_wallet_usernotify) qewallet.userNotify.disconnect(self.on_wallet_usernotify)
except: except Exception:
pass pass
qewallet.userNotify.connect(self.on_wallet_usernotify) qewallet.userNotify.connect(self.on_wallet_usernotify)

2
electrum/gui/qml/qebitcoin.py

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

2
electrum/gui/qml/qeconfig.py

@ -248,7 +248,7 @@ class QEConfig(AuthMixin, QObject):
self._amount = QEAmount() self._amount = QEAmount()
try: try:
x = Decimal(unitAmount) x = Decimal(unitAmount)
except: except Exception:
return self._amount return self._amount
# scale it to max allowed precision, make it an int # 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: else:
try: try:
sd = Decimal(satoshis) sd = Decimal(satoshis)
except: except Exception:
return '' return ''
if plain: if plain:
return self.fx.ccy_amount_str(self.fx.fiat_value(satoshis, rate), add_thousands_sep=False) 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: else:
try: try:
sd = Decimal(satoshis) sd = Decimal(satoshis)
except: except Exception:
return '' return ''
try: try:
td = Decimal(timestamp) td = Decimal(timestamp)
if td == 0: if td == 0:
return '' return ''
except: except Exception:
return '' return ''
dt = datetime.fromtimestamp(int(td)) dt = datetime.fromtimestamp(int(td))
if plain: if plain:
@ -143,7 +143,7 @@ class QEFX(QObject, QtEventListener):
rate = self.fx.exchange_rate() rate = self.fx.exchange_rate()
try: try:
fd = Decimal(fiat) fd = Decimal(fiat)
except: except Exception:
return '' return ''
v = fd / Decimal(rate) * COIN v = fd / Decimal(rate) * COIN
if v.is_nan(): if v.is_nan():

2
electrum/gui/qml/qeinvoice.py

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

4
electrum/gui/qml/qetxdetails.py

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

2
electrum/gui/qml/qewallet.py

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

4
electrum/gui/qt/amountedit.py

@ -97,7 +97,7 @@ class AmountEdit(SizedFreezableLineEdit):
try: try:
text = text.replace(DECIMAL_POINT, '.') text = text.replace(DECIMAL_POINT, '.')
return (int if self.is_int else Decimal)(text) return (int if self.is_int else Decimal)(text)
except: except Exception:
return None return None
def get_amount(self) -> Union[None, Decimal, int]: def get_amount(self) -> Union[None, Decimal, int]:
@ -130,7 +130,7 @@ class BTCAmountEdit(AmountEdit):
try: try:
text = text.replace(DECIMAL_POINT, '.') text = text.replace(DECIMAL_POINT, '.')
x = Decimal(text) x = Decimal(text)
except: except Exception:
return None return None
# scale it to max allowed precision, make it an int # scale it to max allowed precision, make it an int
power = pow(10, self.max_precision()) 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") if v2 is None or isinstance(v2, Decimal) and v2.is_nan(): v2 = -float("inf")
try: try:
return v1 < v2 return v1 < v2
except: except Exception:
return False return False
def get_item_key(tx_item): def get_item_key(tx_item):
@ -538,7 +538,7 @@ class HistoryList(MyTreeView, AcceptFileDragDrop):
else: else:
try: try:
year = int(s) year = int(s)
except: except Exception:
return return
self.start_date = datetime.datetime(year, 1, 1) self.start_date = datetime.datetime(year, 1, 1)
self.end_date = datetime.datetime(year+1, 1, 1) self.end_date = datetime.datetime(year+1, 1, 1)
@ -709,7 +709,7 @@ class HistoryList(MyTreeView, AcceptFileDragDrop):
if value is not None: if value is not None:
self.hm.update_fiat(index) self.hm.update_fiat(index)
else: else:
assert False raise Exception(f"did not expect {column=!r} to get edited")
def on_double_click(self, idx): def on_double_click(self, idx):
tx_item = idx.internalPointer().get_data() tx_item = idx.internalPointer().get_data()

8
electrum/gui/qt/locktimeedit.py

@ -93,7 +93,7 @@ class _LockTimeEditor:
return True return True
try: try:
x = int(x) x = int(x)
except: except Exception:
return False return False
return cls.min_allowed_value <= x <= cls.max_allowed_value return cls.min_allowed_value <= x <= cls.max_allowed_value
@ -120,13 +120,13 @@ class LockTimeRawEdit(QLineEdit, _LockTimeEditor):
def get_locktime(self) -> Optional[int]: def get_locktime(self) -> Optional[int]:
try: try:
return int(str(self.text())) return int(str(self.text()))
except: except Exception:
return None return None
def set_locktime(self, x: Any) -> None: def set_locktime(self, x: Any) -> None:
try: try:
x = int(x) x = int(x)
except: except Exception:
self.setText('') self.setText('')
return return
x = max(x, self.min_allowed_value) x = max(x, self.min_allowed_value)
@ -185,7 +185,7 @@ class LockTimeDateEdit(QDateTimeEdit, _LockTimeEditor):
return return
try: try:
x = int(x) x = int(x)
except: except Exception:
self.setDateTime(QDateTime.currentDateTime()) self.setDateTime(QDateTime.currentDateTime())
return return
dt = datetime.fromtimestamp(x) 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() screen = self.app.desktop().screenGeometry()
assert screen.contains(QRect(*winpos)) assert screen.contains(QRect(*winpos))
self.setGeometry(*winpos) self.setGeometry(*winpos)
except: except Exception:
self.logger.info("using default geometry") self.logger.info("using default geometry")
self.setGeometry(100, 100, 840, 400) self.setGeometry(100, 100, 840, 400)
@ -631,7 +631,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger, QtEventListener):
recent = self.config.get('recently_open', []) recent = self.config.get('recently_open', [])
try: try:
sorted(recent) sorted(recent)
except: except Exception:
recent = [] recent = []
if filename in recent: if filename in recent:
recent.remove(filename) recent.remove(filename)
@ -1294,8 +1294,10 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger, QtEventListener):
else: else:
self.show_message(message) 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 # Needed by QtHandler for hardware wallets
if title is None:
title = _('Question')
dialog = WindowModalDialog(self.top_level_window(), title=title) dialog = WindowModalDialog(self.top_level_window(), title=title)
dialog.setMinimumWidth(400) dialog.setMinimumWidth(400)
clayout = ChoicesLayout(msg, choices, checked_index=default_choice) 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 = SeedDialog(self, seed, passphrase, config=self.config)
d.exec_() 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): help_text=None, show_copy_text_btn=False):
if not data: if not data:
return return
if title is None:
title = _("QR code")
d = QRDialog( d = QRDialog(
data=data, data=data,
parent=parent or self, parent=parent or self,

2
electrum/gui/qt/my_treeview.py

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

2
electrum/gui/qt/settings_dialog.py

@ -287,7 +287,7 @@ class SettingsDialog(QDialog, QtEventListener):
val = block_ex_custom_e.text() val = block_ex_custom_e.text()
try: try:
val = ast.literal_eval(val) # to also accept tuples val = ast.literal_eval(val) # to also accept tuples
except: except Exception:
pass pass
self.config.set_key('block_explorer_custom', val) self.config.set_key('block_explorer_custom', val)
block_ex_custom_e.editingFinished.connect(on_be_edit) 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 from .qrcodewidget import QRDialog
try: try:
s = str(self.text()) s = str(self.text())
except: except Exception:
s = self.text() s = self.text()
if not s: if not s:
return return

6
electrum/gui/text.py

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

4
electrum/interface.py

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

2
electrum/json_db.py

@ -155,7 +155,7 @@ class JsonDB(Logger):
try: try:
json.dumps(key, cls=JsonDBJsonEncoder) json.dumps(key, cls=JsonDBJsonEncoder)
json.dumps(value, cls=JsonDBJsonEncoder) json.dumps(value, cls=JsonDBJsonEncoder)
except: except Exception:
self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})") self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})")
return False return False
if value is not None: 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: def is_old_mpk(mpk: str) -> bool:
try: try:
int(mpk, 16) # test if hex string int(mpk, 16) # test if hex string
except: except Exception:
return False return False
if len(mpk) != 128: if len(mpk) != 128:
return False return False
try: try:
ecc.ECPubkey(bfh('04' + mpk)) ecc.ECPubkey(bfh('04' + mpk))
except: except Exception:
return False return False
return True return True

16
electrum/lnpeer.py

@ -602,7 +602,7 @@ class Peer(Logger):
try: try:
if self.transport: if self.transport:
self.transport.close() self.transport.close()
except: except Exception:
pass pass
self.lnworker.peer_closed(self) self.lnworker.peer_closed(self)
self.got_disconnected.set() self.got_disconnected.set()
@ -1594,7 +1594,7 @@ class Peer(Logger):
raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'') raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE, data=b'')
try: try:
next_chan_scid = processed_onion.hop_data.payload["short_channel_id"]["short_channel_id"] 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') raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00')
next_chan = self.lnworker.get_channel_by_short_id(next_chan_scid) next_chan = self.lnworker.get_channel_by_short_id(next_chan_scid)
local_height = chain.height() local_height = chain.height()
@ -1610,14 +1610,14 @@ class Peer(Logger):
raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message) raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message)
try: try:
next_amount_msat_htlc = processed_onion.hop_data.payload["amt_to_forward"]["amt_to_forward"] 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') raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00')
if not next_chan.can_pay(next_amount_msat_htlc): 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)") 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) raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=outgoing_chan_upd_message)
try: try:
next_cltv_expiry = processed_onion.hop_data.payload["outgoing_cltv_value"]["outgoing_cltv_value"] 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') 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: 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 data = htlc.cltv_expiry.to_bytes(4, byteorder="big") + outgoing_chan_upd_message
@ -1746,7 +1746,7 @@ class Peer(Logger):
try: try:
amt_to_forward = processed_onion.hop_data.payload["amt_to_forward"]["amt_to_forward"] 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") log_fail_reason(f"'amt_to_forward' missing from onion")
raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') 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 raise exc_incorrect_or_unknown_pd
try: try:
cltv_from_onion = processed_onion.hop_data.payload["outgoing_cltv_value"]["outgoing_cltv_value"] 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") log_fail_reason(f"'outgoing_cltv_value' missing from onion")
raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_PAYLOAD, data=b'\x00\x00\x00') 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")) data=htlc.cltv_expiry.to_bytes(4, byteorder="big"))
try: try:
total_msat = processed_onion.hop_data.payload["payment_data"]["total_msat"] 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" total_msat = amt_to_forward # fall back to "amt_to_forward"
if not is_trampoline and amt_to_forward != htlc.amount_msat: if not is_trampoline and amt_to_forward != htlc.amount_msat:
@ -1789,7 +1789,7 @@ class Peer(Logger):
try: try:
payment_secret_from_onion = processed_onion.hop_data.payload["payment_data"]["payment_secret"] payment_secret_from_onion = processed_onion.hop_data.payload["payment_data"]["payment_secret"]
except: except Exception:
if total_msat > amt_to_forward: if total_msat > amt_to_forward:
# payment_secret is required for MPP # payment_secret is required for MPP
log_fail_reason(f"'payment_secret' missing from onion") 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) invoice = lndecode(connect_contents)
nodeid_bytes = invoice.pubkey.serialize() nodeid_bytes = invoice.pubkey.serialize()
nodeid_hex = nodeid_bytes.hex() nodeid_hex = nodeid_bytes.hex()
except: except Exception:
# node id as hex? # node id as hex?
nodeid_hex = connect_contents nodeid_hex = connect_contents
if rest == '': if rest == '':
@ -1479,7 +1479,7 @@ def extract_nodeid(connect_contents: str) -> Tuple[bytes, Optional[str]]:
node_id = bfh(nodeid_hex) node_id = bfh(nodeid_hex)
if len(node_id) != 33: if len(node_id) != 33:
raise Exception() raise Exception()
except: except Exception:
raise ConnStringFormatError(_('Invalid node ID, must be 33 bytes and hexadecimal')) raise ConnStringFormatError(_('Invalid node ID, must be 33 bytes and hexadecimal'))
return node_id, rest 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) self.wallet.set_reserved_state_of_address(addr, reserved=True)
try: try:
self.save_channel(chan) self.save_channel(chan)
except: except Exception:
chan.set_state(ChannelState.REDEEMED) chan.set_state(ChannelState.REDEEMED)
self.remove_channel(chan.channel_id) self.remove_channel(chan.channel_id)
raise raise
@ -1516,13 +1516,13 @@ class LNWallet(LNWorker):
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception() if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_typed payload['raw'] = channel_update_typed
return payload return payload
except: # FIXME: too broad except Exception: # FIXME: too broad
try: try:
message_type, payload = decode_msg(channel_update_as_received) message_type, payload = decode_msg(channel_update_as_received)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception() if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_as_received payload['raw'] = channel_update_as_received
return payload return payload
except: except Exception:
return None return None
@staticmethod @staticmethod

12
electrum/network.py

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

4
electrum/paymentrequest.py

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

8
electrum/plugins/bitbox02/bitbox02.py

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

4
electrum/plugins/coldcard/coldcard.py

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

2
electrum/plugins/digitalbitbox/digitalbitbox.py

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

2
electrum/plugins/jade/jade.py

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

2
electrum/plugins/keepkey/qt.py

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

6
electrum/plugins/labels/labels.py

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

4
electrum/plugins/ledger/ledger.py

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

2
electrum/plugins/revealer/revealer.py

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

6
electrum/plugins/trustedcoin/trustedcoin.py

@ -133,12 +133,12 @@ class TrustedCoinCosignerClient(Logger):
try: try:
r = await resp.json() r = await resp.json()
message = r['message'] message = r['message']
except: except Exception:
message = await resp.text() message = await resp.text()
raise TrustedCoinException(message, resp.status) raise TrustedCoinException(message, resp.status)
try: try:
return await resp.json() return await resp.json()
except: except Exception:
return await resp.text() return await resp.text()
def send_request(self, method, relative_url, data=None, *, timeout=None): def send_request(self, method, relative_url, data=None, *, timeout=None):
@ -165,7 +165,7 @@ class TrustedCoinCosignerClient(Logger):
on_finish=self.handle_response, on_finish=self.handle_response,
timeout=timeout) timeout=timeout)
else: else:
assert False raise Exception(f"unexpected {method=!r}")
except TrustedCoinException: except TrustedCoinException:
raise raise
except Exception as e: 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': if sys.byteorder == 'little':
x = struct.unpack('<16L', bytes([x for x in block[0:64]])) x = struct.unpack('<16L', bytes([x for x in block[0:64]]))
else: else:
raise "Error!!" raise Exception(f"unsupported {sys.byteorder=!r}")
a = state[0] a = state[0]
b = state[1] b = state[1]
c = state[2] c = state[2]

2
electrum/scripts/txbroadcast.py

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

2
electrum/scripts/txradar.py

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

4
electrum/simple_config.py

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

2
electrum/storage.py

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

2
electrum/submarine_swaps.py

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

16
electrum/tests/test_blockchain.py

@ -4,7 +4,7 @@ import os
from electrum import constants, blockchain from electrum import constants, blockchain
from electrum.simple_config import SimpleConfig 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 electrum.util import bfh, make_dir
from . import ElectrumTestCase from . import ElectrumTestCase
@ -418,11 +418,11 @@ class TestBlockchain(ElectrumTestCase):
# Make sure that we don't generate compacts with the 0x00800000 bit set # Make sure that we don't generate compacts with the 0x00800000 bit set
self.assertEqual(0x02008000, Blockchain.target_to_bits(0x80)) 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) 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) Blockchain.bits_to_target(0x04923456)
with self.assertRaises(Exception): # overflow with self.assertRaises(InvalidHeader): # overflow
Blockchain.bits_to_target(0xff123456) Blockchain.bits_to_target(0xff123456)
@ -441,20 +441,20 @@ class TestVerifyHeader(ElectrumTestCase):
Blockchain.verify_header(self.header, self.prev_hash, self.target) Blockchain.verify_header(self.header, self.prev_hash, self.target)
def test_expected_hash_mismatch(self): def test_expected_hash_mismatch(self):
with self.assertRaises(Exception): with self.assertRaises(InvalidHeader):
Blockchain.verify_header(self.header, self.prev_hash, self.target, Blockchain.verify_header(self.header, self.prev_hash, self.target,
expected_header_hash="foo") expected_header_hash="foo")
def test_prev_hash_mismatch(self): def test_prev_hash_mismatch(self):
with self.assertRaises(Exception): with self.assertRaises(InvalidHeader):
Blockchain.verify_header(self.header, "foo", self.target) Blockchain.verify_header(self.header, "foo", self.target)
def test_target_mismatch(self): def test_target_mismatch(self):
with self.assertRaises(Exception): with self.assertRaises(InvalidHeader):
other_target = Blockchain.bits_to_target(0x1d00eeee) other_target = Blockchain.bits_to_target(0x1d00eeee)
Blockchain.verify_header(self.header, self.prev_hash, other_target) Blockchain.verify_header(self.header, self.prev_hash, other_target)
def test_insufficient_pow(self): def test_insufficient_pow(self):
with self.assertRaises(Exception): with self.assertRaises(InvalidHeader):
self.header["nonce"] = 42 self.header["nonce"] = 42
Blockchain.verify_header(self.header, self.prev_hash, self.target) 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.address_synchronizer import TX_HEIGHT_UNCONFIRMED
from electrum.simple_config import SimpleConfig from electrum.simple_config import SimpleConfig
from electrum.transaction import Transaction, TxOutput, tx_from_any from electrum.transaction import Transaction, TxOutput, tx_from_any
from electrum.util import UserFacingException
from . import ElectrumTestCase from . import ElectrumTestCase
from .test_wallet_vertical import WalletIntegrityHelper from .test_wallet_vertical import WalletIntegrityHelper
@ -91,14 +92,14 @@ class TestCommands(ElectrumTestCase):
config=self.config)['wallet'] config=self.config)['wallet']
cmds = Commands(config=self.config) cmds = Commands(config=self.config)
# single address tests # 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" 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 await cmds.getprivatekeys("bc1qgfam82qk7uwh5j2xxmcd8cmklpe0zackyj6r23", wallet=wallet) # not in wallet
self.assertEqual("p2wpkh:L4jkdiXszG26SUYvwwJhzGwg37H2nLhrbip7u6crmgNeJysv5FHL", self.assertEqual("p2wpkh:L4jkdiXszG26SUYvwwJhzGwg37H2nLhrbip7u6crmgNeJysv5FHL",
await cmds.getprivatekeys("bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw", wallet=wallet)) await cmds.getprivatekeys("bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw", wallet=wallet))
# list of addresses tests # list of addresses tests
with self.assertRaises(Exception): with self.assertRaises(UserFacingException):
await cmds.getprivatekeys(['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'asd'], wallet=wallet) await cmds.getprivatekeys(['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'asd'], wallet=wallet)
self.assertEqual(['p2wpkh:L4jkdiXszG26SUYvwwJhzGwg37H2nLhrbip7u6crmgNeJysv5FHL', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'], self.assertEqual(['p2wpkh:L4jkdiXszG26SUYvwwJhzGwg37H2nLhrbip7u6crmgNeJysv5FHL', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'],
await cmds.getprivatekeys(['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'], wallet=wallet)) await cmds.getprivatekeys(['bc1q2ccr34wzep58d4239tl3x3734ttle92a8srmuw', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'], wallet=wallet))
@ -111,14 +112,14 @@ class TestCommands(ElectrumTestCase):
config=self.config)['wallet'] config=self.config)['wallet']
cmds = Commands(config=self.config) cmds = Commands(config=self.config)
# single address tests # 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" 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 await cmds.getprivatekeys("bc1qgfam82qk7uwh5j2xxmcd8cmklpe0zackyj6r23", wallet=wallet) # not in wallet
self.assertEqual("p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2", self.assertEqual("p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2",
await cmds.getprivatekeys("bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af", wallet=wallet)) await cmds.getprivatekeys("bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af", wallet=wallet))
# list of addresses tests # list of addresses tests
with self.assertRaises(Exception): with self.assertRaises(UserFacingException):
await cmds.getprivatekeys(['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'asd'], wallet=wallet) await cmds.getprivatekeys(['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'asd'], wallet=wallet)
self.assertEqual(['p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'], self.assertEqual(['p2wpkh:L15oxP24NMNAXxq5r2aom24pHPtt3Fet8ZutgL155Bad93GSubM2', 'p2wpkh:L4rYY5QpfN6wJEF4SEKDpcGhTPnCe9zcGs6hiSnhpprZqVywFifN'],
await cmds.getprivatekeys(['bc1q3g5tmkmlvxryhh843v4dz026avatc0zzr6h3af', 'bc1q9pzjpjq4nqx5ycnywekcmycqz0wjp2nq604y2n'], wallet=wallet)) 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 hex
try: try:
return binascii.unhexlify(raw).hex() return binascii.unhexlify(raw).hex()
except: except Exception:
pass pass
# try base43 # try base43
try: try:
return base_decode(raw, base=43).hex() return base_decode(raw, base=43).hex()
except: except Exception:
pass pass
# try base64 # try base64
if raw[0:6] in ('cHNidP', b'cHNidP'): # base64 psbt if raw[0:6] in ('cHNidP', b'cHNidP'): # base64 psbt
try: try:
return base64.b64decode(raw).hex() return base64.b64decode(raw).hex()
except: except Exception:
pass pass
# raw bytes (do not strip whitespaces in this case) # raw bytes (do not strip whitespaces in this case)
if isinstance(raw_unstripped, bytes): if isinstance(raw_unstripped, bytes):

8
electrum/util.py

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

2
electrum/verifier.py

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

18
electrum/wallet.py

@ -653,7 +653,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
text_dec = Decimal(text) text_dec = Decimal(text)
text_dec_rounded = Decimal(fx.ccy_amount_str(text_dec, add_thousands_sep=False)) text_dec_rounded = Decimal(fx.ccy_amount_str(text_dec, add_thousands_sep=False))
reset = text_dec_rounded == def_fiat_rounded reset = text_dec_rounded == def_fiat_rounded
except: except Exception:
# garbage. not resetting, but not saving either # garbage. not resetting, but not saving either
return False return False
if reset: if reset:
@ -673,7 +673,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
fiat_value = self.fiat_value.get(ccy, {}).get(txid) fiat_value = self.fiat_value.get(ccy, {}).get(txid)
try: try:
return Decimal(fiat_value) return Decimal(fiat_value)
except: except Exception:
return return
def is_mine(self, address) -> bool: 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: def export_private_key(self, address: str, password: Optional[str]) -> str:
if self.is_watching_only(): 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): 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): 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) index = self.get_address_index(address)
pk, compressed = self.keystore.get_private_key(index, password) pk, compressed = self.keystore.get_private_key(index, password)
txin_type = self.get_txin_type(address) txin_type = self.get_txin_type(address)
@ -840,7 +840,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
try: try:
self.cpfp(tx, 0) self.cpfp(tx, 0)
can_cpfp = True can_cpfp = True
except: except Exception:
can_cpfp = False can_cpfp = False
else: else:
status = _('Local') status = _('Local')
@ -1107,7 +1107,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
for x in data: for x in data:
try: try:
req = Request(**x) req = Request(**x)
except: except Exception:
raise FileImportFailed(_("Invalid invoice format")) raise FileImportFailed(_("Invalid invoice format"))
self.add_payment_request(req, write_to_disk=False) self.add_payment_request(req, write_to_disk=False)
self.save_db() self.save_db()
@ -1121,7 +1121,7 @@ class Abstract_Wallet(ABC, Logger, EventListener):
for x in data: for x in data:
try: try:
invoice = Invoice(**x) invoice = Invoice(**x)
except: except Exception:
raise FileImportFailed(_("Invalid invoice format")) raise FileImportFailed(_("Invalid invoice format"))
self.save_invoice(invoice, write_to_disk=False) self.save_invoice(invoice, write_to_disk=False)
self.save_db() self.save_db()
@ -3460,7 +3460,7 @@ class Simple_Deterministic_Wallet(Simple_Wallet, Deterministic_Wallet):
self.keystore = load_keystore(self.db, 'keystore') # type: KeyStoreWithMPK self.keystore = load_keystore(self.db, 'keystore') # type: KeyStoreWithMPK
try: try:
xtype = bip32.xpub_type(self.keystore.xpub) xtype = bip32.xpub_type(self.keystore.xpub)
except: except Exception:
xtype = 'standard' xtype = 'standard'
self.txin_type = 'p2pkh' if xtype == 'standard' else xtype 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): def load_data(self, s):
try: try:
self.data = json.loads(s) self.data = json.loads(s)
except: except Exception:
try: try:
d = ast.literal_eval(s) d = ast.literal_eval(s)
labels = d.get('labels', {}) labels = d.get('labels', {})
@ -109,7 +109,7 @@ class WalletDB(JsonDB):
try: try:
json.dumps(key) json.dumps(key)
json.dumps(value) json.dumps(value)
except: except Exception:
self.logger.info(f'Failed to convert label to json format: {key}') self.logger.info(f'Failed to convert label to json format: {key}')
continue continue
self.data[key] = value self.data[key] = value

Loading…
Cancel
Save