コード例 #1
0
ファイル: script.py プロジェクト: ebcabaybay/swiftarm
    def test_create_barter_record(self):
        """
        1. Create a single signed barter record
        2. Send signature request from SELF to NODE
        3. Add signature and send barter record from NODE to SELF
        4. Check database for the new record
        """
        community = BarterCommunity.create_community(self._my_member)
        address = self._dispersy.socket.get_address()

        # create node and ensure that SELF knows the node address
        node = BarterNode()
        node.init_socket()
        node.set_community(community)
        node.init_my_member()
        yield 0.11
        assert self.is_database_empty(
            community), "Database should be empty (for this community id)"

        # send single signed barter record
        message = community.create_barter_record(
            Member.get_instance(node.my_member.public_key), 10, 2)
        yield 0.11

        # receive signature request
        _, message = node.receive_message(
            addresses=[address], message_names=[u"dispersy-signature-request"])
        assert message.payload.message.name == u"barter-record"
        assert message.payload.message.authentication.members[
            0].public_key == community.my_member.public_key
        assert message.payload.message.authentication.members[
            1].public_key == node.my_member.public_key
        assert message.payload.message.authentication.signed_members[0][0]
        assert not message.payload.message.authentication.is_signed
        assert not message.payload.message.authentication.signed_members[1][0]
        assert message.payload.message.payload.first_upload == 10
        assert message.payload.message.payload.second_upload == 2

        # create signature and send data back
        message = message.payload.message
        first_signature_offset = len(message.packet) - sum(
            member.signature_length
            for member in message.authentication.members)
        signature = node.my_member.sign(message.packet,
                                        length=first_signature_offset)
        message.authentication.set_signature(
            Member.get_instance(node.my_member.public_key), signature)
        node.send_message(message, address)
        yield 0.11
        try:
            community._database.execute(
                u"SELECT 1 FROM record WHERE community = ? AND global_time = ? AND first_member = ? AND second_member = ? AND upload_first_member = ? AND upload_second_member = ?",
                (community.database_id, message.distribution.global_time,
                 node.my_member.database_id, community._my_member.database_id,
                 10, 2)).next()
        except StopIteration:
            assert False

        # cleanup
        community.create_dispersy_destroy_community(u"hard-kill")
コード例 #2
0
    def test_incoming_barter_record(self):
        """
        1. Create a record signed only by NODE
        2. Send signature request from NODE to SELF
        3. Receive signature reply from SELF to NODE
        4. Check the signature
        5. Send double signed record from NODE to SELF
        6. Check that the record is stored in the database at SELF
        """
        community = BarterCommunity.create_community(self._my_member)
        address = self._dispersy.socket.get_address()

        # create node and ensure that SELF knows the node address
        node = BarterNode()
        node.init_socket()
        node.set_community(community)
        node.init_my_member()
        yield 0.11
        assert self.is_database_empty(community), "Database should be empty (for this community id)"

        # 1. Create a record signed only by NODE
        self_member = Member(community._my_member.public_key, sync_with_database=False)
        record = node.create_barter_record(self_member, 10, 2, 1)

        # 2. Send signature request from NODE to SELF
        request = node.create_dispersy_signature_request_message(record, 2, self_member)
        node.send_message(request, address)
        yield 0.11

        # 3. Receive signature reply from SELF to NODE
        # 4. Check the signature
        _, response = node.receive_message(addresses=[address], message_names=[u"dispersy-signature-response"])
        first_signature_offset = len(record.packet) - sum([member.signature_length for member in record.authentication.members])
        identifier = sha1(request.packet).digest()
        assert response.payload.identifier == identifier
        assert self_member.verify(record.packet[:first_signature_offset], response.payload.signature)

        # 5. Send double signed record from NODE to SELF
        second_signature_offset = len(record.packet) - record.authentication.members[1].signature_length
        packet = record.packet[:second_signature_offset] + response.payload.signature
        node.send_packet(packet, address)
        yield 0.11

        # 6. Check that the record is stored in the database at SELF
        try:
            community._database.execute(u"SELECT 1 FROM record WHERE community = ? AND global_time = ? AND first_member = ? AND second_member = ? AND upload_first_member = ? AND upload_second_member = ?",
                                        (community.database_id, 1, node.my_member.database_id, community._my_member.database_id, 10, 2)).next()
        except StopIteration:
            assert False

        # cleanup
        community.create_dispersy_destroy_community(u"hard-kill")
コード例 #3
0
    def test_create_barter_record(self):
        """
        1. Create a single signed barter record
        2. Send signature request from SELF to NODE
        3. Add signature and send barter record from NODE to SELF
        4. Check database for the new record
        """
        community = BarterCommunity.create_community(self._my_member)
        address = self._dispersy.socket.get_address()

        # create node and ensure that SELF knows the node address
        node = BarterNode()
        node.init_socket()
        node.set_community(community)
        node.init_my_member()
        yield 0.11
        assert self.is_database_empty(community), "Database should be empty (for this community id)"

        # send single signed barter record
        message = community.create_barter_record(Member.get_instance(node.my_member.public_key), 10, 2)
        yield 0.11

        # receive signature request
        _, message = node.receive_message(addresses=[address], message_names=[u"dispersy-signature-request"])
        assert message.payload.message.name == u"barter-record"
        assert message.payload.message.authentication.members[0].public_key == community.my_member.public_key
        assert message.payload.message.authentication.members[1].public_key == node.my_member.public_key
        assert message.payload.message.authentication.signed_members[0][0]
        assert not message.payload.message.authentication.is_signed
        assert not message.payload.message.authentication.signed_members[1][0]
        assert message.payload.message.payload.first_upload == 10
        assert message.payload.message.payload.second_upload == 2

        # create signature and send data back
        message = message.payload.message
        first_signature_offset = len(message.packet) - sum(member.signature_length for member in message.authentication.members)
        signature = node.my_member.sign(message.packet, length=first_signature_offset)
        message.authentication.set_signature(Member.get_instance(node.my_member.public_key), signature)
        node.send_message(message, address)
        yield 0.11
        try:
            community._database.execute(u"SELECT 1 FROM record WHERE community = ? AND global_time = ? AND first_member = ? AND second_member = ? AND upload_first_member = ? AND upload_second_member = ?",
                                        (community.database_id, message.distribution.global_time, node.my_member.database_id, community._my_member.database_id, 10, 2)).next()
        except StopIteration:
            assert False

        # cleanup
        community.create_dispersy_destroy_community(u"hard-kill")
コード例 #4
0
ファイル: script.py プロジェクト: ebcabaybay/swiftarm
    def run(self):
        ec = ec_generate_key(u"low")
        self._my_member = Member.get_instance(ec_to_public_bin(ec),
                                              ec_to_private_bin(ec),
                                              sync_with_database=True)

        self.caller(self.test_incoming_barter_record)
コード例 #5
0
    def join_community(self, my_member):
        self.my_member = my_member

        master_key = "3081a7301006072a8648ce3d020106052b81040027038192000404f10c33b03d2a09943d6d6a4b2cf4fe3129e5dce1df446a27d0ce00d48c845a4eff8102ef3becd6bc07c65953c824d227ebc110016d5ba71163bf6fb83fde7cdccf164bb007e27d07da952c47d30cf9c843034dc7a4603af3a84f8997e5d046e6a5f1ad489add6878898079a4663ade502829577c7d1e27302a3d5ea0ae06e83641a093a87465fdd4a3b43e031a9555".decode(
            "HEX")
        master = Member(master_key)

        community = DemersTest.join_community(master, self.my_member)
        return community
コード例 #6
0
    def join_community(self, my_member):
        self.my_member = my_member

        master_key = "3081a7301006072a8648ce3d020106052b81040027038192000403cbbfd2dfb67a7db66c88988df56f93fa6e7f982f9a6a0fa8898492c8b8cae23e10b159ace60b7047012082a5aa4c6e221d7e58107bb550436d57e046c11ab4f51f0ab18fa8f58d0346cc12d1cc2b61fc86fe5ed192309152e11e3f02489e30c7c971dd989e1ce5030ea0fb77d5220a92cceb567cbc94bc39ba246a42e215b55e9315b543ddeff0209e916f77c0d747".decode(
            "HEX")
        master = Member(master_key)

        return AllChannelCommunity.join_community(master,
                                                  self.my_member,
                                                  self.my_member,
                                                  integrate_with_tribler=False)
コード例 #7
0
ファイル: script.py プロジェクト: zzmjohn/tribler
    def join_community(self, my_member):
        self.my_member = my_member

        master_key = "3081a7301006072a8648ce3d020106052b81040027038192000404f10c33b03d2a09943d6d6a4b2cf4fe3129e5dce1df446a27d0ce00d48c845a4eff8102ef3becd6bc07c65953c824d227ebc110016d5ba71163bf6fb83fde7cdccf164bb007e27d07da952c47d30cf9c843034dc7a4603af3a84f8997e5d046e6a5f1ad489add6878898079a4663ade502829577c7d1e27302a3d5ea0ae06e83641a093a87465fdd4a3b43e031a9555".decode(
            "HEX")
        master = Member(master_key)

        log(self._logfile,
            "joining community with kargs",
            kargs=self.community_kargs)

        if self.community_type == 'search':
            community = SearchCommunity.join_community(
                master,
                self.my_member,
                self.my_member,
                integrate_with_tribler=False,
                log_searches=True,
                **self.community_kargs)
        elif self.community_type == 'hsearch':
            community = HSearchCommunity.join_community(
                master,
                self.my_member,
                self.my_member,
                integrate_with_tribler=False,
                log_searches=True,
                **self.community_kargs)
        else:
            community = PSearchCommunity.join_community(
                master,
                self.my_member,
                self.my_member,
                integrate_with_tribler=False,
                log_searches=True,
                **self.community_kargs)

        self._add_taste_buddies = community.add_taste_buddies
        community.add_taste_buddies = self.log_taste_buddies

        self._manual_create_introduction_request = community.create_introduction_request
        if self.manual_connect:
            community.create_introduction_request = lambda destination, allow_sync: self._manual_create_introduction_request(
                destination, False)

        if int(self._my_name) <= self.late_join:
            self._create_introduction_request = community.create_introduction_request
            community.create_introduction_request = lambda *args: None

        self._dispersy.callback.register(self.monitor_taste_buddy, delay=1.0)

        return community
コード例 #8
0
 def load_community(cls, master, swift_process):
     dispersy = Dispersy.get_instance()
     try:
         # test if this community already exists
         classification, = next(dispersy.database.execute(u"SELECT classification FROM community WHERE master = ?", (master.database_id,)))
     except StopIteration:
         # join the community with a new my_member, using a cheap cryptography key
         ec = ec_generate_key(u"NID_secp160r1")
         return cls.join_community(master, Member(ec_to_public_bin(ec), ec_to_private_bin(ec)), swift_process)
     else:
         if classification == cls.get_classification():
             return super(EffortCommunity, cls).load_community(master, swift_process)
         else:
             raise RuntimeError("Unable to load an EffortCommunity that has been killed")
コード例 #9
0
    def setUp(self, annotate=True):
        yield super(CommunityTestSuite, self).setUp(annotate=annotate)

        dummy1_wallet = DummyWallet1()
        dummy2_wallet = DummyWallet2()

        self.market_community = MarketCommunity(self.dispersy,
                                                self.master_member,
                                                self.member)
        self.market_community.initialize(wallets={
            dummy1_wallet.get_identifier():
            dummy1_wallet,
            dummy2_wallet.get_identifier():
            dummy2_wallet
        },
                                         use_database=False)
        self.market_community.use_local_address = True
        self.dispersy._lan_address = ("127.0.0.1", 1234)
        self.dispersy._endpoint.open(self.dispersy)

        self.dispersy.attach_community(self.market_community)

        eccrypto = ECCrypto()
        ec = eccrypto.generate_key(u"curve25519")
        member = Member(self.dispersy, ec, 1)

        trader_id = hashlib.sha1(member.public_key).digest().encode('hex')
        self.ask = Ask(
            MessageId(TraderId('0'), MessageNumber('message_number')),
            OrderId(TraderId(trader_id), OrderNumber(1234)),
            Price(63400, 'DUM1'), Quantity(30, 'DUM2'), Timeout(3600),
            Timestamp.now())
        self.ask.sign(member)

        self.bid = Bid(
            MessageId(TraderId('1'), MessageNumber('message_number')),
            OrderId(TraderId(trader_id), OrderNumber(1235)),
            Price(343, 'DUM1'), Quantity(22, 'DUM2'), Timeout(3600),
            Timestamp.now())
        self.bid.sign(member)
        self.order = Order(
            OrderId(TraderId(self.market_community.mid), OrderNumber(24)),
            Price(20, 'DUM1'), Quantity(30, 'DUM2'), Timeout(3600.0),
            Timestamp.now(), False)
        self.proposed_trade = Trade.propose(
            MessageId(TraderId('0'), MessageNumber('message_number')),
            OrderId(TraderId('0'), OrderNumber(23)),
            OrderId(TraderId(self.market_community.mid), OrderNumber(24)),
            Price(20, 'DUM1'), Quantity(30, 'DUM2'), Timestamp.now())
コード例 #10
0
    def join_community(self, my_member):
        self.my_member = my_member
        
        master_key = "3081a7301006072a8648ce3d020106052b81040027038192000403cbbfd2dfb67a7db66c88988df56f93fa6e7f982f9a6a0fa8898492c8b8cae23e10b159ace60b7047012082a5aa4c6e221d7e58107bb550436d57e046c11ab4f51f0ab18fa8f58d0346cc12d1cc2b61fc86fe5ed192309152e11e3f02489e30c7c971dd989e1ce5030ea0fb77d5220a92cceb567cbc94bc39ba246a42e215b55e9315b543ddeff0209e916f77c0d747".decode("HEX")
        master = Member.get_instance(master_key)

        assert my_member.public_key
        assert my_member.private_key
        assert master.public_key
        assert not master.private_key

        dprint("-master- ", master.database_id, " ", id(master), " ", master.mid.encode("HEX"), force=1)
        dprint("-my member- ", my_member.database_id, " ", id(my_member), " ", my_member.mid.encode("HEX"), force=1)

        return AllChannelCommunity.join_community(master, my_member, my_member, integrate_with_tribler = False)
コード例 #11
0
    def get_master_members(cls):
#generated: Mon May  7 17:43:59 2012
#curve: high <<< NID_sect571r1 >>>
#len: 571 bits ~ 144 bytes signature
#pub: 170 3081a7301006072a8648ce3d020106052b81040027038192000405c09348b2243e53fa190f17fc8c9843d61fc67e8ea22d7b031913ffc912897b57be780c06213dbf937d87e3ef1d48bf8f76e03d5ec40b1cdb877d9fa1ec1f133a412601c262d9ef01840ffc49d6131b1df9e1eac41a8ff6a1730d4541a64e733ed7cee415b220e4a0d2e8ace5099520bf8896e09cac3800a62974f5574910d75166d6529dbaf016e78090afbfaf8373
#pub-sha1 2782dc9253cef6cc9272ee8ed675c63743c4eb3a
#-----BEGIN PUBLIC KEY-----
#MIGnMBAGByqGSM49AgEGBSuBBAAnA4GSAAQFwJNIsiQ+U/oZDxf8jJhD1h/Gfo6i
#LXsDGRP/yRKJe1e+eAwGIT2/k32H4+8dSL+PduA9XsQLHNuHfZ+h7B8TOkEmAcJi
#2e8BhA/8SdYTGx354erEGo/2oXMNRUGmTnM+187kFbIg5KDS6KzlCZUgv4iW4Jys
#OACmKXT1V0kQ11Fm1lKduvAW54CQr7+vg3M=
#-----END PUBLIC KEY-----
        master_key = "3081a7301006072a8648ce3d020106052b81040027038192000405c09348b2243e53fa190f17fc8c9843d61fc67e8ea22d7b031913ffc912897b57be780c06213dbf937d87e3ef1d48bf8f76e03d5ec40b1cdb877d9fa1ec1f133a412601c262d9ef01840ffc49d6131b1df9e1eac41a8ff6a1730d4541a64e733ed7cee415b220e4a0d2e8ace5099520bf8896e09cac3800a62974f5574910d75166d6529dbaf016e78090afbfaf8373".decode("HEX")
        master = Member(master_key)
        return [master]
コード例 #12
0
    def get_master_members(cls):
# generated: Fri Nov 25 10:51:27 2011
# curve: high <<< NID_sect571r1 >>>
# len: 571 bits ~ 144 bytes signature
# pub: 170 3081a7301006072a8648ce3d020106052b81040027038192000405548a13626683d4788ab19393fa15c9e9d6f5ce0ff47737747fa511af6c4e956f523dc3d1ae8d7b83b850f21ab157dd4320331e2f136aa01e70d8c96df665acd653725e767da9b5079f25cebea808832cd16015815797906e90753d135ed2d796b9dfbafaf1eae2ebea3b8846716c15814e96b93ae0f5ffaec44129688a38ea35f879205fdbe117323e73076561f112
# pub-sha1 8164f55c2f828738fa779570e4605a81fec95c9d
# -----BEGIN PUBLIC KEY-----
# MIGnMBAGByqGSM49AgEGBSuBBAAnA4GSAAQFVIoTYmaD1HiKsZOT+hXJ6db1zg/0
# dzd0f6URr2xOlW9SPcPRro17g7hQ8hqxV91DIDMeLxNqoB5w2Mlt9mWs1lNyXnZ9
# qbUHnyXOvqgIgyzRYBWBV5eQbpB1PRNe0teWud+6+vHq4uvqO4hGcWwVgU6WuTrg
# 9f+uxEEpaIo46jX4eSBf2+EXMj5zB2Vh8RI=
# -----END PUBLIC KEY-----
        master_key = "3081a7301006072a8648ce3d020106052b81040027038192000405548a13626683d4788ab19393fa15c9e9d6f5ce0ff47737747fa511af6c4e956f523dc3d1ae8d7b83b850f21ab157dd4320331e2f136aa01e70d8c96df665acd653725e767da9b5079f25cebea808832cd16015815797906e90753d135ed2d796b9dfbafaf1eae2ebea3b8846716c15814e96b93ae0f5ffaec44129688a38ea35f879205fdbe117323e73076561f112".decode("HEX")
        master = Member(master_key)
        return [master]
コード例 #13
0
ファイル: script.py プロジェクト: ebcabaybay/swiftarm
 def find_peer_by_name(self, peername):
     assert isinstance(peername, str)
     if not peername in self._members:
         with open('data/peers') as fp:
             for line in fp:
                 name, ip, port, public_key, _ = line.split()
                 if name == peername:
                     public_key = public_key.decode("HEX")
                     self._members[name] = (Member(public_key,
                                                   sync_with_database=True),
                                            (ip, int(port)))
                     break
             else:
                 raise ValueError("Node with name '%s' not in nodes db" %
                                  peername)
     return self._members[peername]
コード例 #14
0
 def get_master_members(cls):
     #generated: Mon May  7 17:43:59 2012
     #curve: high <<< NID_sect571r1 >>>
     #len: 571 bits ~ 144 bytes signature
     #pub: 170 3081a7301006072a8648ce3d020106052b81040027038192000405c09348b2243e53fa190f17fc8c9843d61fc67e8ea22d7b031913ffc912897b57be780c06213dbf937d87e3ef1d48bf8f76e03d5ec40b1cdb877d9fa1ec1f133a412601c262d9ef01840ffc49d6131b1df9e1eac41a8ff6a1730d4541a64e733ed7cee415b220e4a0d2e8ace5099520bf8896e09cac3800a62974f5574910d75166d6529dbaf016e78090afbfaf8373
     #pub-sha1 2782dc9253cef6cc9272ee8ed675c63743c4eb3a
     #-----BEGIN PUBLIC KEY-----
     #MIGnMBAGByqGSM49AgEGBSuBBAAnA4GSAAQFwJNIsiQ+U/oZDxf8jJhD1h/Gfo6i
     #LXsDGRP/yRKJe1e+eAwGIT2/k32H4+8dSL+PduA9XsQLHNuHfZ+h7B8TOkEmAcJi
     #2e8BhA/8SdYTGx354erEGo/2oXMNRUGmTnM+187kFbIg5KDS6KzlCZUgv4iW4Jys
     #OACmKXT1V0kQ11Fm1lKduvAW54CQr7+vg3M=
     #-----END PUBLIC KEY-----
     #       master_key = "3081a7301006072a8648ce3d020106052b81040027038192000405c09348b2243e53fa190f17fc8c9843d61fc67e8ea22d7b031913ffc912897b57be780c06213dbf937d87e3ef1d48bf8f76e03d5ec40b1cdb877d9fa1ec1f133a412601c262d9ef01840ffc49d6131b1df9e1eac41a8ff6a1730d4541a64e733ed7cee415b220e4a0d2e8ace5099520bf8896e09cac3800a62974f5574910d75166d6529dbaf016e78090afbfaf8373".decode("HEX")
     master_key = "3081a7301006072a8648ce3d020106052b81040027038192000407a7857439f8a9b29adb351a8cf90e4e79fcf0272c56c23211d0f626621baf3a81346261a8c7d6b1ea3b2a2112eef4fa7e3196bea668577eb2560295b67a67670bc324a2bb7b84a104de819ef872f67dfa6f8cc7ef47ab58a30793df986f7213d4e60e17ec85ab4ec5be6f53bb004f672c5d74d7eb5382e758898382459f636c8a87b39d3448f7d36c1ab21daf185c90".decode(
         "HEX")
     master = Member(master_key)
     return [master]
コード例 #15
0
    def _decode_ping_pong(self, placeholder, offset, data):
        if len(data) < offset + 3:
            raise DropPacket("Insufficient packet size (_decode_ping_pong)")

        key_length, identifier = self._struct_BH.unpack_from(data, offset)
        offset += 3

        if len(data) < offset + key_length:
            raise DropPacket("Insufficient packet size (_decode_ping_pong)")
        try:
            member = Member(data[offset:offset + key_length])
        except:
            raise DropPacket("Invalid public key (_decode_ping_pong)")
        offset += key_length

        return offset, placeholder.meta.payload.Implementation(
            placeholder.meta.payload, identifier, member)
コード例 #16
0
    def run(self):
        ec = ec_generate_key(u"low")
        self._my_member = Member.get_instance(ec_to_public_bin(ec), ec_to_private_bin(ec), sync_with_database=True)

        self.caller(self.test_incoming_barter_record)
コード例 #17
0
 def get_master_members(cls):
     return [Member(MASTER_MEMBER_PUBLIC_KEY)]
コード例 #18
0
ファイル: script.py プロジェクト: ebcabaybay/swiftarm
    def test_incoming_barter_record(self):
        """
        1. Create a record signed only by NODE
        2. Send signature request from NODE to SELF
        3. Receive signature reply from SELF to NODE
        4. Check the signature
        5. Send double signed record from NODE to SELF
        6. Check that the record is stored in the database at SELF
        """
        community = BarterCommunity.create_community(self._my_member)
        address = self._dispersy.socket.get_address()

        # create node and ensure that SELF knows the node address
        node = BarterNode()
        node.init_socket()
        node.set_community(community)
        node.init_my_member()
        yield 0.11
        assert self.is_database_empty(
            community), "Database should be empty (for this community id)"

        # 1. Create a record signed only by NODE
        self_member = Member(community._my_member.public_key,
                             sync_with_database=False)
        record = node.create_barter_record(self_member, 10, 2, 1)

        # 2. Send signature request from NODE to SELF
        request = node.create_dispersy_signature_request_message(
            record, 2, self_member)
        node.send_message(request, address)
        yield 0.11

        # 3. Receive signature reply from SELF to NODE
        # 4. Check the signature
        _, response = node.receive_message(
            addresses=[address],
            message_names=[u"dispersy-signature-response"])
        first_signature_offset = len(record.packet) - sum([
            member.signature_length for member in record.authentication.members
        ])
        identifier = sha1(request.packet).digest()
        assert response.payload.identifier == identifier
        assert self_member.verify(record.packet[:first_signature_offset],
                                  response.payload.signature)

        # 5. Send double signed record from NODE to SELF
        second_signature_offset = len(
            record.packet) - record.authentication.members[1].signature_length
        packet = record.packet[:second_signature_offset] + response.payload.signature
        node.send_packet(packet, address)
        yield 0.11

        # 6. Check that the record is stored in the database at SELF
        try:
            community._database.execute(
                u"SELECT 1 FROM record WHERE community = ? AND global_time = ? AND first_member = ? AND second_member = ? AND upload_first_member = ? AND upload_second_member = ?",
                (community.database_id, 1, node.my_member.database_id,
                 community._my_member.database_id, 10, 2)).next()
        except StopIteration:
            assert False

        # cleanup
        community.create_dispersy_destroy_community(u"hard-kill")
コード例 #19
0
ファイル: script.py プロジェクト: ebcabaybay/swiftarm
    def run(self):
        ec = ec_generate_key(u"low")                    
        self._my_member = Member.get_instance(ec_to_public_bin(ec), ec_to_private_bin(ec), sync_with_database=True)

        self.caller(self.test_incoming_channel_propagate)
        self.caller(self.test_outgoing_channel_propagate)
コード例 #20
0
ファイル: script.py プロジェクト: ebcabaybay/swiftarm
    def run(self):
        if __debug__: log("barter.log", "start-barter-script")
        # this master key NEEDS to be the same as that in BarterTrackerScript as they work together
        master_key = "3081a7301006072a8648ce3d020106052b81040027038192000403cbbfd2dfb67a7db66c88988df56f93fa6e7f982f9a6a0fa8898492c8b8cae23e10b159ace60b7047012082a5aa4c6e221d7e58107bb550436d57e046c11ab4f51f0ab18fa8f58d0346cc12d1cc2b61fc86fe5ed192309152e11e3f02489e30c7c971dd989e1ce5030ea0fb77d5220a92cceb567cbc94bc39ba246a42e215b55e9315b543ddeff0209e916f77c0d747".decode(
            "HEX")

        # remove all trackers.  this experiment may not be contaminated by outside influences
        self._dispersy.database.execute(
            u"DELETE FROM candidate where community=0")
        assert self._dispersy._total_send == 0
        assert self._dispersy._total_received == 0

        self._members = {}
        self.original_on_incoming_packets = self._dispersy.on_incoming_packets
        self.original_send = self._dispersy._send

        def _select_candidate_addresses(community_id, address_count,
                                        diff_range, age_range):
            addresses = set()
            sql = u"""SELECT host, port
                      FROM candidate
                      WHERE community = ?
                      ORDER BY RANDOM()
                      LIMIT ?"""
            addresses.update([
                (str(host), port)
                for host, port in self._dispersy.database.execute(
                    sql, (community_id, address_count - len(addresses)))
            ])

            # return what we have
            if addresses:
                log("dispersy.log", "found-candidates")
            return addresses
            # return set(["1.1.1.1",1111]) # send UDP packet to nowhere

        self._dispersy._select_candidate_addresses = _select_candidate_addresses

        #
        # Read our configuration from the peer.conf file
        # name, ip, port, public and private key
        #
        with open('data/peer.conf') as fp:
            my_name, ip, port, public_key, private_key = fp.readline().split()
            public_key = public_key.decode("HEX")
            private_key = private_key.decode("HEX")
            my_address = (ip, int(port))
        if __debug__: log("barter.log", "read-config-done")

        # create my member
        my_member = Member(public_key, private_key, sync_with_database=True)
        dprint(my_member)
        my_public_key = public_key

        # populate the candidate and user tables
        if __debug__:
            _peer_counter = 0
        # assume that this will be the ID, check after community is joined that the value is correct
        community_database_id = 1
        _peer_ids = {}
        all_peers = []
        execute = self._dispersy.database.execute
        with open('data/peers') as file:
            for index, line in zip(count(), file):
                name, ip, port, public_key, private_key = line.split(' ')
                if __debug__:
                    _peer_counter += 1
                    log("barter.log",
                        "read-peer-config",
                        position=_peer_counter,
                        name=name,
                        ip=ip,
                        port=port)
                port = int(port)
                public_key = public_key.decode('HEX')
                private_key = private_key.strip().decode(
                    "HEX")  # stip to remove newline character
                _peer_ids[public_key] = int(name)
                all_peers.append((index, (ip, port), public_key, private_key))
                if name == my_name: continue

                #self._dispersy._send([(ip, port)], [message.packet])
                execute(
                    u"INSERT OR IGNORE INTO candidate(community, host, port, incoming_time, outgoing_time) VALUES(?, ?, ?, DATETIME(), '2010-01-01 00:00:00')",
                    (community_database_id, unicode(ip), port))
                # execute(u"INSERT OR IGNORE INTO user(mid, public_key, host, port) VALUES(?, ?, ?, ?)", (buffer(sha1(public_key).digest()), buffer(public_key), unicode(ip), port))
                #if __debug__:
                #    log("barter.log", "mid_add", mid=sha1(public_key).digest())

        # join the barter community with the newly created member
        self._barter = BarterCommunity.join_community(
            sha1(master_key).digest(), master_key, my_member)
        assert self._barter.database_id == community_database_id

        self._barter._peer_ids = _peer_ids  # we set this internally in the BarterCommunity object

        # generate and insert all dispersy-identity messages
        incoming_packets = []
        meta = self._barter.get_meta_message(u"dispersy-identity")
        for index, address, public_key, private_key in all_peers:
            temp_member = Member(public_key,
                                 private_key,
                                 sync_with_database=False)
            message = meta.impl(
                authentication=(temp_member, ),
                distribution=(index + 10, ),  # give it a global time
                payload=(address, ))
            incoming_packets.append((address, message.packet))
        self._barter.dispersy.on_incoming_packets(incoming_packets)

        dprint("Joined barter community ", self._barter._my_member)
        if __debug__:
            log("barter.log", "joined-barter-community")
            log("barter.log",
                "barter-community-property",
                name="candidate_request_initial_delay",
                value=self._barter.dispersy_candidate_request_initial_delay)
            log("barter.log",
                "barter-community-property",
                name="candidate_request_interval",
                value=self._barter.dispersy_candidate_request_interval)
            log("barter.log",
                "barter-community-property",
                name="sync_initial_delay",
                value=self._barter.dispersy_sync_initial_delay.__doc__)
            log("barter.log",
                "barter-community-property",
                name="sync_interval",
                value=self._barter.dispersy_sync_interval.__doc__)
            log("barter.log",
                "barter-community-property",
                name="sync_member_count",
                value=self._barter.dispersy_sync_member_count)
            log("barter.log",
                "barter-community-property",
                name="sync_response_limit",
                value=self._barter.dispersy_sync_response_limit)
            log("barter.log",
                "barter-community-property",
                name="timestep",
                value=self._timestep)
            log("barter.log",
                "barter-community-property",
                name="barter_history_size",
                value="unused_(currently_using_FullSyncDistribution)")
            log("barter.log",
                "barter-community-property",
                name="barter_forward_record_on_creation",
                value=self._barter.barter_forward_record_on_creation)
            log("barter.log",
                "barter-community-property",
                name="barter_push_node_count",
                value=self._barter.get_meta_message(
                    u"barter-record").destination.node_count)
            log("barter.log",
                "barter-community-property",
                name="peer_id",
                value=_peer_ids[my_public_key])

        yield 2.0

        if __debug__:
            log("barter.log", "done-reading-peers")

        yield 2.0

        # open the scenario files, as generated from Mircea's Scenario
        # Generator
        bartercast_fp = open('data/bartercast.log')
        availability_fp = open('data/availability.log')

        self._stepcount = 0

        # wait until we reach the starting time
        yield self.sleep(initial_delay=True)

        self._stepcount = 1

        # start the scenario
        while True:
            # get commands
            barter_cmds = self.get_commands_from_fp(bartercast_fp,
                                                    self._stepcount)
            availability_cmds = self.get_commands_from_fp(
                availability_fp, self._stepcount)

            # if there are no commands exit the while loop
            if barter_cmds == -1 and availability_cmds == -1:
                if __debug__: log("barter.log", "no-commands")
                break
            else:
                # if there is a start in the avaibility_cmds then go
                # online
                if availability_cmds != -1 and 'start' in availability_cmds:
                    self.set_online()

                # if there are barter_cmds then execute them
                if barter_cmds != -1:
                    for cmd in barter_cmds:
                        name, up, down = cmd.split()
                        up, down = map(int, (up, down))
                        # note a peer creates a record when it has
                        # interest (e.g. it's upload is larger than
                        # its download)
                        if up >= down:
                            peer_member, address = self.find_peer_by_name(name)
                            self._barter.create_barter_record(
                                peer_member, up, down)

                # if there is a stop in the availability_cmds then go
                # offline
                if availability_cmds != -1 and 'stop' in availability_cmds:
                    self.set_offline()

            # sleep until the next step
            delay = self.sleep()
            if delay >= 0.0:
                yield delay
            else:
                break
            self._stepcount += 1

        # I finished the scenario execution. I should stay online
        # until killed. Note that I can still sync and exchange
        # messages with other peers.
        delay = self.sleep()
        while delay >= 0.0:
            # wait to be killed
            yield 5.0

        while True:
            now = time.time()
            if now >= self._shutdown_timestamp:
                break
            yield 5.0