Skip to content

Commit

Permalink
add bugbear no-qa directives
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmarcello committed Apr 3, 2024
1 parent 953a7d7 commit 616c932
Show file tree
Hide file tree
Showing 40 changed files with 106 additions and 105 deletions.
6 changes: 3 additions & 3 deletions counterparty-cli/counterpartycli/clientapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def handle_exception(exc_type, exc_value, exc_traceback):
):
raise ConfigurationError("invalid RPC port number")
except: # noqa: E722
raise Exception(
raise Exception( # noqa: B904
"Please specific a valid port number counterparty-rpc-port configuration parameter"
)

Expand Down Expand Up @@ -143,7 +143,7 @@ def handle_exception(exc_type, exc_value, exc_traceback):
if not (int(config.WALLET_PORT) > 1 and int(config.WALLET_PORT) < 65535):
raise ConfigurationError("invalid wallet API port number")
except: # noqa: E722
raise ConfigurationError(
raise ConfigurationError( # noqa: B904
"Please specific a valid port number wallet-port configuration parameter"
)

Expand Down Expand Up @@ -218,7 +218,7 @@ def handle_exception(exc_type, exc_value, exc_traceback):
config.BURN_END = config.BURN_END_REGTEST
config.UNSPENDABLE = custom_args[0]
else:
raise "Custom net parameter needs to be like UNSPENDABLE_ADDRESS|ADDRESSVERSION|P2SH_ADDRESSVERSION (version bytes in HH format)"
raise "Custom net parameter needs to be like UNSPENDABLE_ADDRESS|ADDRESSVERSION|P2SH_ADDRESSVERSION (version bytes in HH format)" # noqa: B016
elif config.REGTEST:
config.MAGIC_BYTES = config.MAGIC_BYTES_REGTEST
if config.TESTCOIN:
Expand Down
4 changes: 2 additions & 2 deletions counterparty-cli/counterpartycli/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def get_pubkey_monosig(pubkeyhash, pubkey_resolver=input_pubkey):
try:
pubkey = script.private_key_to_public_key(private_key)
except script.AltcoinSupportError:
raise InputError("invalid private key")
raise InputError("invalid private key") # noqa: B904
if pubkeyhash != script.pubkey_to_pubkeyhash(binascii.unhexlify(bytes(pubkey, "utf-8"))):
raise InputError("provided public or private key does not match the source address")

Expand Down Expand Up @@ -270,7 +270,7 @@ def generate_move_random_hash(move):

args.wager = util.value_in(args.wager, "XCP")
random, move_random_hash = generate_move_random_hash(args.move)
setattr(args, "move_random_hash", move_random_hash)
args.move_random_hash = move_random_hash
print(f"random: {random}")
print(f"move_random_hash: {move_random_hash}")

Expand Down
4 changes: 2 additions & 2 deletions counterparty-cli/counterpartycli/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@


# generate commented config file from arguments list (client.CONFIG_ARGS and server.CONFIG_ARGS) and known values
def generate_config_file(filename, config_args, known_config={}, overwrite=False):
def generate_config_file(filename, config_args, known_config={}, overwrite=False): # noqa: B006
if not overwrite and os.path.exists(filename):
return

Expand Down Expand Up @@ -179,7 +179,7 @@ def generate_config_files():

def zip_folder(folder_path, zip_path):
zip_file = zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(folder_path):
for root, dirs, files in os.walk(folder_path): # noqa: B007
for a_file in files:
zip_file.write(os.path.join(root, a_file))
zip_file.close()
Expand Down
2 changes: 1 addition & 1 deletion counterparty-cli/counterpartycli/wallet/bitcoincore.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def is_locked():
else:
return True # Wallet is locked
else:
False
False # noqa: B018


def unlock(passphrase):
Expand Down
2 changes: 1 addition & 1 deletion counterparty-lib/counterpartylib/lib/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def pack(address):
except bitcoin.base58.InvalidBase58Error as e:
raise e
except Exception as e: # noqa: F841
raise Exception(
raise Exception( # noqa: B904
f"The address {address} is not a valid bitcoin address ({'testnet' if config.TESTNET or config.REGTEST else 'mainnet'})"
)
else:
Expand Down
16 changes: 8 additions & 8 deletions counterparty-lib/counterpartylib/lib/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ class BackendError(Exception):


def check_backend_state():
f"""Checks blocktime of last block to see if {config.BTC_NAME} Core is running behind."""
f"""Checks blocktime of last block to see if {config.BTC_NAME} Core is running behind.""" # noqa: B021
block_count = backend.getblockcount()
block_hash = backend.getblockhash(block_count)
cblock = backend.getblock(block_hash)
Expand All @@ -226,7 +226,7 @@ class DatabaseError(Exception):


def check_database_state(db, blockcount):
f"""Checks {config.XCP_NAME} database to see if is caught up with backend."""
f"""Checks {config.XCP_NAME} database to see if is caught up with backend.""" # noqa: B021
if ledger.CURRENT_BLOCK_INDEX + 1 < blockcount:
raise DatabaseError(f"{config.XCP_NAME} database is behind backend.")
logger.debug("Database state check passed.")
Expand All @@ -245,7 +245,7 @@ def db_query(db, statement, bindings=(), callback=None, **callback_args):
if re.search(r"\b" + word + "\b", statement.lower()):
raise APIError(f"Forbidden word in query: '{word}'.")

if hasattr(callback, "__call__"):
if callable(callback):
cursor.execute(statement, bindings)
for row in cursor:
callback(row, **callback_args)
Expand Down Expand Up @@ -477,7 +477,7 @@ def adjust_get_sends_memo_filters(filters):
try:
filter_["value"] = bytes.fromhex(filter_["value"])
except ValueError as e: # noqa: F841
raise APIError("Invalid memo_hex value")
raise APIError("Invalid memo_hex value") # noqa: B904


def adjust_get_sends_results(query_result):
Expand Down Expand Up @@ -546,7 +546,7 @@ def compose_transaction(
elif pubkey == None: # noqa: E711
provided_pubkeys = []
else:
assert False
assert False # noqa: B011

# Get additional pubkeys from `source` and `destination` params.
# Convert `source` and `destination` to pubkeyhash form.
Expand Down Expand Up @@ -733,7 +733,7 @@ def get_method(**kwargs):
try:
return get_rows(self.db, table=table, **kwargs)
except TypeError as e: # TODO: generalise for all API methods
raise APIError(str(e))
raise APIError(str(e)) # noqa: B904

return get_method

Expand Down Expand Up @@ -783,7 +783,7 @@ def create_method(**kwargs):
error_msg = f"Error composing {tx} transaction via API: {str(error)}"
logging.warning(error_msg)
logging.warning(traceback.format_exc())
raise JSONRPCDispatchException(
raise JSONRPCDispatchException( # noqa: B904
code=JSON_RPC_ERROR_API_COMPOSE, message=error_msg
)

Expand Down Expand Up @@ -905,7 +905,7 @@ def get_block_info(block_index):
elif len(blocks) == 0:
raise exceptions.DatabaseError("No blocks found.")
else:
assert False
assert False # noqa: B011
cursor.close()
return block

Expand Down
2 changes: 1 addition & 1 deletion counterparty-lib/counterpartylib/lib/backend/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def sort_unspent_txouts(unspent, unconfirmed=False, dust_size=config.DEFAULT_REG


def get_btc_supply(normalize=False):
f"""returns the total supply of {config.BTC} (based on what Bitcoin Core says the current block height is)"""
f"""returns the total supply of {config.BTC} (based on what Bitcoin Core says the current block height is)""" # noqa: B021
block_count = getblockcount()
blocks_remaining = block_count
total_supply = 0
Expand Down
4 changes: 2 additions & 2 deletions counterparty-lib/counterpartylib/lib/backend/addrindexrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def rpc_call(payload):
try:
response_json = response.json()
except json.decoder.JSONDecodeError as e: # noqa: F841
raise BackendRPCError(
raise BackendRPCError( # noqa: B904
f"Received invalid JSON from backend with a response of {str(response.status_code) + ' ' + response.reason}"
)

Expand Down Expand Up @@ -707,7 +707,7 @@ def send(self, query, timeout=ADDRINDEXRS_CLIENT_TIMEOUT, retry=0):
return self._send(query, timeout=timeout)
except BrokenPipeError:
if retry > 3:
raise Exception("Too many retries, please check addrindexrs")
raise Exception("Too many retries, please check addrindexrs") # noqa: B904
self.sock.close()
self.connect()
return self.send(query, timeout=timeout, retry=retry + 1)
Expand Down
2 changes: 1 addition & 1 deletion counterparty-lib/counterpartylib/lib/backend/indexd.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def rpc_call(payload):
try:
response_json = response.json()
except json.decoder.JSONDecodeError as e: # noqa: F841
raise BackendRPCError(
raise BackendRPCError( # noqa: B904
f"Received invalid JSON from backend with a response of {str(response.status_code) + ' ' + response.reason}"
)

Expand Down
2 changes: 1 addition & 1 deletion counterparty-lib/counterpartylib/lib/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def parse_tx(db, tx):

return True
except Exception as e:
raise exceptions.ParseTransactionError(f"{e}")
raise exceptions.ParseTransactionError(f"{e}") # noqa: B904
finally:
cursor.close()

Expand Down
2 changes: 1 addition & 1 deletion counterparty-lib/counterpartylib/lib/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,7 @@ def check_change(protocol_change, change_name):
if ledger.CURRENT_BLOCK_INDEX >= protocol_change["block_index"]:
raise VersionUpdateRequiredError(explanation)
else:
warnings.warn(explanation)
warnings.warn(explanation) # noqa: B028


def software_version():
Expand Down
2 changes: 1 addition & 1 deletion counterparty-lib/counterpartylib/lib/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
def rowtracer(cursor, sql):
"""Converts fetched SQL data into dict-style"""
dictionary = {}
for index, (name, type_) in enumerate(cursor.getdescription()):
for index, (name, type_) in enumerate(cursor.getdescription()): # noqa: B007
dictionary[name] = sql[index]
return dictionary

Expand Down
2 changes: 1 addition & 1 deletion counterparty-lib/counterpartylib/lib/gettxinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def parse_transaction_vouts(decoded_tx):
new_destination, new_data = decode_checkmultisig(asm, decoded_tx)
potential_dispensers[-1] = (new_destination, output_value)
except script.MultiSigAddressError:
raise DecodeError("invalid OP_CHECKMULTISIG")
raise DecodeError("invalid OP_CHECKMULTISIG") # noqa: B904
elif (
ledger.enabled("p2sh_addresses")
and asm[0] == OP_HASH160 # noqa: F405
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def read_string(self):
try:
length = self.read_compact_size()
except IndexError:
raise SerializationError("attempt to read past end of buffer")
raise SerializationError("attempt to read past end of buffer") # noqa: B904

return self.read_bytes(length)

Expand All @@ -67,7 +67,7 @@ def read_bytes(self, length):
self.read_cursor += length
return result
except IndexError:
raise SerializationError("attempt to read past end of buffer")
raise SerializationError("attempt to read past end of buffer") # noqa: B904

def read_boolean(self):
return self.read_bytes(1)[0] != chr(0)
Expand Down
16 changes: 8 additions & 8 deletions counterparty-lib/counterpartylib/lib/kickstart/blocks_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ def open_leveldb(db_dir):
try:
import plyvel
except: # noqa: E722
raise Exception("Please install the plyvel package via pip3.")
raise Exception("Please install the plyvel package via pip3.") # noqa: B904

try:
return plyvel.DB(db_dir, create_if_missing=False, compression=None)
except plyvel._plyvel.IOError as e:
logger.info(str(e))
raise Exception("Ensure that bitcoind is stopped.")
raise Exception("Ensure that bitcoind is stopped.") # noqa: B904


def fetch_blocks(bitcoind_dir, db_path, queue, first_block_index, parser_config):
Expand Down Expand Up @@ -81,7 +81,7 @@ def fetch_blocks(bitcoind_dir, db_path, queue, first_block_index, parser_config)
)

ledger.CURRENT_BLOCK_INDEX = db_block[1]
for i, transaction in enumerate(block["transactions"]):
for i, transaction in enumerate(block["transactions"]): # noqa: B007
try:
block["transactions"][i]["parsed_vouts"] = gettxinfo.parse_transaction_vouts(
block["transactions"][i]
Expand Down Expand Up @@ -194,21 +194,21 @@ def read_transaction(self, vds, use_txid=True):

transaction["coinbase"] = False
transaction["vin"] = []
for i in range(vds.read_compact_size()):
for i in range(vds.read_compact_size()): # noqa: B007
vin = self.read_tx_in(vds)
transaction["vin"].append(vin)
transaction["coinbase"] = transaction["coinbase"] or vin["coinbase"]

transaction["vout"] = []
for i in range(vds.read_compact_size()):
for i in range(vds.read_compact_size()): # noqa: B007
transaction["vout"].append(self.read_tx_out(vds))

transaction["vtxinwit"] = []
if transaction["segwit"]:
offset_before_tx_witnesses = vds.read_cursor - start_pos
for vin in transaction["vin"]:
for vin in transaction["vin"]: # noqa: B007
witnesses_count = vds.read_compact_size()
for i in range(witnesses_count):
for i in range(witnesses_count): # noqa: B007
witness_length = vds.read_compact_size()
witness = vds.read_bytes(witness_length)
transaction["vtxinwit"].append(witness)
Expand Down Expand Up @@ -258,7 +258,7 @@ def read_block(self, vds, only_header=False, use_txid=True):
return block
block["transaction_count"] = vds.read_compact_size()
block["transactions"] = []
for i in range(block["transaction_count"]):
for i in range(block["transaction_count"]): # noqa: B007
block["transactions"].append(self.read_transaction(vds, use_txid=use_txid))
return block

Expand Down
6 changes: 3 additions & 3 deletions counterparty-lib/counterpartylib/lib/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ def generate_asset_id(asset_name, block_index):
try:
asset_id = int(asset_name[1:])
except ValueError:
raise exceptions.AssetNameError("non‐numeric asset name starts with ‘A’")
raise exceptions.AssetNameError("non‐numeric asset name starts with ‘A’") # noqa: B904

# Number must be in range.
if not (26**12 + 1 <= asset_id <= 2**64 - 1):
Expand Down Expand Up @@ -812,7 +812,7 @@ def insert_record(db, table_name, record, event):
# This function allows you to update a record using an INSERT.
# The `block_index` and `rowid` fields allow you to
# order updates and retrieve the row with the current data.
def insert_update(db, table_name, id_name, id_value, update_data, event, event_info={}):
def insert_update(db, table_name, id_name, id_value, update_data, event, event_info={}): # noqa: B006
cursor = db.cursor()
# select records to update
select_query = f"""
Expand Down Expand Up @@ -2141,7 +2141,7 @@ def get_value_by_block_index(change_name, block_index=None):
max_block_index = -1

if config.REGTEST:
for key, value in PROTOCOL_CHANGES[change_name]["testnet"]:
for key, value in PROTOCOL_CHANGES[change_name]["testnet"]: # noqa: B007
if int(key) > int(max_block_index):
max_block_index = key
return PROTOCOL_CHANGES[change_name]["testnet"][max_block_index]["value"]
Expand Down
4 changes: 2 additions & 2 deletions counterparty-lib/counterpartylib/lib/messages/btcpay.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def validate(db, source, order_match_id, block_index):
problems.append(f"no such order match {order_match_id}")
return None, None, None, None, order_match, problems
elif len(order_matches) > 1:
assert False
assert False # noqa: B011
else:
order_match = order_matches[0]

Expand Down Expand Up @@ -101,7 +101,7 @@ def validate(db, source, order_match_id, block_index):
escrowed_asset = order_match["backward_asset"]
escrowed_quantity = order_match["backward_quantity"]
else:
assert False
assert False # noqa: B011

return destination, btc_quantity, escrowed_asset, escrowed_quantity, order_match, problems

Expand Down
2 changes: 1 addition & 1 deletion counterparty-lib/counterpartylib/lib/messages/cancel.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def parse(db, tx, message):
rps.cancel_rps(db, offer, "cancelled", tx["block_index"], tx["tx_index"])
# If neither order or bet, mark as invalid.
else:
assert False
assert False # noqa: B011

# Add parsed transaction to message-type–specific table.
bindings = {
Expand Down
8 changes: 4 additions & 4 deletions counterparty-lib/counterpartylib/lib/messages/destroy.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ def unpack(db, message):
asset = ledger.get_asset_name(db, asset_id, ledger.CURRENT_BLOCK_INDEX)

except struct.error:
raise UnpackError("could not unpack") # noqa: F405
raise UnpackError("could not unpack") # noqa: B904, F405

except AssetIDError: # noqa: F405
raise UnpackError("asset id invalid") # noqa: F405
raise UnpackError("asset id invalid") # noqa: B904, F405

return asset, quantity, tag

Expand All @@ -87,12 +87,12 @@ def validate(db, source, destination, asset, quantity):
try:
ledger.get_asset_id(db, asset, ledger.CURRENT_BLOCK_INDEX)
except AssetError: # noqa: F405
raise ValidateError("asset invalid") # noqa: F405
raise ValidateError("asset invalid") # noqa: B904, F405

try:
script.validate(source)
except AddressError:
raise ValidateError("source address invalid") # noqa: F405
raise ValidateError("source address invalid") # noqa: B904, F405

if destination:
raise ValidateError("destination exists") # noqa: F405
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def validate(db, source, move, random, rps_match_id):
problems.append("no such rps match")
return None, rps_match, problems
elif len(rps_matches) > 1:
assert False
assert False # noqa: B011

rps_match = rps_matches[0]

Expand Down
Loading

0 comments on commit 616c932

Please sign in to comment.