Skip to content

Commit

Permalink
Improve error handling in piece bitmask generation
Browse files Browse the repository at this point in the history
Adjusted the method for generating a base64 encoded bitmask of downloaded pieces. Now, it includes a try-except block to handle potential ValueError exceptions that could occur if the list of pieces is corrupted. This change ensures that an empty string is returned instead of allowing the exception to propagate. Additionally, a corresponding test case has been added to verify this new behavior when dealing with corrupted piece lists.
  • Loading branch information
drew2a committed Apr 22, 2024
1 parent 9eac127 commit 0ef78af
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def __init__(self,

def __str__(self):
return "Download <name: '%s' hops: %d checkpoint_disabled: %d>" % \
(self.tdef.get_name(), self.config.get_hops(), self.checkpoint_disabled)
(self.tdef.get_name(), self.config.get_hops(), self.checkpoint_disabled)

def __repr__(self):
return self.__str__()
Expand Down Expand Up @@ -248,7 +248,10 @@ def get_pieces_base64(self) -> bytes:
Returns a base64 encoded bitmask of the pieces that we have.
"""
binary_gen = (int(boolean) for boolean in self.handle.status().pieces)
bits = bitarray(binary_gen)
try:
bits = bitarray(binary_gen)
except ValueError:
return b''
return base64.b64encode(bits.tobytes())

def post_alert(self, alert_type: str, alert_dict: Optional[Dict] = None):
Expand Down
6 changes: 6 additions & 0 deletions src/tribler/core/components/libtorrent/tests/test_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,12 @@ def _repr(s):
assert test_download.get_pieces_base64() == _repr('1111111111111111')


def test_get_pieces_bitmask_corrupted(mock_handle, test_download):
""" Test that the get_pieces_base64() method returns an empty byte string when the pieces bitmask is corrupted. """
test_download.handle.status().pieces = [4]
assert test_download.get_pieces_base64() == b''


async def test_resume_data_failed(test_download):
"""
Testing whether the correct operations happen when an error is raised during resume data saving
Expand Down

0 comments on commit 0ef78af

Please sign in to comment.