Skip to content

Commit

Permalink
check broad Exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
Ouziel committed Feb 26, 2025
1 parent 14cacd4 commit a426baa
Show file tree
Hide file tree
Showing 22 changed files with 41 additions and 41 deletions.
6 changes: 3 additions & 3 deletions counterparty-core/counterpartycore/lib/api/apiserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ def handle_route(**kwargs):
TypeError,
) as e:
return return_result(400, error=str(e), start_time=start_time, query_args=query_args)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 366 in counterparty-core/counterpartycore/lib/api/apiserver.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/apiserver.py#L366

Added line #L366 was not covered by tests
# import traceback
# print(traceback.format_exc())
capture_exception(e)
Expand Down Expand Up @@ -413,7 +413,7 @@ def handle_route(**kwargs):
start_time=start_time,
query_args=query_args,
)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 416 in counterparty-core/counterpartycore/lib/api/apiserver.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/apiserver.py#L416

Added line #L416 was not covered by tests
capture_exception(e)
logger.error("Error in API: %s", e)
return return_result(500, error="Internal server error")
Expand Down Expand Up @@ -607,7 +607,7 @@ def start(self, args, log_stream):
try:
self.process.start()
logger.info("API PID: %s", self.process.pid)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 610 in counterparty-core/counterpartycore/lib/api/apiserver.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/apiserver.py#L610

Added line #L610 was not covered by tests
logger.error(f"Error starting API Server: {e}")
raise e
return self.process
Expand Down
6 changes: 3 additions & 3 deletions counterparty-core/counterpartycore/lib/api/compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ def info_by_tx_hash(db, tx_hash: str):
"""
try:
rawtransaction = backend.bitcoind.getrawtransaction(tx_hash)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 556 in counterparty-core/counterpartycore/lib/api/compose.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/compose.py#L556

Added line #L556 was not covered by tests
raise exceptions.ComposeError("Invalid transaction") from e
return info(db, rawtransaction)

Expand All @@ -570,7 +570,7 @@ def info(db, rawtransaction: str, block_index: int = None):
parse_vouts=True,
block_index=block_index,
)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 573 in counterparty-core/counterpartycore/lib/api/compose.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/compose.py#L573

Added line #L573 was not covered by tests
raise exceptions.ComposeError("Invalid rawtransaction") from e

try:
Expand Down Expand Up @@ -608,7 +608,7 @@ def unpack(db, datahex: str, block_index: int = None):
"""
try:
data = binascii.unhexlify(datahex)
except Exception as e: # noqa
except Exception as e: # pylint: disable=broad-except # noqa

Check warning on line 611 in counterparty-core/counterpartycore/lib/api/compose.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/compose.py#L611

Added line #L611 was not covered by tests
raise exceptions.UnpackError("Data must be in hexadecimal format") from e

if data[: len(config.PREFIX)] == config.PREFIX:
Expand Down
10 changes: 5 additions & 5 deletions counterparty-core/counterpartycore/lib/api/composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def create_tx_output(value, address_or_script, unspent_list, construct_params):
output_script = address_to_script_pub_key(
address_or_script, unspent_list, construct_params
)
except Exception as e:
except Exception as e: # pylint: disable=broad-except
raise exceptions.ComposeError(
f"Invalid script or address for output: {address_or_script} (error: {e})"
) from e
Expand Down Expand Up @@ -435,7 +435,7 @@ def prepare_inputs_set(inputs_set):
if script_pub_key is not None:
try:
script.script_to_asm(script_pub_key)
except Exception as e:
except Exception as e: # pylint: disable=broad-except
raise exceptions.ComposeError(
f"invalid UTXOs: {utxo} (invalid script_pub_key)"
) from e
Expand All @@ -459,7 +459,7 @@ def utxo_to_address(db, utxo):
vout = int(vout)
address = tx["vout"][vout]["scriptPubKey"]["address"]
return address
except Exception as e:
except Exception as e: # pylint: disable=broad-except
raise exceptions.ComposeError(
f"invalid UTXOs: {utxo} (not found in the database or Bitcoin Core)"
) from e
Expand All @@ -479,7 +479,7 @@ def ensure_utxo_is_first(utxo, unspent_list):
if first_utxo["txid"] != txid or first_utxo["vout"] != vout:
try:
value = backend.bitcoind.get_utxo_value(txid, vout)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 482 in counterparty-core/counterpartycore/lib/api/composer.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/composer.py#L482

Added line #L482 was not covered by tests
raise exceptions.ComposeError(f"invalid UTXOs: {utxo} (value not found)") from e
new_unspent_list.insert(
0,
Expand Down Expand Up @@ -1092,7 +1092,7 @@ def compose_transaction(db, name, params, construct_parameters):
# sanity check
try:
check_transaction_sanity(tx_info, result, construct_params)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 1095 in counterparty-core/counterpartycore/lib/api/composer.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/composer.py#L1095

Added line #L1095 was not covered by tests
raise exceptions.ComposeError(str(e)) from e

# return result
Expand Down
2 changes: 1 addition & 1 deletion counterparty-core/counterpartycore/lib/api/healthz.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def healthz(db, check_type: str = "light"):
healthz_heavy(db)
else:
healthz_light(db)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 64 in counterparty-core/counterpartycore/lib/api/healthz.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/api/healthz.py#L64

Added line #L64 was not covered by tests
logger.exception(e)
logger.error(f"Health check failed: {e}")
return False
Expand Down
4 changes: 2 additions & 2 deletions counterparty-core/counterpartycore/lib/backend/bitcoind.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def rpc_call(payload, retry=0):
stack_info=config.VERBOSE > 0,
)
time.sleep(5)
except Exception as e:
except Exception as e: # pylint: disable=broad-except
broken_error = e
break
if broken_error:
Expand Down Expand Up @@ -444,7 +444,7 @@ def sendrawtransaction(signedhex: str):
"""
try:
return rpc("sendrawtransaction", [signedhex])
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 447 in counterparty-core/counterpartycore/lib/backend/bitcoind.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/backend/bitcoind.py#L447

Added line #L447 was not covered by tests
raise exceptions.BitcoindRPCError(f"Error broadcasting transaction: {str(e)}") from e


Expand Down
6 changes: 3 additions & 3 deletions counterparty-core/counterpartycore/lib/backend/rsfetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def get_prefetched_block(self):
# If stopped and queue is empty
logger.debug("Fetcher stopped and prefetch queue is empty.")
return None
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 141 in counterparty-core/counterpartycore/lib/backend/rsfetcher.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/backend/rsfetcher.py#L141

Added line #L141 was not covered by tests
logger.error(f"Error getting prefetched block: {e}")
raise e

Expand Down Expand Up @@ -179,7 +179,7 @@ def prefetch_blocks(self):
logger.debug(f"Waiting to prefetch block {expected_height}...({retry / 10}s)")
# Use Event's wait method instead of time.sleep for better responsiveness
self.stopped_event.wait(retry / 10) # noqa: S311
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 182 in counterparty-core/counterpartycore/lib/backend/rsfetcher.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/backend/rsfetcher.py#L182

Added line #L182 was not covered by tests
if str(e) == "Stopped error":
logger.warning(
"RSFetcher thread found stopped due to an error. Restarting in 5 seconds..."
Expand All @@ -204,7 +204,7 @@ def stop(self):
if self.fetcher:
self.fetcher.stop()
logger.debug("Fetcher stopped.")
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 207 in counterparty-core/counterpartycore/lib/backend/rsfetcher.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/backend/rsfetcher.py#L207

Added line #L207 was not covered by tests
logger.error(f"Error during stop: {e}")
if str(e) != "Stopped error":
raise e
Expand Down
4 changes: 2 additions & 2 deletions counterparty-core/counterpartycore/lib/cli/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def verfif_and_decompress(zst_filepath, sig_url, decompressors_state):
try:
check_signature(zst_filepath, sig_url)
decompress_zst(zst_filepath)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 124 in counterparty-core/counterpartycore/lib/cli/bootstrap.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/cli/bootstrap.py#L124

Added line #L124 was not covered by tests
cprint(f"Failed to verify and decompress {zst_filepath}: {e}", "red")
decompressors_state.value = 1

Expand All @@ -146,7 +146,7 @@ def download_bootstrap_files(data_dir, files):
# download .zst file
try:
zst_filepath = download_zst(data_dir, zst_url)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 149 in counterparty-core/counterpartycore/lib/cli/bootstrap.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/cli/bootstrap.py#L149

Added line #L149 was not covered by tests
cprint(f"Failed to download {zst_url}: {e}", "red")
for decompressor in decompressors:
decompressor.kill()
Expand Down
4 changes: 2 additions & 2 deletions counterparty-core/counterpartycore/lib/cli/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -786,7 +786,7 @@ def run_server(self):
def run(self):
try:
self.run_server()
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 789 in counterparty-core/counterpartycore/lib/cli/server.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/cli/server.py#L789

Added line #L789 was not covered by tests
logger.error("Error in server thread: %s", e)
_thread.interrupt_main()

Expand Down Expand Up @@ -823,7 +823,7 @@ def stop(self):
stats.print_stats(20)
stats = pstats.Stats(self.profiler).sort_stats("tottime")
stats.print_stats(20)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 826 in counterparty-core/counterpartycore/lib/cli/server.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/cli/server.py#L826

Added line #L826 was not covered by tests
logger.error("Error dumping profiler stats: %s", e)
self.profiler = None

Expand Down
2 changes: 1 addition & 1 deletion counterparty-core/counterpartycore/lib/ledger/issuances.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def resolve_subasset_longname(db, asset_name):
_subasset_parent, subasset_longname = assetnames.parse_subasset_from_asset_name(
asset_name, protocol.enabled("allow_subassets_on_numerics")
)
except Exception as e: # noqa: F841
except Exception as e: # pylint: disable=broad-except # noqa: F841

Check warning

Code scanning / pylint

Unused variable 'e'. Warning

Unused variable 'e'.
logger.warning(f"Invalid subasset {asset_name}")
subasset_longname = None

Expand Down
2 changes: 1 addition & 1 deletion counterparty-core/counterpartycore/lib/messages/utxo.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def unpack(message, return_dict=False):
}

return (source, destination, asset, int(quantity))
except Exception as e:
except Exception as e: # pylint: disable=broad-except
raise exceptions.UnpackError(f"Cannot unpack utxo message: {e}") from e

Check warning on line 155 in counterparty-core/counterpartycore/lib/messages/utxo.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/messages/utxo.py#L154-L155

Added lines #L154 - L155 were not covered by tests


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def compose(

try:
data += _encode_mpma_send(db, asset_dest_quant_list, memo=memo, memo_is_hex=memo_is_hex)
except Exception as e:
except Exception as e: # pylint: disable=broad-except
raise exceptions.ComposeError(f"couldn't encode MPMA send: {e}") from e

return (source, [], data)
Expand All @@ -166,7 +166,7 @@ def parse(db, tx, message):
status = "invalid: truncated message"
except (exceptions.AssetNameError, exceptions.AssetIDError) as e: # noqa: F841
status = "invalid: invalid asset name/id"
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 169 in counterparty-core/counterpartycore/lib/messages/versions/mpma.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/messages/versions/mpma.py#L169

Added line #L169 was not covered by tests
status = f"invalid: couldn't unpack; {e}"

cursor = db.cursor()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def _run(self):
if data:
self.client.send(data)
last_run = time.time()
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 47 in counterparty-core/counterpartycore/lib/monitors/telemetry/daemon.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/monitors/telemetry/daemon.py#L47

Added line #L47 was not covered by tests
logger.error(f"Error in telemetry daemon: {e}")
time.sleep(0.5)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self):
def send(self, data, retry=0):
try:
self.client.send(data)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 24 in counterparty-core/counterpartycore/lib/monitors/telemetry/oneshot.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/monitors/telemetry/oneshot.py#L24

Added line #L24 was not covered by tests
if retry < 10:
logger.trace(f"Error in telemetry one shot: {e}. Retrying in 2 seconds...")
time.sleep(2)
Expand All @@ -37,6 +37,6 @@ def submit(self):
collector.close()
if data:
self.send(data)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 40 in counterparty-core/counterpartycore/lib/monitors/telemetry/oneshot.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/monitors/telemetry/oneshot.py#L40

Added line #L40 was not covered by tests
capture_exception(e)
logger.warning(f"Error in telemetry one shot: {e}")
6 changes: 3 additions & 3 deletions counterparty-core/counterpartycore/lib/parser/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def parse_tx(db, tx):
if protocol.enabled("spend_utxo_to_detach") and message_type_id == attach.ID:
moved = move.move_assets(db, tx)

except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 243 in counterparty-core/counterpartycore/lib/parser/blocks.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/parser/blocks.py#L243

Added line #L243 was not covered by tests
raise exceptions.ParseTransactionError(f"{e}") from e
finally:
cursor.close()
Expand Down Expand Up @@ -848,11 +848,11 @@ def start_rsfetcher():
except exceptions.InvalidVersion as e:
logger.error(e)
raise e
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 851 in counterparty-core/counterpartycore/lib/parser/blocks.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/parser/blocks.py#L851

Added line #L851 was not covered by tests
logger.warning(f"Failed to start RSFetcher ({e}). Retrying in 5 seconds...")
try:
fetcher.stop()
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning

Code scanning / pylint

Redefining name 'e' from outer scope (line 851). Warning

Redefining name 'e' from outer scope (line 851).

Check warning on line 855 in counterparty-core/counterpartycore/lib/parser/blocks.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/parser/blocks.py#L855

Added line #L855 was not covered by tests
logger.debug(f"Failed to stop RSFetcher ({e}).")
pass
time.sleep(5)
Expand Down
6 changes: 3 additions & 3 deletions counterparty-core/counterpartycore/lib/parser/follow.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,14 +231,14 @@ async def receive_multipart(self, socket, topic_name):
logger.trace("No message available in topic `%s`", topic_name)
return
raise e
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 234 in counterparty-core/counterpartycore/lib/parser/follow.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/parser/follow.py#L234

Added line #L234 was not covered by tests
logger.error("Error receiving message: %s. Reconnecting...", e)
capture_exception(e)
self.connect_to_zmq()
return
try:
self.receive_message(topic, body, seq)
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 241 in counterparty-core/counterpartycore/lib/parser/follow.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/parser/follow.py#L241

Added line #L241 was not covered by tests
logger.error("Error processing message: %s", e)
# import traceback
# print(traceback.format_exc()) # for debugging
Expand Down Expand Up @@ -294,7 +294,7 @@ async def handle(self):
except asyncio.CancelledError:
logger.debug("BlockchainWatcher.handle() was cancelled.")
break # Exit the loop if the task is cancelled
except Exception as e:
except Exception as e: # pylint: disable=broad-except

Check warning on line 297 in counterparty-core/counterpartycore/lib/parser/follow.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/parser/follow.py#L297

Added line #L297 was not covered by tests
logger.error("Error in handle loop: %s", e)
capture_exception(e)
# import traceback
Expand Down
2 changes: 1 addition & 1 deletion counterparty-core/counterpartycore/lib/parser/p2sh.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def decode_data_redeem_script(redeem_script, p2sh_is_segwit=False):
and redeem_script[pos + 4 + unique_offfset_length]
== bitcoinlib.core.script.OP_EQUAL
)
except Exception as e: # noqa: F841
except Exception as e: # pylint: disable=broad-except # noqa: F841

Check warning

Code scanning / pylint

Unused variable 'e'. Warning

Unused variable 'e'.

Check warning on line 171 in counterparty-core/counterpartycore/lib/parser/p2sh.py

View check run for this annotation

Codecov / codecov/patch

counterparty-core/counterpartycore/lib/parser/p2sh.py#L171

Added line #L171 was not covered by tests
return None, None, False, None

return pubkey, source, redeem_script_is_valid, found_data
Expand Down
2 changes: 1 addition & 1 deletion counterparty-core/counterpartycore/lib/utils/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def pack(address):
validate(address) # This will check if the address is valid
short_address_bytes = bitcoin.base58.decode(address)[:-4]
return short_address_bytes
except Exception as e: # noqa: F841
except Exception as e: # pylint: disable=broad-except # noqa: F841

Check warning

Code scanning / pylint

Unused variable 'e'. Warning

Unused variable 'e'.
raise exceptions.AddressError( # noqa: B904
f"The address {address} is not a valid bitcoin address ({config.NETWORK_NAME})"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def __init__(self):
except KeyboardInterrupt:
print(regtest_node_thread.node.server_out.getvalue())
pass
except Exception as e:
except Exception as e: # pylint: disable=broad-except
print(regtest_node_thread.node.server_out.getvalue())
raise e
finally:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ def stop_counterparty_server(self):
self.counterparty_server_process.terminate()
self.counterparty_server_process.wait()
self.kill_gunicorn_workers()
except Exception as e:
except Exception as e: # pylint: disable=broad-except
print(e)
pass

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ def run_scenarios(serve=False, wsgi_server="gunicorn"):
except KeyboardInterrupt:
print(regtest_node_thread.node.server_out.getvalue())
pass
except Exception as e:
except Exception as e: # pylint: disable=broad-except
print(regtest_node_thread.node.server_out.getvalue())
raise e
finally:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def test_fetcher_singleton():
}
]

except Exception as e:
except Exception as e: # pylint: disable=broad-except
print(f"Error: {e}")
raise
finally:
Expand Down
2 changes: 1 addition & 1 deletion counterparty-core/tools/xcpcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,6 @@ def execute_command():
if __name__ == "__main__":
try:
execute_command()
except Exception as e:
except Exception as e: # pylint: disable=broad-except
cprint(e, "red")
exit(1)

0 comments on commit a426baa

Please sign in to comment.