From 7fe164612a112262b404692e86bb916ccb7e7563 Mon Sep 17 00:00:00 2001 From: drew2a Date: Fri, 8 Dec 2023 11:57:27 +0100 Subject: [PATCH] Remove TrustGraph --- .../trust_calculation/__init__.py | 4 - .../trust_calculation/graph_positioning.py | 74 ----- .../test_graph_positioning.py | 27 -- .../trust_calculation/trust_graph.py | 152 ---------- .../rest/tests/test_settings_endpoint.py | 2 +- .../rest/tests/test_trustview_endpoint.py | 266 ------------------ .../restapi/rest/trustview_endpoint.py | 75 ----- .../components/restapi/restapi_component.py | 4 +- .../gui/dialogs/trustexplanationdialog.py | 21 -- src/tribler/gui/i18n/es_ES.ts | 20 -- src/tribler/gui/i18n/pt_BR.ts | 20 -- src/tribler/gui/i18n/ru_RU.ts | 20 -- src/tribler/gui/i18n/zh_CN.ts | 20 -- src/tribler/gui/qt_resources/mainwindow.ui | 3 - src/tribler/gui/tribler_app.py | 2 - src/tribler/gui/widgets/trustgraphpage.py | 231 --------------- src/tribler/gui/widgets/trustpage.py | 99 ------- 17 files changed, 2 insertions(+), 1038 deletions(-) delete mode 100644 src/tribler/core/components/bandwidth_accounting/trust_calculation/__init__.py delete mode 100644 src/tribler/core/components/bandwidth_accounting/trust_calculation/graph_positioning.py delete mode 100644 src/tribler/core/components/bandwidth_accounting/trust_calculation/test_graph_positioning.py delete mode 100644 src/tribler/core/components/bandwidth_accounting/trust_calculation/trust_graph.py delete mode 100644 src/tribler/core/components/restapi/rest/tests/test_trustview_endpoint.py delete mode 100644 src/tribler/core/components/restapi/rest/trustview_endpoint.py delete mode 100644 src/tribler/gui/dialogs/trustexplanationdialog.py delete mode 100644 src/tribler/gui/widgets/trustgraphpage.py delete mode 100644 src/tribler/gui/widgets/trustpage.py diff --git a/src/tribler/core/components/bandwidth_accounting/trust_calculation/__init__.py b/src/tribler/core/components/bandwidth_accounting/trust_calculation/__init__.py deleted file mode 100644 index 16305ce9af..0000000000 --- a/src/tribler/core/components/bandwidth_accounting/trust_calculation/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -The TrustCalculation package contains the procedures required for -the monitoring of transactions and the calculation of trust -""" diff --git a/src/tribler/core/components/bandwidth_accounting/trust_calculation/graph_positioning.py b/src/tribler/core/components/bandwidth_accounting/trust_calculation/graph_positioning.py deleted file mode 100644 index 694b20054c..0000000000 --- a/src/tribler/core/components/bandwidth_accounting/trust_calculation/graph_positioning.py +++ /dev/null @@ -1,74 +0,0 @@ -import random - -import networkx as nx - - -class GraphPositioning: - """ - This class is for the calculation of the positions of the nodes of - a given tree and from the perspective of a given central node - """ - - @staticmethod - def hierarchy_pos(G, root=None, width=1., vert_gap=0.2, vert_loc=0, xcenter=0.5): - """ - Taken from: https://bit.ly/2tetWxf - - If the graph is a tree this will return the positions to plot this in a - hierarchical layout. - - G: the graph (must be a tree) - - root: the root node of current branch - - if the tree is directed and this is not given, - the root will be found and used - - if the tree is directed and this is given, then the positions - will be just for the descendants of this node. - - if the tree is undirected and not given, then a random - choice will be used. - - width: horizontal space allocated for this branch - avoids overlap - with other branches - - vert_gap: gap between levels of hierarchy - - vert_loc: vertical location of root - - xcenter: horizontal location of root - """ - - if not nx.is_tree(G): - raise TypeError('cannot use hierarchy_pos on a graph that is not a tree') - - if root is None: - if isinstance(G, nx.DiGraph): - # allows back compatibility with nx version 1.11 - root = next(iter(nx.topological_sort(G))) - else: - root = random.choice(list(G.nodes)) - - def _hierarchy_pos(G, root, width=1., vert_gap=0.2, vert_loc=0, xcenter=0.5, pos=None, parent=None): - """ - see hierarchy_pos docstring for most arguments - pos: a dict saying where all nodes go if they have been assigned - parent: parent of this branch. - only affects it if non-directed - """ - - if pos is None: - pos = {root: (xcenter, vert_loc)} - else: - pos[root] = (xcenter, vert_loc) - children = list(G.neighbors(root)) - if not isinstance(G, nx.DiGraph) and parent is not None: - children.remove(parent) - if children: - dx = width / len(children) - nextx = xcenter - width / 2 - dx / 2 - for child in children: - nextx += dx - pos = _hierarchy_pos(G, child, width=dx, vert_gap=vert_gap, - vert_loc=vert_loc - vert_gap, - xcenter=nextx, pos=pos, parent=root) - return pos - - return _hierarchy_pos(G, root, width, vert_gap, vert_loc, xcenter) diff --git a/src/tribler/core/components/bandwidth_accounting/trust_calculation/test_graph_positioning.py b/src/tribler/core/components/bandwidth_accounting/trust_calculation/test_graph_positioning.py deleted file mode 100644 index cf664b2121..0000000000 --- a/src/tribler/core/components/bandwidth_accounting/trust_calculation/test_graph_positioning.py +++ /dev/null @@ -1,27 +0,0 @@ -import networkx as nx -import pytest - -from tribler.core.components.bandwidth_accounting.trust_calculation.graph_positioning import GraphPositioning - - -def test_graph_positioning_not_tree(): - """ - Test whether we get an error if we do not pass a tree to the graph positioning logic - """ - G = nx.DiGraph() - G.add_edge("a", "b") - G.add_edge("b", "a") - with pytest.raises(TypeError): - GraphPositioning.hierarchy_pos(G) - - -def test_graph_positioning(): - """ - Test whether we get a tree layout - """ - G = nx.DiGraph() - G.add_edge("a", "b") - G.add_edge("a", "d") - G.add_edge("b", "c") - result = GraphPositioning.hierarchy_pos(G) - assert len(result.keys()) == 4 diff --git a/src/tribler/core/components/bandwidth_accounting/trust_calculation/trust_graph.py b/src/tribler/core/components/bandwidth_accounting/trust_calculation/trust_graph.py deleted file mode 100644 index 698c12eef0..0000000000 --- a/src/tribler/core/components/bandwidth_accounting/trust_calculation/trust_graph.py +++ /dev/null @@ -1,152 +0,0 @@ -import hashlib -import logging -import math - -import networkx as nx - -from tribler.core.components.bandwidth_accounting.trust_calculation.graph_positioning import GraphPositioning -from tribler.core.exceptions import TrustGraphException -from tribler.core.utilities.unicode import hexlify - -MAX_NODES = 500 -MAX_TRANSACTIONS = 2500 -ROOT_NODE_ID = 0 - - -class TrustGraph(nx.DiGraph): - - def __init__(self, root_key, bandwidth_db, max_nodes=MAX_NODES, max_transactions=MAX_TRANSACTIONS): - nx.DiGraph.__init__(self) - self._logger = logging.getLogger(self.__class__.__name__) - - self.root_key = root_key - self.bandwidth_db = bandwidth_db - - self.max_nodes = max_nodes - self.max_transactions = max_transactions - - self.node_public_keys = [] - self.edge_set = set() - - # The root node is added first so it gets the node id zero. - self.get_or_create_node(root_key) - - def reset(self, root_key): - self.clear() - self.node_public_keys = [] - self.edge_set = set() - - self.get_or_create_node(root_key) - - def set_limits(self, max_nodes=None, max_transactions=None): - if max_nodes: - self.max_nodes = max_nodes - if max_transactions: - self.max_transactions = max_transactions - - def get_or_create_node(self, peer_key, add_if_not_exist=True): - if peer_key in self.node_public_keys: - peer_graph_node_id = self.node_public_keys.index(peer_key) - return self.nodes()[peer_graph_node_id] - - if not add_if_not_exist: - return None - - if self.number_of_nodes() >= self.max_nodes: - raise TrustGraphException(f"Max node peers ({self.max_nodes}) reached in the graph") - - # Node does not exist in the graph so a new node at this point. - # The numeric node id is used here so the id for the new node becomes - # equal to the number of nodes in the graph. - node_id = self.number_of_nodes() - node_attrs = { - 'id': node_id, - 'key': hexlify(peer_key), - 'total_up': self.bandwidth_db.get_total_given(peer_key), - 'total_down': self.bandwidth_db.get_total_taken(peer_key) - } - self.add_node(node_id, **node_attrs) - self.node_public_keys.append(peer_key) - - return self.nodes()[node_id] - - def compose_graph_data(self): - # Reset the graph first - self.reset(self.root_key) - - layer_1 = self.bandwidth_db.get_latest_transactions(self.root_key) - try: - for tx in layer_1: - self.add_bandwidth_transaction(tx) - - # Stop at layer 2 - counter_party = tx.public_key_a if self.root_key != tx.public_key_a else tx.public_key_b - layer_2 = self.bandwidth_db.get_latest_transactions(counter_party) - for tx2 in layer_2: - self.add_bandwidth_transaction(tx2) - - except TrustGraphException as tge: - self._logger.warning("Error composing Trust graph: %s", tge) - - def compute_edge_id(self, transaction): - sha2 = hashlib.sha3_224() # any safe hashing should do - sha2.update(transaction.public_key_a) - sha2.update(transaction.public_key_b) - return sha2.hexdigest()[:64] - - def add_bandwidth_transaction(self, tx): - # First, compose a unique edge id for the transaction and check if it is already added. - edge_id = self.compute_edge_id(tx) - - if len(self.edge_set) >= self.max_transactions: - raise TrustGraphException(f"Max transactions ({self.max_transactions}) reached in the graph") - - if edge_id not in self.edge_set: - peer1 = self.get_or_create_node(tx.public_key_a, add_if_not_exist=True) - peer2 = self.get_or_create_node(tx.public_key_b, add_if_not_exist=True) - - if peer1 and peer2 and peer2['id'] not in self.successors(peer1['id']): - self.add_edge(peer1['id'], peer2['id']) - self.edge_set.add(edge_id) - - def compute_node_graph(self): - undirected_graph = self.to_undirected() - num_nodes = undirected_graph.number_of_nodes() - - # Find bfs tree of the connected components - bfs_tree = nx.bfs_tree(undirected_graph, ROOT_NODE_ID) - - # Position the nodes in a circular fashion according to the bfs tree - pos = GraphPositioning.hierarchy_pos(bfs_tree, root=ROOT_NODE_ID, width=2 * math.pi, xcenter=0.5) - - graph_nodes = [] - graph_edges = [] - index_mapper = {} - - node_id = ROOT_NODE_ID - max_x = max_y = 0.0001 # as close to zero - for _id, (theta, r) in pos.items(): - index_mapper[_id] = node_id - node = undirected_graph.nodes()[_id] - node['id'] = node_id - node_id += 1 - - # convert from polar coordinates to cartesian coordinates - x = r * math.sin(theta) * num_nodes - y = r * math.cos(theta) * num_nodes - node['pos'] = [x, y] - graph_nodes.append(node) - - # max values to be used for normalization - max_x = max(abs(x), max_x) - max_y = max(abs(y), max_y) - - # Normalize the positions - for node in graph_nodes: - node['pos'][0] /= max_x - node['pos'][1] /= max_y - - for edge in undirected_graph.edges(): - graph_edges.append((index_mapper[edge[0]], index_mapper[edge[1]])) - - return {'node': graph_nodes, 'edge': graph_edges} diff --git a/src/tribler/core/components/restapi/rest/tests/test_settings_endpoint.py b/src/tribler/core/components/restapi/rest/tests/test_settings_endpoint.py index c9df86d4f6..0c93cae468 100644 --- a/src/tribler/core/components/restapi/rest/tests/test_settings_endpoint.py +++ b/src/tribler/core/components/restapi/rest/tests/test_settings_endpoint.py @@ -25,7 +25,7 @@ def verify_settings(settings_dict): Verify that the expected sections are present. """ check_section = ['libtorrent', 'general', 'torrent_checking', - 'tunnel_community', 'api', 'trustchain', 'watch_folder'] + 'tunnel_community', 'api', 'watch_folder'] assert settings_dict['settings'] for section in check_section: diff --git a/src/tribler/core/components/restapi/rest/tests/test_trustview_endpoint.py b/src/tribler/core/components/restapi/rest/tests/test_trustview_endpoint.py deleted file mode 100644 index ddd3c23a7f..0000000000 --- a/src/tribler/core/components/restapi/rest/tests/test_trustview_endpoint.py +++ /dev/null @@ -1,266 +0,0 @@ -import random -import secrets -from binascii import unhexlify - -import pytest -from ipv8.keyvault.crypto import default_eccrypto - -from tribler.core.components.bandwidth_accounting.db.database import BandwidthDatabase -from tribler.core.components.bandwidth_accounting.db.transaction import BandwidthTransactionData, EMPTY_SIGNATURE -from tribler.core.components.bandwidth_accounting.trust_calculation.trust_graph import TrustGraph -from tribler.core.components.restapi.rest.base_api_test import do_request -from tribler.core.components.restapi.rest.trustview_endpoint import TrustViewEndpoint -from tribler.core.exceptions import TrustGraphException -from tribler.core.utilities.utilities import MEMORY_DB - - -# pylint: disable=redefined-outer-name - -@pytest.fixture -def endpoint(bandwidth_db): - return TrustViewEndpoint(bandwidth_db) - - -@pytest.fixture -def root_key(): - return default_eccrypto.generate_key("very-low").pub().key_to_bin() - - -@pytest.fixture -def mock_bandwidth_community(mock_ipv8, rest_api): - return rest_api.bandwidth_community - - -@pytest.fixture -def bandwidth_db(root_key): - database = BandwidthDatabase(MEMORY_DB, root_key) - yield database - database.shutdown() - - -@pytest.fixture -async def trust_graph(root_key, bandwidth_db): - return TrustGraph(root_key, bandwidth_db, max_nodes=20, max_transactions=200) - - -def get_random_node_public_key(): - return secrets.token_hex(nbytes=148) - - -def test_initialize(trust_graph): - """ - Tests the initialization of the Trust graph. At least root node should be in the graph. - """ - assert len(trust_graph.node_public_keys) >= 1 - - -def test_get_node_and_reset(root_key, trust_graph): - """ - Tests get node with and without adding to the graph. - Also tests the reset of the graph. - """ - test_node1_key = default_eccrypto.generate_key("very-low").pub().key_to_bin() - test_node1 = trust_graph.get_or_create_node(test_node1_key) - assert test_node1 - - # check that node is added by default if not available in the graph - assert len(trust_graph.node_public_keys) >= 2 - - # Get node without adding to the graph - test_node2_key = default_eccrypto.generate_key("very-low").pub().key_to_bin() - test_node2 = trust_graph.get_or_create_node(test_node2_key, add_if_not_exist=False) - assert test_node2 is None - - # After resetting the graph, there should only be one root node - trust_graph.reset(root_key) - assert len(trust_graph.node_public_keys) == 1 - - -def test_maximum_nodes_in_graph(trust_graph): - """ - Tests the maximum nodes that can be present in the graph. - """ - # Added the MAX_PEERS nodes in the graph (including the root node) - for _ in range(trust_graph.max_nodes - 1): - test_node_key = default_eccrypto.generate_key("very-low").pub().key_to_bin() - test_node = trust_graph.get_or_create_node(test_node_key) - assert test_node - - assert len(trust_graph.node_public_keys) == trust_graph.max_nodes - - # If we try to add more than MAX_PEERS, we expect to get an exception - try: - test_node_key = default_eccrypto.generate_key("very-low").pub().key_to_bin() - trust_graph.get_or_create_node(test_node_key) - except TrustGraphException as tge: - exception_msg = getattr(tge, 'message', repr(tge)) - assert f'Max node peers ({trust_graph.max_nodes}) reached in the graph' in exception_msg - else: - assert False, "Expected to fail but did not." - - -def test_add_bandwidth_transactions(trust_graph): - """ - Tests the maximum blocks/transactions that be be present in the graph. - :return: - """ - - my_pk = trust_graph.root_key - for _ in range(trust_graph.max_nodes - 1): - random_node_pk = unhexlify(get_random_node_public_key()) - random_tx = BandwidthTransactionData(1, random_node_pk, my_pk, EMPTY_SIGNATURE, EMPTY_SIGNATURE, 3000) - trust_graph.add_bandwidth_transaction(random_tx) - - assert trust_graph.number_of_nodes() == trust_graph.max_nodes - - # Already max number of nodes are added to the graph, adding more should raise an exception - try: - tx2 = BandwidthTransactionData(1, my_pk, b"a", EMPTY_SIGNATURE, EMPTY_SIGNATURE, 2000) - trust_graph.add_bandwidth_transaction(tx2) - except TrustGraphException as tge: - exception_msg = getattr(tge, 'message', repr(tge)) - assert f'Max node peers ({trust_graph.max_nodes}) reached in the graph' in exception_msg - else: - assert False, "Expected to fail but did not." - - -async def test_trustview_response(rest_api, root_key, bandwidth_db): - """ - Test whether the trust graph response is correctly returned. - - Scenario: A graph with 3 nodes in each layers (layer 1: friends, layer 2: fofs, layer 3: fofofs). - The current implementation of trust graph only considers two layers, therefore, - number of nodes in the graph = 1 (root node) + 3 (friends) + 3 (fofs) = 7 - number of transactions in the graphs = 3 (root node to friends) + 3 (friends) * 3 (fofs) = 12 - """ - - friends = [ - "4c69624e61434c504b3a2ee28ce24a2259b4e585b81106cdff4359fcf48e93336c11d133b01613f30b03b4db06df27" - "80daac2cdf2ee60be611bf7367a9c1071ac50d65ca5858a50e9578", - "4c69624e61434c504b3a5368c7b39a82063e29576df6d74fba3e0dba3af8e7a304b553b71f08ea6a0730e8cef767a4" - "85dc6f390b6da5631f772941ea69ce2c098d802b7a28b500edf2b3", - "4c69624e61434c504b3a0f3f6318e49ffeb0a160e7fcac5c1d3337ba409b45e1371ddca5e3b364ebdd1b73c775318a" - "533a25335a5c36ae3695f1c3036b651893659fbf2e1f2bce66cf65", - ] - - fofs = [ - "4c69624e61434c504b3a2ee28ce24a2259b4e585b81106cdff4359fcf48e93336c11d133b01613f30b03b4db06df27" - "80daac2cdf2ee60be611bf7367a9c1071ac50d65ca5858a50e9579", - "4c69624e61434c504b3a5368c7b39a82063e29576df6d74fba3e0dba3af8e7a304b553b71f08ea6a0730e8cef767a4" - "85dc6f390b6da5631f772941ea69ce2c098d802b7a28b500edf2b4", - "4c69624e61434c504b3a0f3f6318e49ffeb0a160e7fcac5c1d3337ba409b45e1371ddca5e3b364ebdd1b73c775318a" - "533a25335a5c36ae3695f1c3036b651893659fbf2e1f2bce66cf66", - ] - - fofofs = [ - "4c69624e61434c504b3a2ee28ce24a2259b4e585b81106cdff4359fcf48e93336c11d133b01613f30b03b4db06df27" - "80daac2cdf2ee60be611bf7367a9c1071ac50d65ca5858a50e9580", - "4c69624e61434c504b3a5368c7b39a82063e29576df6d74fba3e0dba3af8e7a304b553b71f08ea6a0730e8cef767a4" - "85dc6f390b6da5631f772941ea69ce2c098d802b7a28b500edf2b5", - "4c69624e61434c504b3a0f3f6318e49ffeb0a160e7fcac5c1d3337ba409b45e1371ddca5e3b364ebdd1b73c775318a" - "533a25335a5c36ae3695f1c3036b651893659fbf2e1f2bce66cf67", - ] - - def verify_response(response_json): - expected_nodes = 1 + len(friends) + len(fofs) - expected_txns = len(friends) + len(friends) * len(fofs) - - assert response_json['graph'] - assert response_json['num_tx'] == expected_txns - assert len(response_json['graph']['node']) == expected_nodes - - for pub_key in friends: - tx1 = BandwidthTransactionData(1, root_key, unhexlify(pub_key), EMPTY_SIGNATURE, EMPTY_SIGNATURE, 3000) - bandwidth_db.BandwidthTransaction.insert(tx1) - - for friend in friends: - for fof in fofs: - tx2 = BandwidthTransactionData(1, unhexlify(friend), unhexlify(fof), EMPTY_SIGNATURE, EMPTY_SIGNATURE, 3000) - bandwidth_db.BandwidthTransaction.insert(tx2) - - for fof in fofs: - for fofof in fofofs: - tx3 = BandwidthTransactionData(1, unhexlify(fof), unhexlify(fofof), EMPTY_SIGNATURE, EMPTY_SIGNATURE, 3000) - bandwidth_db.BandwidthTransaction.insert(tx3) - - response = await do_request(rest_api, 'trustview', expected_code=200) - verify_response(response) - - -def insert_node_transactions(root_key, bandwidth_db, node_public_key=None, count=1): - for idx in range(count): - counterparty = unhexlify(node_public_key if node_public_key else get_random_node_public_key()) - amount = random.randint(10, 100) - tx1 = BandwidthTransactionData(idx, root_key, counterparty, EMPTY_SIGNATURE, EMPTY_SIGNATURE, amount) - bandwidth_db.BandwidthTransaction.insert(tx1) - - -async def test_trustview_max_transactions(rest_api, bandwidth_db, root_key, endpoint): - """ - Test whether the max transactions returned is limited. - """ - - max_txn = 10 - endpoint.trust_graph.set_limits(max_transactions=max_txn) - - # Try adding more transactions than max transactions - insert_node_transactions(root_key, bandwidth_db, count=max_txn + 1) - - # The number of transactions should not be returned more than max transactions - response_json = await do_request(rest_api, 'trustview?refresh=1', expected_code=200) - assert response_json['graph'] - assert response_json['num_tx'] == max_txn - - -async def test_trustview_max_nodes(rest_api, root_key, bandwidth_db, endpoint): - """ - Test whether the number of nodes returned is limited. - """ - - max_nodes = 10 - endpoint.trust_graph.set_limits(max_nodes=max_nodes) - - # Try transactions from more than max nodes - for _ in range(max_nodes): - insert_node_transactions(root_key, bandwidth_db) - - # The number of nodes should not be returned more than max nodes - response_json = await do_request(rest_api, 'trustview?refresh=1', expected_code=200) - assert response_json['graph'] - assert len(response_json['graph']['node']) == max_nodes - - -async def test_trustview_with_refresh(rest_api, root_key, bandwidth_db, endpoint): - """ - Test whether refresh query parameters works as expected. - If refresh parameter is not set, the cached graph is returned otherwise - a new graph is computed and returned. - """ - - # Insert a set of transactions - num_tx_set1 = 10 - insert_node_transactions(root_key, bandwidth_db, count=num_tx_set1) - - # Since graph is not computed yet, freshly computed result is displayed - # so the number of transactions returned should be equal to above number - # of transactions added. - response_json = await do_request(rest_api, 'trustview', expected_code=200) - assert response_json['graph'] - assert response_json['num_tx'] == num_tx_set1 - - # Now insert a second set of transactions - num_tx_set2 = 10 - insert_node_transactions(root_key, bandwidth_db, count=num_tx_set2) - - # At this point, the trust graph should already be computed from the previous API call, - # since the refresh parameter is not set, the cached result should be returned - # which is same as the previous result. - response_json = await do_request(rest_api, 'trustview', expected_code=200) - assert response_json['graph'] - assert response_json['num_tx'] == num_tx_set1 - - # Now if the refresh parameter is set, the graph should be freshly computed and all the - # transactions should be included. Therefore, showing the correct number of transactions. - response_json = await do_request(rest_api, 'trustview?refresh=1', expected_code=200) - assert response_json['graph'] - assert num_tx_set1 <= response_json['num_tx'] == num_tx_set1 + num_tx_set2 diff --git a/src/tribler/core/components/restapi/rest/trustview_endpoint.py b/src/tribler/core/components/restapi/rest/trustview_endpoint.py deleted file mode 100644 index d6edf9d88a..0000000000 --- a/src/tribler/core/components/restapi/rest/trustview_endpoint.py +++ /dev/null @@ -1,75 +0,0 @@ -from functools import cached_property - -from aiohttp import web -from aiohttp_apispec import docs -from ipv8.REST.schema import schema -from marshmallow.fields import Float, Integer, List, String - -from tribler.core.components.bandwidth_accounting.db.database import BandwidthDatabase -from tribler.core.components.bandwidth_accounting.trust_calculation.trust_graph import TrustGraph -from tribler.core.components.restapi.rest.rest_endpoint import RESTEndpoint, RESTResponse -from tribler.core.utilities.unicode import hexlify -from tribler.core.utilities.utilities import froze_it - - -@froze_it -class TrustViewEndpoint(RESTEndpoint): - path = '/trustview' - - def __init__(self, bandwidth_db: BandwidthDatabase): - super().__init__() - self.bandwidth_db = bandwidth_db - - def setup_routes(self): - self.app.add_routes([web.get('', self.get_view)]) - - @cached_property - def trust_graph(self) -> TrustGraph: - trust_graph = TrustGraph(self.bandwidth_db.my_pub_key, self.bandwidth_db) - trust_graph.compose_graph_data() - return trust_graph - - @docs( - tags=["TrustGraph"], - summary="Return the trust graph.", - parameters=[], - responses={ - 200: { - "schema": schema(GraphResponse={ - 'root_public_key': String, - 'graph': schema(Graph={ - 'node': schema(Node={ - 'id': Integer, - 'key': String, - 'pos': [Float], - 'sequence_number': Integer, - 'total_up': Integer, - 'total_down': Integer - }), - 'edge': List(List(Integer)) - }), - 'bootstrap': schema(Bootstrap={ - 'download': Integer, - 'upload': Integer, - 'progress': Float - }), - 'num_tx': Integer - }) - } - } - ) - async def get_view(self, request): - refresh_graph = int(request.query.get('refresh', '0')) - if refresh_graph: - self.trust_graph.compose_graph_data() - - graph_data = self.trust_graph.compute_node_graph() - - return RESTResponse( - { - 'root_public_key': hexlify(self.bandwidth_db.my_pub_key), - 'graph': graph_data, - 'bootstrap': 0, - 'num_tx': len(graph_data['edge']) - } - ) diff --git a/src/tribler/core/components/restapi/restapi_component.py b/src/tribler/core/components/restapi/restapi_component.py index e44bc45c6c..1dd90baaca 100644 --- a/src/tribler/core/components/restapi/restapi_component.py +++ b/src/tribler/core/components/restapi/restapi_component.py @@ -6,6 +6,7 @@ from tribler.core.components.bandwidth_accounting.bandwidth_accounting_component import BandwidthAccountingComponent from tribler.core.components.bandwidth_accounting.restapi.bandwidth_endpoint import BandwidthEndpoint from tribler.core.components.component import Component +from tribler.core.components.content_discovery.content_discovery_component import ContentDiscoveryComponent from tribler.core.components.database.database_component import DatabaseComponent from tribler.core.components.exceptions import NoneComponent from tribler.core.components.ipv8.ipv8_component import Ipv8Component @@ -20,7 +21,6 @@ from tribler.core.components.metadata_store.metadata_store_component import MetadataStoreComponent from tribler.core.components.metadata_store.restapi.metadata_endpoint import MetadataEndpoint from tribler.core.components.metadata_store.restapi.search_endpoint import SearchEndpoint -from tribler.core.components.content_discovery.content_discovery_component import ContentDiscoveryComponent from tribler.core.components.reporter.exception_handler import CoreExceptionHandler, default_core_exception_handler from tribler.core.components.reporter.reported_error import ReportedError from tribler.core.components.reporter.reporter_component import ReporterComponent @@ -33,7 +33,6 @@ from tribler.core.components.restapi.rest.settings_endpoint import SettingsEndpoint from tribler.core.components.restapi.rest.shutdown_endpoint import ShutdownEndpoint from tribler.core.components.restapi.rest.statistics_endpoint import StatisticsEndpoint -from tribler.core.components.restapi.rest.trustview_endpoint import TrustViewEndpoint from tribler.core.components.torrent_checker.torrent_checker_component import TorrentCheckerComponent from tribler.core.components.tunnel.tunnel_component import TunnelsComponent from tribler.core.utilities.unicode import hexlify @@ -98,7 +97,6 @@ async def run(self): resource_monitor=resource_monitor_component.resource_monitor, core_exception_handler=self._core_exception_handler) self.maybe_add(BandwidthEndpoint, bandwidth_accounting_component.community) - self.maybe_add(TrustViewEndpoint, bandwidth_accounting_component.database) self.maybe_add(DownloadsEndpoint, libtorrent_component.download_manager, metadata_store=metadata_store_component.mds, tunnel_community=tunnel_community) self.maybe_add(CreateTorrentEndpoint, libtorrent_component.download_manager) diff --git a/src/tribler/gui/dialogs/trustexplanationdialog.py b/src/tribler/gui/dialogs/trustexplanationdialog.py deleted file mode 100644 index 7c35fdabfd..0000000000 --- a/src/tribler/gui/dialogs/trustexplanationdialog.py +++ /dev/null @@ -1,21 +0,0 @@ -from PyQt5 import uic -from PyQt5.QtWidgets import QSizePolicy - -from tribler.gui.dialogs.dialogcontainer import DialogContainer -from tribler.gui.utilities import connect, get_ui_file_path - - -class TrustExplanationDialog(DialogContainer): - def __init__(self, parent): - DialogContainer.__init__(self, parent) - - uic.loadUi(get_ui_file_path('trustexplanation.ui'), self.dialog_widget) - - self.dialog_widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) - connect(self.dialog_widget.close_button.clicked, self.close_dialog) - - self.update_window() - - def update_window(self): - self.dialog_widget.adjustSize() - self.on_main_window_resize() diff --git a/src/tribler/gui/i18n/es_ES.ts b/src/tribler/gui/i18n/es_ES.ts index 0606bac42f..e58955e46a 100644 --- a/src/tribler/gui/i18n/es_ES.ts +++ b/src/tribler/gui/i18n/es_ES.ts @@ -566,11 +566,6 @@ Tenga en cuenta que los valores decimales están truncados. Remove from channel Borrar del canal - - - The graph below is based on your historical interactions with other users in the network. It shows <strong>%(num_interactions)s</strong> interactions made by <strong>%(num_users)s</strong> users.<br/> - El siguiente gráfico se basa en sus interacciones históricas con otros usuarios de la red. Muestra las <strong>%(num_interactions)s</strong> interacciones realizadas por <strong>%(num_users)s</strong> otros usuarios.<br/> - Each tag should be at least %d characters and can be at most %d characters. @@ -1217,11 +1212,6 @@ Si no está seguro, pulse "No". Más adelante podrá eliminar esas car SAVE GUARDAR - - - CLOSE - CERRAR - Add torrent(s) to personal channel @@ -1402,11 +1392,6 @@ Si no está seguro, pulse "No". Más adelante podrá eliminar esas car Bandwidth Tokens Tokens de ancho de banda - - - <html><head/><body><p>In Tribler, you compensate other users for the bandwidth you use when downloading with anonymity. When uploading content to other (Tribler) users, you earn <span style=" font-style:italic;">bandwidth tokens</span>. If you accumulate more bandwidth tokens, you get preferential treatment when downloading anonymously, which results in higher download speeds.</p><p>The exact amount of bandwidth tokens you pay to others, depends on the level of anonymity. This is the number of other users, or <span style=" font-style:italic;">hops</span>, you use during a download. If you download with three hop anonymity, your encrypted data is sent through the machines of three other Tribler users. Increasing the number of hops benefits anonymity but costs you more bandwidth tokens.</p><p>For example, if you download a <span style=" font-weight:600;">1 Gigabyte</span> video with one hop anonymity, you pay <span style=" font-weight:600;">1 Gigabyte</span> worth of bandwidth tokens. Each additional hop increases the amount of bandwidth tokens you have to pay. When downloading the same file using three hops, you pay <span style=" font-weight:600;">3 Gigabyte</span> of bandwidth tokens instead.</p></body></html> - <html><head/><body><p>En Tribler, compensas a otros usuarios por el ancho de banda que utilizas al descargar con anonimato. Cuando subes contenidos a otros usuarios (de Tribler), ganas <span style=" font-style:italic;">tokens de ancho de banda</span>. Si acumulas más tokens de ancho de banda, obtienes un trato preferente al descargar de forma anónima, lo que se traduce en mayores velocidades de descarga.</p><p>La cantidad exacta de tokens de ancho de banda que pagas a los demás, depende del nivel de anonimato. Esto es el número de otros usuarios, o <span style=" font-style:italic;">saltos</span>, que utilizas durante una descarga. Si descargas con tres saltos de anonimato, tus datos cifrados se envían a través de las máquinas de otros tres usuarios de Tribler. Aumentar el número de saltos beneficia el anonimato, pero te cuesta más tokens de ancho de banda.</p><p>P.ej., si descargas un <span style=" font-weight:600;">1 gigabyte</span> de vídeo con un salto de anonimato, pagas con <span style=" font-weight:600;">1 gigabyte</span> en tokens de ancho de banda. Cada salto adicional aumenta la cantidad de tokens de ancho de banda que tienes que pagar en <span style=" font-weight:600;">3 gigabyte</span> de tokens de ancho de banda en su lugar.</p></body></html> - Edit metadata @@ -2180,11 +2165,6 @@ Alto anonimato Trust statistics Estadísticas de confianza - - - Show trust graph - Mostrar en un gráfico - You can build trust by contributing bandwidth to the Tribler network. This is done by letting Tribler run idle. diff --git a/src/tribler/gui/i18n/pt_BR.ts b/src/tribler/gui/i18n/pt_BR.ts index 9abfa7023d..5fa18231b0 100644 --- a/src/tribler/gui/i18n/pt_BR.ts +++ b/src/tribler/gui/i18n/pt_BR.ts @@ -945,11 +945,6 @@ You can not undo this action. %(seconds)is - - - The graph below is based on your historical interactions with other users in the network. It shows <strong>%(num_interactions)s</strong> interactions made by <strong>%(num_users)s</strong> users.<br/> - - Please select the files @@ -1424,21 +1419,11 @@ New remote results received: %(num_remote_results)i DOWNLOAD BAIXAR - - - Bandwidth Tokens - Tokens de banda - <html><head/><body><p>In Tribler, you compensate other users for the bandwidth you use when downloading with anonymity. When uploading content to other (Tribler) users, you earn <span style=" font-style:italic;">bandwidth tokens</span>. If you accumulate more bandwidth tokens, you get preferential treatment when downloading anonymously, which results in higher download speeds.</p><p>The exact amount of bandwidth tokens you pay to others, depends on the level of anonymity. This is the number of other users, or <span style=" font-style:italic;">hops</span>, you use during a download. If you download with three hop anonymity, your encrypted data is sent through the machines of three other Tribler users. Increasing the number of hops benefits anonymity but costs you more bandwidth tokens.</p><p>For example, if you download a <span style=" font-weight:600;">1 Gigabyte</span> video with one hop anonymity, you pay <span style=" font-weight:600;">1 Gigabyte</span> worth of bandwidth tokens. Each additional hop increases the amount of bandwidth tokens you have to pay. When downloading the same file using three hops, you pay <span style=" font-weight:600;">3 Gigabyte</span> of bandwidth tokens instead.</p></body></html> - - - CLOSE - FECHAR - Additional information: @@ -2251,11 +2236,6 @@ High anonymity Trust statistics Estatísticas de Confiança - - - You can build trust by contributing bandwidth to the Tribler network. This is done by letting Tribler run idle. - Você pode ganhar confiança contribuindo banda para a rede Tribler. Faça isso simplesmente deixando o Tribler aberto - - MBytes diff --git a/src/tribler/gui/i18n/ru_RU.ts b/src/tribler/gui/i18n/ru_RU.ts index 32f7eb4e3b..fb946376b6 100644 --- a/src/tribler/gui/i18n/ru_RU.ts +++ b/src/tribler/gui/i18n/ru_RU.ts @@ -889,11 +889,6 @@ You can not undo this action. Tribler settings Настройки Tribler - - - The graph below is based on your historical interactions with other users in the network. It shows <strong>%(num_interactions)s</strong> interactions made by <strong>%(num_users)s</strong> users.<br/> - Этот граф построен по данным взаимодействия вашего Tribler с другими пользователями. Он показывает <strong>%(num_interactions)s</strong> взаимодействий <strong>%(num_users)s</strong> пользователей.<br/> - Show Tribler window @@ -1379,21 +1374,11 @@ New remote results received: %(num_remote_results)i DOWNLOAD СКАЧАТЬ - - - <html><head/><body><p>In Tribler, you compensate other users for the bandwidth you use when downloading with anonymity. When uploading content to other (Tribler) users, you earn <span style=" font-style:italic;">bandwidth tokens</span>. If you accumulate more bandwidth tokens, you get preferential treatment when downloading anonymously, which results in higher download speeds.</p><p>The exact amount of bandwidth tokens you pay to others, depends on the level of anonymity. This is the number of other users, or <span style=" font-style:italic;">hops</span>, you use during a download. If you download with three hop anonymity, your encrypted data is sent through the machines of three other Tribler users. Increasing the number of hops benefits anonymity but costs you more bandwidth tokens.</p><p>For example, if you download a <span style=" font-weight:600;">1 Gigabyte</span> video with one hop anonymity, you pay <span style=" font-weight:600;">1 Gigabyte</span> worth of bandwidth tokens. Each additional hop increases the amount of bandwidth tokens you have to pay. When downloading the same file using three hops, you pay <span style=" font-weight:600;">3 Gigabyte</span> of bandwidth tokens instead.</p></body></html> - <html><head/><body><p>Когда Tribler скачивает торрент анонимно, Вы отдаёте <span style=" font-style:italic;">трафик-токены</span> тем другим пользователям Tribler, кто обеспечил Вашу анонимность. Когда другой пользователь Tribler скачивает торрент с Вашей машины, <span style=" font-style:italic;">Вы</span> получаете от него трафик-токены. Пользователи с более высоким балансом трафик-токенов получают преимущество в обслуживании при анонимном скачивании. </p><p>Цена анонимного трафика в трафик-токенах зависит от выбранного Вами уровня анонимности. По сути, уровень анонимности это число <span style=" font-style:italic;">промежуточных узлов</span>, используемых во время закачки. К примеру, на уровне анонимности "3" данные, передаваемые на Вашу машину пересылаются через компьютеры трёх других случайных пользователей Tribler. Увеличение уровня анонимности может добавить безопасности, но снижает производительность и увеличивает цену закачки в трафик-токенах.</p><p>К примеру, закачка <span style=" font-weight:600;">1 Гигабайта</span> видео через 1 промежуточный узел (т.е. "уровень анонимности 1") <span style=" font-weight:600;">1 Гигабайт</span> обойдётся Вам в 1 Гбайт трафик-токенов. Ввод каждого дополнительного промежуточного узла удорожает трафик. Закачка того же 1 Гигабайта видео через три узла обойдётся уже в <span style=" font-weight:600;">3 Гбайт</span> трафик-токенов.</p></body></html> - CLOSE ЗАКРЫТЬ - - - Bandwidth Tokens - Трафик-токены - Suggest Tags @@ -2151,11 +2136,6 @@ High anonymity Trust statistics Статистика доверия - - - You can build trust by contributing bandwidth to the Tribler network. This is done by letting Tribler run idle. - Tribler зарабатывает репутацию для Вашего компьютера, предоставляя его в качестве промежуточного узла для анонимизации других пользователей. Это происходит в то время, когда Tribler простаивает. - - MBytes diff --git a/src/tribler/gui/i18n/zh_CN.ts b/src/tribler/gui/i18n/zh_CN.ts index b7998b6d1a..36c42e0cc4 100644 --- a/src/tribler/gui/i18n/zh_CN.ts +++ b/src/tribler/gui/i18n/zh_CN.ts @@ -929,11 +929,6 @@ New remote results received: %(num_remote_results)i 远程响应:%(num_complete_peers)i / %(total_peers)i 收到新的远程结果:%(num_remote_results)i - - - The graph below is based on your historical interactions with other users in the network. It shows <strong>%(num_interactions)s</strong> interactions made by <strong>%(num_users)s</strong> users.<br/> - 下方的图表基于你与其他用户在网络中的交互历史。它显示了 <strong>%(num_users)s</strong> 个用户所作的 <strong>%(num_interactions)s</strong> 项交互。<br/> - Please select the files @@ -1202,11 +1197,6 @@ New remote results received: %(num_remote_results)i Form - - - Form - 窗体 - Add torrent(s) to personal channel @@ -1407,11 +1397,6 @@ New remote results received: %(num_remote_results)i Bandwidth Tokens 带宽代币 - - - <html><head/><body><p>In Tribler, you compensate other users for the bandwidth you use when downloading with anonymity. When uploading content to other (Tribler) users, you earn <span style=" font-style:italic;">bandwidth tokens</span>. If you accumulate more bandwidth tokens, you get preferential treatment when downloading anonymously, which results in higher download speeds.</p><p>The exact amount of bandwidth tokens you pay to others, depends on the level of anonymity. This is the number of other users, or <span style=" font-style:italic;">hops</span>, you use during a download. If you download with three hop anonymity, your encrypted data is sent through the machines of three other Tribler users. Increasing the number of hops benefits anonymity but costs you more bandwidth tokens.</p><p>For example, if you download a <span style=" font-weight:600;">1 Gigabyte</span> video with one hop anonymity, you pay <span style=" font-weight:600;">1 Gigabyte</span> worth of bandwidth tokens. Each additional hop increases the amount of bandwidth tokens you have to pay. When downloading the same file using three hops, you pay <span style=" font-weight:600;">3 Gigabyte</span> of bandwidth tokens instead.</p></body></html> - <html><head/><body><p>在 Tribler 进行匿名下载时你将补偿带宽给其他用户。当上传内容给其他(Tribler)用户时,你会挣到<span style=" font-style:italic;">带宽代币</span>。如果你积攒了越多的带宽代币,匿名下载时就可以受到越好的优待,从而提高下载速度。</p><p>你要支付给其他人的带宽代币确切数量,取决于使用的匿名级别。即是你下载期间的其他用户的数量,或称为<span style=" font-style:italic;">跃点数</span>。如果你以三个跃点进行匿名下载,加密数据将经由其他三个 Tribler 用户发送。跃点数的增加有利于匿名性,但也会消费更多的带宽代币。</p><p>例如,你要以一个跃点的匿名性下载 <span style=" font-weight:600;">1 GB</span> 的视频,你就支付价值 <span style=" font-weight:600;">1 GB</span> 的带宽代币。每额外增加一个跃点,就会增加一倍你需要支付的带宽代币。当你以三个跃点来下载同个文件,你就将支付 <span style=" font-weight:600;">3 GB</span> 的带宽代币。</p></body></html> - CLOSE @@ -2177,11 +2162,6 @@ High anonymity Trust statistics 信任统计信息 - - - You can build trust by contributing bandwidth to the Tribler network. This is done by letting Tribler run idle. - 你可以通过向 Tribler 网络贡献带宽来构建信任。让 Tribler 待机运行就可以进行。 - - MBytes diff --git a/src/tribler/gui/qt_resources/mainwindow.ui b/src/tribler/gui/qt_resources/mainwindow.ui index 1e1a96d55b..3d0e4cb716 100644 --- a/src/tribler/gui/qt_resources/mainwindow.ui +++ b/src/tribler/gui/qt_resources/mainwindow.ui @@ -4447,13 +4447,10 @@ background: none; clicked_menu_button_subscriptions() on_search_text_change() clicked_menu_button_discovered() - clicked_menu_button_trust() on_settings_button_click() - on_trust_button_click() clicked_menu_button_search() clicked_force_shutdown() clicked_skip_conversion() - clicked_menu_button_trust_graph() clicked_menu_button_popular() diff --git a/src/tribler/gui/tribler_app.py b/src/tribler/gui/tribler_app.py index 1ba80c0b97..d2d847a8f9 100644 --- a/src/tribler/gui/tribler_app.py +++ b/src/tribler/gui/tribler_app.py @@ -58,8 +58,6 @@ def parse_sys_args(self, args): if '--testnet' in sys.argv[1:]: os.environ['TESTNET'] = "YES" - if '--trustchain-testnet' in sys.argv[1:]: - os.environ['TRUSTCHAIN_TESTNET'] = "YES" if '--chant-testnet' in sys.argv[1:]: os.environ['CHANT_TESTNET'] = "YES" if '--tunnel-testnet' in sys.argv[1:]: diff --git a/src/tribler/gui/widgets/trustgraphpage.py b/src/tribler/gui/widgets/trustgraphpage.py deleted file mode 100644 index f4c5164329..0000000000 --- a/src/tribler/gui/widgets/trustgraphpage.py +++ /dev/null @@ -1,231 +0,0 @@ -import math - -import numpy as np -import pyqtgraph as pg -from PyQt5 import QtCore -from PyQt5.QtNetwork import QNetworkRequest -from PyQt5.QtWidgets import QWidget - -from tribler.gui.defs import ( - COLOR_DEFAULT, - COLOR_GREEN, - COLOR_NEUTRAL, - COLOR_RED, - COLOR_ROOT, - COLOR_SELECTED, - HTML_SPACE, - TB, - TRUST_GRAPH_PEER_LEGENDS, -) -from tribler.gui.network.request_manager import request_manager -from tribler.gui.sentry_mixin import AddBreadcrumbOnShowMixin -from tribler.gui.utilities import connect, format_size, html_label, tr - - -class TrustGraph(pg.GraphItem): - def __init__(self): - pg.GraphItem.__init__(self) - self.data = None - - # Support dragging the nodes - self.dragPoint = None - self.dragOffset = None - - def set_node_selection_listener(self, listener): - connect(self.scatter.sigClicked, listener) - - def setData(self, **data): - self.data = data - if 'pos' in self.data: - num_nodes = self.data['pos'].shape[0] - self.data['data'] = np.empty(num_nodes, dtype=[('index', int)]) - self.data['data']['index'] = np.arange(num_nodes) - pg.GraphItem.setData(self, **self.data) - - def mouseDragEvent(self, event): - if event.button() != QtCore.Qt.LeftButton: - event.ignore() - return - - if event.isStart(): - clicked_position = event.buttonDownPos() - clicked_nodes = self.scatter.pointsAt(clicked_position) - if not clicked_nodes: - event.ignore() - return - - self.dragPoint = clicked_nodes[0] - clicked_index = clicked_nodes[0].data()[0] - self.dragOffset = self.data['pos'][clicked_index] - clicked_position - - elif event.isFinish(): - self.dragPoint = None - return - - elif self.dragPoint is None: - event.ignore() - return - - # Update position of the node and re-render the graph - clicked_index = self.dragPoint.data()[0] - if clicked_index == 0: - event.ignore() - return - self.data['pos'][clicked_index] = event.pos() + self.dragOffset - - pg.GraphItem.setData(self, **self.data) - event.accept() - - -class TrustGraphPage(AddBreadcrumbOnShowMixin, QWidget): - def __init__(self): - QWidget.__init__(self) - self.trust_graph = None - self.graph_view = None - self.selected_node = dict() - - self.root_public_key = None - self.graph_data = None - self.rest_request = None - - def showEvent(self, QShowEvent): - super().showEvent(QShowEvent) - self.fetch_graph_data() - - def hideEvent(self, QHideEvent): - super().hideEvent(QHideEvent) - - def initialize_trust_graph(self): - pg.setConfigOption('background', '#222222') - pg.setConfigOption('foreground', '#555') - pg.setConfigOption('antialias', True) - - graph_layout = pg.GraphicsLayoutWidget() - self.graph_view = graph_layout.addViewBox() - self.graph_view.setAspectLocked() - self.graph_view.setMenuEnabled(False) - self.reset_graph() - - # To disable zoom in the graph, wheel event is overridden. To enable it again, remove the statement below. - self.graph_view.wheelEvent = lambda evt: None - - self.trust_graph = TrustGraph() - self.trust_graph.set_node_selection_listener(self.on_node_clicked) - self.graph_view.addItem(self.trust_graph) - self.graph_view.addItem(pg.TextItem(text='YOU')) - self.window().trust_graph_plot_widget.layout().addWidget(graph_layout) - - connect(self.window().tr_control_refresh_btn.clicked, self.fetch_graph_data) - - self.window().tr_selected_node_pub_key.setHidden(True) - self.window().tr_selected_node_stats.setHidden(True) - self.window().trust_graph_progress_bar.setHidden(True) - - def on_node_clicked(self, top_point, *_other_overlapping_points): - clicked_node_data = top_point.ptsClicked[0].data() - clicked_node = self.graph_data['node'][clicked_node_data[0]] - - if not self.selected_node: - self.selected_node = dict() - elif 'spot' in self.selected_node and self.selected_node['spot']: - self.selected_node['spot'].setBrush(self.selected_node['color']) - - self.selected_node['public_key'] = clicked_node['key'] - self.selected_node['total_up'] = clicked_node.get('total_up', 0) - self.selected_node['total_down'] = clicked_node.get('total_down', 0) - self.selected_node['color'] = self.get_node_color(clicked_node) - self.selected_node['spot'] = top_point.ptsClicked[0] - - spot = top_point.ptsClicked[0] - spot.setBrush(COLOR_SELECTED) - - self.update_status_bar(self.selected_node) - - def update_status_bar(self, selected_node): - if not selected_node: - return - - peer_message = f"User {HTML_SPACE * 16}{selected_node.get('public_key', '')[:74]}..." - self.window().tr_selected_node_pub_key.setHidden(False) - self.window().tr_selected_node_pub_key.setText(peer_message) - - diff = selected_node.get('total_up', 0) - selected_node.get('total_down', 0) - color = COLOR_GREEN if diff > 0 else COLOR_RED if diff < 0 else COLOR_DEFAULT - bandwidth_message = ( - "Bandwidth " - + HTML_SPACE * 2 - + " Given " - + HTML_SPACE - + html_label(format_size(selected_node.get('total_up', 0))) - + " Taken " - + HTML_SPACE - + html_label(format_size(selected_node.get('total_down', 0))) - + " Balance " - + HTML_SPACE - + html_label(format_size(diff), color=color) - ) - self.window().tr_selected_node_stats.setHidden(False) - self.window().tr_selected_node_stats.setText(bandwidth_message) - - def reset_graph(self): - self.graph_view.setXRange(-1, 1) - self.graph_view.setYRange(-1, 1) - - def fetch_graph_data(self, checked=False): - if self.rest_request: - self.rest_request.cancel() - request_manager.get("trustview", self.on_received_data, url_params={'refresh': 1}, - priority=QNetworkRequest.LowPriority) - - def on_received_data(self, data): - if data is None or not isinstance(data, dict) or 'graph' not in data: - return - self.update_gui_labels(data) - - self.root_public_key = data['root_public_key'] - self.graph_data = data['graph'] - - plot_data = dict() - plot_data['pxMode'] = False - plot_data['pen'] = (100, 100, 100, 150) - plot_data['brush'] = (255, 0, 0, 255) - plot_data['pos'] = np.array([node['pos'] for node in data['graph']['node']]) - plot_data['size'] = np.array([self.get_node_size(node) for node in data['graph']['node']]) - plot_data['symbolBrush'] = np.array([self.get_node_color(node) for node in data['graph']['node']]) - - # If there are edges, only then set 'adj' keyword - if data['graph']['edge']: - plot_data['adj'] = np.array(data['graph']['edge']) - - self.trust_graph.setData(**plot_data) - - def get_node_color(self, node, selected=False): - if not selected and self.root_public_key == node['key']: - return COLOR_ROOT - if selected and self.selected_node and self.selected_node.get('public_key', None) == node['key']: - return COLOR_SELECTED - diff = node.get('total_up', 0) - node.get('total_down', 0) - return COLOR_GREEN if diff > 0 else COLOR_NEUTRAL if diff == 0 else COLOR_RED - - def get_node_size(self, node): - # User root node is bigger than normal nodes - min_size = 0.01 if node['key'] != self.root_public_key else 0.1 - - diff = abs(node.get('total_up', 0) - node.get('total_down', 0)) - if diff == 0: - return min_size - elif diff > 10 * TB: # max token balance limit - return 0.1 # max node size in graph - elif diff > TB: - return 0.05 + 0.005 * diff / TB # 0.005 for each extra TB of balance - return math.log(diff, 2) / 512 + min_size - - def update_gui_labels(self, data): - header_message = tr( - "The graph below is based on your historical interactions with other users in the " - "network. It shows %(num_interactions)s interactions " - "made by %(num_users)s users." - "
" - ) % {'num_interactions': data['num_tx'], 'num_users': len(data['graph']['node'])} - self.window().trust_graph_explanation_label.setText(header_message) - self.window().trust_graph_status_bar.setText(TRUST_GRAPH_PEER_LEGENDS) diff --git a/src/tribler/gui/widgets/trustpage.py b/src/tribler/gui/widgets/trustpage.py deleted file mode 100644 index 8c958e90d6..0000000000 --- a/src/tribler/gui/widgets/trustpage.py +++ /dev/null @@ -1,99 +0,0 @@ -from typing import Dict - -from PyQt5.QtWidgets import QWidget - -from tribler.gui.defs import PB, TB -from tribler.gui.dialogs.trustexplanationdialog import TrustExplanationDialog -from tribler.gui.network.request_manager import request_manager -from tribler.gui.sentry_mixin import AddBreadcrumbOnShowMixin -from tribler.gui.utilities import connect -from tribler.gui.widgets.graphs.dataplot import TimeSeriesDataPlot - - -class TrustSeriesPlot(TimeSeriesDataPlot): - def __init__(self, parent, **kargs): - series = [ - {'name': 'Token balance', 'pen': (224, 94, 0), 'symbolBrush': (224, 94, 0), 'symbolPen': 'w'}, - ] - super().__init__(parent, 'Token balance over time', series, **kargs) - self.setLabel('left', 'Data', units='B') - self.setLimits(yMin=-TB, yMax=PB) - - -class TrustPage(AddBreadcrumbOnShowMixin, QWidget): - """ - This page shows various trust statistics. - """ - - def __init__(self): - QWidget.__init__(self) - self.trust_plot = None - self.history = None - self.byte_scale = 1024 * 1024 - self.dialog = None - - def initialize_trust_page(self): - vlayout = self.window().plot_widget.layout() - if vlayout.isEmpty(): - self.trust_plot = TrustSeriesPlot(self.window().plot_widget) - vlayout.addWidget(self.trust_plot) - - connect(self.window().trust_explain_button.clicked, self.on_info_button_clicked) - - def on_info_button_clicked(self, checked): - self.dialog = TrustExplanationDialog(self.window()) - self.dialog.show() - - def received_bandwidth_statistics(self, statistics: Dict) -> None: - """ - We received bandwidth statistics from the Tribler core. Update the labels on the trust page with the - received information. - :param statistics: The received statistics, in JSON format. - """ - if not statistics or "statistics" not in statistics: - return - - statistics = statistics["statistics"] - total_up = statistics.get("total_given", 0) - total_down = statistics.get("total_taken", 0) - - self.window().trust_contribution_amount_label.setText(f"{total_up // self.byte_scale} MBytes") - self.window().trust_consumption_amount_label.setText(f"{total_down // self.byte_scale} MBytes") - - self.window().trust_people_helped_label.setText("%d" % statistics["num_peers_helped"]) - self.window().trust_people_helped_you_label.setText("%d" % statistics["num_peers_helped_by"]) - - def load_history(self) -> None: - """ - Load the bandwidth balance history by initiating a request to the Tribler core. - """ - request_manager.get("bandwidth/history", self.received_history) - - def received_history(self, history: Dict): - """ - We received the bandwidth history from the Tribler core. Plot it in the trust chart. - :param history: The received bandwidth history, in JSON format. - """ - if history: - self.history = history["history"] - self.plot_absolute_values() - - def plot_absolute_values(self) -> None: - """ - Plot the evolution of the token balance. - """ - if self.history: - min_balance = min(item['balance'] for item in self.history) - max_balance = max(item['balance'] for item in self.history) - half = (max_balance - min_balance) / 2 - min_limit = min(-TB, min_balance - half) - max_limit = max(PB, max_balance + half) - self.trust_plot.setLimits(yMin=min_limit, yMax=max_limit) - self.trust_plot.setYRange(min_balance, max_balance) - - # Convert all dates to a datetime object - for history_item in self.history: - timestamp = history_item["timestamp"] // 1000 - self.trust_plot.add_data(timestamp, [history_item["balance"]]) - - self.trust_plot.render_plot()