Skip to content

Commit

Permalink
Merge pull request #7982 from drew2a/fix/7981
Browse files Browse the repository at this point in the history
Handle corupted pieces in a handle status
  • Loading branch information
drew2a committed Apr 22, 2024
2 parents 3df32a1 + 0ef78af commit 37e8bb9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 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
17 changes: 15 additions & 2 deletions src/tribler/core/components/libtorrent/tests/test_download.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from asyncio import Future, sleep
from base64 import b64encode
from pathlib import Path
from typing import Generator
from unittest.mock import MagicMock, Mock, PropertyMock, patch

import libtorrent as lt
import pytest
from _pytest.logging import LogCaptureFixture
from bitarray import bitarray
from ipv8.util import succeed
from libtorrent import bencode

Expand Down Expand Up @@ -494,11 +496,22 @@ def test_get_pieces_bitmask(mock_handle, test_download):
"""
Testing whether a correct pieces bitmask is returned when requested
"""

def _repr(s):
""" Helper function to return the base64 representation of a bitarray"""
return b64encode(bitarray(s).tobytes())

test_download.handle.status().pieces = [True, False, True, False, False]
assert test_download.get_pieces_base64() == b"oA=="
assert test_download.get_pieces_base64() == _repr('10100')

test_download.handle.status().pieces = [True] * 16
assert test_download.get_pieces_base64() == b"//8="
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):
Expand Down

0 comments on commit 37e8bb9

Please sign in to comment.