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


Python KeyChain.setFace方法代码示例

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


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

示例1: main

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import setFace [as 别名]
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage), None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

    echo = Echo(keyChain, certificateName)
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while echo._responseCount < 1:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)    

    face.shutdown()
开发者ID:bboalimoe,项目名称:PyNDN2,代码行数:31,代码来源:test_publish_async_ndnx.py

示例2: main

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import setFace [as 别名]
def main():
    face = Face("localhost")

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage), None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-reposerver")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER)

    echo = RepoServer(keyChain, certificateName)
    prefix = Name("/ndn/ucla.edu/bms")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while True: 
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
开发者ID:remap,项目名称:BMS-REPO,代码行数:30,代码来源:server.py

示例3: BaseNode

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import setFace [as 别名]
class BaseNode(object):
    """
    This class contains methods/attributes common to both node and controller.
    
    """
    def __init__(self):
        """
        Initialize the network and security classes for the node
        """
        super(BaseNode, self).__init__()

        self._identityStorage = IotIdentityStorage()
        self._identityManager = IotIdentityManager(self._identityStorage)
        self._policyManager = IotPolicyManager(self._identityStorage)

        # hopefully there is some private/public key pair available
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._registrationFailures = 0
        self._prepareLogging()

        self._setupComplete = False
        self._instanceSerial = None

        # waiting devices register this prefix and respond to discovery
        # or configuration interest
        self._hubPrefix = Name('/localhop/configure')

    def getSerial(self):
        """
         Since you may wish to run two nodes on a Raspberry Pi, each
         node will generate a unique serial number each time it starts up.
        """
        if self._instanceSerial is None:
            prefixLen = 4
            prefix = ''
            for i in range(prefixLen):
                prefix += (chr(random.randint(0,0xff)))
            suffix = self.getDeviceSerial().lstrip('0')
            self._instanceSerial = '-'.join([prefix.encode('hex'), suffix])
        return self._instanceSerial

##
# Logging
##
    def _prepareLogging(self):
        self.log = logging.getLogger(str(self.__class__))
        self.log.setLevel(logging.DEBUG)
        logFormat = "%(asctime)-15s %(name)-20s %(funcName)-20s (%(levelname)-8s):\n\t%(message)s"
        self._console = logging.StreamHandler()
        self._console.setFormatter(logging.Formatter(logFormat))
        self._console.setLevel(logging.INFO)
        # without this, a lot of ThreadsafeFace errors get swallowed up
        logging.getLogger("trollius").addHandler(self._console)
        self.log.addHandler(self._console)

    def setLogLevel(self, level):
        """
        Set the log level that will be output to standard error
        :param level: A log level constant defined in the logging module (e.g. logging.INFO) 
        """
        self._console.setLevel(level)

    def getLogger(self):
        """
        :return: The logger associated with this node
        :rtype: logging.Logger
        """
        return self.log

###
# Startup and shutdown
###
    def beforeLoopStart(self):
        """
        Called before the event loop starts.
        """
        pass

    def getDefaultCertificateName(self):
        try:
            certName = self._identityStorage.getDefaultCertificateNameForIdentity( 
                self._policyManager.getDeviceIdentity())
        except SecurityException:
            certName = self._keyChain.getDefaultCertificateName()

        return certName

    def start(self):
        """
        Begins the event loop. After this, the node's Face is set up and it can
        send/receive interests+data
        """
        self.log.info("Starting up")
        self.loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(self.loop, '')
        self.face.setCommandSigningInfo(self._keyChain, self.getDefaultCertificateName())
        self._keyChain.setFace(self.face)

        self._isStopped = False
#.........这里部分代码省略.........
开发者ID:RayneHwang,项目名称:ndn-pi,代码行数:103,代码来源:base_node.py

示例4: IotConsole

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import setFace [as 别名]
class IotConsole(object):
    """
    This uses the controller's credentials to provide a management interface
    to the user.
    It does not go through the security handshake (as it should be run on the
    same device as the controller) and so does not inherit from the BaseNode.
    """

    def __init__(self, networkName, nodeName):
        super(IotConsole, self).__init__()

        self.deviceSuffix = Name(nodeName)
        self.networkPrefix = Name(networkName)
        self.prefix = Name(self.networkPrefix).append(self.deviceSuffix)

        self._identityStorage = IotIdentityStorage()
        self._policyManager = IotPolicyManager(self._identityStorage)
        self._identityManager = IotIdentityManager(self._identityStorage)
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._policyManager.setEnvironmentPrefix(self.networkPrefix)
        self._policyManager.setTrustRootIdentity(self.prefix)
        self._policyManager.setDeviceIdentity(self.prefix)
        self._policyManager.updateTrustRules()

        self.foundCommands = {}
        self.unconfiguredDevices = []

        # TODO: use xDialog in XWindows
        self.ui = Dialog(backtitle="NDN IoT User Console", height=18, width=78)

        trolliusLogger = logging.getLogger("trollius")
        trolliusLogger.addHandler(logging.StreamHandler())

    def start(self):
        """
        Start up the UI
        """
        self.loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(self.loop, "")

        controllerCertificateName = self._identityStorage.getDefaultCertificateNameForIdentity(self.prefix)
        self.face.setCommandSigningInfo(self._keyChain, controllerCertificateName)
        self._keyChain.setFace(self.face)  # shouldn't be necessarym but doesn't hurt

        self._isStopped = False
        self.face.stopWhen(lambda: self._isStopped)

        self.loop.call_soon(self.displayMenu)
        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            pass
        except Exception as e:
            print(e)
            # self.log('Exception', e)
        finally:
            self._isStopped = True

    def stop(self):
        self._isStopped = True

    #######
    # GUI
    #######

    def displayMenu(self):

        menuOptions = OrderedDict(
            [
                ("List network services", self.listCommands),
                ("Pair a device", self.pairDevice),
                ("Express interest", self.expressInterest),
                ("Quit", self.stop),
            ]
        )
        (retCode, retStr) = self.ui.mainMenu("Main Menu", menuOptions.keys())

        if retCode == Dialog.DIALOG_ESC or retCode == Dialog.DIALOG_CANCEL:
            # TODO: ask if you're sure you want to quit
            self.stop()
        if retCode == Dialog.DIALOG_OK:
            menuOptions[retStr]()

    #######
    # List all commands
    ######
    def listCommands(self):
        self._requestDeviceList(self._showCommandList, self.displayMenu)

    def _requestDeviceList(self, successCallback, timeoutCallback):
        self.ui.alert("Requesting services list...", False)
        interestName = Name(self.prefix).append("listCommands")
        interest = Interest(interestName)
        interest.setInterestLifetimeMilliseconds(3000)
        # self.face.makeCommandInterest(interest)
        self.face.expressInterest(
            interest,
            self._makeOnCommandListCallback(successCallback),
            self._makeOnCommandListTimeoutCallback(timeoutCallback),
#.........这里部分代码省略.........
开发者ID:RayneHwang,项目名称:ndn-pi,代码行数:103,代码来源:iot_console.py

示例5: NaiveEDLParserAndPublisher

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import setFace [as 别名]
class NaiveEDLParserAndPublisher(object):
    def __init__(self, applyEDLAdjustment=True):
        # prepare trollius logging
        self.prepareLogging()

        self._events = dict()
        self._running = False
        self._applyEDLAdjustment = applyEDLAdjustment

        # NDN related variables
        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop)

        # Use the system default key chain and certificate name to sign commands.
        self._keyChain = KeyChain()
        self._keyChain.setFace(self._face)
        self._certificateName = self._keyChain.getDefaultCertificateName()
        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
        self._memoryContentCache = MemoryContentCache(self._face)

        # Publishing parameters conf  iguration
        self._translationServiceUrl = "http://the-archive.la/losangeles/services/get-youtube-url"
        self._namePrefixString = "/ndn/edu/ucla/remap/test/edl/"

        self._dataLifetime = 2000
        self._publishBeforeSeconds = 3
        self._translateBeforeSeconds = 60
        self._currentIdx = 0

        # Youtube related variables:
        # Channel Global song: UCSMJaKICZKXkpvr7Gj8pPUg
        # Channel Los Angeles: UCeuQoBBzMW6SWkxd8_1I8NQ
        # self._channelID = 'UCSMJaKICZKXkpvr7Gj8pPUg'
        self._channelID = "UCSMJaKICZKXkpvr7Gj8pPUg"
        self._accessKey = "AIzaSyCe8t7PnmWjMKZ1gBouhP1zARpqNwHAs0s"
        # queryStr = 'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics,status&key=' + apiKey + '&id='
        # Video query example
        # https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics,status&key=AIzaSyDUY_AX1iJQcwCW1mASEp5GcLtq1V9BM1Q&id=_ebELPKANxo
        # Channel query example
        # https://www.googleapis.com/youtube/v3/search?key=AIzaSyCe8t7PnmWjMKZ1gBouhP1zARpqNwHAs0s&channelId=UCSMJaKICZKXkpvr7Gj8pPUg&part=snippet,id&order=date&maxResults=20
        self._videoUrlDict = dict()

        self._edlAdjustmentDict = dict()
        return

    def getClipUrlOAuth(self):
        self._videoUrlDict = dict((k.lower(), v) for k, v in getAllVideosFromChannel().iteritems())

    # Old getClipUrl function that looks at the public Youtube channel without using Python API
    def getClipUrl(self, nextPageToken=None):
        options = {"part": "snippet,id", "order": "date", "maxResults": "20"}
        if nextPageToken is not None:
            options["pageToken"] = nextPageToken
        prefix = "https://www.googleapis.com/youtube/v3/search?"

        queryUrl = prefix + "key=" + self._accessKey + "&channelId=" + self._channelID
        for item in options:
            queryUrl += "&" + item + "=" + options[item]
        result = json.loads(urllib.urlopen(queryUrl).read())
        for item in result["items"]:
            if "snippet" in item and "id" in item and "videoId" in item["id"]:
                self._videoUrlDict[item["snippet"]["title"].lower()] = item["id"]["videoId"]
            else:
                print("Unexpected JSON from youtube channel query")
        if "nextPageToken" in result:
            self.getClipUrl(result["nextPageToken"])
        else:
            if __debug__:
                print("Building videoUrl dict finished; number of entries: " + str(len(self._videoUrlDict)))
                # for item in self._videoUrlDict:
                #  print("* " + item)
        return

    def parse(self, fileName):
        isEventBegin = False
        lastEventID = -1
        with open(fileName, "r") as edlFile:
            for line in edlFile:
                if isEventBegin:
                    components = line.split()
                    try:
                        eventID = int(components[0])
                    except ValueError:
                        print("Cannot cast " + components[0] + " to eventID")
                        continue
                    # We seem to have a fixed number of components here;
                    # reference: http://www.edlmax.com/maxguide.html
                    reelName = components[1]
                    channel = components[2]
                    trans = components[3]

                    timeComponentsIdx = len(components) - 4

                    srcStartTime = components[timeComponentsIdx]
                    srcEndTime = components[timeComponentsIdx + 1]
                    dstStartTime = components[timeComponentsIdx + 2]
                    dstEndTime = components[timeComponentsIdx + 3]

                    self._events[eventID] = json.loads(
                        '{ \
#.........这里部分代码省略.........
开发者ID:peetonn,项目名称:EDL-parser,代码行数:103,代码来源:test_edl_parser.py

示例6: BaseNode

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import setFace [as 别名]
class BaseNode(object):
    """
    This class contains methods/attributes common to both node and controller.
    """
    def __init__(self, transport = None, conn = None):
        """
        Initialize the network and security classes for the node
        """
        super(BaseNode, self).__init__()
        self.faceTransport = transport
        self.faceConn = conn
        
        self._identityStorage = BasicIdentityStorage()

        self._identityManager = IdentityManager(self._identityStorage, FilePrivateKeyStorage())
        self._policyManager = IotPolicyManager(self._identityStorage)

        # hopefully there is some private/public key pair available
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._registrationFailures = 0
        self._prepareLogging()

        self._setupComplete = False


##
# Logging
##
    def _prepareLogging(self):
        self.log = logging.getLogger(str(self.__class__))
        self.log.setLevel(logging.DEBUG)
        logFormat = "%(asctime)-15s %(name)-20s %(funcName)-20s (%(levelname)-8s):\n\t%(message)s"
        self._console = logging.StreamHandler()
        self._console.setFormatter(logging.Formatter(logFormat))
        self._console.setLevel(logging.INFO)
        # without this, a lot of ThreadsafeFace errors get swallowed up
        logging.getLogger("trollius").addHandler(self._console)
        self.log.addHandler(self._console)

    def setLogLevel(self, level):
        """
        Set the log level that will be output to standard error
        :param level: A log level constant defined in the logging module (e.g. logging.INFO) 
        """
        self._console.setLevel(level)

    def getLogger(self):
        """
        :return: The logger associated with this node
        :rtype: logging.Logger
        """
        return self.log

###
# Startup and shutdown
###
    def beforeLoopStart(self):
        """
        Called before the event loop starts.
        """
        pass

    def getDefaultCertificateName(self):
        try:
            certName = self._identityStorage.getDefaultCertificateNameForIdentity( 
                self._policyManager.getDeviceIdentity())
        except SecurityException as e:
            # zhehao: in the case of producer's /localhop prefixes, the default key is not defined in ndnsec-public-info.db
            certName = self._keyChain.createIdentityAndCertificate(self._policyManager.getDeviceIdentity())
            #certName = self._keyChain.getDefaultCertificateName()
            #print(certName.toUri())
        return certName

    def start(self):
        """
        Begins the event loop. After this, the node's Face is set up and it can
        send/receive interests+data
        """
        self.log.info("Starting up")
        self.loop = asyncio.get_event_loop()
        
        if (self.faceTransport == None or self.faceTransport == ''):
            self.face = ThreadsafeFace(self.loop)
        else:
            self.face = ThreadsafeFace(self.loop, self.faceTransport, self.faceConn)
        
        self.face.setCommandSigningInfo(self._keyChain, self.getDefaultCertificateName())
        
        self._keyChain.setFace(self.face)

        self._isStopped = False
        self.beforeLoopStart()
        
        try:
            self.loop.run_forever()
        except Exception as e:
            self.log.exception(exc_info=True)
        finally:
            self.stop()
#.........这里部分代码省略.........
开发者ID:remap,项目名称:ndn-flow,代码行数:103,代码来源:base_node.py

示例7: Bootstrap

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import setFace [as 别名]
class Bootstrap(object):
    """
    Create a Bootstrap object. Bootstrap object provides interface for setting up KeyChain, default certificate name;
    (as a producer) requesting publishing authorization from controller; and (as a consumer) keeping track of changes

    :param face: the face for communicating with a local / remote forwarder
    :type face: ThreadsafeFace

    TODO: support Face as well as ThreadsafeFace
    """
    def __init__(self, face):
        self._defaultIdentity = None
        self._defaultCertificateName = None
        
        self._controllerName = None
        self._controllerCertificate = None

        self._applicationName = ""

        self._identityManager = IdentityManager(BasicIdentityStorage(), FilePrivateKeyStorage())

        self._policyManager = ConfigPolicyManager()
        self._policyManager.config.read("validator \n \
            {                                      \n \
              rule                                 \n \
              {                                    \n \
                id \"initial rule\"                \n \
                for data                           \n \
                checker                            \n \
                {                                  \n \
                  type hierarchical                \n \
                }                                  \n \
              }                                    \n \
            }", "initial-schema")
        # keyChain is what we return to the application after successful setup
        # TODO: should we separate keyChain from internal KeyChain used to verify trust schemas?
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._face = face
        # setFace for keyChain or else it won't be able to express interests for certs
        self._keyChain.setFace(self._face)
        self._certificateContentCache = MemoryContentCache(face)
        
        self._trustSchemas = dict()

###############################################
# Initial keyChain and defaultCertificate setup
###############################################
    def setupDefaultIdentityAndRoot(self, defaultIdentityOrFileName, signerName = None, onSetupComplete = None, onSetupFailed = None):
        """
        Sets up the keyChain, default key name and certificate name according to given 
        configuration. If successful, this KeyChain and default certificate name will be 
        returned to the application, which can be passed to instances like Consumer, Discovery, etc

        :param defaultIdentityOrFileName: if str, the name of the configuration file; if Name, 
          the default identity name of this IoT node. The node will use the default keys and 
          certificate of that identity name.
        :type defaultIdentityOrFileName: Name or str
        :param signerName: (optional) the expected signing identity of the certificate
        :type signerName: Name
        :param onSetupComplete: (optional) onSetupComplete(Name, KeyChain) will be called if 
          set up's successful
        :type onSetupComplete: function object
        :param onSetupFailed: (optional) onSetupFailed(msg) will be called if setup fails
        :type onSetupFailed: function object
        """
        def helper(identityName, signerName):
            try:
                self._defaultIdentity = identityName
                self._defaultCertificateName = self._identityManager.getDefaultCertificateNameForIdentity(self._defaultIdentity)
                self._defaultKeyName = self._identityManager.getDefaultKeyNameForIdentity(identityName)
            except SecurityException:
                msg = "Identity " + identityName.toUri() + " in configuration does not exist. Please configure the device with this identity first."
                if onSetupFailed:
                    onSetupFailed(msg)
                return

            if not self._defaultCertificateName:
                msg = "Unable to get default certificate name for identity " + identityName.toUri() + ". Please configure the device with this identity first."
                if onSetupFailed:
                    onSetupFailed(msg)
                return

            if not self._defaultKeyName:
                msg = "Unable to get default key name for identity " + identityName.toUri() + ". Please configure the device with this identity first."
                if onSetupFailed:
                    onSetupFailed(msg)
                return
            
            # Note we'll not be able to issue face commands before this point
            self._face.setCommandSigningInfo(self._keyChain, self._defaultCertificateName)
            # Serve our own certificate
            self._certificateContentCache.registerPrefix(Name(self._defaultCertificateName).getPrefix(-1), self.onRegisterFailed)
            self._certificateContentCache.add(self._keyChain.getCertificate(self._defaultCertificateName))

            actualSignerName = self._keyChain.getCertificate(self._defaultCertificateName).getSignature().getKeyLocator().getKeyName()    
            if not signerName:
                print "Deriving from " + actualSignerName.toUri() + " for controller name"
            else:
                if signerName and actualSignerName.toUri() != signerName.toUri():
#.........这里部分代码省略.........
开发者ID:remap,项目名称:ndn-flow,代码行数:103,代码来源:bootstrap.py

示例8: BmsNode

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import setFace [as 别名]
class BmsNode(object):
    def __init__(self):
        self.conf = None
        self._keyChain = None
        self._certificateName = None

        self._dataQueue = dict()
        self._memoryContentCache = None
        self._identityName = None

        self._aggregation = Aggregation()

    def setConfiguration(self, fileName, trustSchemaFile):
        self.conf = BoostInfoParser()
        self.conf.read(fileName)
        self._identityName = Name(self.conf.getNodePrefix())
        self._trustSchemaFile = trustSchemaFile

    def onDataNotFound(self, prefix, interest, face, interestFilterId, filter):
        #print('Data not found for ' + interest.getName().toUri())
        return

    def startPublishing(self):
        # One-time security setup
        self.prepareLogging()

        privateKeyStorage = FilePrivateKeyStorage()
        identityStorage = BasicIdentityStorage()
        policyManager = ConfigPolicyManager(self._trustSchemaFile)

        self._keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), policyManager)
        self._certificateName = self._keyChain.createIdentityAndCertificate(self._identityName)

        print("My Identity name: " + self._identityName.toUri())
        print("My certificate name: " + self._certificateName.toUri())
        certificateData = self._keyChain.getIdentityManager()._identityStorage.getCertificate(self._certificateName, True)
        print("My certificate string: " + b64encode(certificateData.wireEncode().toBuffer()))
        # self._keyChain.getIdentityCertificate(self._certificateName).)

        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop)
        self._keyChain.setFace(self._face)

        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
        self._memoryContentCache = MemoryContentCache(self._face)

        # We should only ask for cert to be signed upon the first run of a certain aggregator
        if DO_CERT_SETUP:
            if (KeyLocator.getFromSignature(certificateData.getSignature()).getKeyName().equals(self._certificateName.getPrefix(-1))):
                # Need to configure for mini-ndn; aggregation node runs outside of mini-ndn first so that signed cert get installed and mini-ndn won't ask for this again
                print("certificate " + self._certificateName.toUri() + " asking for signature")
                response = urllib2.urlopen("http://192.168.56.1:5000/bms-cert-hack?cert=" + b64encode(certificateData.wireEncode().toBuffer()) + "&cert_prefix=" + self._identityName.toUri() + '&subject_name=' + self._identityName.toUri()).read()
                
                signedCertData = Data()
                signedCertData.wireDecode(Blob(b64decode(response)))

                self._memoryContentCache.add(signedCertData)
                cmdline = ['ndnsec-install-cert', '-']
                p = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
                # desanitize + sign in GET request
                cert, err = p.communicate(response)
                if p.returncode != 0:
                    raise RuntimeError("ndnsec-install-cert error")
            else:
                self._memoryContentCache.add(certificateData)
        else:
            self._memoryContentCache.add(certificateData)

        dataNode = self.conf.getDataNode()
        childrenNode = self.conf.getChildrenNode()

        self._memoryContentCache.registerPrefix(Name(self._identityName), self.onRegisterFailed, self.onDataNotFound)

        # For each type of data, we refresh each type of aggregation according to the interval in the configuration
        for i in range(len(dataNode.subtrees)):
            dataType = dataNode.subtrees.keys()[i]
            aggregationParams = self.conf.getProducingParamsForAggregationType(dataNode.subtrees.items()[i][1])

            if childrenNode == None:
                self._dataQueue[dataType] = DataQueue(None, None, None)
                self.generateData(dataType, 2, 0)

            for aggregationType in aggregationParams:
                childrenList = OrderedDict()
                if childrenNode != None:

                    for j in range(len(childrenNode.subtrees)):
                        if dataType in childrenNode.subtrees.items()[j][1].subtrees['data'].subtrees:
                            if aggregationType in childrenNode.subtrees.items()[j][1].subtrees['data'].subtrees[dataType].subtrees:
                                childrenList[childrenNode.subtrees.items()[j][0]] = self.conf.getProducingParamsForAggregationType(childrenNode.subtrees.items()[j][1].subtrees['data'].subtrees[dataType])[aggregationType]

                self.startPublishingAggregation(aggregationParams[aggregationType], childrenList, dataType, aggregationType)
        return

    def startPublishingAggregation(self, params, childrenList, dataType, aggregationType):
        if __debug__:
            print('Start publishing for ' + dataType + '-' + aggregationType)
        
        # aggregation calculating and publishing mechanism
        publishingPrefix = Name(self._identityName).append(DATA_COMPONENT).append(dataType).append(AGGREGATION_COMPONENT).append(aggregationType)
#.........这里部分代码省略.........
开发者ID:zhehaowang,项目名称:bms-node,代码行数:103,代码来源:bms_node.py


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