当前位置: 首页>>代码示例>>Python>>正文


Python DHT.add_known_node方法代码示例

本文整理汇总了Python中dht.DHT.add_known_node方法的典型用法代码示例。如果您正苦于以下问题:Python DHT.add_known_node方法的具体用法?Python DHT.add_known_node怎么用?Python DHT.add_known_node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在dht.DHT的用法示例。


在下文中一共展示了DHT.add_known_node方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: CryptoTransportLayer

# 需要导入模块: from dht import DHT [as 别名]
# 或者: from dht.DHT import add_known_node [as 别名]

#.........这里部分代码省略.........
        else:
            # Known peer
            if pub:
                # test if we have to update the pubkey
                if not self.peers[uri].pub:
                    self.log.info("Setting public key for seed node")
                    self.peers[uri].pub = pub.decode('hex')
                    self.trigger_callbacks('peer', self.peers[uri])

                if self.peers[uri].pub != pub.decode('hex'):
                    self.log.info("Updating public key for node")
                    self.peers[uri].nickname = nickname
                    self.peers[uri].pub = pub.decode('hex')

                    self.trigger_callbacks('peer', self.peers[uri])

            if msg_type == 'hello_request':
                # reply only if necessary
                self.send_enc(uri, hello_response(self.get_profile()))

    def _on_message(self, msg):

        # here goes the application callbacks
        # we get a "clean" msg which is a dict holding whatever
        # self.log.info("[On Message] Data received: %s" % msg)

        pubkey = msg.get('pubkey')
        uri = msg.get('uri')
        ip = urlparse(uri).hostname
        port = urlparse(uri).port
        guid = msg.get('senderGUID')
        nickname = msg.get('senderNick')[:120]

        self.dht.add_known_node((ip, port, guid, nickname))
        self.log.info('On Message: %s' % json.dumps(msg, ensure_ascii=False))
        self.dht.add_peer(self, uri, pubkey, guid, nickname)
        t = Thread(target=self.trigger_callbacks, args=(msg['type'], msg,))
        t.start()

    def _on_raw_message(self, serialized):
        try:

            msg = json.loads(serialized)
            self.log.info("Message Received [%s]" % msg.get('type', 'unknown'))

            if msg.get('type') is None:

                data = msg.get('data').decode('hex')
                sig = msg.get('sig').decode('hex')

                try:
                    cryptor = makePrivCryptor(self.secret)

                    try:
                        data = cryptor.decrypt(data)
                    except Exception as e:
                        self.log.info('Exception: %s' % e)

                    self.log.debug('Signature: %s' % sig.encode('hex'))
                    self.log.debug('Signed Data: %s' % data)

                    # Check signature
                    data_json = json.loads(data)
                    sigCryptor = makePubCryptor(data_json['pubkey'])
                    if sigCryptor.verify(sig, data):
                        self.log.info('Verified')
开发者ID:BombazineDoll,项目名称:OpenBazaar,代码行数:70,代码来源:transport.py

示例2: CryptoTransportLayer

# 需要导入模块: from dht import DHT [as 别名]
# 或者: from dht.DHT import add_known_node [as 别名]

#.........这里部分代码省略.........
        if uri not in self._peers:
            # Unknown peer
            self._log.info('Add New Peer: %s' % uri)
            self.create_peer(uri, pub, guid)

            if not msg_type:
                self.send_enc(uri, hello_request(self.get_profile()))
            elif msg_type == 'hello_request':
                self.send_enc(uri, hello_response(self.get_profile()))

        else:
            # Known peer
            if pub:
                # test if we have to update the pubkey
                if not self._peers[uri]._pub:
                    self._log.info("Setting public key for seed node")
                    self._peers[uri]._pub = pub.decode('hex')
                    self.trigger_callbacks('peer', self._peers[uri])

                if self._peers[uri]._pub != pub.decode('hex'):
                    self._log.info("Updating public key for node")
                    self._peers[uri]._nickname = nickname
                    self._peers[uri]._pub = pub.decode('hex')

                    self.trigger_callbacks('peer', self._peers[uri])

            if msg_type == 'hello_request':
                # reply only if necessary
                self.send_enc(uri, hello_response(self.get_profile()))



    def on_message(self, msg):

        # here goes the application callbacks
        # we get a "clean" msg which is a dict holding whatever
        self._log.info("[On Message] Data received: %s" % msg)

        pubkey = msg.get('pubkey')
        uri = msg.get('uri')
        ip = urlparse(uri).hostname
        port = urlparse(uri).port
        guid = msg.get('senderGUID')

        self._dht.add_active_peer(self, (pubkey, uri, guid))
        self._dht.add_known_node((ip, port, guid))

        self.trigger_callbacks(msg['type'], msg)


    def on_raw_message(self, serialized):

        try:
            # Try to deserialize cleartext message
            msg = json.loads(serialized)
            self._log.info("Message Received [%s]" % msg.get('type', 'unknown'))

        except ValueError:
            try:
                # Encrypted?
                try:
                  msg = self._myself.decrypt(serialized)
                  msg = json.loads(msg)

                  self._log.info("Decrypted Message [%s]"
                               % msg.get('type', 'unknown'))
                except:
                  self._log.error("Could not decrypt message: %s" % msg)
                  return
            except:
                self._log.info("Bad Message: %s..."
                               % self._myself.decrypt(serialized))
                traceback.print_exc()
                return

        if msg.get('type') != '':

          msg_type = msg.get('type')
          msg_uri = msg.get('uri')
          msg_guid = msg.get('guid')

          self._log.info(msg.get('type'))

          #
          # if msg_type.startswith('hello') and msg_uri:
          #     self.init_peer(msg)
          #     for uri, pub in msg.get('peers', {}).iteritems():
          #         # Do not add yourself as a peer
          #         if uri != self._uri:
          #             self.init_peer({'uri': uri, 'pub': pub})
          #     self._log.info("Update peer table [%s peers]" % len(self._peers))
          #
          # elif msg_type == 'goodbye' and msg_uri:
          #     self._log.info("Received goodbye from %s" % msg_uri)
          #     self.remove_peer(msg_uri)
          #
          # else:
          self.on_message(msg)
        else:
          self._log.error('Received a message with no type')
开发者ID:RagnarDanneskjold,项目名称:OpenBazaar,代码行数:104,代码来源:crypto2crypto.py

示例3: CryptoTransportLayer

# 需要导入模块: from dht import DHT [as 别名]
# 或者: from dht.DHT import add_known_node [as 别名]

#.........这里部分代码省略.........

        for seed in seed_peers:
            self._log.info('Initializing Seed Peer(s): [%s]' % seed)

            def cb(msg):
                self._dht._iterativeFind(self._guid, self._dht._knownNodes, 'findNode')
                callback(msg)

            self.connect('tcp://%s:12345' % seed, callback=cb)

        # Try to connect to known peers
        known_peers = self._db.peers.find()
        for known_peer in known_peers:
            def cb(msg):
                #self._dht._iterativeFind(self._guid, self._dht._knownNodes, 'findNode')
                callback(msg)

            self.connect(known_peer['uri'], callback=cb)


        # self.listen(self.pubkey) # Turn on zmq socket
        #
        # if seed_uri:
        #     self._log.info('Initializing Seed Peer(s): [%s]' % seed_uri)
        #     seed_peer = CryptoPeerConnection(self, seed_uri)
        #     self._dht.start(seed_peer)

    def connect(self, uri, callback):

        def cb(msg):
            ip = urlparse(uri).hostname
            port = urlparse(uri).port

            self._dht.add_known_node((ip, port, peer._guid))



            # Turning off peers
            #self._init_peer({'uri': seed_uri, 'guid':seed_guid})

            # Add to routing table
            #self.addCryptoPeer(peer)

            callback(msg)

        peer = CryptoPeerConnection(self, uri, callback=cb)

        return peer


    def get_crypto_peer(self, guid, uri, pubkey=None, nickname=None):

      if guid == self.guid:
        self._log.info('Trying to get crypto peer for yourself')
        return

      self._log.info('%s %s %s %s' % (guid, uri, pubkey, nickname))

      peer = CryptoPeerConnection(self, uri, pubkey, guid=guid, nickname=nickname)
      return peer

    def addCryptoPeer(self, peer_to_add):

        foundOutdatedPeer = False
        for idx, peer in enumerate(self._dht._activePeers):
开发者ID:benhc123,项目名称:OpenBazaar,代码行数:69,代码来源:crypto2crypto.py

示例4: CryptoTransportLayer

# 需要导入模块: from dht import DHT [as 别名]
# 或者: from dht.DHT import add_known_node [as 别名]

#.........这里部分代码省略.........
      self._db.settings.update({"id":'%s' % self._market_id}, {"$set": {"secret":self.secret, "pubkey":self.pubkey, "guid":self.guid}}, True)

    def _generate_new_bitmessage_address(self):
      # Use the guid generated previously as the key
      self.bitmessage = self._bitmessage_api.createRandomAddress(self.guid.encode('base64'), 
            False, 1.05, 1.1111)
      self._db.settings.update({"id":'%s' % self._market_id}, {"$set": {"bitmessage":self.bitmessage}}, True)


    def join_network(self, seed_uri, callback=lambda msg: None):

        if seed_uri:
            self._log.info('Initializing Seed Peer(s): [%s]' % (seed_uri))

            def cb(msg):
                self._dht._iterativeFind(self._guid, self._dht._knownNodes, 'findNode')
                callback(msg)

            self.connect(seed_uri, callback=cb)

        # self.listen(self.pubkey) # Turn on zmq socket
        #
        # if seed_uri:
        #     self._log.info('Initializing Seed Peer(s): [%s]' % seed_uri)
        #     seed_peer = CryptoPeerConnection(self, seed_uri)
        #     self._dht.start(seed_peer)

    def connect(self, uri, callback):

        def cb(msg):
            ip = urlparse(uri).hostname
            port = urlparse(uri).port

            self._dht.add_known_node((ip, port, peer._guid))

            # Turning off peers
            #self.init_peer({'uri': seed_uri, 'guid':seed_guid})

            # Add to routing table
            self.addCryptoPeer(peer)
            callback(msg)

        peer = CryptoPeerConnection(self, uri, callback=cb)

        return peer


    def get_crypto_peer(self, guid, uri, pubkey=None):

      if guid == self.guid:
        self._log.info('Trying to get cryptopeer for yourself')
        return

      peer = CryptoPeerConnection(self, uri, pubkey, guid=guid)
      return peer

    def addCryptoPeer(self, peer_to_add):

        foundOutdatedPeer = False
        for idx, peer in enumerate(self._dht._activePeers):

            if (peer._address, peer._guid, peer._pub) == (peer_to_add._address, peer_to_add._guid, peer_to_add._pub):
                self._log.info('Found existing peer, not adding.')
                return

            if peer._guid == peer_to_add._guid or peer._pub == peer_to_add._pub or peer._address == peer_to_add._address:
开发者ID:Artea,项目名称:OpenBazaar,代码行数:70,代码来源:crypto2crypto.py


注:本文中的dht.DHT.add_known_node方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。