From 04a8ed9313ef431b3cf2679299ad82102ff04566 Mon Sep 17 00:00:00 2001 From: Gabriel Levcovitz Date: Wed, 13 Mar 2024 12:47:35 -0300 Subject: [PATCH] chore: remove unnecessary asserts --- hathor/cli/db_export.py | 2 -- hathor/cli/db_import.py | 1 - hathor/cli/events_simulator/scenario.py | 3 +-- hathor/cli/mining.py | 2 -- hathor/client.py | 2 -- hathor/consensus/block_consensus.py | 12 +++------- hathor/consensus/transaction_consensus.py | 10 --------- hathor/graphviz.py | 4 ---- hathor/indexes/height_index.py | 4 +--- hathor/indexes/manager.py | 1 - hathor/indexes/memory_timestamp_index.py | 1 - hathor/indexes/memory_tips_index.py | 3 --- hathor/indexes/memory_tokens_index.py | 5 ----- hathor/indexes/memory_tx_group_index.py | 5 +---- hathor/indexes/mempool_tips_index.py | 3 --- hathor/indexes/rocksdb_tokens_index.py | 7 ------ hathor/indexes/rocksdb_tx_group_index.py | 5 ----- hathor/indexes/utxo_index.py | 3 --- hathor/manager.py | 7 ------ hathor/merged_mining/coordinator.py | 2 -- hathor/p2p/sync_v1/agent.py | 3 --- hathor/p2p/sync_v1/downloader.py | 1 - hathor/p2p/sync_v2/agent.py | 22 ++++++------------- .../sync_v2/blockchain_streaming_client.py | 1 - hathor/p2p/sync_v2/mempool.py | 1 - hathor/p2p/sync_v2/streamers.py | 4 +--- .../sync_v2/transaction_streaming_client.py | 5 +---- hathor/reward_lock/reward_lock.py | 1 - hathor/simulator/patches.py | 1 - hathor/stratum/stratum.py | 1 - hathor/transaction/resources/transaction.py | 1 - hathor/transaction/storage/cache_storage.py | 3 --- hathor/transaction/storage/memory_storage.py | 2 -- .../storage/transaction_storage.py | 13 +---------- hathor/transaction/storage/traversal.py | 3 --- hathor/util.py | 1 - .../token_creation_transaction_verifier.py | 3 +-- hathor/verification/transaction_verifier.py | 2 -- hathor/verification/vertex_verifier.py | 2 -- hathor/wallet/base_wallet.py | 3 --- slow_tests/test_simulator.py | 4 ++-- tests/resources/transaction/test_pushtx.py | 5 +---- tests/tx/test_indexes3.py | 1 - tests/tx/test_indexes4.py | 1 - tests/tx/test_tips.py | 3 +-- tests/unittest.py | 2 -- tests/utils.py | 9 +++----- 47 files changed, 24 insertions(+), 156 deletions(-) diff --git a/hathor/cli/db_export.py b/hathor/cli/db_export.py index 62187e021..b00d9596d 100644 --- a/hathor/cli/db_export.py +++ b/hathor/cli/db_export.py @@ -85,7 +85,6 @@ def iter_tx(self) -> Iterator['BaseTransaction']: soft_voided_ids = set(settings.SOFT_VOIDED_TX_IDS) for tx in self._iter_tx: - assert tx.hash is not None # XXX: if we're skipping voided transactions, we have to be careful not to skip soft-voided ones if self.skip_voided: voided_by = tx.get_metadata().voided_by or set() @@ -110,7 +109,6 @@ def run(self) -> None: # nothing, and it's probably better to finish sooner than expected, rather than later than expected total = self.tx_storage.get_vertices_count() for tx in tx_progress(self.iter_tx(), log=self.log, total=total): - assert tx.hash is not None tx_meta = tx.get_metadata() if tx.is_block: assert isinstance(tx, Block) diff --git a/hathor/cli/db_import.py b/hathor/cli/db_import.py index a43132c40..6a266f169 100644 --- a/hathor/cli/db_import.py +++ b/hathor/cli/db_import.py @@ -86,7 +86,6 @@ def _import_txs(self) -> Iterator['BaseTransaction']: sys.exit(2) tx = tx_or_block_from_bytes(tx_bytes) assert tx is not None - assert tx.hash is not None tx.storage = self.tx_storage self.manager.on_new_tx(tx, quiet=True, fails_silently=False, skip_block_weight_verification=True) yield tx diff --git a/hathor/cli/events_simulator/scenario.py b/hathor/cli/events_simulator/scenario.py index 25723697a..8a2d20251 100644 --- a/hathor/cli/events_simulator/scenario.py +++ b/hathor/cli/events_simulator/scenario.py @@ -99,7 +99,6 @@ def simulate_reorg(simulator: 'Simulator', manager: 'HathorManager') -> None: def simulate_unvoided_transaction(simulator: 'Simulator', manager: 'HathorManager') -> None: from hathor.conf.get_settings import get_global_settings from hathor.simulator.utils import add_new_block, add_new_blocks, gen_new_tx - from hathor.util import not_none settings = get_global_settings() assert manager.wallet is not None @@ -132,7 +131,7 @@ def simulate_unvoided_transaction(simulator: 'Simulator', manager: 'HathorManage block.parents = [ block.parents[0], settings.GENESIS_TX1_HASH, - not_none(tx2.hash), + tx2.hash, ] block.update_hash() assert manager.propagate_tx(block, fails_silently=False) diff --git a/hathor/cli/mining.py b/hathor/cli/mining.py index 38c08adde..a769ed3a0 100644 --- a/hathor/cli/mining.py +++ b/hathor/cli/mining.py @@ -119,7 +119,6 @@ def execute(args: Namespace) -> None: block_bytes = base64.b64decode(data['block_bytes']) block = Block.create_from_struct(block_bytes) - assert block.hash is not None assert isinstance(block, Block) print('Mining block with weight {}'.format(block.weight)) @@ -130,7 +129,6 @@ def execute(args: Namespace) -> None: block = q_out.get() block.update_hash() - assert block.hash is not None print('[{}] New block found: {} (nonce={}, weight={})'.format(datetime.datetime.now(), block.hash.hex(), block.nonce, block.weight)) diff --git a/hathor/client.py b/hathor/client.py index 4f7ab4475..1c68f6787 100644 --- a/hathor/client.py +++ b/hathor/client.py @@ -338,7 +338,6 @@ def _on_new_tx(self, key: HathorEvents, args: EventArguments) -> None: async def submit(self, block: Block) -> Optional[BlockTemplate]: if await self.submit(block): - assert block.hash is not None return self.manager.make_block_template(block.hash) else: return None @@ -397,7 +396,6 @@ def create_tx_from_dict(data: dict[str, Any], update_hash: bool = False, tx = cls(**data) if update_hash: tx.update_hash() - assert tx.hash is not None if hash_bytes: assert tx.hash == hash_bytes, f'Hashes differ: {tx.hash!r} != {hash_bytes!r}' if metadata: diff --git a/hathor/consensus/block_consensus.py b/hathor/consensus/block_consensus.py index 644a53238..7ce12f458 100644 --- a/hathor/consensus/block_consensus.py +++ b/hathor/consensus/block_consensus.py @@ -20,7 +20,7 @@ from hathor.conf.get_settings import get_global_settings from hathor.profiler import get_cpu_profiler from hathor.transaction import BaseTransaction, Block, Transaction, sum_weights -from hathor.util import classproperty, not_none +from hathor.util import classproperty if TYPE_CHECKING: from hathor.consensus.context import ConsensusAlgorithmContext @@ -107,7 +107,6 @@ def update_voided_info(self, block: Block) -> None: return assert block.storage is not None - assert block.hash is not None storage = block.storage assert storage.indexes is not None @@ -216,8 +215,8 @@ def update_voided_info(self, block: Block) -> None: if common_block not in heads: self.context.mark_as_reorg(common_block) else: - best_block_tips = [not_none(blk.hash) for blk in heads] - best_block_tips.append(not_none(block.hash)) + best_block_tips = [blk.hash for blk in heads] + best_block_tips.append(block.hash) storage.update_best_block_tips_cache(best_block_tips) if not meta.voided_by: self.context.mark_as_reorg(common_block) @@ -231,7 +230,6 @@ def union_voided_by_from_parents(self, block: Block) -> set[bytes]: """ voided_by: set[bytes] = set() for parent in block.get_parents(): - assert parent.hash is not None parent_meta = parent.get_metadata() voided_by2 = parent_meta.voided_by if voided_by2: @@ -370,7 +368,6 @@ def add_voided_by(self, block: Block, voided_hash: Optional[bytes] = None) -> bo the block's own hash. """ assert block.storage is not None - assert block.hash is not None storage = block.storage @@ -401,7 +398,6 @@ def remove_voided_by(self, block: Block, voided_hash: Optional[bytes] = None) -> the block's own hash. """ assert block.storage is not None - assert block.hash is not None storage = block.storage @@ -454,7 +450,6 @@ def _score_block_dfs(self, block: BaseTransaction, used: set[bytes], """ Internal method to run a DFS. It is used by `calculate_score()`. """ assert block.storage is not None - assert block.hash is not None assert block.is_block storage = block.storage @@ -475,7 +470,6 @@ def _score_block_dfs(self, block: BaseTransaction, used: set[bytes], from hathor.transaction.storage.traversal import BFSTimestampWalk bfs = BFSTimestampWalk(storage, is_dag_verifications=True, is_left_to_right=False) for tx in bfs.run(parent, skip_root=False): - assert tx.hash is not None assert not tx.is_block if tx.hash in used: diff --git a/hathor/consensus/transaction_consensus.py b/hathor/consensus/transaction_consensus.py index 286a2534d..2b25ad703 100644 --- a/hathor/consensus/transaction_consensus.py +++ b/hathor/consensus/transaction_consensus.py @@ -59,7 +59,6 @@ def mark_inputs_as_used(self, tx: Transaction) -> None: def mark_input_as_used(self, tx: Transaction, txin: TxInput) -> None: """ Mark a given input as used """ - assert tx.hash is not None assert tx.storage is not None spent_tx = tx.storage.get_transaction(txin.tx_id) @@ -117,7 +116,6 @@ def check_twins(self, tx: Transaction, transactions: Iterable[BaseTransaction]) :param transactions: list of transactions to be checked if they are twins with self """ - assert tx.hash is not None assert tx.storage is not None # Getting tx metadata to save the new twins @@ -128,7 +126,6 @@ def check_twins(self, tx: Transaction, transactions: Iterable[BaseTransaction]) sorted_outputs = sorted(tx.outputs, key=lambda x: (x.script, x.value)) for candidate in transactions: - assert candidate.hash is not None # If quantity of inputs is different, it's not a twin. if len(candidate.inputs) != len(tx.inputs): @@ -170,7 +167,6 @@ def check_twins(self, tx: Transaction, transactions: Iterable[BaseTransaction]) def update_voided_info(self, tx: Transaction) -> None: """ This method should be called only once when the transactions is added to the DAG. """ - assert tx.hash is not None assert tx.storage is not None voided_by: set[bytes] = set() @@ -267,7 +263,6 @@ def check_conflicts(self, tx: Transaction) -> None: The verification is made for each input, and `self` is only marked as winner if it wins in all its inputs. """ - assert tx.hash is not None assert tx.storage is not None self.log.debug('tx.check_conflicts', tx=tx.hash_hex) @@ -326,7 +321,6 @@ def mark_as_winner(self, tx: Transaction) -> None: """ Mark a transaction as winner when it has a conflict and its aggregated weight is the greatest one. """ - assert tx.hash is not None self.log.debug('tx.mark_as_winner', tx=tx.hash_hex) meta = tx.get_metadata() assert bool(meta.conflict_with) # FIXME: this looks like a runtime guarantee, MUST NOT be an assert @@ -341,7 +335,6 @@ def remove_voided_by(self, tx: Transaction, voided_hash: bytes) -> bool: """ from hathor.transaction.storage.traversal import BFSTimestampWalk - assert tx.hash is not None assert tx.storage is not None meta = tx.get_metadata() @@ -382,7 +375,6 @@ def mark_as_voided(self, tx: Transaction) -> None: """ Mark a transaction as voided when it has a conflict and its aggregated weight is NOT the greatest one. """ - assert tx.hash is not None self.log.debug('tx.mark_as_voided', tx=tx.hash_hex) meta = tx.get_metadata() assert bool(meta.conflict_with) @@ -395,7 +387,6 @@ def add_voided_by(self, tx: Transaction, voided_hash: bytes) -> bool: """ Add a hash from `meta.voided_by` and its descendants (both from verification DAG and funds tree). """ - assert tx.hash is not None assert tx.storage is not None meta = tx.get_metadata() @@ -415,7 +406,6 @@ def add_voided_by(self, tx: Transaction, voided_hash: bytes) -> bool: check_list: list[Transaction] = [] for tx2 in bfs.run(tx, skip_root=False): assert tx2.storage is not None - assert tx2.hash is not None meta2 = tx2.get_metadata() if tx2.is_block: diff --git a/hathor/graphviz.py b/hathor/graphviz.py index c75074576..978df0edf 100644 --- a/hathor/graphviz.py +++ b/hathor/graphviz.py @@ -63,7 +63,6 @@ def __init__(self, storage: TransactionStorage, include_funds: bool = False, def get_node_label(self, tx: BaseTransaction) -> str: """ Return the node's label for tx. """ - assert tx.hash is not None if tx.hash in self.labels: parts = [self.labels[tx.hash]] else: @@ -79,7 +78,6 @@ def get_node_label(self, tx: BaseTransaction) -> str: def get_node_attrs(self, tx: BaseTransaction) -> dict[str, str]: """ Return node's attributes. """ - assert tx.hash is not None node_attrs = {'label': self.get_node_label(tx)} if tx.is_block: @@ -151,7 +149,6 @@ def dot(self, format: str = 'pdf') -> Digraph: if self.only_blocks and not tx.is_block: continue - assert tx.hash is not None name = tx.hash.hex() node_attrs = self.get_node_attrs(tx) @@ -204,7 +201,6 @@ def tx_neighborhood(self, tx: BaseTransaction, format: str = 'pdf', while to_visit: level, tx = to_visit.pop() - assert tx.hash is not None assert tx.storage is not None name = tx.hash.hex() node_attrs = self.get_node_attrs(tx) diff --git a/hathor/indexes/height_index.py b/hathor/indexes/height_index.py index 7bf91e181..abebfdc55 100644 --- a/hathor/indexes/height_index.py +++ b/hathor/indexes/height_index.py @@ -19,7 +19,6 @@ from hathor.indexes.scope import Scope from hathor.transaction import BaseTransaction, Block from hathor.types import VertexId -from hathor.util import not_none SCOPE = Scope( include_blocks=True, @@ -66,7 +65,6 @@ def init_loop_step(self, tx: BaseTransaction) -> None: if tx.is_genesis: return assert isinstance(tx, Block) - assert tx.hash is not None if tx.get_metadata().voided_by: return self.add_new(tx.get_height(), tx.hash, tx.timestamp) @@ -118,7 +116,7 @@ def update_new_chain(self, height: int, block: Block) -> None: add_to_index: list[_AddToIndexItem] = [] while self.get(block_height) != side_chain_block.hash: add_to_index.append( - _AddToIndexItem(block_height, not_none(side_chain_block.hash), side_chain_block.timestamp) + _AddToIndexItem(block_height, side_chain_block.hash, side_chain_block.timestamp) ) side_chain_block = side_chain_block.get_block_parent() diff --git a/hathor/indexes/manager.py b/hathor/indexes/manager.py index 967ba7225..e681f716b 100644 --- a/hathor/indexes/manager.py +++ b/hathor/indexes/manager.py @@ -229,7 +229,6 @@ def del_tx(self, tx: BaseTransaction, *, remove_all: bool = False, relax_assert: :param tx: Transaction to be deleted """ assert tx.storage is not None - assert tx.hash is not None if remove_all: # We delete from indexes in two cases: (i) mark tx as voided, and (ii) remove tx. diff --git a/hathor/indexes/memory_timestamp_index.py b/hathor/indexes/memory_timestamp_index.py index f041f6296..a6c1c06a0 100644 --- a/hathor/indexes/memory_timestamp_index.py +++ b/hathor/indexes/memory_timestamp_index.py @@ -47,7 +47,6 @@ def force_clear(self) -> None: self._index = SortedKeyList(key=lambda x: (x.timestamp, x.hash)) def add_tx(self, tx: BaseTransaction) -> bool: - assert tx.hash is not None # It is safe to use the in operator because it is O(log(n)). # http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html#sortedcontainers.SortedList.__contains__ element = TransactionIndexElement(tx.timestamp, tx.hash) diff --git a/hathor/indexes/memory_tips_index.py b/hathor/indexes/memory_tips_index.py index 47d8c0eca..58c9f447a 100644 --- a/hathor/indexes/memory_tips_index.py +++ b/hathor/indexes/memory_tips_index.py @@ -78,7 +78,6 @@ def add_tx(self, tx: BaseTransaction) -> bool: :param tx: Transaction to be added """ - assert tx.hash is not None assert tx.storage is not None if tx.hash in self.tx_last_interval: return False @@ -110,7 +109,6 @@ def add_tx(self, tx: BaseTransaction) -> bool: def del_tx(self, tx: BaseTransaction, *, relax_assert: bool = False) -> None: """ Remove a transaction from the index. """ - assert tx.hash is not None assert tx.storage is not None interval = self.tx_last_interval.pop(tx.hash, None) @@ -134,7 +132,6 @@ def update_tx(self, tx: BaseTransaction, *, relax_assert: bool = False) -> None: """ Update a tx according to its children. """ assert tx.storage is not None - assert tx.hash is not None meta = tx.get_metadata() if meta.voided_by: diff --git a/hathor/indexes/memory_tokens_index.py b/hathor/indexes/memory_tokens_index.py index 8b001dc51..26223feaa 100644 --- a/hathor/indexes/memory_tokens_index.py +++ b/hathor/indexes/memory_tokens_index.py @@ -80,7 +80,6 @@ def force_clear(self) -> None: def _add_to_index(self, tx: BaseTransaction, index: int) -> None: """ Add tx to mint/melt indexes and total amount """ - assert tx.hash is not None tx_output = tx.outputs[index] token_uid = tx.get_token_uid(tx_output.get_token_index()) @@ -98,7 +97,6 @@ def _add_to_index(self, tx: BaseTransaction, index: int) -> None: def _remove_from_index(self, tx: BaseTransaction, index: int) -> None: """ Remove tx from mint/melt indexes and total amount """ - assert tx.hash is not None tx_output = tx.outputs[index] token_uid = tx.get_token_uid(tx_output.get_token_index()) @@ -125,7 +123,6 @@ def add_tx(self, tx: BaseTransaction) -> None: if tx.version == TxVersion.TOKEN_CREATION_TRANSACTION: from hathor.transaction.token_creation_tx import TokenCreationTransaction tx = cast(TokenCreationTransaction, tx) - assert tx.hash is not None status = self._tokens[tx.hash] status._name = tx.token_name status._symbol = tx.token_symbol @@ -137,7 +134,6 @@ def add_tx(self, tx: BaseTransaction) -> None: transactions = self._tokens[token_uid]._transactions # It is safe to use the in operator because it is O(log(n)). # http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html#sortedcontainers.SortedList.__contains__ - assert tx.hash is not None element = TransactionIndexElement(tx.timestamp, tx.hash) if element in transactions: return @@ -162,7 +158,6 @@ def del_tx(self, tx: BaseTransaction) -> None: # if it's a TokenCreationTransaction, remove it from index if tx.version == TxVersion.TOKEN_CREATION_TRANSACTION: - assert tx.hash is not None del self._tokens[tx.hash] def iter_all_tokens(self) -> Iterator[tuple[bytes, TokenIndexInfo]]: diff --git a/hathor/indexes/memory_tx_group_index.py b/hathor/indexes/memory_tx_group_index.py index 3d99ecd35..99a679f21 100644 --- a/hathor/indexes/memory_tx_group_index.py +++ b/hathor/indexes/memory_tx_group_index.py @@ -20,7 +20,6 @@ from hathor.indexes.tx_group_index import TxGroupIndex from hathor.transaction import BaseTransaction -from hathor.util import not_none logger = get_logger() @@ -40,7 +39,7 @@ def force_clear(self) -> None: self.index = defaultdict(set) def _add_tx(self, key: KT, tx: BaseTransaction) -> None: - self.index[key].add((tx.timestamp, not_none(tx.hash))) + self.index[key].add((tx.timestamp, tx.hash)) @abstractmethod def _extract_keys(self, tx: BaseTransaction) -> Iterable[KT]: @@ -48,13 +47,11 @@ def _extract_keys(self, tx: BaseTransaction) -> Iterable[KT]: raise NotImplementedError def add_tx(self, tx: BaseTransaction) -> None: - assert tx.hash is not None for key in self._extract_keys(tx): self._add_tx(key, tx) def remove_tx(self, tx: BaseTransaction) -> None: - assert tx.hash is not None for key in self._extract_keys(tx): self.index[key].discard((tx.timestamp, tx.hash)) diff --git a/hathor/indexes/mempool_tips_index.py b/hathor/indexes/mempool_tips_index.py index 460764239..222cc8140 100644 --- a/hathor/indexes/mempool_tips_index.py +++ b/hathor/indexes/mempool_tips_index.py @@ -104,14 +104,12 @@ def _add_many(self, txs: Iterable[bytes]) -> None: # PROVIDES: def update(self, tx: BaseTransaction, *, remove: Optional[bool] = None) -> None: - assert tx.hash is not None assert tx.storage is not None tx_meta = tx.get_metadata() to_remove: set[bytes] = set() to_remove_parents: set[bytes] = set() tx_storage = tx.storage for tip_tx in self.iter(tx_storage): - assert tip_tx.hash is not None meta = tip_tx.get_metadata() # a new tx/block added might cause a tx in the tips to become voided. For instance, there might be a tx1 a # double spending tx2, where tx1 is valid and tx2 voided. A new block confirming tx2 will make it valid @@ -175,7 +173,6 @@ def update(self, tx: BaseTransaction, *, remove: Optional[bool] = None) -> None: self._discard_many(set(tx.parents)) if tx.is_transaction and tx_meta.first_block is None: - assert tx.hash is not None self._add(tx.hash) def iter(self, tx_storage: 'TransactionStorage', max_timestamp: Optional[float] = None) -> Iterator[Transaction]: diff --git a/hathor/indexes/rocksdb_tokens_index.py b/hathor/indexes/rocksdb_tokens_index.py index b978d9c38..a00d39812 100644 --- a/hathor/indexes/rocksdb_tokens_index.py +++ b/hathor/indexes/rocksdb_tokens_index.py @@ -252,8 +252,6 @@ def _subtract_from_total(self, token_uid: bytes, amount: int) -> None: def _add_utxo(self, tx: BaseTransaction, index: int) -> None: """ Add tx to mint/melt indexes and total amount """ - assert tx.hash is not None - tx_output = tx.outputs[index] token_uid = tx.get_token_uid(tx_output.get_token_index()) @@ -270,7 +268,6 @@ def _add_utxo(self, tx: BaseTransaction, index: int) -> None: def _remove_utxo(self, tx: BaseTransaction, index: int) -> None: """ Remove tx from mint/melt indexes and total amount """ - assert tx.hash is not None tx_output = tx.outputs[index] token_uid = tx.get_token_uid(tx_output.get_token_index()) @@ -291,7 +288,6 @@ def add_tx(self, tx: BaseTransaction) -> None: if tx.version == TxVersion.TOKEN_CREATION_TRANSACTION: from hathor.transaction.token_creation_tx import TokenCreationTransaction tx = cast(TokenCreationTransaction, tx) - assert tx.hash is not None self.log.debug('create_token_info', tx=tx.hash_hex, name=tx.token_name, symb=tx.token_symbol) self._create_token_info(tx.hash, tx.token_name, tx.token_symbol) @@ -299,7 +295,6 @@ def add_tx(self, tx: BaseTransaction) -> None: # Adding this tx to the transactions key list assert isinstance(tx, Transaction) for token_uid in tx.tokens: - assert tx.hash is not None self._add_transaction(token_uid, tx.timestamp, tx.hash) for tx_input in tx.inputs: @@ -322,12 +317,10 @@ def del_tx(self, tx: BaseTransaction) -> None: # Removing this tx from the transactions key list assert isinstance(tx, Transaction) for token_uid in tx.tokens: - assert tx.hash is not None self._remove_transaction(token_uid, tx.timestamp, tx.hash) # if it's a TokenCreationTransaction, remove it from index if tx.version == TxVersion.TOKEN_CREATION_TRANSACTION: - assert tx.hash is not None self._destroy_token(tx.hash) def iter_all_tokens(self) -> Iterator[tuple[bytes, TokenIndexInfo]]: diff --git a/hathor/indexes/rocksdb_tx_group_index.py b/hathor/indexes/rocksdb_tx_group_index.py index cf47e5dc8..f640fbafa 100644 --- a/hathor/indexes/rocksdb_tx_group_index.py +++ b/hathor/indexes/rocksdb_tx_group_index.py @@ -75,7 +75,6 @@ def _to_rocksdb_key(self, key: KT, tx: Optional[BaseTransaction] = None) -> byte rocksdb_key = self._serialize_key(key) assert len(rocksdb_key) == self._KEY_SIZE if tx: - assert tx.hash is not None assert len(tx.hash) == 32 rocksdb_key += struct.pack('>I', tx.timestamp) + tx.hash assert len(rocksdb_key) == self._KEY_SIZE + 4 + 32 @@ -94,15 +93,11 @@ def _from_rocksdb_key(self, rocksdb_key: bytes) -> tuple[KT, int, bytes]: return key, timestamp, tx_hash def add_tx(self, tx: BaseTransaction) -> None: - assert tx.hash is not None - for key in self._extract_keys(tx): self.log.debug('put key', key=key) self._db.put((self._cf, self._to_rocksdb_key(key, tx)), b'') def remove_tx(self, tx: BaseTransaction) -> None: - assert tx.hash is not None - for key in self._extract_keys(tx): self.log.debug('delete key', key=key) self._db.delete((self._cf, self._to_rocksdb_key(key, tx))) diff --git a/hathor/indexes/utxo_index.py b/hathor/indexes/utxo_index.py index 5ccbf07e4..bfdc0df78 100644 --- a/hathor/indexes/utxo_index.py +++ b/hathor/indexes/utxo_index.py @@ -59,7 +59,6 @@ def __repr__(self): @classmethod def from_tx_output(cls, tx: BaseTransaction, index: int, tx_output: TxOutput) -> 'UtxoIndexItem': - assert tx.hash is not None settings = get_global_settings() if tx_output.is_token_authority(): @@ -136,7 +135,6 @@ def _update_executed(self, tx: BaseTransaction) -> None: - inputs are removed from the index """ tx_meta = tx.get_metadata() - assert tx.hash is not None assert not tx_meta.voided_by log = self.log.new(tx=tx.hash_hex) log.debug('update executed') @@ -170,7 +168,6 @@ def _update_voided(self, tx: BaseTransaction) -> None: - outpus are removed from the index """ tx_meta = tx.get_metadata() - assert tx.hash is not None assert tx_meta.voided_by log = self.log.new(tx=tx.hash_hex) log.debug('update voided') diff --git a/hathor/manager.py b/hathor/manager.py index 928c383ad..a34a18955 100644 --- a/hathor/manager.py +++ b/hathor/manager.py @@ -432,8 +432,6 @@ def _initialize_components_full_verification(self) -> None: self.log.debug('load blocks and transactions') for tx in self.tx_storage._topological_sort_dfs(): - assert tx.hash is not None - tx_meta = tx.get_metadata() t2 = time.time() @@ -493,7 +491,6 @@ def _initialize_components_full_verification(self) -> None: block_count += 1 # this works because blocks on the best chain are iterated from lower to higher height - assert tx.hash is not None assert tx_meta.validation.is_at_least_basic() assert isinstance(tx, Block) blk_height = tx.get_height() @@ -656,7 +653,6 @@ def _verify_checkpoints(self) -> None: tx = self.tx_storage.get_transaction(checkpoint.hash) except TransactionDoesNotExist as e: raise InitializationError(f'Expected checkpoint does not exist in database: {checkpoint}') from e - assert tx.hash is not None tx_meta = tx.get_metadata() if tx_meta.height != checkpoint.height: raise InitializationError( @@ -785,7 +781,6 @@ def _make_block_template(self, parent_block: Block, parent_txs: 'ParentTxs', cur with_weight_decay: bool = False) -> BlockTemplate: """ Further implementation of making block template, used by make_block_template and make_custom_block_template """ - assert parent_block.hash is not None # the absolute minimum would be the previous timestamp + 1 timestamp_abs_min = parent_block.timestamp + 1 # and absolute maximum limited by max time between blocks @@ -957,7 +952,6 @@ def on_new_tx(self, tx: BaseTransaction, *, conn: Optional[HathorProtocol] = Non :param skip_block_weight_verification: if True will not check the tx PoW """ assert self.tx_storage.is_only_valid_allowed() - assert tx.hash is not None already_exists = False if self.tx_storage.transaction_exists(tx.hash): @@ -1058,7 +1052,6 @@ def tx_fully_validated(self, tx: BaseTransaction, *, quiet: bool) -> None: This might happen immediately after we receive the tx, if we have all dependencies already. Or it might happen later. """ - assert tx.hash is not None assert self.tx_storage.indexes is not None # Publish to pubsub manager the new tx accepted, now that it's full validated diff --git a/hathor/merged_mining/coordinator.py b/hathor/merged_mining/coordinator.py index 1a9ac39ff..9a191a47b 100644 --- a/hathor/merged_mining/coordinator.py +++ b/hathor/merged_mining/coordinator.py @@ -664,12 +664,10 @@ async def submit_to_hathor(self, job: SingleMinerJob, aux_pow: BitcoinAuxPow) -> block = job.hathor_block block.aux_pow = aux_pow block.update_hash() - assert block.hash is not None block_hash = Hash(block.hash) if block_hash.to_weight() < block.weight: self.log.debug('high hash for Hathor, keep mining') return - assert block.hash is not None if job.hathor_height is not None: if self.coordinator.should_skip_hathor_submit(job.hathor_height): self.log.debug('share is too late, skip Hathor submit') diff --git a/hathor/p2p/sync_v1/agent.py b/hathor/p2p/sync_v1/agent.py index a1a03a27b..2060c755f 100644 --- a/hathor/p2p/sync_v1/agent.py +++ b/hathor/p2p/sync_v1/agent.py @@ -603,7 +603,6 @@ def handle_data(self, payload: str) -> None: return assert tx is not None - assert tx.hash is not None self.log.debug('tx received from peer', tx=tx.hash_hex, peer=self.protocol.get_peer_id()) @@ -612,7 +611,6 @@ def handle_data(self, payload: str) -> None: # Will it reduce peer reputation score? return tx.storage = self.protocol.node.tx_storage - assert tx.hash is not None key = self.get_data_key(tx.hash) deferred = self.deferred_by_key.pop(key, None) @@ -674,7 +672,6 @@ def on_tx_success(self, tx: 'BaseTransaction') -> 'BaseTransaction': # the parameter of the second callback is the return of the first # so I need to return the same tx to guarantee that all peers will receive it if tx: - assert tx.hash is not None if self.manager.tx_storage.transaction_exists(tx.hash): self.manager.tx_storage.compare_bytes_with_local_tx(tx) success = True diff --git a/hathor/p2p/sync_v1/downloader.py b/hathor/p2p/sync_v1/downloader.py index 2b3b786bc..d8b3c12cf 100644 --- a/hathor/p2p/sync_v1/downloader.py +++ b/hathor/p2p/sync_v1/downloader.py @@ -247,7 +247,6 @@ def on_error(self, failure: Failure) -> None: def on_new_tx(self, tx: 'BaseTransaction') -> None: """ This is called when a new transaction arrives. """ - assert tx.hash is not None self.log.debug('new tx/block', tx=tx.hash_hex) details = self.pending_transactions.get(tx.hash, None) diff --git a/hathor/p2p/sync_v2/agent.py b/hathor/p2p/sync_v2/agent.py index b2ee4543b..780e84f41 100644 --- a/hathor/p2p/sync_v2/agent.py +++ b/hathor/p2p/sync_v2/agent.py @@ -337,7 +337,6 @@ def run_sync_mempool(self) -> Generator[Any, Any, None]: def get_my_best_block(self) -> _HeightInfo: """Return my best block info.""" bestblock = self.tx_storage.get_best_block() - assert bestblock.hash is not None meta = bestblock.get_metadata() assert meta.validation.is_fully_connected() return _HeightInfo(height=bestblock.get_height(), id=bestblock.hash) @@ -609,11 +608,11 @@ def on_block_complete(self, blk: Block, vertex_list: list[BaseTransaction]) -> G """This method is called when a block and its transactions are downloaded.""" # Note: Any vertex and block could have already been added by another concurrent syncing peer. for tx in vertex_list: - if not self.tx_storage.transaction_exists(not_none(tx.hash)): + if not self.tx_storage.transaction_exists(tx.hash): self.manager.on_new_tx(tx, propagate_to_peers=False, fails_silently=False) yield deferLater(self.reactor, 0, lambda: None) - if not self.tx_storage.transaction_exists(not_none(blk.hash)): + if not self.tx_storage.transaction_exists(blk.hash): self.manager.on_new_tx(blk, propagate_to_peers=False, fails_silently=False) def get_peer_block_hashes(self, heights: list[int]) -> Deferred[list[_HeightInfo]]: @@ -774,7 +773,6 @@ def handle_blocks(self, payload: str) -> None: # Not a block. Punish peer? return blk.storage = self.tx_storage - assert blk.hash is not None assert self._blk_streaming_client is not None self._blk_streaming_client.handle_blocks(blk) @@ -839,7 +837,7 @@ def handle_get_best_block(self, _payload: str) -> None: meta = best_block.get_metadata() assert meta.validation.is_fully_connected() payload = BestBlockPayload( - block=not_none(best_block.hash), + block=best_block.hash, height=not_none(meta.height), ) self.send_message(ProtocolMessages.BEST_BLOCK, payload.json()) @@ -862,8 +860,8 @@ def start_transactions_streaming(self, partial_blocks: list[Block]) -> Deferred[ limit=self.DEFAULT_STREAMING_LIMIT) start_from: list[bytes] = [] - first_block_hash = not_none(partial_blocks[0].hash) - last_block_hash = not_none(partial_blocks[-1].hash) + first_block_hash = partial_blocks[0].hash + last_block_hash = partial_blocks[-1].hash self.log.info('requesting transactions streaming', start_from=[x.hex() for x in start_from], first_block=first_block_hash.hex(), @@ -878,8 +876,8 @@ def resume_transactions_streaming(self) -> Deferred[StreamEnd]: partial_blocks = self._tx_streaming_client.partial_blocks[idx:] assert partial_blocks start_from = list(self._tx_streaming_client._waiting_for) - first_block_hash = not_none(partial_blocks[0].hash) - last_block_hash = not_none(partial_blocks[-1].hash) + first_block_hash = partial_blocks[0].hash + last_block_hash = partial_blocks[-1].hash self.log.info('requesting transactions streaming', start_from=[x.hex() for x in start_from], first_block=first_block_hash.hex(), @@ -954,8 +952,6 @@ def handle_get_transactions_bfs(self, payload: str) -> None: self.log.debug('requested start_from_hash not found', start_from_hash=start_from_hash.hex()) self.send_message(ProtocolMessages.NOT_FOUND, start_from_hash.hex()) return - assert tx.hash is not None - assert first_block.hash is not None meta = tx.get_metadata() if meta.first_block != first_block.hash: self.log.debug('requested start_from not confirmed by first_block', @@ -1023,7 +1019,6 @@ def handle_transaction(self, payload: str) -> None: # tx_bytes = bytes.fromhex(payload) tx_bytes = base64.b64decode(payload) tx = tx_or_block_from_bytes(tx_bytes) - assert tx.hash is not None if not isinstance(tx, Transaction): self.log.warn('not a transaction', hash=tx.hash_hex) # Not a transaction. Punish peer? @@ -1070,7 +1065,6 @@ def get_data(self, tx_id: bytes, origin: str) -> Deferred[BaseTransaction]: def _on_get_data(self, tx: BaseTransaction, origin: str) -> None: """ Called when a requested tx is received. """ - assert tx.hash is not None deferred = self._deferred_txs.pop(tx.hash, None) if deferred is None: # Peer sent the wrong transaction?! @@ -1148,14 +1142,12 @@ def handle_data(self, payload: str) -> None: return assert tx is not None - assert tx.hash is not None if self.protocol.node.tx_storage.get_genesis(tx.hash): # We just got the data of a genesis tx/block. What should we do? # Will it reduce peer reputation score? return tx.storage = self.protocol.node.tx_storage - assert tx.hash is not None if self.partial_vertex_exists(tx.hash): # transaction already added to the storage, ignore it diff --git a/hathor/p2p/sync_v2/blockchain_streaming_client.py b/hathor/p2p/sync_v2/blockchain_streaming_client.py index 3635396b9..a08b305de 100644 --- a/hathor/p2p/sync_v2/blockchain_streaming_client.py +++ b/hathor/p2p/sync_v2/blockchain_streaming_client.py @@ -104,7 +104,6 @@ def handle_blocks(self, blk: Block) -> None: # return # Check for repeated blocks. - assert blk.hash is not None is_duplicated = False if self.partial_vertex_exists(blk.hash): # We reached a block we already have. Skip it. diff --git a/hathor/p2p/sync_v2/mempool.py b/hathor/p2p/sync_v2/mempool.py index b914804e9..d4eb7bfe6 100644 --- a/hathor/p2p/sync_v2/mempool.py +++ b/hathor/p2p/sync_v2/mempool.py @@ -133,6 +133,5 @@ def _next_missing_dep(self, tx: BaseTransaction) -> Optional[bytes]: def _add_tx(self, tx: BaseTransaction) -> None: """Add tx to the DAG.""" - assert tx.hash is not None self.missing_tips.discard(tx.hash) self.manager.on_new_tx(tx) diff --git a/hathor/p2p/sync_v2/streamers.py b/hathor/p2p/sync_v2/streamers.py index 22dbd8360..df11131ba 100644 --- a/hathor/p2p/sync_v2/streamers.py +++ b/hathor/p2p/sync_v2/streamers.py @@ -170,7 +170,6 @@ def send_next(self) -> None: cur = self.current_block assert cur is not None - assert cur.hash is not None meta = cur.get_metadata() if meta.voided_by: @@ -251,7 +250,7 @@ def get_iter(self) -> Iterator[BaseTransaction]: root = self.start_from skip_root = False self.log.debug('iterating over transactions from block', - block=not_none(self.current_block.hash).hex(), + block=self.current_block.hash.hex(), height=self.current_block.get_height(), start_from=self.start_from, skip_root=skip_root) @@ -287,7 +286,6 @@ def send_next(self) -> None: return assert isinstance(cur, Transaction) - assert cur.hash is not None cur_metadata = cur.get_metadata() if cur_metadata.first_block is None: diff --git a/hathor/p2p/sync_v2/transaction_streaming_client.py b/hathor/p2p/sync_v2/transaction_streaming_client.py index b46ea546b..d1b068222 100644 --- a/hathor/p2p/sync_v2/transaction_streaming_client.py +++ b/hathor/p2p/sync_v2/transaction_streaming_client.py @@ -28,7 +28,6 @@ from hathor.transaction import BaseTransaction from hathor.transaction.exceptions import HathorError, TxValidationError from hathor.types import VertexId -from hathor.util import not_none if TYPE_CHECKING: from hathor.p2p.sync_v2.agent import NodeBlockSync @@ -117,7 +116,6 @@ def handle_transaction(self, tx: BaseTransaction) -> None: self.fails(TooManyVerticesReceivedError()) return - assert tx.hash is not None self.log.debug('tx received', tx_id=tx.hash.hex()) self._queue.append(tx) assert len(self._queue) <= self._tx_max_quantity @@ -141,7 +139,7 @@ def process_queue(self) -> Generator[Any, Any, None]: self._is_processing = True try: tx = self._queue.popleft() - self.log.debug('processing tx', tx_id=not_none(tx.hash).hex()) + self.log.debug('processing tx', tx_id=tx.hash.hex()) yield self._process_transaction(tx) finally: self._is_processing = False @@ -151,7 +149,6 @@ def process_queue(self) -> Generator[Any, Any, None]: @inlineCallbacks def _process_transaction(self, tx: BaseTransaction) -> Generator[Any, Any, None]: """Process transaction.""" - assert tx.hash is not None # Run basic verification. if not tx.is_genesis: diff --git a/hathor/reward_lock/reward_lock.py b/hathor/reward_lock/reward_lock.py index 45f252d08..cd088905b 100644 --- a/hathor/reward_lock/reward_lock.py +++ b/hathor/reward_lock/reward_lock.py @@ -43,7 +43,6 @@ def get_spent_reward_locked_info(tx: 'Transaction', storage: 'VertexStorageProto unlocked.""" from hathor.transaction.transaction import RewardLockedInfo for blk in iter_spent_rewards(tx, storage): - assert blk.hash is not None needed_height = _spent_reward_needed_height(blk, storage) if needed_height > 0: return RewardLockedInfo(blk.hash, needed_height) diff --git a/hathor/simulator/patches.py b/hathor/simulator/patches.py index 3c056249e..95e9d4ebf 100644 --- a/hathor/simulator/patches.py +++ b/hathor/simulator/patches.py @@ -26,7 +26,6 @@ class SimulatorVertexVerifier(VertexVerifier): @classmethod def verify_pow(cls, vertex: BaseTransaction, *, override_weight: Optional[float] = None) -> None: - assert vertex.hash is not None logger.new().debug('Skipping VertexVerifier.verify_pow() for simulator') diff --git a/hathor/stratum/stratum.py b/hathor/stratum/stratum.py index 2b9dd8322..6cc6d7dea 100644 --- a/hathor/stratum/stratum.py +++ b/hathor/stratum/stratum.py @@ -523,7 +523,6 @@ def handle_submit(self, params: dict, msgid: Optional[str]) -> None: else: tx.nonce = int(params['nonce'], 16) tx.update_hash() - assert tx.hash is not None self.log.debug('share received', block=tx, block_base=block_base.hex(), block_base_hash=block_base_hash.hex()) diff --git a/hathor/transaction/resources/transaction.py b/hathor/transaction/resources/transaction.py index 8b755ae02..796030c0d 100644 --- a/hathor/transaction/resources/transaction.py +++ b/hathor/transaction/resources/transaction.py @@ -86,7 +86,6 @@ def get_tx_extra_data(tx: BaseTransaction, *, detail_tokens: bool = True) -> dic tx2 = tx.storage.get_transaction(tx_in.tx_id) tx2_out = tx2.outputs[tx_in.index] output = tx2_out.to_json(decode_script=True) - assert tx2.hash is not None output['tx_id'] = tx2.hash_hex output['index'] = tx_in.index diff --git a/hathor/transaction/storage/cache_storage.py b/hathor/transaction/storage/cache_storage.py index 8a1937a03..f8f058e5f 100644 --- a/hathor/transaction/storage/cache_storage.py +++ b/hathor/transaction/storage/cache_storage.py @@ -141,7 +141,6 @@ def _flush_to_storage(self, dirty_txs_copy: set[bytes]) -> None: self.store._save_transaction(tx) def remove_transaction(self, tx: BaseTransaction) -> None: - assert tx.hash is not None super().remove_transaction(tx) self.cache.pop(tx.hash, None) self.dirty_txs.discard(tx.hash) @@ -160,7 +159,6 @@ def get_all_genesis(self) -> set[BaseTransaction]: def _save_transaction(self, tx: BaseTransaction, *, only_metadata: bool = False) -> None: """Saves the transaction without modifying TimestampIndex entries (in superclass).""" - assert tx.hash is not None self._update_cache(tx) self.dirty_txs.add(tx.hash) @@ -179,7 +177,6 @@ def _update_cache(self, tx: BaseTransaction) -> None: If we need to evict a tx from cache and it's dirty, write it to disk immediately. """ - assert tx.hash is not None _tx = self.cache.get(tx.hash, None) if not _tx: if len(self.cache) >= self.capacity: diff --git a/hathor/transaction/storage/memory_storage.py b/hathor/transaction/storage/memory_storage.py index f7f897b73..25dba96ee 100644 --- a/hathor/transaction/storage/memory_storage.py +++ b/hathor/transaction/storage/memory_storage.py @@ -61,7 +61,6 @@ def set_migration_state(self, migration_name: str, state: MigrationState) -> Non pass def remove_transaction(self, tx: BaseTransaction) -> None: - assert tx.hash is not None super().remove_transaction(tx) self.transactions.pop(tx.hash, None) self.metadata.pop(tx.hash, None) @@ -71,7 +70,6 @@ def save_transaction(self, tx: 'BaseTransaction', *, only_metadata: bool = False self._save_transaction(tx, only_metadata=only_metadata) def _save_transaction(self, tx: BaseTransaction, *, only_metadata: bool = False) -> None: - assert tx.hash is not None if not only_metadata: self.transactions[tx.hash] = self._clone(tx) meta = getattr(tx, '_metadata', None) diff --git a/hathor/transaction/storage/transaction_storage.py b/hathor/transaction/storage/transaction_storage.py index fd57323a9..f3f6bed60 100644 --- a/hathor/transaction/storage/transaction_storage.py +++ b/hathor/transaction/storage/transaction_storage.py @@ -49,7 +49,6 @@ from hathor.transaction.transaction import Transaction from hathor.transaction.transaction_metadata import TransactionMetadata from hathor.types import VertexId -from hathor.util import not_none cpu = get_cpu_profiler() @@ -331,14 +330,12 @@ def _save_or_verify_genesis(self) -> None: for tx in genesis_txs: try: - assert tx.hash is not None tx2 = self.get_transaction(tx.hash) assert tx == tx2 except TransactionDoesNotExist: self.save_transaction(tx) self.add_to_indexes(tx) tx2 = tx - assert tx2.hash is not None self._genesis_cache[tx2.hash] = tx2 self._saving_genesis = False @@ -347,7 +344,6 @@ def _save_to_weakref(self, tx: BaseTransaction) -> None: """ if self._tx_weakref_disabled: return - assert tx.hash is not None tx2 = self._tx_weakref.get(tx.hash, None) if tx2 is None: self._tx_weakref[tx.hash] = tx @@ -359,7 +355,6 @@ def _remove_from_weakref(self, tx: BaseTransaction) -> None: """ if self._tx_weakref_disabled: return - assert tx.hash is not None self._tx_weakref.pop(tx.hash, None) def get_transaction_from_weakref(self, hash_bytes: bytes) -> Optional[BaseTransaction]: @@ -425,7 +420,6 @@ def save_transaction(self: 'TransactionStorage', tx: BaseTransaction, *, only_me :param tx: Transaction to save :param only_metadata: Don't save the transaction, only the metadata of this transaction """ - assert tx.hash is not None meta = tx.get_metadata() self.pre_save_validation(tx, meta) @@ -438,7 +432,6 @@ def pre_save_validation(self, tx: BaseTransaction, tx_meta: TransactionMetadata) This method receives the transaction AND the metadata in order to avoid calling ".get_metadata()" which could potentially create a fresh metadata. """ - assert tx.hash is not None assert tx_meta.hash is not None assert tx.hash == tx_meta.hash, f'{tx.hash.hex()} != {tx_meta.hash.hex()}' self._validate_partial_marker_consistency(tx_meta) @@ -498,9 +491,8 @@ def remove_transactions(self, txs: list[BaseTransaction]) -> None: """ parents_to_update: dict[bytes, list[bytes]] = defaultdict(list) dangling_children: set[bytes] = set() - txset = {not_none(tx.hash) for tx in txs} + txset = {tx.hash for tx in txs} for tx in txs: - assert tx.hash is not None tx_meta = tx.get_metadata() assert not tx_meta.validation.is_checkpoint() for parent in set(tx.parents) - txset: @@ -535,7 +527,6 @@ def transaction_exists(self, hash_bytes: bytes) -> bool: def compare_bytes_with_local_tx(self, tx: BaseTransaction) -> bool: """Compare byte-per-byte `tx` with the local transaction.""" - assert tx.hash is not None # XXX: we have to accept any scope because we only want to know what bytes we have stored with tx_allow_context(self, allow_scope=TxAllowScope.ALL): local_tx = self.get_transaction(tx.hash) @@ -1370,7 +1361,6 @@ def __init__(self, tx: BaseTransaction): heapq.heapify(to_visit) while to_visit: item = heapq.heappop(to_visit) - assert item.tx.hash is not None yield item.tx # XXX: We can safely discard because no other tx will try to visit this one, since timestamps are strictly # higher in children, meaning we cannot possibly have item.tx as a descendant of any tx in to_visit. @@ -1404,7 +1394,6 @@ def _run_topological_sort_dfs(self, root: BaseTransaction, visited: dict[bytes, stack = [root] while stack: tx = stack[-1] - assert tx.hash is not None if tx.hash in visited: if visited[tx.hash] == 0: visited[tx.hash] = 1 # 1 = Visited diff --git a/hathor/transaction/storage/traversal.py b/hathor/transaction/storage/traversal.py index fc6bbc110..d88b47b9d 100644 --- a/hathor/transaction/storage/traversal.py +++ b/hathor/transaction/storage/traversal.py @@ -134,7 +134,6 @@ def run(self, root: Union['BaseTransaction', Iterable['BaseTransaction']], *, roots = root if isinstance(root, Iterable) else [root] for root in roots: - assert root.hash is not None self.seen.add(root.hash) if not skip_root: self._push_visit(root) @@ -143,7 +142,6 @@ def run(self, root: Union['BaseTransaction', Iterable['BaseTransaction']], *, while not self._is_empty(): tx = self._pop_visit() - assert tx.hash is not None yield tx if not self._ignore_neighbors: self.add_neighbors(tx) @@ -172,7 +170,6 @@ def _pop_visit(self) -> 'BaseTransaction': tx = item.tx # We can safely remove it because we are walking in topological order # and it won't appear again in the future because this would be a cycle. - assert tx.hash is not None self.seen.remove(tx.hash) return tx diff --git a/hathor/util.py b/hathor/util.py index b66acee2a..cd1f0b090 100644 --- a/hathor/util.py +++ b/hathor/util.py @@ -477,7 +477,6 @@ def _tx_progress(iter_tx: Iterator['BaseTransaction'], *, log: 'structlog.stdlib if dt_next > _DT_ITER_NEXT_WARN: log.warn('iterator was slow to yield', took_sec=dt_next) - assert tx.hash is not None # XXX: this is only informative and made to work with either partially/fully validated blocks/transactions meta = tx.get_metadata() if meta.height: diff --git a/hathor/verification/token_creation_transaction_verifier.py b/hathor/verification/token_creation_transaction_verifier.py index 66d96f111..4d0ac543c 100644 --- a/hathor/verification/token_creation_transaction_verifier.py +++ b/hathor/verification/token_creation_transaction_verifier.py @@ -18,7 +18,6 @@ from hathor.transaction.transaction import TokenInfo from hathor.transaction.util import clean_token_string from hathor.types import TokenUid -from hathor.util import not_none class TokenCreationTransactionVerifier: @@ -36,7 +35,7 @@ def verify_minted_tokens(self, tx: TokenCreationTransaction, token_dict: dict[To :raises InputOutputMismatch: if sum of inputs is not equal to outputs and there's no mint/melt """ # make sure tokens are being minted - token_info = token_dict[not_none(tx.hash)] + token_info = token_dict[tx.hash] if token_info.amount <= 0: raise InvalidToken('Token creation transaction must mint new tokens') diff --git a/hathor/verification/transaction_verifier.py b/hathor/verification/transaction_verifier.py index 2d86883c2..c634ba1d8 100644 --- a/hathor/verification/transaction_verifier.py +++ b/hathor/verification/transaction_verifier.py @@ -83,7 +83,6 @@ def verify_sigops_input(self, tx: Transaction) -> None: spent_tx = tx.get_spent_tx(tx_input) except TransactionDoesNotExist: raise InexistentInput('Input tx does not exist: {}'.format(tx_input.tx_id.hex())) - assert spent_tx.hash is not None if tx_input.index >= len(spent_tx.outputs): raise InexistentInput('Output spent by this input does not exist: {} index {}'.format( tx_input.tx_id.hex(), tx_input.index)) @@ -106,7 +105,6 @@ def verify_inputs(self, tx: Transaction, *, skip_script: bool = False) -> None: try: spent_tx = tx.get_spent_tx(input_tx) - assert spent_tx.hash is not None if input_tx.index >= len(spent_tx.outputs): raise InexistentInput('Output spent by this input does not exist: {} index {}'.format( input_tx.tx_id.hex(), input_tx.index)) diff --git a/hathor/verification/vertex_verifier.py b/hathor/verification/vertex_verifier.py index 80a621502..8947dd591 100644 --- a/hathor/verification/vertex_verifier.py +++ b/hathor/verification/vertex_verifier.py @@ -73,7 +73,6 @@ def verify_parents(self, vertex: BaseTransaction) -> None: for parent_hash in vertex.parents: try: parent = vertex.storage.get_transaction(parent_hash) - assert parent.hash is not None if vertex.timestamp <= parent.timestamp: raise TimestampError('tx={} timestamp={}, parent={} timestamp={}'.format( vertex.hash_hex, @@ -129,7 +128,6 @@ def verify_pow(self, vertex: BaseTransaction, *, override_weight: Optional[float :raises PowError: when the hash is equal or greater than the target """ - assert vertex.hash is not None numeric_hash = int(vertex.hash_hex, vertex.HEX_BASE) minimum_target = vertex.get_target(override_weight) if numeric_hash >= minimum_target: diff --git a/hathor/wallet/base_wallet.py b/hathor/wallet/base_wallet.py index ec5e2dc5e..7b38dfa12 100644 --- a/hathor/wallet/base_wallet.py +++ b/hathor/wallet/base_wallet.py @@ -517,7 +517,6 @@ def on_new_tx(self, tx: BaseTransaction) -> None: If an output matches, will add it to the unspent_txs dict. If an input matches, removes from unspent_txs dict and adds to spent_txs dict. """ - assert tx.hash is not None meta = tx.get_metadata() if meta.voided_by is not None: @@ -614,7 +613,6 @@ def on_tx_voided(self, tx: Transaction) -> None: :param tx: Transaction that was voided :type tx: :py:class:`hathor.transaction.Transaction` """ - assert tx.hash is not None assert tx.storage is not None should_update = False @@ -736,7 +734,6 @@ def on_tx_winner(self, tx: Transaction) -> None: :param tx: Transaction that was voided :type tx: :py:class:`hathor.transaction.Transaction` """ - assert tx.hash is not None assert tx.storage is not None should_update = False diff --git a/slow_tests/test_simulator.py b/slow_tests/test_simulator.py index 59c4c1967..f5477ad59 100644 --- a/slow_tests/test_simulator.py +++ b/slow_tests/test_simulator.py @@ -26,8 +26,8 @@ def setUp(self): print('Simulation seed config:', self.random_seed) print('-'*30) - def verify_pow(self) -> None: - assert self.hash is not None + def verify_pow(_) -> None: + pass self.old_verify_pow = BaseTransaction.verify_pow BaseTransaction.verify_pow = verify_pow diff --git a/tests/resources/transaction/test_pushtx.py b/tests/resources/transaction/test_pushtx.py index e861283df..7ed5b3e36 100644 --- a/tests/resources/transaction/test_pushtx.py +++ b/tests/resources/transaction/test_pushtx.py @@ -7,7 +7,6 @@ from hathor.transaction import Transaction, TxInput from hathor.transaction.resources import PushTxResource from hathor.transaction.scripts import P2PKH, parse_address_script -from hathor.util import not_none from hathor.wallet.base_wallet import WalletInputInfo, WalletOutputInfo from hathor.wallet.resources import SendTokensResource from tests import unittest @@ -100,7 +99,7 @@ def test_push_tx(self) -> Generator: # invalid transaction, without forcing tx.timestamp = 5 - tx.inputs = [TxInput(not_none(blocks[1].hash), 0, b'')] + tx.inputs = [TxInput(blocks[1].hash, 0, b'')] script_type_out = parse_address_script(blocks[1].outputs[0].script) assert script_type_out is not None private_key = self.manager.wallet.get_private_key(script_type_out.address) @@ -226,7 +225,6 @@ def test_spending_voided(self) -> Generator: p2pkh = parse_address_script(txout.script) assert p2pkh is not None private_key = wallet.get_private_key(p2pkh.address) - assert tx.hash is not None inputs = [WalletInputInfo(tx_id=tx.hash, index=0, private_key=private_key)] outputs = [WalletOutputInfo(address=decode_address(p2pkh.address), value=txout.value, timelock=None), ] tx2 = self.get_tx(inputs, outputs) @@ -237,7 +235,6 @@ def test_spending_voided(self) -> Generator: # Now we set this tx2 as voided and try to push a tx3 that spends tx2 tx_meta = tx2.get_metadata() - assert tx2.hash is not None tx_meta.voided_by = {tx2.hash} self.manager.tx_storage.save_transaction(tx2, only_metadata=True) diff --git a/tests/tx/test_indexes3.py b/tests/tx/test_indexes3.py index 8a1f27ea6..c7a513acf 100644 --- a/tests/tx/test_indexes3.py +++ b/tests/tx/test_indexes3.py @@ -92,7 +92,6 @@ def test_topological_iterators(self): # XXX: sanity check that the children metadata is properly set (this is needed for one of the iterators) for tx in tx_storage.get_all_transactions(): - assert tx.hash is not None for parent_tx in map(tx_storage.get_transaction, tx.parents): self.assertIn(tx.hash, parent_tx.get_metadata().children) diff --git a/tests/tx/test_indexes4.py b/tests/tx/test_indexes4.py index cc0e726a3..7777d69e1 100644 --- a/tests/tx/test_indexes4.py +++ b/tests/tx/test_indexes4.py @@ -123,7 +123,6 @@ def test_topological_iterators(self): # XXX: sanity check that the children metadata is properly set (this is needed for one of the iterators) for tx in tx_storage.get_all_transactions(): - assert tx.hash is not None for parent_tx in map(tx_storage.get_transaction, tx.parents): self.assertIn(tx.hash, parent_tx.get_metadata().children) diff --git a/tests/tx/test_tips.py b/tests/tx/test_tips.py index 9fbc0af46..ce2194bef 100644 --- a/tests/tx/test_tips.py +++ b/tests/tx/test_tips.py @@ -167,8 +167,7 @@ class SyncV1TipsTestCase(unittest.SyncV1Params, BaseTipsTestCase): __test__ = True def get_tips(self): - from hathor.util import not_none - return {not_none(tx.hash) for tx in self.manager.tx_storage.iter_mempool_tips_from_tx_tips()} + return {tx.hash for tx in self.manager.tx_storage.iter_mempool_tips_from_tx_tips()} class SyncV2TipsTestCase(unittest.SyncV2Params, BaseTipsTestCase): diff --git a/tests/unittest.py b/tests/unittest.py index 939e32853..d99b94925 100644 --- a/tests/unittest.py +++ b/tests/unittest.py @@ -298,7 +298,6 @@ def assertIsTopological(self, tx_sequence: Iterator[BaseTransaction], message: O valid_deps = set(get_all_genesis_hashes(self._settings) if initial is None else initial) for tx in tx_sequence: - assert tx.hash is not None for dep in tx.get_all_dependencies(): self.assertIn(dep, valid_deps, message) valid_deps.add(tx.hash) @@ -426,7 +425,6 @@ def get_all_executed_or_voided( tx_voided = set() tx_partial = set() for tx in tx_storage.get_all_transactions(): - assert tx.hash is not None tx_meta = tx.get_metadata() if not tx_meta.validation.is_fully_connected(): tx_partial.add(tx.hash) diff --git a/tests/utils.py b/tests/utils.py index fff406b36..0e3ec7c90 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -24,7 +24,7 @@ from hathor.transaction.scripts import P2PKH, HathorScript, Opcode, parse_address_script from hathor.transaction.token_creation_tx import TokenCreationTransaction from hathor.transaction.util import get_deposit_amount -from hathor.util import Random, not_none +from hathor.util import Random try: import rocksdb # noqa: F401 @@ -73,7 +73,6 @@ def gen_custom_tx(manager: HathorManager, tx_inputs: list[tuple[BaseTransaction, value = 0 parents = [] for tx_base, txout_index in tx_inputs: - assert tx_base.hash is not None spent_tx = tx_base spent_txout = spent_tx.outputs[txout_index] p2pkh = parse_address_script(spent_txout.script) @@ -81,7 +80,6 @@ def gen_custom_tx(manager: HathorManager, tx_inputs: list[tuple[BaseTransaction, from hathor.wallet.base_wallet import WalletInputInfo, WalletOutputInfo value += spent_txout.value - assert spent_tx.hash is not None private_key = wallet.get_private_key(p2pkh.address) inputs.append(WalletInputInfo(tx_id=spent_tx.hash, index=txout_index, private_key=private_key)) if not tx_base.is_block: @@ -110,7 +108,6 @@ def gen_custom_tx(manager: HathorManager, tx_inputs: list[tuple[BaseTransaction, tx2.parents = parents[:2] if len(tx2.parents) < 2: if base_parent: - assert base_parent.hash is not None tx2.parents.append(base_parent.hash) elif not tx_base.is_block: tx2.parents.append(tx_base.parents[0]) @@ -426,7 +423,7 @@ def create_tokens(manager: 'HathorManager', address_b58: Optional[str] = None, m deposit_input = [] while total_reward < deposit_amount: block = add_new_block(manager, advance_clock=1, address=address) - deposit_input.append(TxInput(not_none(block.hash), 0, b'')) + deposit_input.append(TxInput(block.hash, 0, b'')) total_reward += block.outputs[0].value if total_reward > deposit_amount: @@ -516,7 +513,7 @@ def add_tx_with_data_script(manager: 'HathorManager', data: list[str], propagate burn_input = [] while total_reward < burn_amount: block = add_new_block(manager, advance_clock=1, address=address) - burn_input.append(TxInput(not_none(block.hash), 0, b'')) + burn_input.append(TxInput(block.hash, 0, b'')) total_reward += block.outputs[0].value # Create the change output, if needed