From d31fe1cad016b2d6fd64a79f554b6884a11d5c86 Mon Sep 17 00:00:00 2001 From: "V.G. Bulavintsev" Date: Wed, 3 Jun 2020 14:07:11 +0200 Subject: [PATCH] Remove CreditMining feature --- .isort.cfg | 2 +- .../tribler_common/simpledefs.py | 2 - src/tribler-core/run_market_helper.py | 1 - src/tribler-core/run_tunnel_helper.py | 1 - .../config/test_tribler_config.py | 16 - .../tribler_core/config/tribler_config.py | 19 - .../tribler_core/config/tribler_config.spec | 5 - src/tribler-core/tribler_core/logger.yaml | 12 +- .../modules/credit_mining/__init__.py | 3 - .../credit_mining/credit_mining_manager.py | 352 ------- .../credit_mining/credit_mining_policy.py | 292 ------ .../credit_mining/credit_mining_source.py | 59 -- .../tests/test_credit_mining_manager.py | 466 ---------- .../tests/test_credit_mining_policies.py | 368 -------- .../tests/test_credit_mining_sources.py | 35 - .../modules/libtorrent/download.py | 3 - .../modules/libtorrent/download_config.py | 6 - .../modules/libtorrent/download_config.spec | 1 - .../modules/libtorrent/download_manager.py | 12 - .../libtorrent/restapi/downloads_endpoint.py | 4 +- .../libtorrent/tests/test_download_manager.py | 3 - .../tribler_core/restapi/events_endpoint.py | 2 - .../tribler_core/restapi/settings_endpoint.py | 23 - .../restapi/tests/test_events_endpoint.py | 1 - .../restapi/tests/test_settings_endpoint.py | 1 - src/tribler-core/tribler_core/session.py | 11 - .../tools/data/state_dir_dummy/triblerd.conf | 1 - .../tests/tools/data/test_rss_cm.xml | 31 - .../tests/tools/test_as_server.py | 2 - src/tribler-gui/tribler_gui/debug_window.py | 23 +- src/tribler-gui/tribler_gui/defs.py | 4 +- .../tribler_gui/event_request_manager.py | 2 - .../tribler_gui/qt_resources/mainwindow.ui | 867 ++---------------- .../tribler_gui/qt_resources/torrents_list.ui | 218 ++--- .../tests/fake_tribler_api/models/download.py | 4 +- .../tests/fake_tribler_api/tribler_data.py | 6 - src/tribler-gui/tribler_gui/tests/test_gui.py | 7 - src/tribler-gui/tribler_gui/tribler_window.py | 7 - .../widgets/channelcontentswidget.py | 1 - .../tribler_gui/widgets/downloadspage.py | 43 +- .../tribler_gui/widgets/settingspage.py | 17 +- .../widgets/subscriptionswidget.py | 56 +- .../tribler_gui/widgets/tokenminingpage.py | 123 --- .../tribler_gui/widgets/trustpage.py | 12 +- 44 files changed, 204 insertions(+), 2920 deletions(-) delete mode 100644 src/tribler-core/tribler_core/modules/credit_mining/__init__.py delete mode 100644 src/tribler-core/tribler_core/modules/credit_mining/credit_mining_manager.py delete mode 100644 src/tribler-core/tribler_core/modules/credit_mining/credit_mining_policy.py delete mode 100644 src/tribler-core/tribler_core/modules/credit_mining/credit_mining_source.py delete mode 100644 src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_manager.py delete mode 100644 src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_policies.py delete mode 100644 src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_sources.py delete mode 100644 src/tribler-core/tribler_core/tests/tools/data/test_rss_cm.xml delete mode 100644 src/tribler-gui/tribler_gui/widgets/tokenminingpage.py diff --git a/.isort.cfg b/.isort.cfg index 455257877e8..05e59737462 100644 --- a/.isort.cfg +++ b/.isort.cfg @@ -10,4 +10,4 @@ force_sort_within_sections=True line_length=120 known_future_library=future known_first_party=tribler_core,tribler_gui,tribler_common,run_tribler -known_third_party=pony,twisted,six,anydex,ipv8,libtorrent,lz4,PyQt5,zope,aiohttp,psutil,configobj,ipv8_service,asynctest,numpy,networkx,async_timeout,cherrypy,nose,validate,check_os,matplotlib,pyqtgraph,_socket +known_third_party=pony,twisted,six,anydex,ipv8,libtorrent,lz4,PyQt5,zope,aiohttp,psutil,configobj,ipv8_service,asynctest,numpy,networkx,async_timeout,cherrypy,nose,validate,check_os,matplotlib,pyqtgraph,_socket,PIL diff --git a/src/tribler-common/tribler_common/simpledefs.py b/src/tribler-common/tribler_common/simpledefs.py index 0de1a2058de..6712bfcd885 100644 --- a/src/tribler-common/tribler_common/simpledefs.py +++ b/src/tribler-common/tribler_common/simpledefs.py @@ -75,7 +75,6 @@ STATE_START_TORRENT_CHECKER = 'Starting torrent checker...' STATE_START_API_ENDPOINTS = 'Starting API endpoints...' STATE_START_WATCH_FOLDER = 'Starting watch folder...' -STATE_START_CREDIT_MINING = 'Starting credit mining...' STATE_START_RESOURCE_MONITOR = 'Starting resource monitor...' STATE_READABLE_STARTED = 'Started' @@ -98,7 +97,6 @@ class NTFY(Enum): UPGRADER_STARTED = "upgrader_started" UPGRADER_DONE = "upgrader_done" CHANNEL_ENTITY_UPDATED = "channel_entity_updated" - CREDIT_MINING_ERROR = "credit_mining_error" LOW_SPACE = "low_space" EVENTS_START = "events_start" TRIBLER_EXCEPTION = "tribler_exception" diff --git a/src/tribler-core/run_market_helper.py b/src/tribler-core/run_market_helper.py index fb409a1cb57..28837e0a078 100644 --- a/src/tribler-core/run_market_helper.py +++ b/src/tribler-core/run_market_helper.py @@ -42,7 +42,6 @@ async def signal_handler(sig): config.set_torrent_checking_enabled(False) config.set_libtorrent_enabled(True) config.set_http_api_enabled(True) - config.set_credit_mining_enabled(False) config.set_dummy_wallets_enabled(True) config.set_popularity_community_enabled(False) config.set_chant_enabled(False) diff --git a/src/tribler-core/run_tunnel_helper.py b/src/tribler-core/run_tunnel_helper.py index 46e42ab05ee..0b5451748f1 100644 --- a/src/tribler-core/run_tunnel_helper.py +++ b/src/tribler-core/run_tunnel_helper.py @@ -125,7 +125,6 @@ async def start(self, options): config.set_ipv8_port(ipv8_port) config.set_ipv8_address(options.ipv8_address) config.set_trustchain_enabled(True) - config.set_credit_mining_enabled(False) config.set_market_community_enabled(False) config.set_dht_enabled(True) config.set_tunnel_community_exitnode_enabled(bool(options.exit)) diff --git a/src/tribler-core/tribler_core/config/test_tribler_config.py b/src/tribler-core/tribler_core/config/test_tribler_config.py index c9b96b2a390..031c692eca9 100644 --- a/src/tribler-core/tribler_core/config/test_tribler_config.py +++ b/src/tribler-core/tribler_core/config/test_tribler_config.py @@ -78,11 +78,6 @@ def test_tunnel_community_socks5_listen_ports(self): self.tribler_config.set_tunnel_community_socks5_listen_ports(ports) self.assertListEqual(self.tribler_config.get_tunnel_community_socks5_listen_ports(), ports) - def test_credit_mining_sources(self): - source_list = "listitem" - self.tribler_config.set_credit_mining_sources(source_list) - self.assertEqual(self.tribler_config.get_credit_mining_sources(), source_list) - def test_bootstrap_configs(self): self.tribler_config.set_bootstrap_enabled(False) @@ -283,17 +278,6 @@ def test_get_set_methods_resource_monitor(self): self.tribler_config.set_cpu_priority_order(3) self.assertEqual(self.tribler_config.get_cpu_priority_order(), 3) - def test_get_set_methods_credit_mining(self): - """ - Check whether credit mining get and set methods are working as expected. - """ - self.tribler_config.set_credit_mining_enabled(True) - self.assertEqual(self.tribler_config.get_credit_mining_enabled(), True) - self.tribler_config.set_credit_mining_sources(True) - self.assertEqual(self.tribler_config.get_credit_mining_sources(), True) - self.tribler_config.set_credit_mining_disk_space(1024 ** 2) - self.assertEqual(self.tribler_config.get_credit_mining_disk_space(), 1024 ** 2) - def test_get_set_methods_dht(self): """ Check whether dht get and set methods are working as expected. diff --git a/src/tribler-core/tribler_core/config/tribler_config.py b/src/tribler-core/tribler_core/config/tribler_config.py index fb5827c6535..8c95d086f5e 100644 --- a/src/tribler-core/tribler_core/config/tribler_config.py +++ b/src/tribler-core/tribler_core/config/tribler_config.py @@ -594,22 +594,3 @@ def set_resource_monitor_history_size(self, value): def get_resource_monitor_history_size(self): return self.config['resource_monitor']['history_size'] - - # Credit mining - def set_credit_mining_enabled(self, value): - self.config['credit_mining']['enabled'] = value - - def get_credit_mining_enabled(self): - return self.config['credit_mining']['enabled'] - - def set_credit_mining_sources(self, source_list): - self.config['credit_mining']['sources'] = source_list - - def get_credit_mining_sources(self): - return self.config['credit_mining']['sources'] - - def set_credit_mining_disk_space(self, value): - self.config['credit_mining']['max_disk_space'] = value - - def get_credit_mining_disk_space(self): - return self.config['credit_mining']['max_disk_space'] diff --git a/src/tribler-core/tribler_core/config/tribler_config.spec b/src/tribler-core/tribler_core/config/tribler_config.spec index 18934689df1..3970ce3d1b6 100644 --- a/src/tribler-core/tribler_core/config/tribler_config.spec +++ b/src/tribler-core/tribler_core/config/tribler_config.spec @@ -99,11 +99,6 @@ cpu_priority = integer(min=0, max=5, default=1) poll_interval = integer(min=1, default=5) history_size = integer(min=1, default=20) -[credit_mining] -enabled = boolean(default=False) -sources = string_list(default=list()) -max_disk_space = integer(min=0, default=53687091200) - [popularity_community] enabled = boolean(default=True) cache_dir = string(default=health_cache) diff --git a/src/tribler-core/tribler_core/logger.yaml b/src/tribler-core/tribler_core/logger.yaml index f760fd3cbd2..44939342676 100644 --- a/src/tribler-core/tribler_core/logger.yaml +++ b/src/tribler-core/tribler_core/logger.yaml @@ -75,7 +75,7 @@ loggers: propagate: no asyncio: - level: DEBUG + level: INFO handlers: [console, error_console, info_memory_handler, error_memory_handler] propagate: no @@ -99,16 +99,6 @@ loggers: handlers: [console, error_console, info_memory_handler, error_memory_handler] propagate: no - CreditMiningManager: - level: INFO - handlers: [console, error_console, info_memory_handler, error_memory_handler] - propagate: no - - CreditMiningSource: - level: INFO - handlers: [console, error_console, info_memory_handler, error_memory_handler] - propagate: no - TrustChainDB: level: INFO handlers: [console, error_console, info_memory_handler, error_memory_handler] diff --git a/src/tribler-core/tribler_core/modules/credit_mining/__init__.py b/src/tribler-core/tribler_core/modules/credit_mining/__init__.py deleted file mode 100644 index 45733d29dd0..00000000000 --- a/src/tribler-core/tribler_core/modules/credit_mining/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -""" -CreditMining. -""" diff --git a/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_manager.py b/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_manager.py deleted file mode 100644 index bf16236cb3f..00000000000 --- a/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_manager.py +++ /dev/null @@ -1,352 +0,0 @@ -import logging -import os -import time -from asyncio import Future, ensure_future, gather -from binascii import unhexlify - -from ipv8.taskmanager import TaskManager - -import psutil - -from tribler_common.simpledefs import ( - DLSTATUS_DOWNLOADING, - DLSTATUS_SEEDING, - DLSTATUS_STOPPED, - DLSTATUS_STOPPED_ON_ERROR, - DOWNLOAD, - NTFY, - UPLOAD, -) - -from tribler_core.modules.credit_mining.credit_mining_policy import InvestmentPolicy, MB -from tribler_core.modules.credit_mining.credit_mining_source import ChannelSource -from tribler_core.modules.libtorrent.download_config import DownloadConfig -from tribler_core.modules.libtorrent.torrentdef import TorrentDefNoMetainfo -from tribler_core.utilities.unicode import hexlify - - -class CreditMiningTorrent(object): - """ - Wrapper class for Credit Mining download - """ - - def __init__(self, infohash, name, download=None, state=None): - self.infohash = infohash - self.name = name - self.download = download - self.state = state - self.sources = set() - self.force_checked = False - self.to_start = False - self.start_time = time.time() - self.mining_state = {} - - def get_storage(self): - """ Returns the total and used storage of the torrent.""" - full_size = self.download.get_def().get_length() - progress = self.download.get_state().get_progress() - return full_size, progress * full_size - - -class CreditMiningSettings(object): - """ - This class contains settings used by the credit mining manager - """ - - def __init__(self, config=None): - self.max_torrents_active = 8 - self.max_torrents_listed = 100 - # Note: be sure to set this interval to something that gives torrents a fair chance of - # discovering peers and uploading data - self.auto_manage_interval = 120 - self.hops = 1 - # Maximum number of bytes of disk space that credit mining is allowed to use. - self.max_disk_space = config.get_credit_mining_disk_space() if config else 50 * 1024 ** 3 - self.low_disk_space = 1000 * 1024 ** 2 - self.save_path = config.get_default_destination_dir() / 'credit_mining' - - -class CreditMiningManager(TaskManager): - """ - Class to manage all the credit mining activities - """ - - def __init__(self, session, settings=None, policies=None): - super(CreditMiningManager, self).__init__() - self._logger = logging.getLogger(self.__class__.__name__) - self._logger.info('Starting CreditMiningManager') - - self.session = session - self.settings = settings or CreditMiningSettings(session.config) - - self.sources = {} - self.torrents = {} - self.policies = [] - self.upload_mode = False - - # Our default policy [2019-01-24]: torrents are selected based on investment policy - self.policies = policies or [InvestmentPolicy()] - - if not self.settings.save_path.exists(): - os.makedirs(self.settings.save_path) - - self.register_task('check_disk_space', self.check_disk_space, interval=30) - self.num_checkpoints = len(list(self.session.dlmgr.get_checkpoint_dir().glob('*.conf'))) - - async def add_sources(): - await self.session_ready - for source in self.session.config.get_credit_mining_sources(): - self.add_source(source) - - self.session_ready = Future() - self.register_task('add_sources', add_sources) - - async def shutdown(self, remove_downloads=False): - """ - Shutting down credit mining manager. It also stops and remove all the sources. - """ - self._logger.info('Shutting down CreditMiningManager') - - await self.shutdown_task_manager() - - if remove_downloads and self.sources: - await gather(*[self.remove_source(source) for source in list(self.sources.keys())]) - - def get_free_disk_space(self): - return psutil.disk_usage(str(self.settings.save_path)).free - - def check_mining_directory(self): - # Check that credit mining directory exists, if not try to re-create it. - # FIXME: add exception for the case where there is an error trying to read check a forbidden directory - if not self.settings.save_path.exists(): - try: - os.makedirs(self.settings.save_path) - error_message = u"Credit mining directory [%s] does not exist. Tribler will re-create the " \ - u"directory and resume again.
If you wish to disable credit mining entirely, " \ - u"please go to Settings >> ANONYMITY >> Token mining. " % \ - self.settings.save_path - except OSError: - ensure_future(self.shutdown()) - error_message = u"Credit mining directory [%s] was deleted or does not exist and Tribler could not " \ - u"re-create the directory again. Credit mining will shutdown. Try restarting " \ - u"Tribler.
If you wish to disable credit mining entirely, please go to " \ - u"Settings >> ANONYMITY >> Token mining. " % self.settings.save_path - - gui_message = {"message": error_message} - self.session.notifier.notify(NTFY.CREDIT_MINING_ERROR, gui_message) - return False - return True - - def check_disk_space(self): - if not self.check_mining_directory(): - return - - # Note that we have a resource monitor that monitors the disk where the state-directory resides. - # However, since the credit mining directory can be on a different disk, we query the disk space ourselves. - is_low = self.get_free_disk_space() < self.settings.low_disk_space - if self.upload_mode != is_low: - self._logger.info('Setting upload mode to %s', is_low) - - self.upload_mode = is_low - - for download in self.session.dlmgr.get_downloads(): - if download.config.get_credit_mining(): - if download.handle and download.handle.is_valid(): - download.handle.set_upload_mode(is_low) - - def add_source(self, source_str): - """ - Add new source to the credit mining manager - """ - if source_str not in self.sources: - num_torrents = len(self.torrents) - - if isinstance(source_str, str): - source = ChannelSource(self.session, unhexlify(source_str), self.on_torrent_insert) - else: - self._logger.error('Cannot add unknown source %s', source_str) - return - - self.sources[source_str] = source - source.start() - self._logger.info('Added source %s', source_str) - - # If we don't have any torrents and the select LoopingCall is running, stop it. - # It will restart immediately after we have enough torrents. - if num_torrents == 0 and self.is_pending_task_active('select_torrents'): - self.cancel_pending_task('select_torrents') - else: - self._logger.info('Already have source %s', source_str) - - async def remove_source(self, source_str): - """ - remove source by stop the downloading and remove its metainfo for all its swarms - """ - if source_str in self.sources: - source = self.sources.pop(source_str) - await source.stop() - self._logger.info('Removed source %s', source_str) - - coros = [] - for infohash, torrent in list(self.torrents.items()): - if source_str in torrent.sources: - torrent.sources.remove(source_str) - if not torrent.sources: - del self.torrents[infohash] - - if torrent.download: - coros.append(self.session.dlmgr.remove_download(torrent.download, remove_content=True)) - self._logger.info('Removing torrent %s', torrent.infohash) - self._logger.info('Removing %s download(s)', len(coros)) - - self.cancel_all_pending_tasks() - if coros: - await gather(*coros) - else: - self._logger.error('Cannot remove non-existing source %s', source_str) - - def on_torrent_insert(self, source_str, infohash, name): - """ - Callback function called by the source when a new torrent is discovered - """ - self._logger.debug('Received torrent %s from %s', infohash, source_str) - - if source_str not in self.sources: - self._logger.debug('Skipping torrent %s (unknown source %s)', infohash, source_str) - return - - # Did we already get this torrent from another source? - if infohash in self.torrents: - self.torrents[infohash].sources.add(source_str) - self._logger.debug('Skipping torrent %s (already known)', infohash) - return - - # If a download already exists or already has a checkpoint, skip this torrent - if self.session.dlmgr.get_download(unhexlify(infohash)) or \ - (self.session.dlmgr.get_checkpoint_dir() / infohash).with_suffix('.conf').exists(): - self._logger.debug('Skipping torrent %s (download already running or scheduled to run)', infohash) - return - - if len(self.torrents) >= self.settings.max_torrents_listed: - self._logger.debug('Skipping torrent %s (limit reached)', infohash) - return - - self.torrents[infohash] = CreditMiningTorrent(infohash, name) - self.torrents[infohash].sources.add(source_str) - self._logger.info('Starting torrent %s', infohash) - - magnet = u'magnet:?xt=urn:btih:%s&dn=%s' % (infohash, name) - - dl_config = DownloadConfig() - dl_config.set_hops(self.settings.hops) - dl_config.set_dest_dir(self.settings.save_path) - dl_config.set_credit_mining(True) - dl_config.set_user_stopped(True) - - self.session.dlmgr.start_download(tdef=TorrentDefNoMetainfo(unhexlify(infohash), name, magnet), - config=dl_config, hidden=True) - - def get_reserved_space_left(self): - # Calculate number of bytes we have left for storing torrent data. - # We could also get the size of the download directory ourselves (without libtorrent), but depending - # on the size of the directory and the number of files in it, this could use too many resources. - bytes_left = self.settings.max_disk_space - for download in self.session.dlmgr.get_downloads(): - ds = download.get_state() - if ds.get_status() in [DLSTATUS_DOWNLOADING, DLSTATUS_SEEDING, - DLSTATUS_STOPPED, DLSTATUS_STOPPED_ON_ERROR]: - bytes_left -= ds.get_progress() * download.get_def().get_length() - return bytes_left - - def schedule_new_torrents(self): - # Storage available for mining - bytes_left = self.get_reserved_space_left() - - # Determine which torrent to start and which to stop. - loaded_torrents = [torrent for torrent in self.torrents.values() if torrent.download] - policy_results = [iter(policy.sort(loaded_torrents)) for policy in self.policies] - - to_start = [] - iterations = 0 - bytes_scheduled = 0 - while iterations - len(to_start) < len(policy_results): - if len(to_start) >= self.settings.max_torrents_active: - break - - policy_index = len(to_start) % len(self.policies) - policy_result = policy_results[policy_index] - - for torrent in policy_result: - if torrent not in to_start: - # We add torrents such that the total bytes of all running torrents is < max_disk_space. - bytes_todo = self.policies[policy_index].get_reserved_bytes(torrent) - if bytes_left >= bytes_scheduled + bytes_todo: - to_start.append(torrent) - self.policies[policy_index].schedule(torrent, to_start=True) - bytes_scheduled += bytes_todo - break - iterations += 1 - return to_start - - def select_torrents(self): - """ - Function to select which torrent in the torrent list will be downloaded in the - next iteration. It depends on the source and applied policy. - """ - self._logger.info("select torrents") - if self.policies and self.torrents: - - # Schedule new torrents to start mining - self.schedule_new_torrents() - - for policy in self.policies: - self._logger.info("Running policy:%s", policy) - policy.run() - - def monitor_downloads(self, dslist): - stopped = 0 - num_downloading = num_seeding = 0 - bytes_downloaded = bytes_uploaded = 0 - for ds in dslist: - download = ds.get_download() - - if download.config.get_credit_mining(): - tdef = download.get_def() - infohash = hexlify(tdef.get_infohash()) - - if infohash not in self.torrents: - self.torrents[infohash] = CreditMiningTorrent(infohash, tdef.get_name()) - - self.torrents[infohash].download = download - self.torrents[infohash].state = ds - - if ds.get_status() in [DLSTATUS_DOWNLOADING]: - num_downloading += 1 - elif ds.get_status() in [DLSTATUS_SEEDING]: - num_seeding += 1 - elif ds.get_status() in [DLSTATUS_STOPPED, DLSTATUS_STOPPED_ON_ERROR]: - stopped += 1 - - bytes_uploaded += ds.get_total_transferred(UPLOAD) - bytes_downloaded += ds.get_total_transferred(DOWNLOAD) - - if ds.get_status() == DLSTATUS_STOPPED_ON_ERROR: - self._logger.error('Got an error for credit mining download %s', infohash) - if infohash in self.torrents and not self.torrents[infohash].force_checked: - self._logger.info('Attempting to recheck download %s', infohash) - download.force_recheck() - self.torrents[infohash].force_checked = True - - self._logger.info('Downloading: %d, Uploading: %d, Stopped: %d', num_seeding, num_downloading, stopped) - self._logger.info('%d active download(s), %.3f MB uploaded, %.3f MB downloaded', - num_seeding + num_downloading, bytes_uploaded / MB, bytes_downloaded / MB) - - if not self.session_ready.done() and len(dslist) == self.num_checkpoints: - self.session_ready.set_result(None) - - # We start the looping call when all torrents have been loaded - total = num_seeding + num_downloading + stopped - if not self.is_pending_task_active('select_torrents') and total >= self.settings.max_torrents_active: - self.register_task('select_torrents', self.select_torrents, interval=self.settings.auto_manage_interval) - - return num_downloading, num_seeding, stopped, bytes_downloaded, bytes_uploaded diff --git a/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_policy.py b/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_policy.py deleted file mode 100644 index 792b686f93a..00000000000 --- a/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_policy.py +++ /dev/null @@ -1,292 +0,0 @@ -""" -Supported credit mining policy. -Author(s): Egbert Bouman, Mihai Capota, Elric Milon, Ardhi Putra -""" -import logging -import random -import time - -from tribler_common.simpledefs import ( - DLSTATUS_DOWNLOADING, - DLSTATUS_SEEDING, - DLSTATUS_STOPPED, - DLSTATUS_STOPPED_ON_ERROR, - DOWNLOAD, - UPLOAD, -) - -MB = 1024 * 1024 -HOUR = 3600 -DAY = 86400 -WEEK = 7 * DAY - - -class BasePolicy(object): - """ - Base class for determining what swarm selection policy will be applied - """ - - def __init__(self): - self._logger = logging.getLogger(self.__class__.__name__) - self.torrents = {} - self.started_in_iteration = 0 - self.stopped_in_iteration = 0 - - def sort(self, torrents): - raise NotImplementedError() - - def schedule(self, torrent, to_start=True): - """ - Schedules the torrent to start or stop. It also adds the torrent to the policy list. - """ - torrent.to_start = to_start - self.torrents[torrent.infohash] = torrent - - def run(self): - """ - Runs an iteration of the Basic policy. - For each torrent in the policy session, - - Start the stopped torrent if it is set to start - - Stop the running torrent if it is set to stop - - For the rest, make no changes - """ - self.started_in_iteration = self.stopped_in_iteration = 0 - for torrent in self.torrents.values(): - if not torrent.download: - continue - - status = torrent.download.get_state().get_status() - if torrent.to_start and status == DLSTATUS_STOPPED: - torrent.download.resume() - self.started_in_iteration += 1 - elif not torrent.to_start and status not in [DLSTATUS_STOPPED, DLSTATUS_STOPPED_ON_ERROR]: - torrent.download.stop() - self.stopped_in_iteration += 1 - torrent.to_start = False - - self._logger.info('Started %d torrent(s), stopped %d torrent(s)', - self.started_in_iteration, self.stopped_in_iteration) - - def get_reserved_bytes(self, torrent): - """ - Returns the storage(bytes) required for downloading remaining content of the torrent. - """ - total_bytes, downloaded_bytes = torrent.get_storage() - return total_bytes - downloaded_bytes - - -class RandomPolicy(BasePolicy): - """ - A credit mining policy that chooses a swarm randomly - """ - - def sort(self, torrents): - result = torrents[:] - random.shuffle(result) - return result - - -class SeederRatioPolicy(BasePolicy): - """ - Find the most underseeded swarm to boost. - """ - - def sort(self, torrents): - def sort_key(torrent): - ds = torrent.state - seeds, peers = ds.get_num_seeds_peers() if ds else (0, 1) - return seeds / float(seeds + peers) - - return sorted(torrents, key=sort_key, reverse=True) - - -class UploadPolicy(BasePolicy): - """ - Choose swarm such that we maximize the total upload. - """ - - def sort(self, torrents): - def sort_key(torrent): - if torrent.download and torrent.download.handle: - status = torrent.download.handle.status() - return status.total_upload / float(status.active_time) if status.active_time else 0.0 - return 0.0 - - return sorted(torrents, key=sort_key, reverse=True) - - -class InvestmentState(object): - """ - Represents the credit mining state for a torrent. - """ - def __init__(self, state_id, upload_mode, bandwidth_limit, promotion_ratio=1): - self.state_id = state_id - self.bandwidth_limit = bandwidth_limit - self.upload_mode = upload_mode - self.promotion_ratio = promotion_ratio - - def is_promotion_ready(self, download, upload): - """ - Check if a torrent with given download and upload value is eligible for promotion to the next - investment state. - """ - if self.upload_mode: - return upload >= self.bandwidth_limit * self.promotion_ratio - return download >= self.bandwidth_limit - - -class InvestmentPolicy(BasePolicy): - """ - Policy to select and promote torrents based on the (upload) yield on the investment(download). - Higher the yield, higher will be the allowance to do investment download. - """ - - def __init__(self, states=None): - super(InvestmentPolicy, self).__init__() - self.investment_states = states if states else self.get_default_investment_states() - self.num_uploading_in_iteration = 0 - self.num_downloading_in_iteration = 0 - - @staticmethod - def get_default_investment_states(): - """ - Default investment state has the following parameters: - - Starting investment value, say a - - Alternating Download (0) and Upload mode (1) - - Promotion ratio = Upload/Download = 1 - - The value of investment in each state follows the following half series: - a, a + a/2, ... - The inital values of a = 5 MB - Then the sequence becomes 5, 7, 10, 15, 22, 33, 49, 73, 109, 163, ... - :return: Dict of investment states - """ - investment = 5 - states = {} - for level in range(10): - download_state = 2 * level - upload_state = download_state + 1 - states[download_state] = InvestmentState(download_state, download_state % 2, investment * MB) - states[upload_state] = InvestmentState(upload_state, upload_state % 2, investment * MB) - investment = investment + investment//2 - return states - - def schedule_start(self, torrent): - if torrent.infohash not in self.torrents: - up = torrent.state.get_total_transferred(UPLOAD) - down = torrent.state.get_total_transferred(DOWNLOAD) - torrent.mining_state['start_time'] = time.time() - torrent.mining_state['initial_upload'] = up - torrent.mining_state['initial_download'] = down - torrent.mining_state['state_id'] = self.compute_state(down, up) - torrent.to_start = True - self.torrents[torrent.infohash] = torrent - - def compute_state(self, download, upload): - state_id = 0 - for state in self.investment_states.values(): - state_id = state.state_id - if (state.upload_mode and upload < state.bandwidth_limit * state.promotion_ratio) \ - or (not state.upload_mode and download < state.bandwidth_limit): - break - return state_id - - def sort(self, torrents): - def sort_key(torrent): - if torrent.download and torrent.download.handle: - status = torrent.download.handle.status() - return status.total_upload / float(status.active_time) if status.active_time else 0.0 - return 0.0 - - return sorted(torrents, key=sort_key, reverse=True) - - def promote_torrent(self, torrent): - """ - Promotes the torrent to the next investment state. Since investment states alternates in - upload and download, the torrent is restarted with new state's upload mode. - """ - current_state_id = torrent.mining_state.get('state_id', 0) - if len(self.investment_states) == current_state_id + 1: - return - next_state = self.investment_states[current_state_id + 1] - torrent.mining_state['state_id'] = current_state_id + 1 - if next_state.upload_mode: - torrent.download.set_upload_mode(True) - else: - torrent.download.set_upload_mode(False) - torrent.download.resume() - - def run(self): - """ - Run an iteration of the policy. - - If torrent has no yield for a week, stop it. - If torrent is scheduled to be started, - - promote torrent if it is ready for promotion - - otherwise ensure the torrent is correct mode - Else - - stop the torrent - """ - self.started_in_iteration = self.stopped_in_iteration = 0 - self.num_uploading_in_iteration = self.num_downloading_in_iteration = 0 - for torrent in self.torrents.values(): - if not torrent.download: - continue - - torrent_state = torrent.download.get_state() - eta = torrent_state.get_eta() - if eta == 0: - torrent.download.set_upload_mode(True) - torrent.download.resume() - self.num_uploading_in_iteration += 1 - self.started_in_iteration += 1 - continue - - upload = torrent_state.get_total_transferred(UPLOAD) - download = torrent_state.get_total_transferred(DOWNLOAD) - - # Remove the torrent if upload is too low in a week's time - diff_time = time.time() - torrent.start_time - diff_upload = upload - torrent.mining_state.get('initial_upload', 0) - if diff_time > WEEK and diff_upload < 5 * MB: - torrent.download.stop() - self.stopped_in_iteration += 1 - continue - - investment_state = self.investment_states[torrent.mining_state.get('state_id', 0)] - if torrent.to_start: - if investment_state.is_promotion_ready(download, upload): - self.promote_torrent(torrent) - if self.investment_states[torrent.mining_state['state_id']].upload_mode: - self.num_uploading_in_iteration += 1 - else: - self.num_downloading_in_iteration += 1 - else: - status = torrent_state.get_status() - if investment_state.upload_mode and status is not DLSTATUS_SEEDING: - torrent.download.set_upload_mode(True) - torrent.download.resume() - self.num_uploading_in_iteration += 1 - elif not investment_state.upload_mode and status is not DLSTATUS_DOWNLOADING: - torrent.download.set_upload_mode(False) - torrent.download.resume() - self.num_downloading_in_iteration += 1 - self.started_in_iteration += 1 - torrent.to_start = False - else: - torrent.download.stop() - self.stopped_in_iteration += 1 - - self._logger.info('Started %d torrent(s), stopped %d torrent(s)', - self.started_in_iteration, self.stopped_in_iteration) - self._logger.info('Torrents in upload mode: %d, download mode: %d', - self.num_uploading_in_iteration, self.num_downloading_in_iteration) - - def get_reserved_bytes(self, torrent): - """ - Returns the storage(bytes) required for the torrent to move to next investment state's bandwidth limit. - """ - investment_state = self.investment_states[torrent.mining_state.get('state_id', 0)] - _, download_bytes = torrent.get_storage() - diff = investment_state.bandwidth_limit - download_bytes - return diff if diff > 0 else 0 diff --git a/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_source.py b/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_source.py deleted file mode 100644 index 31bb760b4d3..00000000000 --- a/src/tribler-core/tribler_core/modules/credit_mining/credit_mining_source.py +++ /dev/null @@ -1,59 +0,0 @@ -import logging - -from ipv8.taskmanager import TaskManager - -from tribler_core.utilities.unicode import hexlify - - -class BaseSource(TaskManager): - """ - Base class for a credit mining source. - The source specifies where to get torrents from. - """ - - def __init__(self, session, source, torrent_insert_cb): - super(BaseSource, self).__init__() - self._logger = logging.getLogger(BaseSource.__name__) - - self.session = session - self.source = source - self.torrent_insert_callback = torrent_insert_cb - - def start(self): - """ - Start operating mining for this source - """ - self._logger.debug('Start mining %s', str(self)) - - async def stop(self): - """ - Kill tasks on this source - """ - await self.shutdown_task_manager() - self._logger.debug('Stop mining %s', str(self)) - - def __str__(self): - return self.source - - -class ChannelSource(BaseSource): - """ - Credit mining source from a (giga)channel. - """ - - def start(self): - super(ChannelSource, self).start() - - channel = self.session.mds.ChannelMetadata.get_recent_channel_with_public_key(self.source) - if not channel: - self._logger.error("Could not find channel!") - return - - # Add torrents from database - for torrent in channel.contents_list: - self.torrent_insert_callback(hexlify(self.source), - hexlify(torrent.infohash), - torrent.title) - - def __str__(self): - return 'channel:' + hexlify(self.source) diff --git a/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_manager.py b/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_manager.py deleted file mode 100644 index a7568bedb44..00000000000 --- a/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_manager.py +++ /dev/null @@ -1,466 +0,0 @@ -""" -Module of Credit mining function testing. - -Author(s): Mihai Capota, Ardhi Putra -""" -import logging -from asyncio import Future - -from tribler_common.simpledefs import DLSTATUS_DOWNLOADING, DLSTATUS_SEEDING, DLSTATUS_STOPPED, DOWNLOAD, NTFY - -from tribler_core.modules.credit_mining.credit_mining_manager import CreditMiningTorrent -from tribler_core.modules.credit_mining.credit_mining_policy import BasePolicy, MB -from tribler_core.modules.libtorrent.download_config import DownloadConfig -from tribler_core.tests.tools.base_test import MockObject -from tribler_core.tests.tools.test_as_server import BaseTestCase, TestAsServer -from tribler_core.utilities.unicode import hexlify -from tribler_core.utilities.utilities import succeed - - -class FakeTorrent(object): - - def __init__(self, infohash, name): - self.infohash = infohash - self.name = name - - self.download = MockObject() - self.download.upload_mode = False - self.download.running = None - self.download.resume = lambda: setattr(self.download, 'running', True) - self.download.stop = lambda: setattr(self.download, 'running', False) - self.download.credit_mining = True - self.download.config = MockObject() - self.download.config.get_credit_mining = lambda dl=self.download: dl.credit_mining - self.download.config.set_credit_mining = lambda enable, dl=self.download: setattr(dl, 'credit_mining', enable) - self.download.get_handle = lambda: succeed(self.handle) - self.download.checkpoint = lambda: None - self.download.move_storage = lambda _: None - - self.tdef = MockObject() - self.tdef.get_infohash = lambda: self.infohash - self.tdef.get_trackers_as_single_tuple = lambda: () - self.tdef.get_length = lambda: 1024 * 1024 - self.download.get_def = lambda: self.tdef - - self.ds = MockObject() - self.ds.get_status = lambda: DLSTATUS_STOPPED - self.ds.get_progress = lambda: 0.0 - self.ds.get_download = lambda: self.download - self.ds.get_total_transferred = lambda _: 0 - self.download.get_state = lambda: self.ds - - self.handle = MockObject() - self.handle.set_upload_mode = lambda enable: setattr(self.download, 'upload_mode', enable) - self.handle.is_valid = lambda: True - self.get_storage = lambda length=self.tdef.get_length(): (length, 0) - self.download.handle = self.handle - - -class FakePolicy(BasePolicy): - - def __init__(self, reverse): - self._logger = logging.getLogger(self.__class__.__name__) - self.reverse = reverse - self.torrents = {} - - def sort(self, torrents): - return sorted(torrents, key=lambda t: t.infohash, reverse=self.reverse) - - -class TestCreditMiningTorrent(BaseTestCase): - - def test_credit_mining_get_storage(self): - infohash_bin = '0' * 40 - name = u'torrent' - - tdef = MockObject() - tdef.get_infohash = lambda: infohash_bin - tdef.get_name = lambda: name - tdef.get_length = lambda: 1000 - - state = MockObject() - state.get_progress = lambda: 0.5 - - download = MockObject() - download.get_def = lambda: tdef - download.get_state = lambda: state - - torrent = CreditMiningTorrent(infohash_bin, name, download=download) - total, downloaded = torrent.get_storage() - self.assertEqual(total, 1000) - self.assertEqual(downloaded, 500) - - -class TestCreditMiningManager(TestAsServer): - """ - Class to test the credit mining manager - """ - - def __init__(self, *argv, **kwargs): - super(TestCreditMiningManager, self).__init__(*argv, **kwargs) - # Some fake data for convenience - self.cid = '0' * 64 - self.infohash = '0' * 40 - self.infohash_bin = b'\00' * 20 - self.name = u'torrent' - - async def setUp(self): - await super(TestCreditMiningManager, self).setUp() - self.credit_mining_manager = self.session.credit_mining_manager - self.credit_mining_manager.settings.max_torrents_active = 4 - - def setUpPreSession(self): - super(TestCreditMiningManager, self).setUpPreSession() - self.config.set_libtorrent_enabled(True) - self.config.set_credit_mining_enabled(True) - self.config.set_chant_enabled(True) - - async def test_source_add_remove(self): - self.credit_mining_manager.add_source(self.cid) - self.assertIn(self.cid, self.credit_mining_manager.sources) - await self.credit_mining_manager.remove_source(self.cid) - self.assertNotIn(self.cid, self.credit_mining_manager.sources) - - async def test_torrent_remove(self): - removed = [] - - def fake_remove(download, **_): - removed.append(download.get_def().get_infohash()) - return succeed(None) - - self.session.dlmgr.remove_download = fake_remove - - torrents = {i: FakeTorrent(i, self.name + str(i)) for i in range(5)} - self.credit_mining_manager.add_source(self.cid) - for infohash, torrent in torrents.items(): - self.credit_mining_manager.torrents[infohash] = torrent - torrent.sources = set([self.cid]) - await self.credit_mining_manager.remove_source(self.cid) - self.assertTrue(len(self.credit_mining_manager.torrents) == 0) - self.assertEqual(list(torrents.keys()), removed) - - def test_torrent_insert(self): - self.credit_mining_manager.add_source(self.cid) - self.credit_mining_manager.on_torrent_insert(self.cid, self.infohash, self.name) - self.assertIn(self.infohash, self.credit_mining_manager.torrents) - self.assertTrue(self.session.dlmgr.get_download(self.infohash_bin)) - - def test_torrent_insert_unknown_source(self): - self.credit_mining_manager.on_torrent_insert(self.cid, self.infohash, self.name) - self.assertNotIn(self.infohash, self.credit_mining_manager.torrents) - self.assertFalse(self.session.dlmgr.get_download(self.infohash_bin)) - - def test_torrent_insert_duplicate(self): - self.credit_mining_manager.torrents[self.infohash] = CreditMiningTorrent(self.infohash, self.name) - self.credit_mining_manager.on_torrent_insert(self.cid, self.infohash, self.name) - torrent = list(self.credit_mining_manager.torrents.values())[0] - - self.credit_mining_manager.on_torrent_insert(self.cid, self.infohash, self.name) - self.assertIn(torrent, self.credit_mining_manager.torrents.values()) - self.assertFalse(self.session.dlmgr.get_download(self.infohash_bin)) - - # When we add a duplicate from another known source, the set of sources should update - source = '1' * 40 - self.credit_mining_manager.add_source(source) - self.credit_mining_manager.on_torrent_insert(source, self.infohash, self.name) - self.assertIn(source, torrent.sources) - self.assertIn(torrent, self.credit_mining_manager.torrents.values()) - self.assertFalse(self.session.dlmgr.get_download(self.infohash_bin)) - - def test_torrent_insert_limit(self): - self.credit_mining_manager.add_source(self.cid) - self.credit_mining_manager.settings.max_torrents_listed = 0 - self.credit_mining_manager.on_torrent_insert(self.cid, self.infohash, self.name) - self.assertNotIn(self.infohash, self.credit_mining_manager.torrents) - self.assertFalse(self.session.dlmgr.get_download(self.infohash_bin)) - - def test_torrent_insert_existing_download(self): - self.credit_mining_manager.add_source(self.cid) - self.session.dlmgr.downloads[self.infohash_bin] = MockObject() - self.credit_mining_manager.on_torrent_insert(self.cid, self.infohash, self.name) - self.assertNotIn(self.infohash, self.credit_mining_manager.torrents) - del self.session.dlmgr.downloads[self.infohash_bin] - - def test_select_torrent_single_policy(self): - self.credit_mining_manager.monitor_downloads = lambda _: None - self.credit_mining_manager.policies = [FakePolicy(reverse=False)] - - for i in range(5): - self.credit_mining_manager.torrents[i] = FakeTorrent(i, self.name + str(i)) - - self.credit_mining_manager.select_torrents() - - # Torrents 0,1,2,3 should be running according to FakePolicy(reverse=False) - # Torrent 4 should not be running. - torrents = self.credit_mining_manager.torrents - self.assertTrue(all([torrents[i].download.running for i in [0, 1, 2, 3]])) - self.assertFalse(torrents[4].download.running) - - def test_select_torrent_multiple_policies(self): - self.credit_mining_manager.monitor_downloads = lambda _: None - self.credit_mining_manager.policies = [FakePolicy(reverse=False), FakePolicy(reverse=True)] - - for i in range(5): - self.credit_mining_manager.torrents[i] = FakeTorrent(i, self.name + str(i)) - - self.credit_mining_manager.select_torrents() - - # Torrents 0,1 should be running according to FakePolicy(reverse=False) - # Torrents 3,4 should be running according to FakePolicy(reverse=True) - # Torrent 2 should not be running. - torrents = self.credit_mining_manager.torrents - self.assertTrue(all([torrents[i].download.running for i in [0, 1, 3, 4]])) - self.assertFalse(torrents[2].download.running) - - def test_select_torrent_disk_space_limit(self): - self.credit_mining_manager.settings.max_disk_space = 2 * 1024 * 1024 - self.credit_mining_manager.monitor_downloads = lambda _: None - self.credit_mining_manager.policies = [FakePolicy(reverse=False), FakePolicy(reverse=True)] - - for i in range(5): - self.credit_mining_manager.torrents[i] = FakeTorrent(i, self.name + str(i)) - - self.credit_mining_manager.select_torrents() - - # Torrent 0 should be running according to FakePolicy(reverse=False) - # Torrent 4 should be running according to FakePolicy(reverse=True) - # Torrents 1,2,3 should not be running due to max_disk_space. - torrents = self.credit_mining_manager.torrents - self.assertTrue(all([torrents[i].download.running for i in [0, 4]])) - self.assertFalse(any([torrents[i].download.running for i in [1, 2, 3]])) - - def test_monitor_download_start_selecting(self): - self.credit_mining_manager.monitor_downloads([]) - self.assertFalse(self.credit_mining_manager.is_pending_task_active('select_torrents')) - - # If the number of torrents > then max_torrents_active, the select_lc LoopingCall should start - for i in range(5): - self.credit_mining_manager.torrents[hexlify(bytes(i))] = FakeTorrent(bytes(i), self.name + str(i)) - self.credit_mining_manager.monitor_downloads([t.ds for t in self.credit_mining_manager.torrents.values()]) - self.assertTrue(self.credit_mining_manager.is_pending_task_active('select_torrents')) - - def test_monitor_download_insert_torrent(self): - tdef = MockObject() - tdef.get_infohash = lambda: self.infohash_bin - tdef.get_name = lambda: self.name - - download = MockObject() - download.get_def = lambda: tdef - download.force_recheck = lambda: None - download.config = MockObject() - download.config.get_credit_mining = lambda: True - - ds = MockObject() - ds.get_download = lambda: download - ds.get_status = lambda: DLSTATUS_STOPPED - ds.get_total_transferred = lambda _: 0 - - # Credit mining downloads should automatically be inserted in to self.credit_mining_mananger.torrents - self.credit_mining_manager.monitor_downloads([ds]) - self.assertIn(self.infohash, self.credit_mining_manager.torrents) - self.assertEqual(self.credit_mining_manager.torrents[self.infohash].download, download) - - # Normal downloads should be ignored - infohash2_bin = '\01' * 20 - infohash2 = '01' * 20 - tdef.get_infohash = lambda: infohash2_bin - download.config = MockObject() - download.config.get_credit_mining = lambda: False - self.credit_mining_manager.monitor_downloads([ds]) - self.assertNotIn(infohash2, self.credit_mining_manager.torrents) - - def test_monitor_downloads(self): - """ - Test downloads monitoring works as expected. - Scenario: - -------------------------------------------- - Infohash Status Download Upload - 0 Downloading 0 MB 5 MB - 1 Seeding 10 MB 15 MB - 2 Stopped 20 MB 25 MB - 3 Downloading 30 MB 35 MB - 4 Seeding 40 MB 45 MB - 5 Downloading 50 MB 55 MB - - Results: - Seeding = 3, Downloading = 2, Stopped = 1 - Bytes_up = 180 MB, Bytes_down = 150 MB - """ - scenario = MockObject() - scenario.status = [DLSTATUS_DOWNLOADING, DLSTATUS_SEEDING, DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING, - DLSTATUS_SEEDING, DLSTATUS_DOWNLOADING] - scenario.downloads = [10 * i * MB for i in range(6)] - scenario.uploads = [(10 * i + 5) * MB for i in range(6)] - - download = MockObject() - download.tdef = MockObject() - download.tdef.get_infohash = lambda: b'\00' * 20 - download.tdef.get_name = lambda: self.name + str(i) - download.get_def = lambda _download=download: _download.tdef - download.force_recheck = lambda: None - download.config = MockObject() - download.config.get_credit_mining = lambda: True - download.handle = None - - download_states = [] - for i in range(6): - ds = MockObject() - ds.get_download = lambda: download - ds.get_status = lambda _i=i: scenario.status[_i] - ds.get_total_transferred = lambda transfer_type, _i=i: scenario.downloads[_i] \ - if transfer_type == DOWNLOAD else scenario.uploads[_i] - download_states.append(ds) - - # We are only interested in monitoring the states, rathen than policies here. - self.credit_mining_manager.policies = [] - seeding, downloading, stopped, bytes_down, bytes_up = \ - self.credit_mining_manager.monitor_downloads(download_states) - self.assertEqual(seeding, 3) - self.assertEqual(downloading, 2) - self.assertEqual(stopped, 1) - self.assertEqual(bytes_down, sum(scenario.downloads)) - self.assertEqual(bytes_up, sum(scenario.uploads)) - - async def test_check_free_space(self): - self.credit_mining_manager.cancel_pending_task('check_disk_space') - self.credit_mining_manager.settings.low_disk_space = 1024 ** 2 - - downloads = [FakeTorrent(i, self.name + str(i)).download for i in range(5)] - self.session.dlmgr.get_downloads = lambda: downloads - - # Check that all download have upload_mode=False if we have enough disk space - self.credit_mining_manager.get_free_disk_space = lambda: 2 * 1024 ** 2 - self.credit_mining_manager.check_disk_space() - self.assertFalse(any([d.upload_mode for d in downloads])) - - # Check that all download have upload_mode=True if we do not have enough disk space - self.credit_mining_manager.get_free_disk_space = lambda: 1 - self.credit_mining_manager.check_disk_space() - self.assertTrue(all([d.upload_mode for d in downloads])) - - def test_get_reserved_space_left(self): - """ - Tests the reserved space left on disk for credit mining. - Scenario: - - 10 torrents, - - Individual torrent size: 100MB - - Individual download progress: 50% - """ - num_downloads = 10 - used_space = num_downloads * 100 * MB * 0.5 - max_space = self.credit_mining_manager.settings.max_disk_space - - downloads = [] - for i in range(num_downloads): - download = FakeTorrent(i, self.name + str(i)).download - download.get_def().get_length = lambda: 100 * MB - download.get_state().get_progress = lambda: 0.5 - download.get_state().get_status = lambda: DLSTATUS_DOWNLOADING - downloads.append(download) - - self.credit_mining_manager.session.dlmgr.get_downloads = lambda: downloads - - space_left = self.credit_mining_manager.get_reserved_space_left() - self.assertEqual(space_left, max_space - used_space) - - async def test_check_free_space_with_non_existing_path(self): - self.credit_mining_manager.cancel_pending_task('check_disk_space') - self.assertFalse(self.credit_mining_manager.upload_mode) - - # Given: low disk space available - self.credit_mining_manager.settings.low_disk_space = 1024 ** 2 - self.credit_mining_manager.get_free_disk_space = lambda: 1 - - # Should set credit mining to upload state unless the mining path is invalid or does not exist - test_path = self.credit_mining_manager.session.config.get_state_dir() / "fake_dir" - self.credit_mining_manager.settings.save_path = test_path - self.credit_mining_manager.check_disk_space() - self.assertFalse(self.credit_mining_manager.upload_mode) - - async def test_check_mining_directory(self): - """ Tests mining directory exists. If does not exist, it should be created. """ - def fake_notifier_notify(miner, subject, *args): - miner.subject = subject - miner.args = args - - async def on_mining_shutdown(): - await self.credit_mining_manager.shutdown_task_manager() - if not self.credit_mining_manager.shutdown_future.done(): - self.credit_mining_manager.shutdown_future.set_result(None) - - self.credit_mining_manager.shutdown_future = Future() - self.credit_mining_manager.shutdown = on_mining_shutdown - self.credit_mining_manager.session.notifier.notify = lambda subject, args:\ - fake_notifier_notify(self.credit_mining_manager, subject, args) - - test_path = self.credit_mining_manager.session.config.get_state_dir() / "fake_dir" - self.assertFalse(test_path.exists()) - - self.credit_mining_manager.settings.save_path = test_path - self.credit_mining_manager.check_mining_directory() - - self.assertTrue(test_path.exists()) - self.assertEqual(self.credit_mining_manager.subject, NTFY.CREDIT_MINING_ERROR) - self.assertIsNotNone(self.credit_mining_manager.args) - - # Set the path to some non-allowed directory - #test_path = "C:/Windows/system32/credit_mining" if sys.platform == 'win32' else "/root/credit_mining" - #self.credit_mining_manager.settings.save_path = test_path - #FIXME this test will always fail with an exception because it tries to do a forbidden thing - #self.credit_mining_manager.check_mining_directory() - - #self.assertEqual(self.credit_mining_manager.subject, NTFY_CREDIT_MINING) - #self.assertEqual(self.credit_mining_manager.changeType, NTFY_ERROR) - #self.assertIsNotNone(self.credit_mining_manager.args) - #await self.credit_mining_manager.shutdown_future - - async def test_add_download_while_credit_mining(self): - infohash_str = '00' * 20 - infohash_bin = b'\00' * 20 - magnet = 'magnet:?xt=urn:btih:' + ('00' * 20) - - def fake_move_storage(dl, dest_dir): - dl.dest_dir = dest_dir - dl.move_storage_called = True - - def fake_checkpoint(dl): - dl.checkpoint_called = True - return succeed(None) - - def set_credit_mining(dl, value): - dl.credit_mining = value - - # Default download directory - dl_config = DownloadConfig() - download_dir = dl_config.get_dest_dir() - - torrent = FakeTorrent(infohash_bin, self.name) - torrent.download.move_storage_called = False - torrent.download.checkpoint_called = False - torrent.download.set_credit_mining = lambda value, dl=torrent.download: set_credit_mining(dl, value) - torrent.download.move_storage = lambda dest_dir, dl=torrent.download: fake_move_storage(dl, dest_dir) - torrent.download.checkpoint = lambda dl=torrent.download: fake_checkpoint(dl) - - self.credit_mining_manager.torrents[infohash_str] = torrent - - # Credit mining downloads should get moved to download directory and be checkpointed - self.session.dlmgr.get_download = lambda _: torrent.download - await self.session.dlmgr.start_download_from_uri(magnet) - self.assertNotIn(infohash_str, self.credit_mining_manager.torrents) - self.assertTrue(torrent.download.checkpoint_called) - self.assertTrue(torrent.download.move_storage_called) - self.assertEqual(torrent.download.dest_dir, download_dir) - - # Non credit mining downloads should not get removed - torrent.download.move_storage_called = False - torrent.download.checkpoint_called = False - torrent.download.config = MockObject() - torrent.download.config.get_credit_mining = lambda: False - self.session.dlmgr.get_download = lambda _: torrent.download - self.assertFalse(torrent.download.move_storage_called) - self.assertFalse(torrent.download.checkpoint_called) - - async def test_shutdown(self): - self.credit_mining_manager.add_source(self.cid) - await self.credit_mining_manager.shutdown(remove_downloads=True) - self.assertNotIn(self.cid, self.credit_mining_manager.sources) diff --git a/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_policies.py b/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_policies.py deleted file mode 100644 index c6ed4c8d85b..00000000000 --- a/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_policies.py +++ /dev/null @@ -1,368 +0,0 @@ -""" -Module of Credit mining function testing. - -Author(s): Mihai Capota, Ardhi Putra -""" -import time - -from tribler_common.simpledefs import DLSTATUS_DOWNLOADING, DLSTATUS_SEEDING, DLSTATUS_STOPPED, UPLOAD - -from tribler_core.modules.credit_mining.credit_mining_manager import CreditMiningTorrent -from tribler_core.modules.credit_mining.credit_mining_policy import ( - InvestmentPolicy, - InvestmentState, - MB, - RandomPolicy, - SeederRatioPolicy, - UploadPolicy, - WEEK, -) -from tribler_core.tests.tools.base_test import MockObject, TriblerCoreTest - - -class TestCreditMiningPolicies(TriblerCoreTest): - """ - Class to test the credit mining policies - """ - - async def setUp(self): - await super(TestCreditMiningPolicies, self).setUp() - self.torrents = [CreditMiningTorrent(i, 'test torrent %d' % i) for i in range(10)] - try: - self.assertCountEqual # Python 3 - except AttributeError: # Python 2 - self.assertCountEqual = self.assertItemsEqual - - def test_random_policy(self): - policy = RandomPolicy() - - sorted_torrents = policy.sort(self.torrents) - self.assertCountEqual(self.torrents, sorted_torrents, 'Arrays contains different torrents') - - def test_seederratio_policy(self): - for i, torrent in enumerate(self.torrents): - mock_ds = MockObject() - mock_ds.get_num_seeds_peers = lambda index=i: (index, 1) - torrent.state = mock_ds - - policy = SeederRatioPolicy() - sorted_torrents = policy.sort(self.torrents) - expected_torrents = list(reversed(self.torrents)) - - self.assertCountEqual(sorted_torrents, expected_torrents, 'Arrays contains different torrents') - self.assertListEqual(sorted_torrents, expected_torrents, 'Array is not sorted properly') - - def test_upload_based_policy_sort(self): - """ - Tests both UploadPolicy and InvestmentPolicy since they both sorts torrents based on upload. - """ - - def setup_torrents(torrents): - for i, torrent in enumerate(torrents): - mock_status = MockObject() - mock_status.total_upload = i * i - mock_status.active_time = i - - mock_handle = MockObject() - mock_handle.status = lambda status=mock_status: status - - mock_dl = MockObject() - mock_dl.handle = mock_handle - - torrent.download = mock_dl - return torrents - - # Test Upload policy - upload_policy = UploadPolicy() - torrent_collection1 = setup_torrents(self.torrents) - sorted_torrents1 = upload_policy.sort(torrent_collection1) - expected_torrents1 = list(reversed(torrent_collection1)) - - self.assertCountEqual(sorted_torrents1, expected_torrents1, 'Arrays contains different torrents') - self.assertListEqual(sorted_torrents1, expected_torrents1, 'Array is not sorted properly') - - # Test Investment policy - investment_policy = InvestmentPolicy() - torrent_collection2 = setup_torrents(self.torrents) - sorted_torrents2 = investment_policy.sort(torrent_collection2) - expected_torrents2 = list(reversed(torrent_collection2)) - - self.assertCountEqual(sorted_torrents2, expected_torrents2, 'Arrays contains different torrents') - self.assertListEqual(sorted_torrents2, expected_torrents2, 'Array is not sorted properly') - - def test_schedule_start(self): - policy = UploadPolicy() - policy.schedule(self.torrents[0]) - self.assertTrue(self.torrents[0].to_start) - policy.schedule(self.torrents[1], to_start=False) - self.assertFalse(self.torrents[1].to_start) - - def test_basic_policy_run(self): - """ - Test running an iteration of basic policy. - - Scenario: There are 10 torrents with infohashes ordered as 0-9 and the torrents with odd infohashes - are downloading while the rest are stopped. In the next iteration, we assume that all the - torrents with infohashes as multiple of 3 are scheduled to start and the rest to be stopped. - - The scenario is represented in the table below: - Infohash Status To Start -> Result - 0 STOPPED True Started - 1 DOWNLOADING False Stopped - 2 STOPPED False Do Nothing - 3 DOWNLOADING True Do Nothing - 4 STOPPED False Do Nothing - 5 DOWNLOADING False Stopped - 6 STOPPED True Started - 7 DOWNLOADING False Stopped - 8 STOPPED False Do Nothing - 9 DOWNLOADING True Do Nothing - - At the end of the iteration, the following result is expected: - Started = 2 - Stopped = 3 - """ - - scenario = MockObject() - scenario.to_start = [True, False, False, True, False, False, True, False, False, True] - scenario.torrent_status = [DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING, DLSTATUS_STOPPED, - DLSTATUS_DOWNLOADING, DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING, - DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING, DLSTATUS_STOPPED, - DLSTATUS_DOWNLOADING] - - # Any BasicPolicy implementation is fine. - policy = UploadPolicy() - - def get_status(scenario, index): - return scenario.torrent_status[index] - - for i, torrent in enumerate(self.torrents): - torrent.download = MockObject() - torrent.download.state = MockObject() - torrent.download.state.get_status = lambda _scenario=scenario, index=i: get_status(_scenario, index) - torrent.download.get_state = lambda _torrent=torrent: _torrent.download.state - torrent.download.resume = lambda: None - torrent.download.stop = lambda: None - policy.schedule(torrent, to_start=scenario.to_start[i]) - - policy.run() - self.assertEqual(policy.started_in_iteration, 2) - self.assertEqual(policy.stopped_in_iteration, 3) - - def test_basic_policy_run_with_no_downloads(self): - """ - Test running an iteration of basic policy without any downloads. - Policy should just skip those torrents. - """ - policy = UploadPolicy() - for torrent in self.torrents: - policy.schedule(torrent) - - policy.run() - self.assertEqual(policy.started_in_iteration, 0) - self.assertEqual(policy.stopped_in_iteration, 0) - - -class TestInvestmentPolicy(TriblerCoreTest): - """ - Class to test investment policy. - """ - - async def setUp(self): - await super(TestInvestmentPolicy, self).setUp() - self.torrents = [CreditMiningTorrent(i, 'test torrent %d' % i) for i in range(10)] - self.policy = InvestmentPolicy() - - def test_default_states(self): - default_states = self.policy.get_default_investment_states() - self.assertEqual(len(default_states), 20) - - self.assertEqual(default_states[0].state_id, 0) - self.assertEqual(default_states[0].upload_mode, False) - self.assertEqual(default_states[0].bandwidth_limit, 5 * MB) - - self.assertEqual(default_states[19].state_id, 19) - self.assertEqual(default_states[19].upload_mode, True) - self.assertEqual(default_states[19].bandwidth_limit, 163 * MB) - - def test_state_is_promotion_ready(self): - download_state1 = InvestmentState(1, False, 5*MB, promotion_ratio=1) - self.assertFalse(download_state1.is_promotion_ready(4 * MB, 3 * MB)) - self.assertTrue(download_state1.is_promotion_ready(5.1 * MB, 3 * MB)) - self.assertFalse(download_state1.is_promotion_ready(3 * MB, 6 * MB)) - - upload_state1 = InvestmentState(1, True, 5 * MB, promotion_ratio=1) - self.assertFalse(upload_state1.is_promotion_ready(5 * MB, 3 * MB)) - self.assertTrue(upload_state1.is_promotion_ready(5 * MB, 6 * MB)) - - upload_state2 = InvestmentState(1, True, 5 * MB, promotion_ratio=2) - self.assertFalse(upload_state2.is_promotion_ready(5 * MB, 6 * MB)) - self.assertTrue(upload_state2.is_promotion_ready(5 * MB, 10 * MB)) - - def test_compute_investment_state(self): - downloads = [1, 4, 5, 8, 10, 110, 150, 1000] - uploads = [0, 2, 3, 7, 15, 90, 180, 1000] - expected_states = [0, 0, 1, 4, 6, 17, 18, 19] - - for i in range(len(downloads)): - computed_state = self.policy.compute_state(downloads[i] * MB, uploads[i] * MB) - self.assertEqual(expected_states[i], computed_state) - - def test_get_reserved_bytes(self): - self.torrents[0].get_storage = lambda: (10 * MB, 4 * MB) - - # For state 0 with 5MB bandwidth limit - self.torrents[0].mining_state['state_id'] = 0 - self.assertTrue(self.policy.investment_states[0].bandwidth_limit, 5 * MB) - self.assertEqual(self.policy.get_reserved_bytes(self.torrents[0]), 1 * MB) - - # For state 1 with 5MB bandwidth limit - self.torrents[0].mining_state['state_id'] = 1 - self.assertTrue(self.policy.investment_states[0].bandwidth_limit, 5 * MB) - self.assertEqual(self.policy.get_reserved_bytes(self.torrents[0]), 1 * MB) - - # For state 2 with 7MB bandwidth limit - self.torrents[0].mining_state['state_id'] = 2 - self.assertTrue(self.policy.investment_states[1].bandwidth_limit, 7 * MB) - self.assertEqual(self.policy.get_reserved_bytes(self.torrents[0]), 3 * MB) - - def test_schedule_start(self): - self.torrents[0].download = MockObject() - self.torrents[0].state = MockObject() - self.torrents[0].state.get_total_transferred = lambda _: 0 - - time_before = time.time() - self.policy.schedule_start(self.torrents[0]) - self.assertTrue(self.torrents[0].to_start) - added_time = self.torrents[0].mining_state['start_time'] - self.assertTrue(added_time >= time_before) - - # Check adding torrent is done only once on subsequent start - start_time = self.torrents[0].mining_state['start_time'] - self.torrents[0].to_start = False - self.policy.schedule_start(self.torrents[0]) - self.assertTrue(self.torrents[0].to_start) - self.assertEqual(start_time, self.torrents[0].mining_state['start_time']) - - def test_promote_torrent(self): - - def set_upload_mode(upload_mode, torrent): - torrent.upload_mode = upload_mode - - torrent = self.torrents[0] - torrent.download = MockObject() - torrent.download.set_upload_mode = lambda upload_mode, _torrent=torrent: set_upload_mode(upload_mode, _torrent) - torrent.download.resume = lambda: None - - # Promote from state 0 - torrent.upload_mode = False - torrent.mining_state['state_id'] = 0 - self.policy.promote_torrent(torrent) - self.assertEqual(torrent.mining_state['state_id'], 1) - self.assertTrue(torrent.upload_mode) - - # Promote from state 1 - torrent.upload_mode = True - torrent.mining_state['state_id'] = 1 - self.policy.promote_torrent(torrent) - self.assertEqual(torrent.mining_state['state_id'], 2) - self.assertFalse(torrent.upload_mode) - - # Promote from last state - last_state = len(self.policy.investment_states) - 1 - torrent.upload_mode = True # Last state is always in upload mode - torrent.mining_state['state_id'] = last_state - self.policy.promote_torrent(torrent) - self.assertEqual(torrent.mining_state['state_id'], last_state) - self.assertTrue(torrent.upload_mode) - - def test_investment_policy_run(self): - """ - Test running an iteration of investment policy. - - Scenario - ------------------------------------------------ - Infohash, Level, Download, Upload, To start, ETA, Status --> Expected Result - 0 5 20 16 Yes 0 Downloading Upload mode - 1 0 4 2 Yes 1 Downloading Stop - 2 1 5 8 Yes 1 Seeding Promote -> Download mode - 3 9 22 23 Yes 1 Seeding Promote -> Download mode - 4 9 30 25 No 1 Downloading Stop - 5 0 4 3 Yes 1 Downloading Stop; stale - 6 12 40 35 Yes 1 Stopped Download mode - 7 15 50 40 No 1 Seeding Stop - 8 18 160 120 Yes 1 Downloading Do nothing -> Download mode - 9 19 163 170 Yes 1 Stopped Promote -> Upload mode - - At the end of the iteration, the following result is expected: - Started = 6 # Includes downloading and seeding torrents - Stopped = 4 - Upload mode = 2 # New torrents set in upload mode - Download mode = 3 # New torrents set in download mode - """ - - scenario = MockObject() - scenario.downloads = [20, 4, 5, 22, 30, 4, 40, 50, 160, 163] - scenario.uploads = [16, 2, 8, 23, 25, 3, 35, 40, 120, 170] - scenario.levels = [5, 0, 1, 9, 9, 0, 12, 15, 18, 19] - scenario.to_start = [True, False, True, True, False, True, True, False, True, True] - scenario.torrent_status = [DLSTATUS_DOWNLOADING, DLSTATUS_DOWNLOADING, DLSTATUS_SEEDING, - DLSTATUS_SEEDING, DLSTATUS_DOWNLOADING, DLSTATUS_DOWNLOADING, - DLSTATUS_STOPPED, DLSTATUS_SEEDING, DLSTATUS_DOWNLOADING, - DLSTATUS_STOPPED] - - def get_status(scenario, torrent): - return scenario.torrent_status[torrent.infohash] - - def get_eta(torrent): - return 0 if torrent.infohash == 0 else 1 - - def get_total_transferred(scenario, torrent, transfer_type): - if transfer_type == UPLOAD: - return scenario.uploads[torrent.infohash] * MB - return scenario.downloads[torrent.infohash] * MB - - def get_mining_state(scenario, torrent): - mining_state = dict() - mining_state['initial_upload'] = 0 - mining_state['initial_download'] = 0 - mining_state['state_id'] = scenario.levels[torrent.infohash] - return mining_state - - for torrent in self.torrents: - torrent.download = MockObject() - torrent.download.state = MockObject() - torrent.download.state.get_eta = lambda _torrent=torrent: get_eta(_torrent) - torrent.download.state.get_total_transferred = lambda transfer_type, _torrent=torrent, _scenario=scenario: \ - get_total_transferred(_scenario, _torrent, transfer_type) - torrent.mining_state = get_mining_state(scenario, torrent) - torrent.download.state.get_status = lambda _scenario=scenario, _torrent=torrent: \ - get_status(_scenario, _torrent) - torrent.download.get_state = lambda _torrent=torrent: _torrent.download.state - torrent.download.set_upload_mode = lambda _: None - torrent.download.resume = lambda: None - torrent.download.stop = lambda: None - torrent.start_time = time.time() - WEEK - 1 if torrent.infohash == 5 else time.time() - - # Schedule torrent to start or stop - self.policy.schedule(torrent, to_start=scenario.to_start[torrent.infohash]) - - # Torrents are ready, run the policy - self.policy.run() - - self.assertEqual(self.policy.started_in_iteration, 6) - self.assertEqual(self.policy.stopped_in_iteration, 4) - self.assertEqual(self.policy.num_downloading_in_iteration, 3) - self.assertEqual(self.policy.num_uploading_in_iteration, 2) - - def test_investment_policy_run_with_no_downloads(self): - """ - Test running an iteration of investment policy without any downloads. - Policy should just skip those torrents. - """ - for torrent in self.torrents: - self.policy.schedule(torrent) - - self.policy.run() - self.assertEqual(self.policy.started_in_iteration, 0) - self.assertEqual(self.policy.stopped_in_iteration, 0) diff --git a/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_sources.py b/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_sources.py deleted file mode 100644 index 63361fa9e08..00000000000 --- a/src/tribler-core/tribler_core/modules/credit_mining/tests/test_credit_mining_sources.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -Module of Credit mining function testing. - -Author(s): Mihai Capota, Ardhi Putra -""" -import os -from asyncio import Future - -from pony.orm import db_session - -from tribler_core.modules.credit_mining.credit_mining_source import ChannelSource -from tribler_core.tests.tools.test_as_server import TestAsServer -from tribler_core.tests.tools.tools import timeout - - -class TestCreditMiningSources(TestAsServer): - """ - Class to test the credit mining sources - """ - - def setUpPreSession(self): - super(TestCreditMiningSources, self).setUpPreSession() - self.config.set_chant_enabled(True) - - @timeout(5) - async def test_channel_lookup(self): - test_future = Future() - - with db_session: - my_channel = self.session.mds.ChannelMetadata.create_channel('test', 'test') - self.session.mds.TorrentMetadata(origin_id=my_channel.id_, title='testtorrent', infohash=os.urandom(20)) - - source = ChannelSource(self.session, my_channel.public_key, lambda *_: test_future.set_result(None)) - source.start() - await test_future diff --git a/src/tribler-core/tribler_core/modules/libtorrent/download.py b/src/tribler-core/tribler_core/modules/libtorrent/download.py index 0a34c7192bc..4fa602c9137 100644 --- a/src/tribler-core/tribler_core/modules/libtorrent/download.py +++ b/src/tribler-core/tribler_core/modules/libtorrent/download.py @@ -369,9 +369,6 @@ def update_lt_status(self, lt_status): def _stop_if_finished(self): state = self.get_state() - # Credit mining downloads are not affected by seeding policy - if self.config.get_credit_mining(): - return if state.get_status() == DLSTATUS_SEEDING: mode = self.session.config.get_seeding_mode() if mode == 'never' \ diff --git a/src/tribler-core/tribler_core/modules/libtorrent/download_config.py b/src/tribler-core/tribler_core/modules/libtorrent/download_config.py index 2f46b5ef54b..97b63bf8a51 100644 --- a/src/tribler-core/tribler_core/modules/libtorrent/download_config.py +++ b/src/tribler-core/tribler_core/modules/libtorrent/download_config.py @@ -89,12 +89,6 @@ def set_safe_seeding(self, value): def get_safe_seeding(self): return self.config['download_defaults']['safe_seeding'] - def set_credit_mining(self, value): - self.config['download_defaults']['credit_mining'] = value - - def get_credit_mining(self): - return bool(self.config['download_defaults']['credit_mining']) - def set_user_stopped(self, value): self.config['download_defaults']['user_stopped'] = value diff --git a/src/tribler-core/tribler_core/modules/libtorrent/download_config.spec b/src/tribler-core/tribler_core/modules/libtorrent/download_config.spec index 34b83a70551..5dc7beaf8d9 100644 --- a/src/tribler-core/tribler_core/modules/libtorrent/download_config.spec +++ b/src/tribler-core/tribler_core/modules/libtorrent/download_config.spec @@ -7,7 +7,6 @@ user_stopped = boolean(default=False) share_mode = boolean(default=False) upload_mode = boolean(default=False) time_added = integer(default=0) -credit_mining = boolean(default=False) bootstrap_download = boolean(default=False) channel_download = boolean(default=False) add_download_to_channel = boolean(default=False) diff --git a/src/tribler-core/tribler_core/modules/libtorrent/download_manager.py b/src/tribler-core/tribler_core/modules/libtorrent/download_manager.py index de61e152a0a..e57d31b3f2d 100644 --- a/src/tribler-core/tribler_core/modules/libtorrent/download_manager.py +++ b/src/tribler-core/tribler_core/modules/libtorrent/download_manager.py @@ -483,14 +483,6 @@ def start_download(self, torrent_file=None, tdef=None, config=None, checkpoint_d download = self.get_download(infohash) if download and infohash not in self.metainfo_requests: - # If there is an existing credit mining download with the same infohash - # then move to the user download directory and checkpoint the download immediately. - if download.config.get_credit_mining(): - self.tribler_session.credit_mining_manager.torrents.pop(hexlify(tdef.get_infohash()), None) - download.config.set_credit_mining(False) - download.move_storage(config.get_dest_dir()) - download.checkpoint() - new_trackers = list(set(tdef.get_trackers_as_single_tuple()) - set(download.get_def().get_trackers_as_single_tuple())) if new_trackers: @@ -730,8 +722,6 @@ async def sesscb_states_callback(self, states_list): if self.state_cb_count % 4 == 0: if self.tribler_session.tunnel_community: self.tribler_session.tunnel_community.monitor_downloads(states_list) - if self.tribler_session.credit_mining_manager: - self.tribler_session.credit_mining_manager.monitor_downloads(states_list) async def load_checkpoints(self): for filename in self.get_checkpoint_dir().glob('*.conf'): @@ -777,8 +767,6 @@ def load_checkpoint(self, filename): try: if self.download_exists(tdef.get_infohash()): self._logger.info("Not resuming checkpoint because download has already been added") - elif config.get_credit_mining() and not self.tribler_session.config.get_credit_mining_enabled(): - self._logger.info("Not resuming checkpoint since token mining is disabled") else: self.start_download(tdef=tdef, config=config) except Exception: diff --git a/src/tribler-core/tribler_core/modules/libtorrent/restapi/downloads_endpoint.py b/src/tribler-core/tribler_core/modules/libtorrent/restapi/downloads_endpoint.py index 2ad2ef4444d..aefe8bf6940 100644 --- a/src/tribler-core/tribler_core/modules/libtorrent/restapi/downloads_endpoint.py +++ b/src/tribler-core/tribler_core/modules/libtorrent/restapi/downloads_endpoint.py @@ -26,7 +26,8 @@ HTTP_NOT_FOUND, RESTEndpoint, RESTResponse, - RESTStreamResponse) + RESTStreamResponse, +) from tribler_core.restapi.util import return_handled_exception from tribler_core.utilities.path_util import Path from tribler_core.utilities.torrent_utils import get_info_from_handle @@ -264,7 +265,6 @@ async def get_downloads(self, request): "vod_prebuffering_progress_consec": 0, "error": repr(state.get_error()) if state.get_error() else "", "time_added": download.config.get_time_added(), - "credit_mining": download.config.get_credit_mining(), "channel_download": download.config.get_channel_download() } diff --git a/src/tribler-core/tribler_core/modules/libtorrent/tests/test_download_manager.py b/src/tribler-core/tribler_core/modules/libtorrent/tests/test_download_manager.py index 9cb52a41cb9..90a01475ee4 100644 --- a/src/tribler-core/tribler_core/modules/libtorrent/tests/test_download_manager.py +++ b/src/tribler-core/tribler_core/modules/libtorrent/tests/test_download_manager.py @@ -64,7 +64,6 @@ async def setUp(self): self.tribler_session.dlmgr = self.dlmgr self.tribler_session.tunnel_community = None - self.tribler_session.credit_mining_manager = None self.tribler_session.config = MockObject() self.tribler_session.config.get_libtorrent_utp = lambda: True @@ -218,7 +217,6 @@ async def test_start_download_while_getting_metainfo(self): metainfo_session.get_torrents = lambda: [] metainfo_dl = Mock() - metainfo_dl.config.get_credit_mining = lambda: False metainfo_dl.get_def = lambda: Mock(get_infohash=lambda: infohash) self.dlmgr.initialize() @@ -294,7 +292,6 @@ async def test_start_download_existing_download(self): infohash = b'a' * 20 mock_download = Mock() - mock_download.config.get_credit_mining = lambda: False mock_download.get_def = lambda: Mock(get_trackers_as_single_tuple=lambda: ()) mock_ltsession = Mock() diff --git a/src/tribler-core/tribler_core/restapi/events_endpoint.py b/src/tribler-core/tribler_core/restapi/events_endpoint.py index c0242a190cd..09d9a025297 100644 --- a/src/tribler-core/tribler_core/restapi/events_endpoint.py +++ b/src/tribler-core/tribler_core/restapi/events_endpoint.py @@ -35,8 +35,6 @@ def passthrough(x): NTFY.TORRENT_FINISHED: lambda *args: {"infohash": hexlify(args[0]), "name": args[1], "hidden": args[2]}, # Information about some torrent has been updated (e.g. health). Contains updated torrent data NTFY.CHANNEL_ENTITY_UPDATED: passthrough, - # An error arisen in credit mining manager - NTFY.CREDIT_MINING_ERROR: passthrough, # Tribler is going to shutdown. NTFY.TRIBLER_SHUTDOWN_STATE: passthrough, # Remote GigaChannel search results were received by Tribler. Contains received entries. diff --git a/src/tribler-core/tribler_core/restapi/settings_endpoint.py b/src/tribler-core/tribler_core/restapi/settings_endpoint.py index 90d921aa7b9..d72d43c5453 100644 --- a/src/tribler-core/tribler_core/restapi/settings_endpoint.py +++ b/src/tribler-core/tribler_core/restapi/settings_endpoint.py @@ -1,8 +1,5 @@ -from asyncio import gather - from aiohttp import web -from tribler_core.modules.credit_mining.credit_mining_manager import CreditMiningManager from tribler_core.restapi.rest_endpoint import RESTEndpoint, RESTResponse @@ -87,26 +84,6 @@ async def parse_setting(self, section, option, value): if section == "libtorrent" and (option == "max_download_rate" or option == "max_upload_rate"): self.session.dlmgr.update_max_rates_from_config() - if section == 'credit_mining' and option == 'enabled' and \ - value != bool(self.session.credit_mining_manager): - if value: - self.session.credit_mining_manager = CreditMiningManager(self.session) - else: - await self.session.credit_mining_manager.shutdown(remove_downloads=True) - self.session.credit_mining_manager = None - elif section == 'credit_mining' and option == 'sources': - if self.session.config.get_credit_mining_enabled(): - # Out with the old.. - if self.session.credit_mining_manager.sources: - await gather(*[self.session.credit_mining_manager.remove_source(source) for source in - list(self.session.credit_mining_manager.sources.keys())]) - # In with the new - for source in value: - self.session.credit_mining_manager.add_source(source) - elif section == 'credit_mining' and option == 'max_disk_space': - if self.session.config.get_credit_mining_enabled(): - self.session.credit_mining_manager.settings.max_disk_space = value - async def parse_settings_dict(self, settings_dict, depth=1, root_key=None): """ Parse the settings dictionary. diff --git a/src/tribler-core/tribler_core/restapi/tests/test_events_endpoint.py b/src/tribler-core/tribler_core/restapi/tests/test_events_endpoint.py index a8a0d5a74b8..f47ea002200 100644 --- a/src/tribler-core/tribler_core/restapi/tests/test_events_endpoint.py +++ b/src/tribler-core/tribler_core/restapi/tests/test_events_endpoint.py @@ -62,7 +62,6 @@ async def test_events(self): NTFY.CHANNEL_DISCOVERED: {"result": "bla"}, NTFY.TORRENT_FINISHED: (b'a' * 10, None, False), NTFY.LOW_SPACE: ("", ), - NTFY.CREDIT_MINING_ERROR: {"message": "Some credit mining error"}, NTFY.TUNNEL_REMOVE: (Circuit(1234, None), 'test'), NTFY.REMOTE_QUERY_RESULTS: {"query": "test"}, } diff --git a/src/tribler-core/tribler_core/restapi/tests/test_settings_endpoint.py b/src/tribler-core/tribler_core/restapi/tests/test_settings_endpoint.py index f4ff2e382bb..d7525b5f1f4 100644 --- a/src/tribler-core/tribler_core/restapi/tests/test_settings_endpoint.py +++ b/src/tribler-core/tribler_core/restapi/tests/test_settings_endpoint.py @@ -77,7 +77,6 @@ async def test_set_settings(self): """ dcfg = DownloadConfig() - dcfg.get_credit_mining = lambda: False download = MockObject() download.config = dcfg self.session.dlmgr.get_downloads = lambda: [download] diff --git a/src/tribler-core/tribler_core/session.py b/src/tribler-core/tribler_core/session.py index 0e0233110df..7eb3631a8be 100644 --- a/src/tribler-core/tribler_core/session.py +++ b/src/tribler-core/tribler_core/session.py @@ -37,7 +37,6 @@ STATE_LOAD_CHECKPOINTS, STATE_READABLE_STARTED, STATE_START_API, - STATE_START_CREDIT_MINING, STATE_START_LIBTORRENT, STATE_START_TORRENT_CHECKER, STATE_START_WATCH_FOLDER, @@ -141,7 +140,6 @@ def __init__(self, config): self.gigachannel_community = None self.remote_query_community = None - self.credit_mining_manager = None self.market_community = None self.dht_community = None self.payout_manager = None @@ -495,11 +493,6 @@ async def start(self): if self.config.get_ipv8_enabled() and self.config.get_trustchain_enabled(): self.payout_manager = PayoutManager(self.trustchain_community, self.dht_community) - if self.config.get_credit_mining_enabled(): - self.readable_status = STATE_START_CREDIT_MINING - from tribler_core.modules.credit_mining.credit_mining_manager import CreditMiningManager - self.credit_mining_manager = CreditMiningManager(self) - # GigaChannel Manager should be started *after* resuming the downloads, # because it depends on the states of torrent downloads if self.config.get_chant_enabled() and self.config.get_chant_manager_enabled()\ @@ -528,10 +521,6 @@ async def shutdown(self): await self.shutdown_task_manager() self.shutdownstarttime = timemod.time() - if self.credit_mining_manager: - self.notify_shutdown_state("Shutting down Credit Mining...") - await self.credit_mining_manager.shutdown() - self.credit_mining_manager = None if self.torrent_checker: self.notify_shutdown_state("Shutting down Torrent Checker...") diff --git a/src/tribler-core/tribler_core/tests/tools/data/state_dir_dummy/triblerd.conf b/src/tribler-core/tribler_core/tests/tools/data/state_dir_dummy/triblerd.conf index c4ce1523395..6489b9a4e1b 100644 --- a/src/tribler-core/tribler_core/tests/tools/data/state_dir_dummy/triblerd.conf +++ b/src/tribler-core/tribler_core/tests/tools/data/state_dir_dummy/triblerd.conf @@ -16,5 +16,4 @@ port = 8085 key = 129bbdf7199cec22c9e72a2ad965336e [resource_monitor] -[credit_mining] [popularity_community] diff --git a/src/tribler-core/tribler_core/tests/tools/data/test_rss_cm.xml b/src/tribler-core/tribler_core/tests/tools/data/test_rss_cm.xml deleted file mode 100644 index 2a75fa77499..00000000000 --- a/src/tribler-core/tribler_core/tests/tools/data/test_rss_cm.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - Test RSS for Credit Mining - test_rss_cm.xml - Test RSS CM feed. - - en - Tue, 12 May 2015 08:39:23 GMT - Tue, 12 May 2015 08:39:23 GMT - - - - - ubuntu-15.04-desktop-amd64.iso - http://localhost:RANDOMPORT/ubuntu.torrent - - http://localhost:RANDOMPORT.ubuntu.torrent - - - - Pioneer.One.S01E06.720p.x264-VODO.torrent - http://localhost:RANDOMPORT/pioneer.torrent - - http://localhost:RANDOMPORT.pioneer.torrent - - - diff --git a/src/tribler-core/tribler_core/tests/tools/test_as_server.py b/src/tribler-core/tribler_core/tests/tools/test_as_server.py index f4389eef4da..9de094c0d2e 100644 --- a/src/tribler-core/tribler_core/tests/tools/test_as_server.py +++ b/src/tribler-core/tribler_core/tests/tools/test_as_server.py @@ -258,7 +258,6 @@ def setUpPreSession(self): self.config.set_libtorrent_enabled(False) self.config.set_http_api_enabled(False) self.config.set_tunnel_community_enabled(False) - self.config.set_credit_mining_enabled(False) self.config.set_market_community_enabled(False) self.config.set_popularity_community_enabled(False) self.config.set_dht_enabled(False) @@ -316,7 +315,6 @@ async def setup_seeder(self, tdef, seed_dir, port=None): self.seed_config.set_version_checker_enabled(False) self.seed_config.set_bitcoinlib_enabled(False) self.seed_config.set_chant_enabled(False) - self.seed_config.set_credit_mining_enabled(False) self.seed_config.set_resource_monitor_enabled(False) self.seed_config.set_bootstrap_enabled(False) diff --git a/src/tribler-gui/tribler_gui/debug_window.py b/src/tribler-gui/tribler_gui/debug_window.py index 76cd3c969bb..c74f98ce85b 100644 --- a/src/tribler-gui/tribler_gui/debug_window.py +++ b/src/tribler-gui/tribler_gui/debug_window.py @@ -21,7 +21,7 @@ from tribler_gui.event_request_manager import received_events as tribler_received_events from tribler_gui.tribler_request_manager import TriblerNetworkRequest, performed_requests as tribler_performed_requests from tribler_gui.utilities import format_size, get_ui_file_path -from tribler_gui.widgets.tokenminingpage import TimeSeriesPlot +from tribler_gui.widgets.graphs.timeseriesplot import TimeSeriesPlot try: from meliae import scanner @@ -392,16 +392,7 @@ def on_tunnel_circuits(self, circuits): self.add_items_to_tree( self.window().circuits_tree_widget, circuits.get("circuits"), - [ - "circuit_id", - "hops", - "type", - "state", - "bytes_up", - "bytes_down", - "creation_time", - "exit_flags" - ], + ["circuit_id", "hops", "type", "state", "bytes_up", "bytes_down", "creation_time", "exit_flags"], ) def load_tunnel_relays_tab(self): @@ -453,15 +444,7 @@ def load_tunnel_peers_tab(self): def on_tunnel_peers(self, data): if data: self.add_items_to_tree( - self.window().peers_tree_widget, - data.get("peers"), - [ - "ip", - "port", - "mid", - "is_key_compatible", - "flags", - ], + self.window().peers_tree_widget, data.get("peers"), ["ip", "port", "mid", "is_key_compatible", "flags"] ) def load_dht_tab(self): diff --git a/src/tribler-gui/tribler_gui/defs.py b/src/tribler-gui/tribler_gui/defs.py index ed2bd1a9adf..0abfc58ab39 100644 --- a/src/tribler-gui/tribler_gui/defs.py +++ b/src/tribler-gui/tribler_gui/defs.py @@ -20,8 +20,7 @@ PAGE_MARKET_TRANSACTIONS = 11 PAGE_MARKET_WALLETS = 12 PAGE_MARKET_ORDERS = 13 -PAGE_TOKEN_MINING_PAGE = 14 -PAGE_TRUST_GRAPH_PAGE = 15 +PAGE_TRUST_GRAPH_PAGE = 14 PAGE_EDIT_CHANNEL_TORRENTS = 2 @@ -63,7 +62,6 @@ DOWNLOADS_FILTER_COMPLETED = 2 DOWNLOADS_FILTER_ACTIVE = 3 DOWNLOADS_FILTER_INACTIVE = 4 -DOWNLOADS_FILTER_CREDITMINING = 5 DOWNLOADS_FILTER_CHANNELS = 6 DOWNLOADS_FILTER_DEFINITION = { diff --git a/src/tribler-gui/tribler_gui/event_request_manager.py b/src/tribler-gui/tribler_gui/event_request_manager.py index b14089a4f7b..4ddd1c95dca 100644 --- a/src/tribler-gui/tribler_gui/event_request_manager.py +++ b/src/tribler-gui/tribler_gui/event_request_manager.py @@ -32,7 +32,6 @@ class EventRequestManager(QNetworkAccessManager): market_payment_received = pyqtSignal(object) market_payment_sent = pyqtSignal(object) low_storage_signal = pyqtSignal(object) - credit_mining_signal = pyqtSignal(object) tribler_shutdown_signal = pyqtSignal(str) def __init__(self, api_port, api_key): @@ -61,7 +60,6 @@ def __init__(self, api_port, api_key): "market_payment_received": self.market_payment_received.emit, "market_payment_sent": self.market_payment_sent.emit, NTFY.LOW_SPACE.value: self.low_storage_signal.emit, - NTFY.CREDIT_MINING_ERROR.value: self.credit_mining_signal.emit, NTFY.REMOTE_QUERY_RESULTS.value: self.received_remote_query_results.emit, NTFY.TRIBLER_SHUTDOWN_STATE.value: self.tribler_shutdown_signal.emit, NTFY.EVENTS_START.value: self.events_start_received, diff --git a/src/tribler-gui/tribler_gui/qt_resources/mainwindow.ui b/src/tribler-gui/tribler_gui/qt_resources/mainwindow.ui index a585a4322fe..868bc579b7f 100644 --- a/src/tribler-gui/tribler_gui/qt_resources/mainwindow.ui +++ b/src/tribler-gui/tribler_gui/qt_resources/mainwindow.ui @@ -2891,48 +2891,6 @@ High anonymity - - - - font-weight: bold; -color: white; - - - Token mining - - - - - - - Enable token mining (requires Tribler restart) - - - - - - - - 0 - 0 - - - - Tribler uses a blockchain to keep track of your sharing ratio, which eventually prevents freeriding. It is currently still in an early phase of development. -Token mining is the automated process of uploading to swarms in order increase your sharing ratio and your reputation. Go to your discovered channels and pick a channel to mine from. - - - true - - - - - - - Maximum disk space usage (bytes) - - - @@ -4375,40 +4333,6 @@ padding-left: 2px; - - - - - 0 - 0 - - - - - 0 - 36 - - - - - 16777215 - 36 - - - - PointingHandCursor - - - - - - TOKEN MINING - - - true - - - @@ -5635,28 +5559,6 @@ border-radius: 10px; - - - - - 80 - 24 - - - - - 150 - 24 - - - - PointingHandCursor - - - TOKEN MINING - - - @@ -5736,7 +5638,7 @@ border-radius: 10px; padding-left: 10px; padding-right: 10px; - You can build trust by contributing bandwidth to the Tribler network. This is done by letting Tribler run idle, or by mining tokens. + You can build trust by contributing bandwidth to the Tribler network. This is done by letting Tribler run idle. true @@ -8168,7 +8070,7 @@ font-weight: bold; - + QLabel { color: #eee; } @@ -8189,8 +8091,8 @@ font-weight: bold; 0 - - + + 0 @@ -8207,53 +8109,44 @@ font-weight: bold; 0 - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - + + + + 0 + 0 + - - - - - 16 - 18 + 0 + 50 - 16 - 18 + 16777215 + 50 - - PointingHandCursor - - border: none; + color: #eee; +background-color: transparent; +font-size: 20px; +font-weight: bold; +margin: 10px 4px 2px 10px; - + Trust Graph - + Qt::Horizontal - QSizePolicy::Fixed + QSizePolicy::Expanding @@ -8264,57 +8157,42 @@ font-weight: bold; - - - - 0 - 0 - - + - 0 - 50 + 64 + 28 - 16777215 - 50 + 64 + 28 + + PointingHandCursor + - color: #eee; - background-color: transparent; - font-size: 20px; - font-weight: bold; - margin: 10px; -margin-right: 4px; -margin-top: 9px; + margin-right:16px - Token Mining - - - - - - - Qt::Horizontal + REFRESH - - QSizePolicy::Expanding + + + ../images/refresh.png../images/refresh.png - + - 10 - 20 + 18 + 18 - + - + Qt::Horizontal @@ -8333,7 +8211,7 @@ margin-top: 9px; - + Qt::Vertical @@ -8349,12 +8227,20 @@ margin-top: 9px; - + + + + true + + - padding-left: 10px; padding-right: 10px; + padding-left: 10px; padding-right: 10px;margin-bottom:8px; - You pay bandwidth tokens for anonymous downloads and earn tokens for anonymous uploads. With token mining enabled on a channel, Tribler automatically selects the torrents for mining. Note that it may take sometime before the actual values are displayed. + The graph below is based on your historical interactions with other users in the network. + + + Qt::RichText true @@ -8362,9 +8248,9 @@ margin-top: 9px; - + - + 0 0 @@ -8372,605 +8258,70 @@ margin-top: 9px; 0 - 150 + 32 16777215 - 300 + 32 - + QProgressBar { + background-color: #FFF; + border: 0px; + padding: 0px; + height: 10px; + margin: 0 16px; + } + QProgressBar::chunk { + background: #5c58ee; + width:5px + } - + + 0 + + + 24 + + + Qt::AlignCenter + + + QProgressBar::TopToBottom + + + Progress %p% + + + + + + - 20 + 0 - 20 + 0 - 20 + 0 - 20 + 0 - 20 + 0 - - - QWidget { -background-color: #383838; -} -QLabel { -border: none; -} - - - - 0 - - - - - - 0 - 0 - - - - - 0 - 50 - - - - - 16777215 - 50 - - - - font-size: 20px; font-weight: bold; - - - - MBytes - - - Qt::AlignCenter - - - - - - - - 0 - 50 - - - - - 16777215 - 50 - - - - - -1 - - - - font-size: 15px; - - - UPLOAD - - - Qt::AlignCenter - - - - - - - - - - - 16777215 - 16777215 - - - - QWidget { -background-color: #383838; -} -QLabel { -border: none; -} - - - - 0 - - - - - - 0 - 50 - - - - - 16777215 - 50 - - - - font-size: 20px; font-weight: bold; - - - - MBytes - - - Qt::AlignCenter - - - - - - - - 0 - 50 - - - - - 16777215 - 50 - - - - font-size: 15px; - - - DOWNLOAD - - - Qt::AlignCenter - - - - - - - - - - - 16777215 - 16777215 - - - - QWidget { -background-color: #383838; -} -QLabel { -border: none; -} - - - - 0 - - - - - - 0 - 50 - - - - - 16777215 - 50 - - - - font-size: 20px; font-weight: bold; - - - - MBytes - - - Qt::AlignCenter - - - - - - - - 0 - 50 - - - - - 16777215 - 50 - - - - font-size: 15px; - - - DISK USAGE - - - Qt::AlignCenter - - - - - - - - - - - - - - 0 - 0 - - - - - - - - 20 - - - 20 - - - 0 - - - 20 - - - 20 - - - - - - - - - 0 - - - 2 - - - 2 - - - 2 - - - 2 - - - - - - 0 - 250 - - - - - 0 - 250 - - - - false - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - - - - - - - - QLabel { color: #eee; } - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - - 0 - 50 - - - - - 16777215 - 50 - - - - color: #eee; -background-color: transparent; -font-size: 20px; -font-weight: bold; -margin: 10px 4px 2px 10px; - - - Trust Graph - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 10 - 20 - - - - - - - - - 64 - 28 - - - - - 64 - 28 - - - - PointingHandCursor - - - margin-right:16px - - - REFRESH - - - - ../images/refresh.png../images/refresh.png - - - - 18 - 18 - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 20 - 6 - - - - - - - - - true - - - - padding-left: 10px; padding-right: 10px;margin-bottom:8px; - - - The graph below is based on your historical interactions with other users in the network. - - - Qt::RichText - - - true - - - - - - - - 0 - 0 - - - - - 0 - 32 - - - - - 16777215 - 32 - - - - QProgressBar { - background-color: #FFF; - border: 0px; - padding: 0px; - height: 10px; - margin: 0 16px; - } - QProgressBar::chunk { - background: #5c58ee; - width:5px - } - - - 0 - - - 24 - - - Qt::AlignCenter - - - QProgressBar::TopToBottom - - - Progress %p% - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - + + + + 0 + 0 + @@ -9252,12 +8603,6 @@ margin: 10px 4px 2px 10px; QWidget
tribler_gui.widgets.channelcontentswidget.h
- - TokenMiningPage - QWidget -
tribler_gui.widgets.tokenminingpage.h
- 1 -
TrustGraphPage QWidget @@ -9555,22 +8900,6 @@ margin: 10px 4px 2px 10px; - - token_mining_back_button - clicked() - MainWindow - on_page_back_clicked() - - - 216 - 98 - - - 427 - 327 - - - left_menu_button_trust_graph clicked() diff --git a/src/tribler-gui/tribler_gui/qt_resources/torrents_list.ui b/src/tribler-gui/tribler_gui/qt_resources/torrents_list.ui index 414d6dc3207..9ec07a2bb1f 100644 --- a/src/tribler-gui/tribler_gui/qt_resources/torrents_list.ui +++ b/src/tribler-gui/tribler_gui/qt_resources/torrents_list.ui @@ -503,63 +503,9 @@ background-color: transparent;
- - - - - 28 - 28 - - - - - 28 - 28 - - - - PointingHandCursor - - - QToolButton { -border: none; -background-color: transparent; -} - - - Mine credits - - - - ../images/credit_mining_not.png../images/credit_mining_not.png - - - - 18 - 18 - - - -
- - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - -
@@ -630,80 +576,6 @@ background-color: transparent; - - - - - 120 - 24 - - - - - 120 - 24 - - - - PointingHandCursor - - - NEW CHANNEL - - - - - - - - 0 - 0 - - - - - 36 - 16 - - - - - 36 - 16 - - - - - false - - - - PointingHandCursor - - - - - - border:none;margin-left:16px; - - - - - - - ../images/ellipsis.png../images/ellipsis.png - - - - 32 - 32 - - - - false - - - @@ -794,6 +666,96 @@ padding-right: 4px; + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + + 120 + 24 + + + + + 120 + 24 + + + + PointingHandCursor + + + NEW CHANNEL + + + + + + + + 0 + 0 + + + + + 36 + 16 + + + + + 36 + 16 + + + + + false + + + + PointingHandCursor + + + + + + border:none;margin-left:16px; + + + + + + + ../images/ellipsis.png../images/ellipsis.png + + + + 32 + 32 + + + + false + + + diff --git a/src/tribler-gui/tribler_gui/tests/fake_tribler_api/models/download.py b/src/tribler-gui/tribler_gui/tests/fake_tribler_api/models/download.py index 8a4ccd99654..46890b04f83 100644 --- a/src/tribler-gui/tribler_gui/tests/fake_tribler_api/models/download.py +++ b/src/tribler-gui/tribler_gui/tests/fake_tribler_api/models/download.py @@ -10,7 +10,7 @@ class Download(object): - def __init__(self, torrent, is_credit_mining=False, is_channel_download=False): + def __init__(self, torrent, is_channel_download=False): self.torrent = torrent self.status = randint(0, 8) self.anon = True if randint(0, 1) == 0 else False @@ -34,7 +34,6 @@ def __init__(self, torrent, is_credit_mining=False, is_channel_download=False): self.total_pieces = randint(100, 2000) self.has_pieces = [False] * self.total_pieces self.time_added = randint(1400000000, 1484819242) - self.is_credit_mining = is_credit_mining self.is_channel_download = is_channel_download # Set some pieces to True @@ -91,7 +90,6 @@ def get_json(self, get_peers=False, get_pieces=False): "time_added": self.time_added, "vod_mode": False, "vod_prebuffering_progress_consec": 0.34, - "credit_mining": self.is_credit_mining, "num_connected_peers": self.num_connected_peers, "num_connected_seeds": self.num_connected_seeds, "channel_download": self.is_channel_download, diff --git a/src/tribler-gui/tribler_gui/tests/fake_tribler_api/tribler_data.py b/src/tribler-gui/tribler_gui/tests/fake_tribler_api/tribler_data.py index 6995c1902e6..c19245bf84d 100644 --- a/src/tribler-gui/tribler_gui/tests/fake_tribler_api/tribler_data.py +++ b/src/tribler-gui/tribler_gui/tests/fake_tribler_api/tribler_data.py @@ -82,7 +82,6 @@ def generate(self): "trustchain": {"enabled": True}, "tunnel_community": {"exitnode_enabled": True}, "search_community": {"enabled": True}, - "credit_mining": {"enabled": True, "sources": [], "max_disk_space": 100}, "resource_monitor": {"enabled": True}, "chant": {"enabled": True, "channel_edit": True}, }, @@ -214,11 +213,6 @@ def generate_downloads(self): for _ in range(randint(10, 30)): self.start_random_download() - # Start some credit mining downloads - for _ in range(randint(1, 5)): - random_torrent = sample(self.torrents, 1)[0] - self.downloads.append(Download(random_torrent, is_credit_mining=True)) - # Start some channel downloads for _ in range(randint(1, 5)): random_torrent = sample(self.torrents, 1)[0] diff --git a/src/tribler-gui/tribler_gui/tests/test_gui.py b/src/tribler-gui/tribler_gui/tests/test_gui.py index fc6dff385ee..0618b1afd3a 100644 --- a/src/tribler-gui/tribler_gui/tests/test_gui.py +++ b/src/tribler-gui/tribler_gui/tests/test_gui.py @@ -295,11 +295,6 @@ def tst_channels_widget(self, widget, widget_name, sort_column=1): self.wait_for_list_populated(widget.content_table) self.screenshot(window, name=f"{widget_name}-channel_loaded") - # FIXME: credit mining for collections! - # Toggle credit mining - # QTest.mouseClick(widget.credit_mining_button, Qt.LeftButton) - # self.wait_for_signal(widget.subscription_widget.credit_mining_toggled) - # Click the first torrent index = self.get_index_of_row(widget.content_table, 0) widget.content_table.on_table_item_clicked(index) @@ -348,8 +343,6 @@ def test_downloads(self): self.screenshot(window, name="downloads_active") QTest.mouseClick(window.downloads_inactive_button, Qt.LeftButton) self.screenshot(window, name="downloads_inactive") - QTest.mouseClick(window.downloads_creditmining_button, Qt.LeftButton) - self.screenshot(window, name="downloads_creditmining") QTest.mouseClick(window.downloads_channels_button, Qt.LeftButton) self.screenshot(window, name="downloads_channels") diff --git a/src/tribler-gui/tribler_gui/tribler_window.py b/src/tribler-gui/tribler_gui/tribler_window.py index 93986228e44..487c3bdc372 100644 --- a/src/tribler-gui/tribler_gui/tribler_window.py +++ b/src/tribler-gui/tribler_gui/tribler_window.py @@ -229,7 +229,6 @@ def on_state_update(new_state): self.core_manager.events_manager.discovered_channel.connect(self.discovered_page.model.on_new_entry_received) self.trust_page.initialize_trust_page() - self.token_mining_page.initialize_token_mining_page() self.trust_graph_page.initialize_trust_graph() self.stackedWidget.setCurrentIndex(PAGE_LOADING) @@ -306,7 +305,6 @@ def on_state_update(new_state): self.core_manager.events_manager.new_version_available.connect(self.on_new_version_available) self.core_manager.events_manager.tribler_started.connect(self.on_tribler_started) self.core_manager.events_manager.low_storage_signal.connect(self.on_low_storage) - self.core_manager.events_manager.credit_mining_signal.connect(self.on_credit_mining_error) self.core_manager.events_manager.tribler_shutdown_signal.connect(self.on_tribler_shutdown_state_update) # Install signal handler for ctrl+c events @@ -635,8 +633,6 @@ def received_settings(self, settings): self.video_player_page.video_player_port = self.core_manager.api_port self.video_player_page.video_player_api_key = self.core_manager.api_key.decode('utf-8') - # Disable various components based on the settings - self.downloads_creditmining_button.setHidden(not self.tribler_settings["credit_mining"]["enabled"]) self.downloads_all_button.click() # process pending file requests (i.e. someone clicked a torrent file when Tribler was closed) @@ -1068,9 +1064,6 @@ def on_page_back_clicked(self): except IndexError: logging.exception("Unknown page found in stack") - def on_credit_mining_error(self, error): - ConfirmationDialog.show_error(self, "Credit Mining Error", error[u'message']) - def resizeEvent(self, _): # This thing here is necessary to send the resize event to dialogs, etc. self.resize_event.emit() diff --git a/src/tribler-gui/tribler_gui/widgets/channelcontentswidget.py b/src/tribler-gui/tribler_gui/widgets/channelcontentswidget.py index a3879d07d8c..03f6b6d0e61 100644 --- a/src/tribler-gui/tribler_gui/widgets/channelcontentswidget.py +++ b/src/tribler-gui/tribler_gui/widgets/channelcontentswidget.py @@ -51,7 +51,6 @@ def __init__(self, parent=None): # for each external resource (e.g. image/icon), we must reload it manually here. self.channel_options_button.setIcon(QIcon(get_image_path('ellipsis.png'))) self.channel_preview_button.setIcon(QIcon(get_image_path('refresh.png'))) - self.credit_mining_button.setIcon(QIcon(get_image_path('credit_mining_not.png'))) self.default_channel_model = ChannelContentModel diff --git a/src/tribler-gui/tribler_gui/widgets/downloadspage.py b/src/tribler-gui/tribler_gui/widgets/downloadspage.py index 94be36a0b32..8efcb657e8c 100644 --- a/src/tribler-gui/tribler_gui/widgets/downloadspage.py +++ b/src/tribler-gui/tribler_gui/widgets/downloadspage.py @@ -20,7 +20,6 @@ DOWNLOADS_FILTER_ALL, DOWNLOADS_FILTER_CHANNELS, DOWNLOADS_FILTER_COMPLETED, - DOWNLOADS_FILTER_CREDITMINING, DOWNLOADS_FILTER_DEFINITION, DOWNLOADS_FILTER_DOWNLOADING, DOWNLOADS_FILTER_INACTIVE, @@ -28,7 +27,7 @@ from tribler_gui.dialogs.confirmationdialog import ConfirmationDialog from tribler_gui.tribler_action_menu import TriblerActionMenu from tribler_gui.tribler_request_manager import TriblerFileDownloadRequest, TriblerNetworkRequest -from tribler_gui.utilities import compose_magnetlink, format_size, format_speed +from tribler_gui.utilities import compose_magnetlink, format_speed from tribler_gui.widgets.downloadwidgetitem import DownloadWidgetItem from tribler_gui.widgets.loading_list_item import LoadingListItem @@ -38,7 +37,6 @@ "downloads_completed_button": DOWNLOADS_FILTER_COMPLETED, "downloads_active_button": DOWNLOADS_FILTER_ACTIVE, "downloads_inactive_button": DOWNLOADS_FILTER_INACTIVE, - "downloads_creditmining_button": DOWNLOADS_FILTER_CREDITMINING, "downloads_channels_button": DOWNLOADS_FILTER_CHANNELS, } @@ -213,8 +211,6 @@ def on_received_downloads(self, downloads): if len(self.window().downloads_list.selectedItems()) > 0: self.on_download_item_clicked() - self.update_credit_mining_disk_usage() - self.received_downloads.emit(downloads) def update_download_visibility(self): @@ -224,17 +220,13 @@ def update_download_visibility(self): continue filter_match = self.window().downloads_filter_input.text().lower() in item.download_info["name"].lower() - is_creditmining = item.download_info["credit_mining"] is_channel = item.download_info["channel_download"] - if self.filter == DOWNLOADS_FILTER_CREDITMINING: - item.setHidden(not is_creditmining or not filter_match) - elif self.filter == DOWNLOADS_FILTER_CHANNELS: + if self.filter == DOWNLOADS_FILTER_CHANNELS: item.setHidden(not is_channel or not filter_match) else: item.setHidden( not item.get_raw_download_status() in DOWNLOADS_FILTER_DEFINITION[self.filter] or not filter_match - or is_creditmining or is_channel ) @@ -244,37 +236,6 @@ def on_downloads_tab_button_clicked(self, button_name): self.window().downloads_list.clearSelection() self.window().download_details_widget.hide() self.update_download_visibility() - self.update_credit_mining_disk_usage() - - def update_credit_mining_disk_usage(self): - on_credit_mining_tab = self.filter == DOWNLOADS_FILTER_CREDITMINING - self.window().diskspace_usage.setVisible(on_credit_mining_tab) - - if not on_credit_mining_tab or not self.window().tribler_settings or not self.downloads: - return - - bytes_max = self.window().tribler_settings["credit_mining"]["max_disk_space"] - bytes_used = 0 - total_up = total_down = 0 - for download in self.downloads["downloads"]: - if download["credit_mining"] and download["status"] in ( - "DLSTATUS_DOWNLOADING", - "DLSTATUS_SEEDING", - "DLSTATUS_STOPPED", - "DLSTATUS_STOPPED_ON_ERROR", - ): - bytes_used += download["progress"] * download["size"] - total_up += download["total_up"] - total_down += download["total_down"] - self.window().diskspace_usage.setText( - "Disk usage: %s / %s \tUpload: %.3f MB \tDownload: %.3f MB" - % ( - format_size(float(bytes_used)), - format_size(float(bytes_max)), - total_up / 1048576.0, - total_down / 1028576.0, - ) - ) @staticmethod def start_download_enabled(download_widgets): diff --git a/src/tribler-gui/tribler_gui/widgets/settingspage.py b/src/tribler-gui/tribler_gui/widgets/settingspage.py index 61274aadf30..00c65dc87cd 100644 --- a/src/tribler-gui/tribler_gui/widgets/settingspage.py +++ b/src/tribler-gui/tribler_gui/widgets/settingspage.py @@ -1,10 +1,10 @@ import sys +from PIL.ImageQt import ImageQt + from PyQt5 import QtCore, QtGui from PyQt5.QtWidgets import QFileDialog, QLabel, QSizePolicy, QWidget -from PIL.ImageQt import ImageQt - import tribler_core.utilities.json_util as json from tribler_gui.defs import ( @@ -83,7 +83,6 @@ def initialize_settings_page(self): self.window().lt_utp_checkbox, self.window().watchfolder_enabled_checkbox, self.window().allow_exit_node_checkbox, - self.window().credit_mining_enabled_checkbox, self.window().developer_mode_enabled_checkbox, self.window().checkbox_enable_network_statistics, self.window().checkbox_enable_resource_log, @@ -318,8 +317,6 @@ def initialize_with_settings(self, settings): self.window().number_hops_slider.setValue(int(settings['download_defaults']['number_hops'])) self.window().number_hops_slider.valueChanged.connect(self.update_anonymity_cost_label) self.update_anonymity_cost_label(int(settings['download_defaults']['number_hops'])) - self.window().credit_mining_enabled_checkbox.setChecked(settings['credit_mining']['enabled']) - self.window().max_disk_space_input.setText(str(settings['credit_mining']['max_disk_space'])) # Debug self.window().developer_mode_enabled_checkbox.setChecked( @@ -394,7 +391,6 @@ def save_settings(self): 'watch_folder': {}, 'tunnel_community': {}, 'trustchain': {}, - 'credit_mining': {}, 'resource_monitor': {}, 'ipv8': {}, 'chant': {}, @@ -509,15 +505,6 @@ def save_settings(self): ) return - settings_data['credit_mining']['enabled'] = self.window().credit_mining_enabled_checkbox.isChecked() - try: - settings_data['credit_mining']['max_disk_space'] = int(self.window().max_disk_space_input.text()) - except ValueError: - ConfirmationDialog.show_error( - self.window(), "Invalid number", "You've entered an invalid number for max disk space value" - ) - return - settings_data['tunnel_community']['exitnode_enabled'] = self.window().allow_exit_node_checkbox.isChecked() settings_data['download_defaults']['number_hops'] = self.window().number_hops_slider.value() settings_data['download_defaults'][ diff --git a/src/tribler-gui/tribler_gui/widgets/subscriptionswidget.py b/src/tribler-gui/tribler_gui/widgets/subscriptionswidget.py index 495261145a0..0224033212a 100644 --- a/src/tribler-gui/tribler_gui/widgets/subscriptionswidget.py +++ b/src/tribler-gui/tribler_gui/widgets/subscriptionswidget.py @@ -1,13 +1,11 @@ import json -from PyQt5.QtCore import pyqtSignal -from PyQt5.QtGui import QIcon, QPixmap from PyQt5.QtWidgets import QWidget import tribler_core.utilities.json_util as json from tribler_gui.tribler_request_manager import TriblerNetworkRequest -from tribler_gui.utilities import format_votes, get_image_path +from tribler_gui.utilities import format_votes class SubscriptionsWidget(QWidget): @@ -15,13 +13,10 @@ class SubscriptionsWidget(QWidget): This widget shows a favorite button and the number of subscriptions that a specific channel has. """ - credit_mining_toggled = pyqtSignal(bool) - def __init__(self, parent): QWidget.__init__(self, parent) self.subscribe_button = None - self.credit_mining_button = None self.initialized = False self.contents_widget = None @@ -31,10 +26,8 @@ def initialize(self, contents_widget): # returns the current model in use (top of the stack) self.contents_widget = contents_widget self.subscribe_button = self.findChild(QWidget, "subscribe_button") - self.credit_mining_button = self.findChild(QWidget, "credit_mining_button") self.subscribe_button.clicked.connect(self.on_subscribe_button_click) - self.credit_mining_button.clicked.connect(self.on_credit_mining_button_click) self.initialized = True def update_subscribe_button(self, remote_response=None): @@ -45,29 +38,9 @@ def update_subscribe_button(self, remote_response=None): self.subscribe_button.setStyleSheet('border:none; color: %s' % color) self.subscribe_button.setText(format_votes(self.contents_widget.model.channel_info['votes'])) - if self.window().tribler_settings: # It could be that the settings are not loaded yet - self.credit_mining_button.setHidden(not self.window().tribler_settings["credit_mining"]["enabled"]) - self.credit_mining_button.setIcon( - QIcon( - QPixmap( - get_image_path( - 'credit_mining_yes.png' - if self.contents_widget.model.channel_info["public_key"] - in self.window().tribler_settings["credit_mining"]["sources"] - else 'credit_mining_not.png' - ) - ) - ) - ) - else: - self.credit_mining_button.hide() - # Disable channel control buttons for LEGACY_ENTRY channels hide_controls = self.contents_widget.model.channel_info["status"] == 1000 self.subscribe_button.setHidden(hide_controls) - if hide_controls: - # This button could be hidden before for other reasons, that's why we only hide, but not _unhide_ it here - self.credit_mining_button.setHidden(True) def on_subscribe_button_click(self): TriblerNetworkRequest( @@ -77,30 +50,3 @@ def on_subscribe_button_click(self): raw_data=json.dumps({"subscribed": int(not self.contents_widget.model.channel_info["subscribed"])}), method='PATCH', ) - - def on_credit_mining_button_click(self): - old_sources = self.window().tribler_settings["credit_mining"]["sources"] - new_sources = ( - [] - if self.contents_widget.model.channel_info["public_key"] in old_sources - else [self.contents_widget.model.channel_info["public_key"]] - ) - settings = {"credit_mining": {"sources": new_sources}} - - TriblerNetworkRequest("settings", self.on_credit_mining_sources, method='POST', raw_data=json.dumps(settings)) - - def on_credit_mining_sources(self, json_result): - if not json_result: - return - if json_result["modified"]: - old_source = next(iter(self.window().tribler_settings["credit_mining"]["sources"]), None) - if self.contents_widget.model.channel_info["public_key"] != old_source: - self.credit_mining_toggled.emit(True) - new_sources = [self.contents_widget.model.channel_info["public_key"]] - else: - self.credit_mining_toggled.emit(False) - new_sources = [] - - self.window().tribler_settings["credit_mining"]["sources"] = new_sources - - self.update_subscribe_button() diff --git a/src/tribler-gui/tribler_gui/widgets/tokenminingpage.py b/src/tribler-gui/tribler_gui/widgets/tokenminingpage.py deleted file mode 100644 index 2702f52f4d3..00000000000 --- a/src/tribler-gui/tribler_gui/widgets/tokenminingpage.py +++ /dev/null @@ -1,123 +0,0 @@ -import time - -from PyQt5.QtCore import QTimer -from PyQt5.QtGui import QIcon -from PyQt5.QtNetwork import QNetworkRequest -from PyQt5.QtWidgets import QWidget - -from tribler_gui.defs import TB -from tribler_gui.tribler_request_manager import TriblerNetworkRequest -from tribler_gui.utilities import format_size, get_image_path -from tribler_gui.widgets.graphs.timeseriesplot import TimeSeriesPlot - - -class TokenMiningSeriesPlot(TimeSeriesPlot): - def __init__(self, parent, **kargs): - series = [ - {'name': 'Download', 'pen': (255, 0, 0), 'symbolBrush': (255, 0, 0), 'symbolPen': 'w'}, - {'name': 'Upload ', 'pen': (0, 255, 0), 'symbolBrush': (0, 255, 0), 'symbolPen': 'w'}, - ] - super(TokenMiningSeriesPlot, self).__init__(parent, 'Token Mining', series, **kargs) - self.setLabel('left', 'Mined Data', units='bytes') - self.setLimits(yMin=0, yMax=TB) - - -class TokenMiningPage(QWidget): - """ - This page shows various trust statistics. - """ - - REFRESH_INTERVAL_MS = 10000 - TIMEOUT_INTERVAL_MS = 30000 - - def __init__(self): - QWidget.__init__(self) - self.trust_plot = None - self.public_key = None - self.blocks = None - self.byte_scale = 1024 * 1024 - self.dialog = None - - self.downloads_timer = QTimer() - self.downloads_timeout_timer = QTimer() - self.downloads_last_update = 0 - - self.rest_request = None - - def showEvent(self, QShowEvent): - """ - When the downloads tab is clicked, we want to update the downloads list immediately. - """ - super(TokenMiningPage, self).showEvent(QShowEvent) - self.stop_loading_downloads() - self.schedule_downloads_timer(True) - - def initialize_token_mining_page(self): - self.window().token_mining_back_button.setIcon(QIcon(get_image_path('page_back.png'))) - vlayout = self.window().token_mining_plot_widget.layout() - if vlayout.isEmpty(): - self.trust_plot = TokenMiningSeriesPlot(self.window().token_mining_plot_widget) - vlayout.addWidget(self.trust_plot) - - def on_received_stats(self, stats): - total_download = stats.get('total_download', 0) - total_upload = stats.get('total_upload', 0) - self.window().token_mining_upload_amount_label.setText(str(total_upload)) - self.window().token_mining_download_amount_label.setText(str(total_download)) - - def schedule_downloads_timer(self, now=False): - self.downloads_timer = QTimer() - self.downloads_timer.setSingleShot(True) - self.downloads_timer.timeout.connect(self.load_downloads) - self.downloads_timer.start(0 if now else self.REFRESH_INTERVAL_MS) - - self.downloads_timeout_timer = QTimer() - self.downloads_timeout_timer.setSingleShot(True) - self.downloads_timeout_timer.timeout.connect(self.on_downloads_request_timeout) - self.downloads_timeout_timer.start(self.TIMEOUT_INTERVAL_MS) - - def on_downloads_request_timeout(self): - if self.rest_request: - self.rest_request.cancel_request() - self.schedule_downloads_timer() - - def stop_loading_downloads(self): - self.downloads_timer.stop() - self.downloads_timeout_timer.stop() - - def load_downloads(self): - url = "downloads?get_pieces=1" - if time.time() - self.downloads_last_update > self.REFRESH_INTERVAL_MS / 1000: - self.downloads_last_update = time.time() - if self.rest_request: - self.rest_request.cancel_request() - self.rest_request = TriblerNetworkRequest( - url, self.on_received_downloads, priority=QNetworkRequest.LowPriority - ) - - def on_received_downloads(self, downloads): - if not downloads or "downloads" not in downloads or not self.window().tribler_settings: - return # This might happen when just starting or closing Tribler - bytes_max = self.window().tribler_settings["credit_mining"]["max_disk_space"] - bytes_used = 0 - total_up = total_down = 0 - for download in downloads["downloads"]: - if download["credit_mining"] and download["status"] in ( - "DLSTATUS_DOWNLOADING", - "DLSTATUS_SEEDING", - "DLSTATUS_STOPPED", - "DLSTATUS_STOPPED_ON_ERROR", - ): - bytes_used += download["progress"] * download["size"] - total_up += download["total_up"] - total_down += download["total_down"] - - self.window().token_mining_upload_amount_label.setText(format_size(total_up)) - self.window().token_mining_download_amount_label.setText(format_size(total_down)) - self.window().token_mining_disk_usage_label.setText( - "%s / %s" % (format_size(float(bytes_used)), format_size(float(bytes_max))) - ) - - self.trust_plot.add_data(time.time(), [total_down, total_up]) - self.trust_plot.render_plot() - self.schedule_downloads_timer() diff --git a/src/tribler-gui/tribler_gui/widgets/trustpage.py b/src/tribler-gui/tribler_gui/widgets/trustpage.py index da19cfa20a2..5dcba3c0cca 100644 --- a/src/tribler-gui/tribler_gui/widgets/trustpage.py +++ b/src/tribler-gui/tribler_gui/widgets/trustpage.py @@ -3,10 +3,10 @@ from PyQt5.QtWidgets import QWidget -from tribler_gui.defs import GB, PAGE_MARKET, PAGE_TOKEN_MINING_PAGE, TB +from tribler_gui.defs import GB, PAGE_MARKET, TB from tribler_gui.dialogs.trustexplanationdialog import TrustExplanationDialog from tribler_gui.tribler_request_manager import TriblerNetworkRequest -from tribler_gui.widgets.tokenminingpage import TimeSeriesPlot +from tribler_gui.widgets.graphs.timeseriesplot import TimeSeriesPlot class TrustSeriesPlot(TimeSeriesPlot): @@ -36,10 +36,8 @@ def __init__(self): def showEvent(self, QShowEvent): super(TrustPage, self).showEvent(QShowEvent) if self.window().tribler_settings: # It could be that the settings are not loaded yet - self.window().mine_button.setHidden(not self.window().tribler_settings["credit_mining"]["enabled"]) self.window().trade_button.setHidden(not self.window().tribler_settings["market_community"]["enabled"]) else: - self.window().mine_button.hide() self.window().trade_button.hide() def initialize_trust_page(self): @@ -49,7 +47,6 @@ def initialize_trust_page(self): vlayout.addWidget(self.trust_plot) self.window().trade_button.clicked.connect(self.on_trade_button_clicked) - self.window().mine_button.clicked.connect(self.on_mine_button_clicked) self.window().trust_explain_button.clicked.connect(self.on_info_button_clicked) def on_trade_button_clicked(self): @@ -61,11 +58,6 @@ def on_info_button_clicked(self): self.dialog = TrustExplanationDialog(self.window()) self.dialog.show() - def on_mine_button_clicked(self): - self.window().token_mining_page.initialize_token_mining_page() - self.window().navigation_stack.append(self.window().stackedWidget.currentIndex()) - self.window().stackedWidget.setCurrentIndex(PAGE_TOKEN_MINING_PAGE) - def load_blocks(self): TriblerNetworkRequest("ipv8/trustchain/users/%s/blocks" % self.public_key, self.received_trustchain_blocks)