def load_market_community_in_session(self, session, market_member,
                                         mc_community):
        """
        Load the market community and tradechain community in a given session.
        """
        wallets = {
            'BTC':
            BitcoinWallet(
                os.path.join(session.config.get_state_dir(), 'wallet')),
            'MC':
            TrustchainWallet(mc_community),
            'DUM1':
            DummyWallet1(),
            'DUM2':
            DummyWallet2()
        }
        wallets['MC'].check_negative_balance = False

        dispersy = session.get_dispersy_instance()

        # Load MarketCommunity
        market_kargs = {'tribler_session': session, 'wallets': wallets}
        self.market_communities[session] = dispersy.define_auto_load(
            MarketCommunityTests, market_member, kargs=market_kargs,
            load=True)[0]
        return self.market_communities[session]
    def setUp(self, annotate=True):
        yield super(TestTrustchainWallet, self).setUp(annotate=annotate)

        latest_block = MockObject()
        latest_block.transaction = {
            "total_up": 10 * 1024 * 1024,
            "total_down": 5 * 1024 * 1024
        }
        latest_block.previous_hash_requester = 'b' * 5

        self.tc_community = MockObject()
        self.tc_community.add_discovered_candidate = lambda _: None
        self.tc_community.create_introduction_request = lambda *_: None
        self.tc_community.wait_for_intro_of_candidate = lambda _: succeed(None)
        self.tc_community.received_payment_message = lambda *_: None
        self.tc_community.sign_block = lambda *_: None
        self.tc_community.wait_for_signature_request = lambda _: succeed('a')
        self.tc_community.my_member = MockObject()
        self.tc_community.my_member.public_key = 'a' * 20
        self.tc_community.persistence = MockObject()
        self.tc_community.persistence.get_latest = lambda _: latest_block
        self.tc_community.get_candidate = lambda _: MockObject()

        self.tc_wallet = TrustchainWallet(self.tc_community)
class TestTrustchainWallet(TestBase):
    def setUp(self):
        super(TestTrustchainWallet, self).setUp()
        self.initialize(TrustChainCommunity, 2)
        self.tc_wallet = TrustchainWallet(self.nodes[0].overlay)
        self.tc_wallet.MONITOR_DELAY = 0.01
        self.tc_wallet.check_negative_balance = True

    def create_node(self):
        return MockIPv8(u"curve25519",
                        TrustChainCommunity,
                        working_directory=u":memory:")

    def test_get_mc_wallet_name(self):
        """
        Test the identifier of the Trustchain wallet
        """
        self.assertEqual(self.tc_wallet.get_name(), 'Tokens (MB)')

    def test_get_mc_wallet_id(self):
        """
        Test the identifier of a Trustchain wallet
        """
        self.assertEqual(self.tc_wallet.get_identifier(), 'MB')

    @twisted_wrapper
    def test_get_balance(self):
        """
        Test the balance retrieval of a Trustchain wallet
        """
        yield self.introduce_nodes()

        balance = yield self.tc_wallet.get_balance()
        self.assertEqual(balance['available'], 0)

        his_pubkey = self.nodes[0].network.verified_peers[
            0].public_key.key_to_bin()
        tx = {
            'up': 20 * 1024 * 1024,
            'down': 5 * 1024 * 1024,
            'total_up': 20 * 1024 * 1024,
            'total_down': 5 * 1024 * 1024
        }
        self.nodes[0].overlay.sign_block(
            self.nodes[0].network.verified_peers[0],
            public_key=his_pubkey,
            transaction=tx)

        yield self.deliver_messages()

        balance = yield self.tc_wallet.get_balance()
        self.assertEqual(balance['available'], 15)

    def test_create_wallet(self):
        """
        Test whether creating a Trustchain wallet raises an error
        """
        self.assertRaises(RuntimeError, self.tc_wallet.create_wallet)

    @twisted_wrapper
    def test_transfer_invalid(self):
        """
        Test the transfer method of a Trustchain wallet
        """
        test_deferred = Deferred()

        def on_error(failure):
            self.assertIsInstance(failure.value, InsufficientFunds)
            test_deferred.callback(None)

        self.tc_wallet.transfer(200, None).addErrback(on_error)
        yield test_deferred

    @twisted_wrapper
    def test_monitor_transaction(self):
        """
        Test the monitoring of a transaction in a Trustchain wallet
        """
        his_pubkey = self.nodes[0].overlay.my_peer.public_key.key_to_bin()

        tx_deferred = self.tc_wallet.monitor_transaction(
            '%s.1' % his_pubkey.encode('hex'))

        # Now create the transaction
        self.nodes[1].overlay.sign_block(
            self.nodes[1].network.verified_peers[0],
            public_key=his_pubkey,
            transaction={})

        yield tx_deferred

    def test_address(self):
        """
        Test the address of a Trustchain wallet
        """
        self.assertIsInstance(self.tc_wallet.get_address(), str)

    @twisted_wrapper
    def test_get_transaction(self):
        """
        Test the retrieval of transactions of a Trustchain wallet
        """
        def on_transactions(transactions):
            self.assertIsInstance(transactions, list)

        yield self.tc_wallet.get_transactions().addCallback(on_transactions)

    def test_min_unit(self):
        """
        Test the minimum unit of a Trustchain wallet
        """
        self.assertEqual(self.tc_wallet.min_unit(), 1)
 def setUp(self):
     super(TestTrustchainWallet, self).setUp()
     self.initialize(TrustChainCommunity, 2)
     self.tc_wallet = TrustchainWallet(self.nodes[0].overlay)
     self.tc_wallet.MONITOR_DELAY = 0.01
     self.tc_wallet.check_negative_balance = True
Esempio n. 5
0
    def load_ipv8_overlays(self):
        # Discovery Community
        with open(self.session.config.get_permid_keypair_filename(),
                  'r') as key_file:
            content = key_file.read()
        content = content[31:-30].replace('\n', '').decode("BASE64")
        peer = Peer(M2CryptoSK(keystring=content))
        discovery_community = DiscoveryCommunity(peer, self.ipv8.endpoint,
                                                 self.ipv8.network)
        discovery_community.resolve_dns_bootstrap_addresses()
        self.ipv8.overlays.append(discovery_community)
        self.ipv8.strategies.append((RandomChurn(discovery_community), -1))

        if not self.session.config.get_dispersy_enabled():
            self.ipv8.strategies.append((RandomWalk(discovery_community), 20))

        # TriblerChain Community
        if self.session.config.get_trustchain_enabled():
            triblerchain_peer = Peer(self.session.trustchain_keypair)

            from Tribler.community.triblerchain.community import TriblerChainCommunity
            self.triblerchain_community = TriblerChainCommunity(
                triblerchain_peer,
                self.ipv8.endpoint,
                self.ipv8.network,
                tribler_session=self.session,
                working_directory=self.session.config.get_state_dir())
            self.ipv8.overlays.append(self.triblerchain_community)
            self.ipv8.strategies.append(
                (EdgeWalk(self.triblerchain_community), 20))

        # Tunnel Community
        if self.session.config.get_tunnel_community_enabled():
            tunnel_peer = Peer(self.session.trustchain_keypair)

            from Tribler.community.triblertunnel.community import TriblerTunnelCommunity
            self.tunnel_community = TriblerTunnelCommunity(
                tunnel_peer,
                self.ipv8.endpoint,
                self.ipv8.network,
                tribler_session=self.session,
                dht_provider=MainlineDHTProvider(
                    self.mainline_dht,
                    self.session.config.get_dispersy_port()),
                triblerchain_community=self.triblerchain_community)
            self.ipv8.overlays.append(self.tunnel_community)
            self.ipv8.strategies.append(
                (RandomWalk(self.tunnel_community), 20))

        # Market Community
        if self.session.config.get_market_community_enabled():
            wallets = {}

            try:
                from Tribler.community.market.wallet.btc_wallet import BitcoinWallet, BitcoinTestnetWallet
                wallet_type = BitcoinTestnetWallet if self.session.config.get_btc_testnet(
                ) else BitcoinWallet
                btc_wallet = wallet_type(
                    os.path.join(self.session.config.get_state_dir(),
                                 'wallet'))
                wallets[btc_wallet.get_identifier()] = btc_wallet
            except ImportError:
                self._logger.error(
                    "Electrum wallet cannot be found, Bitcoin trading not available!"
                )

            mc_wallet = TrustchainWallet(self.triblerchain_community)
            wallets[mc_wallet.get_identifier()] = mc_wallet

            if self.session.config.get_dummy_wallets_enabled():
                # For debugging purposes, we create dummy wallets
                dummy_wallet1 = DummyWallet1()
                wallets[dummy_wallet1.get_identifier()] = dummy_wallet1

                dummy_wallet2 = DummyWallet2()
                wallets[dummy_wallet2.get_identifier()] = dummy_wallet2

            from Tribler.community.market.community import MarketCommunity
            market_peer = Peer(self.session.tradechain_keypair)

            self.market_community = MarketCommunity(
                market_peer,
                self.ipv8.endpoint,
                self.ipv8.network,
                tribler_session=self.session,
                wallets=wallets,
                working_directory=self.session.config.get_state_dir())

            self.ipv8.overlays.append(self.market_community)

            self.ipv8.strategies.append(
                (RandomWalk(self.market_community), 20))
Esempio n. 6
0
    def load_communities(self):
        self._logger.info("tribler: Preparing communities...")
        now_time = timemod.time()
        default_kwargs = {'tribler_session': self.session}

        # Search Community
        if self.session.config.get_torrent_search_enabled():
            from Tribler.community.search.community import SearchCommunity
            self.dispersy.define_auto_load(SearchCommunity,
                                           self.session.dispersy_member,
                                           load=True,
                                           kargs=default_kwargs)

        # AllChannel Community
        if self.session.config.get_channel_search_enabled():
            from Tribler.community.allchannel.community import AllChannelCommunity
            self.dispersy.define_auto_load(AllChannelCommunity,
                                           self.session.dispersy_member,
                                           load=True,
                                           kargs=default_kwargs)

        # Channel Community
        if self.session.config.get_channel_community_enabled():
            from Tribler.community.channel.community import ChannelCommunity
            self.dispersy.define_auto_load(ChannelCommunity,
                                           self.session.dispersy_member,
                                           load=True,
                                           kargs=default_kwargs)

        # PreviewChannel Community
        if self.session.config.get_preview_channel_community_enabled():
            from Tribler.community.channel.preview import PreviewChannelCommunity
            self.dispersy.define_auto_load(PreviewChannelCommunity,
                                           self.session.dispersy_member,
                                           kargs=default_kwargs)

        # Tunnel Community
        mc_community = None
        if self.session.config.get_tunnel_community_enabled():
            tunnel_settings = TunnelSettings(tribler_session=self.session)
            tunnel_kwargs = {
                'tribler_session': self.session,
                'settings': tunnel_settings
            }

            if self.session.config.get_trustchain_enabled():
                trustchain_kwargs = {'tribler_session': self.session}

                # If the trustchain is enabled, we use the permanent trustchain keypair
                # for both the trustchain and the tunnel community
                keypair = self.session.trustchain_keypair
                dispersy_member = self.dispersy.get_member(
                    private_key=keypair.key_to_bin())

                from Tribler.community.triblerchain.community import TriblerChainCommunity
                mc_community = self.dispersy.define_auto_load(
                    TriblerChainCommunity,
                    dispersy_member,
                    load=True,
                    kargs=trustchain_kwargs)[0]

            else:
                keypair = self.dispersy.crypto.generate_key(u"curve25519")
                dispersy_member = self.dispersy.get_member(
                    private_key=self.dispersy.crypto.key_to_bin(keypair))

            from Tribler.community.tunnel.hidden_community import HiddenTunnelCommunity
            self.tunnel_community = self.dispersy.define_auto_load(
                HiddenTunnelCommunity,
                dispersy_member,
                load=True,
                kargs=tunnel_kwargs)[0]

            # We don't want to automatically load other instances of this community with other master members.
            self.dispersy.undefine_auto_load(HiddenTunnelCommunity)

        # Use the permanent TrustChain ID for Market community/TradeChain if it's available
        if self.session.config.get_market_community_enabled():
            wallets = {}
            btc_wallet = BitcoinWallet(
                os.path.join(self.session.config.get_state_dir(), 'wallet'),
                testnet=self.session.config.get_btc_testnet())
            wallets[btc_wallet.get_identifier()] = btc_wallet

            mc_wallet = TrustchainWallet(mc_community)
            wallets[mc_wallet.get_identifier()] = mc_wallet

            if self.session.config.get_dummy_wallets_enabled():
                # For debugging purposes, we create dummy wallets
                dummy_wallet1 = DummyWallet1()
                wallets[dummy_wallet1.get_identifier()] = dummy_wallet1

                dummy_wallet2 = DummyWallet2()
                wallets[dummy_wallet2.get_identifier()] = dummy_wallet2

            from Tribler.community.market.community import MarketCommunity
            keypair = self.session.tradechain_keypair
            dispersy_member = self.dispersy.get_member(
                private_key=keypair.key_to_bin())

            market_kwargs = {
                'tribler_session': self.session,
                'wallets': wallets
            }
            self.market_community = self.dispersy.define_auto_load(
                MarketCommunity,
                dispersy_member,
                load=True,
                kargs=market_kwargs)[0]

        self.session.config.set_anon_proxy_settings(
            2,
            ("127.0.0.1",
             self.session.config.get_tunnel_community_socks5_listen_ports()))

        self._logger.info("tribler: communities are ready in %.2f seconds",
                          timemod.time() - now_time)
class TestTrustchainWallet(AbstractServer):
    @blocking_call_on_reactor_thread
    @inlineCallbacks
    def setUp(self, annotate=True):
        yield super(TestTrustchainWallet, self).setUp(annotate=annotate)

        latest_block = MockObject()
        latest_block.transaction = {
            "total_up": 10 * 1024 * 1024,
            "total_down": 5 * 1024 * 1024
        }
        latest_block.previous_hash_requester = 'b' * 5

        self.tc_community = MockObject()
        self.tc_community.add_discovered_candidate = lambda _: None
        self.tc_community.create_introduction_request = lambda *_: None
        self.tc_community.wait_for_intro_of_candidate = lambda _: succeed(None)
        self.tc_community.received_payment_message = lambda *_: None
        self.tc_community.sign_block = lambda *_: None
        self.tc_community.wait_for_signature_request = lambda _: succeed('a')
        self.tc_community.my_member = MockObject()
        self.tc_community.my_member.public_key = 'a' * 20
        self.tc_community.persistence = MockObject()
        self.tc_community.persistence.get_latest = lambda _: latest_block
        self.tc_community.get_candidate = lambda _: MockObject()

        self.tc_wallet = TrustchainWallet(self.tc_community)

    def test_get_mc_wallet_name(self):
        """
        Test the identifier of the Trustchain wallet
        """
        self.assertEqual(self.tc_wallet.get_name(), 'Reputation')

    def test_get_mc_wallet_id(self):
        """
        Test the identifier of a Trustchain wallet
        """
        self.assertEqual(self.tc_wallet.get_identifier(), 'MC')

    @deferred(timeout=10)
    def test_get_balance(self):
        """
        Test the balance retrieval of a Trustchain wallet
        """
        def on_balance(balance):
            self.assertEqual(balance['available'], 5)

        return self.tc_wallet.get_balance().addCallback(on_balance)

    def test_create_wallet(self):
        """
        Test whether creating a Trustchain wallet raises an error
        """
        self.assertRaises(RuntimeError, self.tc_wallet.create_wallet)

    @deferred(timeout=10)
    def test_transfer_invalid(self):
        """
        Test the transfer method of a Trustchain wallet
        """
        test_deferred = Deferred()

        def on_error(failure):
            self.assertIsInstance(failure.value, InsufficientFunds)
            test_deferred.callback(None)

        self.tc_wallet.transfer(200, None).addErrback(on_error)
        return test_deferred

    @deferred(timeout=10)
    def test_transfer_missing_member(self):
        """
        Test the transfer method of a Trustchain wallet with a missing member
        """
        candidate = MockObject()
        candidate.get_member = lambda: None
        candidate.sock_addr = None
        self.tc_wallet.check_negative_balance = False
        self.tc_wallet.send_signature = lambda *_: None
        return self.tc_wallet.transfer(200, candidate)

    @deferred(timeout=10)
    def test_monitor_transaction(self):
        """
        Test the monitoring of a transaction in a Trustchain wallet
        """
        def on_transaction(transaction):
            self.assertEqual(transaction, 'a')

        return self.tc_wallet.monitor_transaction('abc.1').addCallback(
            on_transaction)

    def test_address(self):
        """
        Test the address of a Trustchain wallet
        """
        self.assertIsInstance(self.tc_wallet.get_address(), str)

    @deferred(timeout=10)
    def test_get_transaction(self):
        """
        Test the retrieval of transactions of a dummy wallet
        """
        def on_transactions(transactions):
            self.assertIsInstance(transactions, list)

        return self.tc_wallet.get_transactions().addCallback(on_transactions)

    def test_min_unit(self):
        """
        Test the minimum unit of a Trustchain wallet
        """
        self.assertEqual(self.tc_wallet.min_unit(), 1)

    def test_wait_for_intro_of_candidate(self):
        """
        Test waiting for an introduction candidate in the TrustChain wallet
        """
        candidate = MockObject()
        candidate.sock_addr = None
        return self.tc_wallet.wait_for_intro_of_candidate(candidate)