From af7574dc9db8977fa3e1a2f97f732d97c88eceae Mon Sep 17 00:00:00 2001 From: Victor Shyba Date: Tue, 22 Feb 2022 15:51:36 -0300 Subject: [PATCH] replace duplicated code --- lbry/dht/protocol/routing_table.py | 11 +++++------ lbry/extras/daemon/components.py | 5 ++--- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/lbry/dht/protocol/routing_table.py b/lbry/dht/protocol/routing_table.py index 344158a95..b16efb37c 100644 --- a/lbry/dht/protocol/routing_table.py +++ b/lbry/dht/protocol/routing_table.py @@ -6,6 +6,7 @@ import itertools from prometheus_client import Gauge +from lbry import utils from lbry.dht import constants from lbry.dht.protocol.distance import Distance if typing.TYPE_CHECKING: @@ -70,9 +71,8 @@ class KBucket: if len(self.peers) < constants.K: self.peers.append(peer) self.peer_in_routing_table_metric.labels("global").inc() - if peer.node_id[0] == self._node_id[0]: - bits_colliding = 8 - (peer.node_id[1] ^ self._node_id[1]).bit_length() - self.peer_with_x_bit_colliding_metric.labels(amount=(bits_colliding + 8)).inc() + bits_colliding = utils.get_colliding_prefix_bits(peer.node_id, self._node_id, 32) + self.peer_with_x_bit_colliding_metric.labels(amount=bits_colliding).inc() return True else: return False @@ -140,9 +140,8 @@ class KBucket: def remove_peer(self, peer: 'KademliaPeer') -> None: self.peers.remove(peer) self.peer_in_routing_table_metric.labels("global").dec() - if peer.node_id[0] == self._node_id[0]: - bits_colliding = 8 - (peer.node_id[1] ^ self._node_id[1]).bit_length() - self.peer_with_x_bit_colliding_metric.labels(amount=(bits_colliding + 8)).dec() + bits_colliding = utils.get_colliding_prefix_bits(peer.node_id, self._node_id, 32) + self.peer_with_x_bit_colliding_metric.labels(amount=bits_colliding).dec() def key_in_range(self, key: bytes) -> bool: """ Tests whether the specified key (i.e. node ID) is in the range diff --git a/lbry/extras/daemon/components.py b/lbry/extras/daemon/components.py index f51af4f3f..c1e3fe046 100644 --- a/lbry/extras/daemon/components.py +++ b/lbry/extras/daemon/components.py @@ -417,12 +417,11 @@ class BackgroundDownloaderComponent(Component): await asyncio.sleep(self.download_loop_delay_seconds) def _download_next_close_blob_hash(self): - node_id_prefix = int.from_bytes(self.dht_node.protocol.node_id[:4], "big") + node_id = self.dht_node.protocol.node_id for blob_hash in self.dht_node.stored_blob_hashes: - colliding_bits = 32 - int(node_id_prefix ^ int.from_bytes(blob_hash[:4], "big")).bit_length() if blob_hash.hex() in self.blob_manager.completed_blob_hashes: continue - if colliding_bits >= self.MIN_PREFIX_COLLIDING_BITS: + if utils.get_colliding_prefix_bits(node_id, blob_hash, 32) >= self.MIN_PREFIX_COLLIDING_BITS: self.ongoing_download = asyncio.create_task(self.background_downloader.download_blobs(blob_hash.hex())) async def start(self):