def test_add_blocks(self):
        """
        Tests the maximum blocks/transactions that be be present in the graph.
        :return:
        """
        db = MockDatabase()
        block = TestBlock()

        for _ in range(self.trust_graph.max_transactions):
            tx = {
                b"total_up": random.randint(1, 100),
                b"total_down": random.randint(1, 100),
                b"up": random.randint(1, 100),
                b"down": random.randint(1, 100)
            }
            new_block = TrustChainBlock.create(b'tribler_bandwidth', tx, db,
                                               block.public_key)
            db.add_block(new_block)
            self.trust_graph.add_block(new_block)

        self.assertEqual(len(self.trust_graph.transactions),
                         self.trust_graph.max_transactions)

        # Already max transactions are added to the graph, adding more should raise an exception
        try:
            tx = {
                b"total_up": random.randint(1, 100),
                b"total_down": random.randint(1, 100),
                b"up": random.randint(1, 100),
                b"down": random.randint(1, 100)
            }
            new_block = TrustChainBlock.create(b'tribler_bandwidth', tx, db,
                                               block.public_key)
            db.add_block(new_block)
            self.trust_graph.add_block(new_block)
        except TrustGraphException as tge:
            exception_msg = getattr(tge, 'message', repr(tge))
            self.assertTrue(
                'Max transactions reached in the graph' in exception_msg)
        else:
            self.fail("Expected to fail but did not.")
    async def test_get_bootstrap_identity_not_enough_tokens_2(self):
        """
        Testing whether the API returns error 400 if bandwidth is to low when bootstrapping a new identity
        """
        transaction = {b'up': 0, b'down': 100, b'total_up': 0, b'total_down': 100}
        test_block = TrustChainBlock()
        test_block.type = b'tribler_bandwidth'
        test_block.transaction = transaction
        test_block._transaction = encode(transaction)
        test_block.public_key = self.session.trustchain_community.my_peer.public_key.key_to_bin()
        test_block.hash = test_block.calculate_hash()
        self.session.trustchain_community.persistence.add_block(test_block)

        await self.do_request('trustchain/bootstrap?amount=10', expected_code=400)
    def test_get_attributes(self):
        """
        Test the GET: attributes request type
        :return: None
        """
        param_dict = {
            'port': self._master_peer.port,
            'interface': '127.0.0.1',
            'endpoint': 'attestation'
        }

        block = TrustChainBlock()
        block.public_key = self._master_peer.get_overlays()[1].my_peer.public_key.key_to_bin()
        block.transaction = {'name': 123, 'hash': '123', 'metadata': b64encode(json.dumps({'psn': '1234567890'}))}

        self._master_peer.get_overlays()[1].persistence.add_block(block)

        result = yield self._get_style_requests.make_attributes(param_dict)

        self.assertEqual(result, '[[123, "MTIz", "eyJwc24iOiAiMTIzNDU2Nzg5MCJ9"]]',
                         "The response was not as expected. This would suggest that something went wrong "
                         "with the attributes request.")
    async def test_get_bootstrap_identity_all_tokens(self):
        """
        Testing whether the API return all available tokens when no argument is supplied
        """
        transaction = {b'up': 100, b'down': 0, b'total_up': 100, b'total_down': 0}
        transaction2 = {'up': 100, 'down': 0}

        test_block = TrustChainBlock()
        test_block.type = b'tribler_bandwidth'
        test_block.transaction = transaction
        test_block._transaction = encode(transaction)
        test_block.public_key = self.session.trustchain_community.my_peer.public_key.key_to_bin()
        test_block.hash = test_block.calculate_hash()
        self.session.trustchain_community.persistence.add_block(test_block)

        response_dict = await self.do_request('trustchain/bootstrap', expected_code=200)
        self.assertEqual(response_dict['transaction'], transaction2)
    async def test_trustview_response(self):
        """
        Test whether the trust graph response is correctly returned.
        """
        root_key = self.session.trustchain_community.my_peer.public_key.key_to_bin(
        )
        friends = [
            "4c69624e61434c504b3a2ee28ce24a2259b4e585b81106cdff4359fcf48e93336c11d133b01613f30b03b4db06df27"
            "80daac2cdf2ee60be611bf7367a9c1071ac50d65ca5858a50e9578",
            "4c69624e61434c504b3a5368c7b39a82063e29576df6d74fba3e0dba3af8e7a304b553b71f08ea6a0730e8cef767a4"
            "85dc6f390b6da5631f772941ea69ce2c098d802b7a28b500edf2b3",
            "4c69624e61434c504b3a0f3f6318e49ffeb0a160e7fcac5c1d3337ba409b45e1371ddca5e3b364ebdd1b73c775318a"
            "533a25335a5c36ae3695f1c3036b651893659fbf2e1f2bce66cf65",
        ]

        fofs = [
            "4c69624e61434c504b3a2ee28ce24a2259b4e585b81106cdff4359fcf48e93336c11d133b01613f30b03b4db06df27"
            "80daac2cdf2ee60be611bf7367a9c1071ac50d65ca5858a50e9579",
            "4c69624e61434c504b3a5368c7b39a82063e29576df6d74fba3e0dba3af8e7a304b553b71f08ea6a0730e8cef767a4"
            "85dc6f390b6da5631f772941ea69ce2c098d802b7a28b500edf2b4",
            "4c69624e61434c504b3a0f3f6318e49ffeb0a160e7fcac5c1d3337ba409b45e1371ddca5e3b364ebdd1b73c775318a"
            "533a25335a5c36ae3695f1c3036b651893659fbf2e1f2bce66cf66",
        ]

        fofofs = [
            "4c69624e61434c504b3a2ee28ce24a2259b4e585b81106cdff4359fcf48e93336c11d133b01613f30b03b4db06df27"
            "80daac2cdf2ee60be611bf7367a9c1071ac50d65ca5858a50e9580",
            "4c69624e61434c504b3a5368c7b39a82063e29576df6d74fba3e0dba3af8e7a304b553b71f08ea6a0730e8cef767a4"
            "85dc6f390b6da5631f772941ea69ce2c098d802b7a28b500edf2b5",
            "4c69624e61434c504b3a0f3f6318e49ffeb0a160e7fcac5c1d3337ba409b45e1371ddca5e3b364ebdd1b73c775318a"
            "533a25335a5c36ae3695f1c3036b651893659fbf2e1f2bce66cf67",
        ]

        def get_dummy_tx():
            return {
                b'up': random.randint(1, 101),
                b'down': random.randint(1, 101),
                b'total_up': random.randint(1, 101),
                b'total_down': random.randint(1, 101),
            }

        def verify_response(response_json, nodes, tx):
            self.assertIsNotNone(response_json['graph'])
            self.assertEqual(response_json['num_tx'], tx)
            self.assertEqual(len(response_json['graph']['node']), nodes)

        test_block = TrustChainBlock()
        test_block.type = b'tribler_bandwidth'

        for seq, pub_key in enumerate(friends):
            test_block.transaction = get_dummy_tx()
            test_block._transaction = encode(test_block.transaction)

            test_block.sequence_number = seq
            test_block.public_key = root_key
            test_block.link_public_key = unhexlify(pub_key)

            test_block.hash = test_block.calculate_hash()
            self.session.trustchain_community.persistence.add_block(test_block)

        for ind, friend in enumerate(friends):
            for ind2, fof in enumerate(fofs):
                test_block.transaction = get_dummy_tx()
                test_block._transaction = encode(test_block.transaction)

                test_block.sequence_number = ind + ind2
                test_block.public_key = unhexlify(friend)
                test_block.link_public_key = unhexlify(fof)

                test_block.hash = test_block.calculate_hash()
                self.session.trustchain_community.persistence.add_block(
                    test_block)

        for ind3, fof in enumerate(fofs):
            for ind4, fofof in enumerate(fofofs):
                test_block.transaction = get_dummy_tx()
                test_block._transaction = encode(test_block.transaction)

                test_block.sequence_number = ind3 + ind4
                test_block.public_key = unhexlify(fof)
                test_block.link_public_key = unhexlify(fofof)
                test_block.hash = test_block.calculate_hash()
                self.session.trustchain_community.persistence.add_block(
                    test_block)

        res = await self.do_request('trustview?depth=1', expected_code=200)
        verify_response(res, 4, 3)
        res = await self.do_request('trustview?depth=2', expected_code=200)
        verify_response(res, 7, 12)
        res = await self.do_request('trustview?depth=3', expected_code=200)
        verify_response(res, 10, 21)
        res = await self.do_request('trustview?depth=4', expected_code=200)
        verify_response(res, 10, 21)
    async def test_get_statistics(self):
        """
        Testing whether the API returns the correct statistics
        """
        block = TrustChainBlock()
        block.public_key = self.session.trustchain_community.my_peer.public_key.key_to_bin()
        block.link_public_key = unhexlify(b"deadbeef")
        block.link_sequence_number = 21
        block.type = b'tribler_bandwidth'
        block.transaction = {b"up": 42, b"down": 8, b"total_up": 1024,
                             b"total_down": 2048, b"type": b"tribler_bandwidth"}
        block._transaction = encode(block.transaction)
        block.sequence_number = 3
        block.previous_hash = unhexlify(b"babecafe")
        block.signature = unhexlify(b"babebeef")
        block.hash = block.calculate_hash()
        self.session.trustchain_community.persistence.add_block(block)

        response_dict = await self.do_request('trustchain/statistics', expected_code=200)
        self.assertTrue("statistics" in response_dict)
        stats = response_dict["statistics"]
        self.assertEqual(stats["id"], hexlify(self.session.trustchain_community.
                                              my_peer.public_key.key_to_bin()))
        self.assertEqual(stats["total_blocks"], 3)
        self.assertEqual(stats["total_up"], 1024)
        self.assertEqual(stats["total_down"], 2048)
        self.assertEqual(stats["peers_that_pk_helped"], 1)
        self.assertEqual(stats["peers_that_helped_pk"], 1)