def test_find_by_interest(self): self.anchorContainer.insert("group1", self.certificatePath1, 400.0) interest = Interest(self.identity1.getName()) self.assertTrue(self.anchorContainer.find(interest) != None) interest1 = Interest(self.identity1.getName().getPrefix(-1)) self.assertTrue(self.anchorContainer.find(interest1) != None) interest2 = Interest(Name(self.identity1.getName()).appendVersion(1)) self.assertTrue(self.anchorContainer.find(interest2) == None) certificate3 = self.fixture.addCertificate( self.identity1.getDefaultKey(), "3") certificate4 = self.fixture.addCertificate( self.identity1.getDefaultKey(), "4") certificate5 = self.fixture.addCertificate( self.identity1.getDefaultKey(), "5") certificate3Copy = CertificateV2(certificate3) self.anchorContainer.insert("group2", certificate3Copy) self.anchorContainer.insert("group3", certificate4) self.anchorContainer.insert("group4", certificate5) interest3 = Interest(certificate3.getKeyName()) foundCertificate = self.anchorContainer.find(interest3) self.assertTrue(foundCertificate != None) self.assertTrue(interest3.getName().isPrefixOf(foundCertificate.getName())) self.assertTrue(certificate3.getName().equals(foundCertificate.getName())) interest3.getExclude().appendComponent( certificate3.getName().get(CertificateV2.ISSUER_ID_OFFSET)) foundCertificate = self.anchorContainer.find(interest3) self.assertTrue(foundCertificate != None) self.assertTrue(interest3.getName().isPrefixOf(foundCertificate.getName())) self.assertTrue(not foundCertificate.getName().equals(certificate3.getName()))
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) self._dataQueue[dataType + aggregationType] = DataQueue(params, childrenList, publishingPrefix) if len(childrenList.keys()) == 0: # TODO: make start_time optional for leaf nodes self._loop.call_later(int(params['producer_interval']), self.calculateAggregation, dataType, aggregationType, childrenList, int(params['start_time']), int(params['producer_interval']), publishingPrefix, True) else: # express interest for children who produce the same data and aggregation type for childName in childrenList.keys(): name = Name(self._identityName).append(childName).append(DATA_COMPONENT).append(dataType).append(AGGREGATION_COMPONENT).append(aggregationType) interest = Interest(name) # if start_time is specified, we ask for data starting at start_time; # if not, we ask for the right most child and go from there if ('start_time' in childrenList[childName]): endTime = int(childrenList[childName]['start_time']) + int(childrenList[childName]['producer_interval']) interest.getName().append(str(childrenList[childName]['start_time'])).append(str(endTime)) else: # TODO: For now we are playing with historical data, for each run we don't want to miss any data, thus we start with leftMost interest.setChildSelector(0) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(DEFAULT_INTEREST_LIFETIME) if __debug__: print(' Issue interest: ' + interest.getName().toUri()) self._face.expressInterest(interest, self.onData, self.onTimeout) return
def on_interest(self, _prefix, interest: Interest, face, _filter_id, _filter): logging.info('On interest: {}'.format(interest.getName())) if str(interest.getName()) in self.m_name_str_to_data: self.face.putData(self.m_name_str_to_data[str(interest.getName())]) logging.info('Serve data: {}'.format(interest.getName())) else: logging.info('Data does not exist: {}'.format(interest.getName()))
def on_interest(self, _prefix, interest: Interest, face, _filter_id, _filter): name = interest.getName() if not self.storage.exists(str(name)): return raw_data = self.storage.get(str(name)) data = Data() data.wireDecode(Blob(pickle.loads(raw_data))) self.face.putData(data) logging.info('Read handle: serve data {}'.format(interest.getName()))
def reply_to_cmd(self, interest: Interest, response: RepoCommandResponseMessage): """ Reply to a command interest """ logging.info('Reply to command: {}'.format(interest.getName())) response_blob = ProtobufTlv.encode(response) data = Data(interest.getName()) data.metaInfo.freshnessPeriod = 1000 data.setContent(response_blob) self.keychain.sign(data) self.face.putData(data)
def onAccessInterest(prefix, interest, face, interestFilterId, filter): print "On Access request interest: " + interest.getName().toUri() certInterest = Interest(interest.getName().getSubName(4)) certInterest.setName(certInterest.getName().getPrefix(-1)) certInterest.setInterestLifetimeMilliseconds(2000) face.expressInterest( certInterest, lambda memberInterest, memberData: self.onMemberCertificateData( memberInterest, memberData, interest), lambda memberInterest: self.onMemberCertificateTimeout( memberInterest, interest)) print "Retrieving member certificate: " + certInterest.getName().toUri() return
def onDataNotFound(self, prefix, interest, face, interestFilterId, filter): print "Data not found for interest: " + interest.getName().toUri() if interest.getName().get( -3).toEscapedString() == "bout" or interest.getName().get( -3).toEscapedString() == "genericfunctions": if interest.getName().toUri() in self.remainingTasks: # We are already trying to process this task, so we don't add it to the list of tasks pass else: self.remainingTasks[interest.getName().toUri()] = "in-progress" else: print "Got unexpected interest: " + interest.getName().toUri() # .../SAMPLE/<timestamp> timestamp = interest.getName().get(-1) catalogInterest = Interest(self.catalogPrefix) # Traverse catalogs in range from leftmost child catalogInterest.setChildSelector(0) catalogInterest.setMustBeFresh(True) catalogInterest.setInterestLifetimeMilliseconds(4000) exclude = Exclude() exclude.appendAny() exclude.appendComponent(timestamp) catalogInterest.setExclude(catalogInterest) self.face.expressInterest(catalogInterest, self.onCatalogData, self.onCatalogTimeout) print "Expressed catalog interest " + catalogInterest.getName().toUri() return
def _sendCertificateRequest(self, keyIdentity): """ We compose a command interest with our public key info so the controller can sign us a certificate that can be used with other nodes in the network. """ #TODO: GENERATE A NEW PUBLIC/PRIVATE PAIR INSTEAD OF COPYING makeKey = False try: defaultKey = self._identityStorage.getDefaultKeyNameForIdentity( keyIdentity) newKeyName = defaultKey except SecurityException: defaultIdentity = self._keyChain.getDefaultIdentity() defaultKey = self._identityStorage.getDefaultKeyNameForIdentity( defaultIdentity) newKeyName = self._identityStorage.getNewKeyName(keyIdentity, True) makeKey = True self.log.debug("Found key: " + defaultKey.toUri() + " renaming as: " + newKeyName.toUri()) keyType = self._identityStorage.getKeyType(defaultKey) keyDer = self._identityStorage.getKey(defaultKey) if makeKey: try: privateDer = self._identityManager.getPrivateKey(defaultKey) except SecurityException: # XXX: is recovery impossible? pass else: try: self._identityStorage.addKey(newKeyName, keyType, keyDer) self._identityManager.addPrivateKey(newKeyName, privateDer) except SecurityException: # TODO: key shouldn't exist... pass message = CertificateRequestMessage() message.command.keyType = keyType message.command.keyBits = keyDer.toRawStr() for component in range(newKeyName.size()): message.command.keyName.components.append( newKeyName.get(component).toEscapedString()) paramComponent = ProtobufTlv.encode(message) interestName = Name(self._policyManager.getTrustRootIdentity()).append( "certificateRequest").append(paramComponent) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds( 10000) # takes a tick to verify and sign self._hmacHandler.signInterest(interest, keyName=self.prefix) self.log.info("Sending certificate request to controller") self.log.debug("Certificate request: " + interest.getName().toUri()) self.face.expressInterest(interest, self._onCertificateReceived, self._onCertificateTimeout)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) interest = Interest() interest.wireDecode(TlvInterest) # Use a hard-wired secret for testing. In a real application the signer # ensures that the verifier knows the shared key and its keyName. key = Blob(bytearray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ])) if KeyChain.verifyInterestWithHmacWithSha256(interest, key): dump("Hard-coded interest signature verification: VERIFIED") else: dump("Hard-coded interest signature verification: FAILED") freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) keyName = Name("key1") dump("Signing fresh interest", freshInterest.getName().toUri()) KeyChain.signWithHmacWithSha256(freshInterest, key, keyName) if KeyChain.verifyInterestWithHmacWithSha256(freshInterest, key): dump("Freshly-signed interest signature verification: VERIFIED") else: dump("Freshly-signed interest signature verification: FAILED")
def __init__(self, face, encryptResult, link = None): # Set up face self.face = face self._encryptResult = encryptResult self._link = link self.databaseFilePath = "policy_config/test_consumer_dpu.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass self.groupName = Name("/org/openmhealth/haitao") # Set up the keyChain. identityStorage = BasicIdentityStorage() privateKeyStorage = FilePrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) # Authorized identity identityName = Name("/ndn/edu/basel/dpu") # Function name: the function that this DPU provides self._functionName = "bounding_box" self._identityName = identityName self.certificateName = self.keyChain.createIdentityAndCertificate(identityName) # TODO: if using BasicIdentityStorage and FilePrivateKeyStorage # For some reason this newly generated cert is not installed by default, calling keyChain sign later would result in error #self.keyChain.installIdentityCertificate() self.face.setCommandSigningInfo(self.keyChain, self.certificateName) consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName) consumerCertificate = identityStorage.getCertificate(self.certificateName) self.consumer = Consumer( face, self.keyChain, self.groupName, identityName, Sqlite3ConsumerDb(self.databaseFilePath)) # TODO: Read the private key to decrypt d-key...this may or may not be ideal base64Content = None with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile: print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri") base64Content = keyFile.read() #print base64Content der = Blob(base64.b64decode(base64Content), False) self.consumer.addDecryptionKey(consumerKeyName, der) self.memoryContentCache = MemoryContentCache(self.face) self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound) self.memoryContentCache.add(consumerCertificate) accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time()))) self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout) print "Access request interest name: " + accessRequestInterest.getName().toUri() self._tasks = dict() return
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/faces/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printFaceStatuses(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch(face, interest, None, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): interest = Interest() interest.wireDecode(TlvInterest) # Use a hard-wired secret for testing. In a real application the signer # ensures that the verifier knows the shared key and its keyName. key = Blob(bytearray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ])) if KeyChain.verifyInterestWithHmacWithSha256(interest, key): dump("Hard-coded interest signature verification: VERIFIED") else: dump("Hard-coded interest signature verification: FAILED") freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) keyName = Name("key1") dump("Signing fresh interest", freshInterest.getName().toUri()) KeyChain.signWithHmacWithSha256(freshInterest, key, keyName) if KeyChain.verifyInterestWithHmacWithSha256(freshInterest, key): dump("Freshly-signed interest signature verification: VERIFIED") else: dump("Freshly-signed interest signature verification: FAILED")
def onCatalogData(self, interest, data): # Find the next catalog print "Received catalog data " + data.getName().toUri() catalogTimestamp = data.getName().get(-2) exclude = Exclude() exclude.appendAny() exclude.appendComponent(catalogTimestamp) nextCatalogInterest = Interest(interest.getName()) nextCatalogInterest.setExclude(exclude) nextCatalogInterest.setChildSelector(0) nextCatalogInterest.setMustBeFresh(True) nextCatalogInterest.setInterestLifetimeMilliseconds(2000) self.face.expressInterest(nextCatalogInterest, self.onCatalogData, self.onCatalogTimeout) print "Expressed catalog interest " + nextCatalogInterest.getName( ).toUri() # We ignore the version in the catalog if self.encrypted: self.consumer.consume(contentName, self.onCatalogConsumeComplete, self.onConsumeFailed) else: self.onCatalogConsumeComplete(data, data.getContent())
def main(): # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/rib/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printRibEntries(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch(face, interest, None, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def _sendCertificateRequest(self, keyIdentity): """ We compose a command interest with our public key info so the controller can sign us a certificate that can be used with other nodes in the network. """ try: defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(keyIdentity) except SecurityException: defaultKey = self._identityManager.generateRSAKeyPairAsDefault(keyIdentity) self.log.debug("Key name: " + defaultKey.toUri()) message = CertificateRequestMessage() publicKey = self._identityManager.getPublicKey(defaultKey) message.command.keyType = publicKey.getKeyType() message.command.keyBits = publicKey.getKeyDer().toRawStr() for component in range(defaultKey.size()): message.command.keyName.components.append(defaultKey.get(component).toEscapedString()) paramComponent = ProtobufTlv.encode(message) interestName = Name(self._policyManager.getTrustRootIdentity()).append("certificateRequest").append(paramComponent) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(10000) # takes a tick to verify and sign self._hmacHandler.signInterest(interest, keyName=self.prefix) self.log.info("Sending certificate request to controller") self.log.debug("Certificate request: "+interest.getName().toUri()) self.face.expressInterest(interest, self._onCertificateReceived, self._onCertificateTimeout)
def main(): # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/rib/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printRibEntries(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch( face, interest, SegmentFetcher.DontVerifySegment, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
async def send_temp_interest(self): """ Send a temperature interest to the producer """ interest_name = Name(self.prefix).append(str(int(time.time()) - 1)) interest = Interest(interest_name) interest.interestLifetimeMilliseconds = 4000 logging.info('Fetching {}'.format(str(interest.getName()))) print('Fetching {}'.format(str(interest.getName()))) data = await fetch_data_packet(self.face, interest) if isinstance(data, Data): self.process_temp_data(data) else: logging.info('Failed to fetch {}'.format(str(interest.getName())))
async def send_cmd_interest(self): event_loop = asyncio.get_event_loop() face_task = event_loop.create_task(self.face_loop()) parameter = RepoCommandParameterMessage() for compo in self.prefix: parameter.repo_command_parameter.name.component.append(compo.getValue().toBytes()) parameter.repo_command_parameter.start_block_id = self.latest_tp parameter.repo_command_parameter.end_block_id = parameter.repo_command_parameter.start_block_id param_blob = ProtobufTlv.encode(parameter) # Prepare cmd interest name = Name(self.repo_name).append("insert").append(Name.Component(param_blob)) interest = Interest(name) interest.canBePrefix = True self.face.makeCommandInterest(interest) logging.info("Express interest: {}".format(interest.getName())) ret = await fetch_data_packet(self.face, interest) if not isinstance(ret, Data): logging.warning("Insertion failed") else: # Parse response response = RepoCommandResponseMessage() try: ProtobufTlv.decode(response, ret.content) logging.info('Insertion command accepted: status code {}' .format(response.repo_command_response.status_code)) except RuntimeError as exc: logging.warning('Response decoding failed', exc)
def run(self): # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/faces/channels")) interest.setInterestLifetimeMilliseconds(4000) self.dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False self.printChannelStatuses(content) def onError(errorCode, message): enabled[0] = False self.dump(message) SegmentFetcher.fetch(face, interest, None, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) # print('==================run Channels_status_getter finished===================') face.shutdown() return (self.total_result)
def nfdRegisterPrefix(self, registeredPrefixId, prefix, onInterest, onRegisterFailed, onRegisterSuccess, flags, commandKeyChain, commandCertificateName, face): """ Do the work of registerPrefix to register with NFD. :param int registeredPrefixId: The getNextEntryId() which registerPrefix got so it could return it to the caller. If this is 0, then don't add to _registeredPrefixTable (assuming it has already been done). """ if commandKeyChain == None: raise RuntimeError( "registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo." ) if commandCertificateName.size() == 0: raise RuntimeError( "registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo." ) controlParameters = ControlParameters() controlParameters.setName(prefix) controlParameters.setForwardingFlags(flags) controlParameters.setOrigin(65) commandInterest = Interest() if self.isLocal(): commandInterest.setName(Name("/localhost/nfd/rib/register")) # The interest is answered by the local host, so set a short timeout. commandInterest.setInterestLifetimeMilliseconds(2000.0) else: commandInterest.setName(Name("/localhop/nfd/rib/register")) # The host is remote, so set a longer timeout. commandInterest.setInterestLifetimeMilliseconds(4000.0) # NFD only accepts TlvWireFormat packets. commandInterest.getName().append( controlParameters.wireEncode(TlvWireFormat.get())) self.makeCommandInterest(commandInterest, commandKeyChain, commandCertificateName, TlvWireFormat.get()) # Send the registration interest. response = Node._RegisterResponse(prefix, onRegisterFailed, onRegisterSuccess, registeredPrefixId, self, onInterest, face) self.expressInterest(self.getNextEntryId(), commandInterest, response.onData, response.onTimeout, None, TlvWireFormat.get(), face)
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) self._dataQueue[dataType + aggregationType] = DataQueue( params, childrenList, publishingPrefix) if len(childrenList.keys()) == 0: # TODO: make start_time optional for leaf nodes self._loop.call_later(int(params['producer_interval']), self.calculateAggregation, dataType, aggregationType, childrenList, int(params['start_time']), int(params['producer_interval']), publishingPrefix, True) else: # express interest for children who produce the same data and aggregation type for childName in childrenList.keys(): name = Name(self._identityName).append(childName).append( DATA_COMPONENT).append(dataType).append( AGGREGATION_COMPONENT).append(aggregationType) interest = Interest(name) # if start_time is specified, we ask for data starting at start_time; # if not, we ask for the right most child and go from there if ('start_time' in childrenList[childName]): endTime = int(childrenList[childName]['start_time']) + int( childrenList[childName]['producer_interval']) interest.getName().append( str(childrenList[childName]['start_time'])).append( str(endTime)) else: # TODO: For now we are playing with historical data, for each run we don't want to miss any data, thus we start with leftMost interest.setChildSelector(0) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds( DEFAULT_INTEREST_LIFETIME) if __debug__: print(' Issue interest: ' + interest.getName().toUri()) self._face.expressInterest(interest, self.onData, self.onTimeout) return
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) dump(freshInterest.toUri()) freshInterest.setMinSuffixComponents(4) freshInterest.setMaxSuffixComponents(6) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData(bytearray( [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.setInterestLifetimeMilliseconds(30000) freshInterest.setChildSelector(1) freshInterest.setMustBeFresh(True); freshInterest.setScope(2) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) # 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) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, certificateName) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest( reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnVerifyFailed("Freshly-signed Interest"))
def processFaceStatus(encodedFaceStatus, prefix, uri, face, enabled): """ This is called when all the segments are received to decode the encodedFaceStatus as a TLV FaceStatus message. If the face ID exists for the face URL, use it to call registerRoute(), otherwise send a /localhost/nfd/faces/create command to create the face. :param Blob encodedFaceStatus: The TLV-encoded FaceStatus. :param Name prefix: The prefix name to register. :param str uri: The remote URI in case we need to tell NFD to create a face. :param Face face: The Face which is used to sign the command interest and call expressInterest. :param enabled: On success or error, set enabled[0] = False. :type enabled: An array with one bool element """ if encodedFaceStatus.size() == 0: # No result, so we need to tell NFD to create the face. # Encode the ControlParameters. message = \ control_parameters_pb2.ControlParametersTypes.ControlParametersMessage() message.control_parameters.uri = uri encodedControlParameters = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/faces/create")) interest.getName().append(encodedControlParameters) interest.setInterestLifetimeMilliseconds(10000) def onData(localInterest, data): processCreateFaceResponse(data.getContent(), prefix, face, enabled) def onTimeout(localInterest): enabled[0] = False dump("Face create command timed out.") # Sign and express the interest. face.makeCommandInterest(interest) face.expressInterest(interest, onData, onTimeout) else: decodedFaceStatus = face_status_pb2.FaceStatusMessage() ProtobufTlv.decode(decodedFaceStatus, encodedFaceStatus) faceId = decodedFaceStatus.face_status[0].face_id dump("Found face ID ", faceId) registerRoute(prefix, faceId, face, enabled)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = (Interest(Name("/ndn/abc")) .setMustBeFresh(False) .setMinSuffixComponents(4) .setMaxSuffixComponents(6) .setInterestLifetimeMilliseconds(30000) .setChildSelector(1) .setMustBeFresh(True)) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData(bytearray( [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # Set up the KeyChain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag(SafeBag (Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) validator = Validator(ValidationPolicyFromPib(keyChain.getPib())) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) validator.validate( reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"), makeFailureCallback("Freshly-signed Interest"))
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = (Interest( Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents( 4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds( 30000).setChildSelector(1).setMustBeFresh(True)) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData( bytearray([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F ])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # Set up the KeyChain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) validator = Validator(ValidationPolicyFromPib(keyChain.getPib())) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) validator.validate(reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"), makeFailureCallback("Freshly-signed Interest"))
def test_max_ndn_packet_size(self): # Construct an interest whose encoding is one byte larger than getMaxNdnPacketSize. targetSize = Face.getMaxNdnPacketSize() + 1 # Start with an interest which is almost the right size. interest = Interest() interest.getName().append(bytearray(targetSize)) initialSize = interest.wireEncode().size() # Now replace the component with the desired size which trims off the extra encoding. interest.setName( (Name().append(bytearray(targetSize - (initialSize - targetSize))))) interestSize = interest.wireEncode().size() self.assertEqual(targetSize, interestSize, "Wrong interest size for MaxNdnPacketSize") with self.assertRaises(RuntimeError): # If no error is raised, then expressInterest didn't throw an # exception when the interest size exceeds getMaxNdnPacketSize() self.face.expressInterest(interest, Mock(), Mock())
def sendInterest(self, name): interest = Interest(name) interestName = interest.getName() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) self.face.expressInterest( interest, None, None ) ## set None --> sent out only, don't wait for Data and Timeout print "Sent Interest for %s" % interestName
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) prefix = Name("/nfd/edu/ucla/remap/test") # Route to aleph.ndn.ucla.edu. Have to use the canonical name with an IP # address and port. uri = "udp4://128.97.98.7:6363" # The default Face connects to the local NFD. face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Create the /localhost/nfd/faces/query command interest, including the # FaceQueryFilter. Construct the FaceQueryFilter using the structure in # face_query_filter_pb2 which was produced by protoc. message = face_query_filter_pb2.FaceQueryFilterMessage() filter = message.face_query_filter.add() filter.uri = uri encodedFilter = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/faces/query")) interest.getName().append(encodedFilter) enabled = [True] def onComplete(content): processFaceStatus(content, prefix, uri, face, enabled) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch(face, interest, None, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = (Interest( Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents( 4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds( 30000).setChildSelector(1).setMustBeFresh(True)) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData( bytearray([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F ])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # Set up the KeyChain. pibImpl = PibMemory() keyChain = KeyChain(pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl)) # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager. keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest(reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnValidationFailed("Freshly-signed Interest"))
def registerRoute(prefix, faceId, face, enabled): """ Use /localhost/nfd/rib/register to register the prefix to the faceId. :param Name prefix: The prefix name to register. :param int faceId: The face ID. :param Face face: The Face which is used to sign the command interest and call expressInterest. :param enabled: On success or error, set enabled[0] = False. :type enabled: An array with one bool element """ # Use default values origin = 255 cost = 0 CHILD_INHERIT = 1 flags = CHILD_INHERIT message = control_parameters_pb2.ControlParametersTypes.ControlParametersMessage( ) for i in range(prefix.size()): message.control_parameters.name.component.append( prefix[i].getValue().toBytes()) message.control_parameters.face_id = faceId message.control_parameters.origin = origin message.control_parameters.cost = cost message.control_parameters.flags = flags encodedControlParameters = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/rib/register")) interest.getName().append(encodedControlParameters) interest.setInterestLifetimeMilliseconds(10000) # Sign and express the interest. face.makeCommandInterest(interest) def onData(localInterest, data): enabled[0] = False processRegisterResponse(data.getContent()) def onTimeout(localInterest): enabled[0] = False dump("Register route command timed out.") face.expressInterest(interest, onData, onTimeout)
def on_interest(prefix, interest: Interest, face, _filter_id, _filter): logging.info('On interest: {}'.format(interest.getName())) print('On interest: {}'.format(interest.getName())) if str(interest.getName()[:-1]) in dict1: face.putData(dict1[str(interest.getName()[:-1])][str(interest.getName())]) logging.info('Serve data: {}'.format(interest.getName())) else: logging.info('Data does not exist: {}'.format(interest.getName()))
def main(): prefix = Name("/nfd/edu/ucla/remap/test") # Route to aleph.ndn.ucla.edu. Have to use the canonical name with an IP # address and port. uri = "udp4://128.97.98.7:6363" # The default Face connects to the local NFD. face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Create the /localhost/nfd/faces/query command interest, including the # FaceQueryFilter. Construct the FaceQueryFilter using the structure in # face_query_filter_pb2 which was produced by protoc. message = face_query_filter_pb2.FaceQueryFilterMessage() filter = message.face_query_filter.add() filter.uri = uri encodedFilter = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/faces/query")) interest.getName().append(encodedFilter) enabled = [True] def onComplete(content): processFaceStatus(content, prefix, uri, face, enabled) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch( face, interest, SegmentFetcher.DontVerifySegment, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def onSyncTimeout(self, interest): newInterest = Interest(Name(self._syncPrefix).append(self._currentDigest)) newInterest.setInterestLifetimeMilliseconds(self._syncInterestLifetime) newInterest.setMustBeFresh(True) self._numOutstandingInterest -= 1 print "re-expressing: " + newInterest.getName().toUri() if self._numOutstandingInterest <= 0: self._face.expressInterest(newInterest, self.onSyncData, self.onSyncTimeout) self._numOutstandingInterest += 1 return
def test_append_parameters_digest(self): name = Name("/local/ndn/prefix") interest = Interest(name) self.assertTrue(not interest.hasApplicationParameters()) # No parameters yet, so it should do nothing. interest.appendParametersDigestToName() self.assertEqual("/local/ndn/prefix", interest.getName().toUri()) applicationParameters = Blob(bytearray([ 0x23, 0x01, 0xC0 ])) interest.setApplicationParameters(applicationParameters) self.assertTrue(interest.hasApplicationParameters()) interest.appendParametersDigestToName() self.assertEqual(name.size() + 1, interest.getName().size()) self.assertTrue(interest.getName().getPrefix(-1).equals(name)) SHA256_LENGTH = 32 self.assertEqual(SHA256_LENGTH, interest.getName().get(-1).getValue().size()) self.assertEqual(interest.getName().toUri(), "/local/ndn/prefix/" + "params-sha256=a16cc669b4c9ef6801e1569488513f9523ffb28a39e53aa6e11add8d00a413fc")
def _sendCertificateRequest(self, keyIdentity): """ We compose a command interest with our public key info so the controller can sign us a certificate that can be used with other nodes in the network. """ #TODO: GENERATE A NEW PUBLIC/PRIVATE PAIR INSTEAD OF COPYING makeKey = False try: defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(keyIdentity) newKeyName = defaultKey except SecurityException: defaultIdentity = self._keyChain.getDefaultIdentity() defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(defaultIdentity) newKeyName = self._identityStorage.getNewKeyName(keyIdentity, True) makeKey = True self.log.debug("Found key: " + defaultKey.toUri()+ " renaming as: " + newKeyName.toUri()) keyType = self._identityStorage.getKeyType(defaultKey) keyDer = self._identityStorage.getKey(defaultKey) if makeKey: try: privateDer = self._identityManager.getPrivateKey(defaultKey) except SecurityException: # XXX: is recovery impossible? pass else: try: self._identityStorage.addKey(newKeyName, keyType, keyDer) self._identityManager.addPublicKey(newKeyName, keyDer) self._identityManager.addPrivateKey(newKeyName, privateDer) except SecurityException: # TODO: key shouldn't exist... pass message = CertificateRequestMessage() message.command.keyType = keyType message.command.keyBits = keyDer.toRawStr() for component in range(newKeyName.size()): message.command.keyName.components.append(newKeyName.get(component).toEscapedString()) paramComponent = ProtobufTlv.encode(message) interestName = Name(self._policyManager.getTrustRootIdentity()).append("certificateRequest").append(paramComponent) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(10000) # takes a tick to verify and sign self._hmacHandler.signInterest(interest, keyName=self.prefix) self.log.info("Sending certificate request to controller") self.log.debug("Certificate request: "+interest.getName().toUri()) self.face.expressInterest(interest, self._onCertificateReceived, self._onCertificateTimeout)
def registerRoute(prefix, faceId, face, enabled): """ Use /localhost/nfd/rib/register to register the prefix to the faceId. :param Name prefix: The prefix name to register. :param int faceId: The face ID. :param Face face: The Face which is used to sign the command interest and call expressInterest. :param enabled: On success or error, set enabled[0] = False. :type enabled: An array with one bool element """ # Use default values origin = 255 cost = 0 CHILD_INHERIT = 1 flags = CHILD_INHERIT message = control_parameters_pb2.ControlParametersTypes.ControlParametersMessage() for i in range(prefix.size()): message.control_parameters.name.component.append(prefix[i].getValue().toBytes()) message.control_parameters.face_id = faceId message.control_parameters.origin = origin message.control_parameters.cost = cost message.control_parameters.flags = flags encodedControlParameters = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/rib/register")) interest.getName().append(encodedControlParameters) interest.setInterestLifetimeMilliseconds(10000) # Sign and express the interest. face.makeCommandInterest(interest) def onData(localInterest, data): enabled[0] = False processRegisterResponse(data.getContent()) def onTimeout(localInterest): enabled[0] = False dump("Register route command timed out.") face.expressInterest(interest, onData, onTimeout)
def start(self): """ Starts the discovery """ interest = Interest(Name(self._syncPrefix).append(self._initialDigest)) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(self._syncInterestLifetime) self._face.expressInterest(interest, self.onSyncData, self.onSyncTimeout) self._numOutstandingInterest += 1 if __debug__: print("Express interest: " + interest.getName().toUri()) return
def generateKeyAndSendNewInterest(self, probeTokenData): """ """ pib = self.keyChain.getPib() try: identity = pib.getIdentity(self.identityName) self.key = self.keyChain.createKey(identity) except Exception as e: identity = self.keyChain.createIdentityV2(self.identityName) self.key = identity.getDefaultKey() cert = CertificateV2() cert.setName( Name(self.key.getName()).append("cert-request").appendVersion( int(time.time()))) cert.getMetaInfo().setType(ContentType.KEY) cert.getMetaInfo().setFreshnessPeriod(24 * 3600) cert.setContent(self.key.getPublicKey()) signingInfo = SigningInfo(self.key) now = Common.getNowMilliseconds() signingInfo.setValidityPeriod( ValidityPeriod(now, now + 24 * 3600 * 1000.0)) self.keyChain.sign(cert, signingInfo) #cert = self.keyChain.selfSign(self.key) # Does not work because validity period is greater than certserver default interestName = Name(self.caPrefix).append("CA").append("_NEW") newInterest = Interest(interestName) newInterest.setMustBeFresh(True) newInterest.setCanBePrefix(False) ecdhPub = "{}\n".format(self.ecdh.getBase64PubKey()) ecdhCertReq = "{}\n".format( b64encode(cert.wireEncode().toBytes()).decode('utf-8')) probeToken = "{}\n".format( b64encode(probeTokenData.wireEncode().toBytes()).decode('utf-8')) jsonDump = json.dumps( { "ecdh-pub": ecdhPub, "cert-request": ecdhCertReq, "probe-token": probeToken }, indent=4) print(jsonDump) newInterest.setApplicationParameters(jsonDump) newInterest.appendParametersDigestToName() self.keyChain.sign(newInterest, SigningInfo(self.key)) print(newInterest.getName()) self.face.expressInterest(newInterest, self.onNewData, self.onTimeout)
def __init__(self, face): # Set up face self.face = face self.databaseFilePath = "policy_config/test_consumer.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass self.groupName = Name("/org/openmhealth/zhehao") # Set up the keyChain. identityStorage = BasicIdentityStorage() privateKeyStorage = FilePrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) # Authorized identity identityName = Name("/org/openmhealth/dvu-python-3") # Unauthorized identity #identityName = Name("/org/openmhealth/dvu-python-1") self.certificateName = self.keyChain.createIdentityAndCertificate(identityName) self.face.setCommandSigningInfo(self.keyChain, self.certificateName) consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName) consumerCertificate = identityStorage.getCertificate(self.certificateName) self.consumer = Consumer( face, self.keyChain, self.groupName, identityName, Sqlite3ConsumerDb(self.databaseFilePath)) # TODO: Read the private key to decrypt d-key...this may or may not be ideal base64Content = None with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile: print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri") base64Content = keyFile.read() #print base64Content der = Blob(base64.b64decode(base64Content), False) self.consumer.addDecryptionKey(consumerKeyName, der) self.memoryContentCache = MemoryContentCache(self.face) self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound) self.memoryContentCache.add(consumerCertificate) accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time()))) self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout) print "Access request interest name: " + accessRequestInterest.getName().toUri() self.consumeCatalog = True return
def sendProbeInterest(self): probeInterest = Interest( Name(self.caPrefix).append("CA").append("_PROBE")) probeInterest.setMustBeFresh(True) probeInterest.setCanBePrefix(False) probeInterest.setApplicationParameters( json.dumps({"email": "*****@*****.**"}, indent=4)) probeInterest.appendParametersDigestToName() print("Expressing interest: {}".format(probeInterest.getName())) self.face.expressInterest(probeInterest, self.onProbeData, self.onTimeout)
async def retry_or_fail(interest: Interest): """ Retry for up to FETCHER_MAX_ATTEMPT_NUMBER times, and write to storage. """ nonlocal n_success, n_fail, cur_id, final_id # Need to check sequence number, in case this task was added to the event queue before # final_id is set seq = int(str(interest.getName()[-1])) if seq > final_id: semaphore.release() return logging.info('retry_or_fail(): {}'.format(interest.getName())) for _ in range(FETCHER_MAX_ATTEMPT_NUMBER): response = await fetch_data_packet(face, interest) success = False if isinstance(response, Data): final_id_component = response.metaInfo.getFinalBlockId() if final_id_component.isSegment(): final_id = final_id_component.toSegment() logging.info('final_id is set to {}'.format(final_id)) success = True break else: await asyncio.sleep(FETCHER_RETRY_INTERVAL / 1000.0) if success: n_success += 1 else: n_fail += 1 # Exit if all data fetched, or n_fail reaches a threshold if n_fail >= FETCHER_FAIL_EXIT_THRESHOLD or n_success + n_fail >= final_id - start_block_id + 1: done.set() semaphore.release() after_fetched(response)
def test_find_by_interest(self): self.anchorContainer.insert("group1", self.certificatePath1, 400.0) interest = Interest(self.identity1.getName()) self.assertTrue(self.anchorContainer.find(interest) != None) interest1 = Interest(self.identity1.getName().getPrefix(-1)) self.assertTrue(self.anchorContainer.find(interest1) != None) interest2 = Interest(Name(self.identity1.getName()).appendVersion(1)) self.assertTrue(self.anchorContainer.find(interest2) == None) certificate3 = self.fixture.addCertificate( self.identity1.getDefaultKey(), "3") certificate4 = self.fixture.addCertificate( self.identity1.getDefaultKey(), "4") certificate5 = self.fixture.addCertificate( self.identity1.getDefaultKey(), "5") certificate3Copy = CertificateV2(certificate3) self.anchorContainer.insert("group2", certificate3Copy) self.anchorContainer.insert("group3", certificate4) self.anchorContainer.insert("group4", certificate5) interest3 = Interest(certificate3.getKeyName()) foundCertificate = self.anchorContainer.find(interest3) self.assertTrue(foundCertificate != None) self.assertTrue(interest3.getName().isPrefixOf( foundCertificate.getName())) self.assertTrue(certificate3.getName().equals( foundCertificate.getName())) interest3.getExclude().appendComponent(certificate3.getName().get( CertificateV2.ISSUER_ID_OFFSET)) foundCertificate = self.anchorContainer.find(interest3) self.assertTrue(foundCertificate != None) self.assertTrue(interest3.getName().isPrefixOf( foundCertificate.getName())) self.assertTrue( not foundCertificate.getName().equals(certificate3.getName()))
def sendInterest_to_DE(self, name): interest = Interest(name) interestName = interest.getName() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) #if uri not in self.outstanding: #self.outstanding[uri] = 1 # self.face.expressInterest(interest, self.onData, self._onTimeout) self.face.expressInterest( interest, None, None ) ## set None --> sent out only, don't wait for Data and Timeout print "Sent Push-Interest for %s" % interestName
def handle_completion(self): content = bytearray() for i in sorted(self.segments): segment = self.segments[i] content.extend(segment.getContent().buf()) interest = Interest(Name(self.name)) blob = Blob(content) size = blob.size() Log.info( "Received all segments ({} bytes) for interest '{}':\n{}".format( size, Util.interest_to_string(interest), urllib.parse.unquote(blob.toRawStr()))) data = Data(interest.getName()) data.setContent(blob) self.on_data(self, data)
def expressInterestPirAndRepeat(self): self.log.debug("callbackCountUniqueData: " + str(self._callbackCountUniqueData) + ", callbackCountTimeout: " + str(self._callbackCountTimeout)) # Express interest for each pir we have discovered for pir in self.getPirs(): interest = Interest(Name(pir.id)) interest.setExclude(pir.status.getExclude()) interest.setInterestLifetimeMilliseconds(1000.0) interest.setChildSelector(1) self.face.expressInterest(interest, self.onDataPir, self.onTimeoutPir) self._countExpressedInterests += 1 debugStr = "Sent interest: " + interest.getName().toUri() debugStr += "\tExclude: " + interest.getExclude().toUri() debugStr += "\tLifetime: " + str(interest.getInterestLifetimeMilliseconds()) self.log.debug(debugStr) # Reschedule again in 0.5 sec self.loop.call_later(1.0, self.expressInterestPirAndRepeat)
def sendAppRequest(self, certificateName, dataPrefix, applicationName, onRequestSuccess, onRequestFailed): message = AppRequestMessage() for component in range(certificateName.size()): message.command.idName.components.append(certificateName.get(component).toEscapedString()) for component in range(dataPrefix.size()): message.command.dataPrefix.components.append(dataPrefix.get(component).toEscapedString()) message.command.appName = applicationName paramComponent = ProtobufTlv.encode(message) requestInterest = Interest(Name(self._controllerName).append("requests").append(paramComponent)) requestInterest.setInterestLifetimeMilliseconds(4000) self._face.makeCommandInterest(requestInterest) appRequestTimeoutCnt = 3 self._face.expressInterest(requestInterest, lambda interest, data : self.onAppRequestData(interest, data, onRequestSuccess, onRequestFailed), lambda interest : self.onAppRequestTimeout(interest, onRequestSuccess, onRequestFailed, appRequestTimeoutCnt)) print "Application publish request sent: " + requestInterest.getName().toUri() return
def __init__(self, face, encryptResult, defaultPrefix, link = None): # Set up face self.face = face self._encryptResult = encryptResult self._link = link self.databaseFilePath = "policy_config/test_consumer_dpu.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass self.groupName = Name(defaultPrefix) # Set up the keyChain. identityStorage = BasicIdentityStorage() privateKeyStorage = FilePrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) # Authorized identity identityName = Name("/ndn/edu/basel/dpu") # Function name: the function that this DPU provides self._functionName = "bounding_box" self._identityName = identityName self.certificateName = self.keyChain.createIdentityAndCertificate(identityName) # TODO: if using BasicIdentityStorage and FilePrivateKeyStorage # For some reason this newly generated cert is not installed by default, calling keyChain sign later would result in error #self.keyChain.installIdentityCertificate() self.memoryContentCache = MemoryContentCache(self.face) try: commandSigningKeyChain = KeyChain() print "Default certificate name is: " + self.keyChain.getDefaultCertificateName().toUri() self.face.setCommandSigningInfo(commandSigningKeyChain, commandSigningKeyChain.getDefaultCertificateName()) self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound) except SecurityException as e: print str(e) print "Cannot use default certificate, use created certificate in FilePrivateKeyStorage" self.face.setCommandSigningInfo(self.keyChain, self.certificateName) self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound) consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName) consumerCertificate = identityStorage.getCertificate(self.certificateName) self.consumer = Consumer( face, self.keyChain, self.groupName, identityName, Sqlite3ConsumerDb(self.databaseFilePath)) # TODO: Read the private key to decrypt d-key...this may or may not be ideal base64Content = None with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile: print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri") base64Content = keyFile.read() #print base64Content der = Blob(base64.b64decode(base64Content), False) self.consumer.addDecryptionKey(consumerKeyName, der) self.memoryContentCache.add(consumerCertificate) accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time()))) self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout) print "Access request interest name: " + accessRequestInterest.getName().toUri() self._tasks = dict() return
def makePublicKeyInterest(self): interest = Interest(Name("/")) interest.getName().append(self._keyChain.getCertificate(self._certificateName).getPublicKeyInfo().getKeyDer()) return interest
def test_matches_data(self): interest = Interest(Name("/A")) interest.setMinSuffixComponents(2) interest.setMaxSuffixComponents(2) interest.getKeyLocator().setType(KeyLocatorType.KEYNAME) interest.getKeyLocator().setKeyName(Name("/B")) interest.getExclude().appendComponent(Name.Component("J")) interest.getExclude().appendAny() data = Data(Name("/A/D")) signature = Sha256WithRsaSignature() signature.getKeyLocator().setType(KeyLocatorType.KEYNAME) signature.getKeyLocator().setKeyName(Name("/B")) data.setSignature(signature) self.assertEqual(interest.matchesData(data), True) # Check violating MinSuffixComponents. data1 = Data(data) data1.setName(Name("/A")) self.assertEqual(interest.matchesData(data1), False) interest1 = Interest(interest) interest1.setMinSuffixComponents(1) self.assertEqual(interest1.matchesData(data1), True) # Check violating MaxSuffixComponents. data2 = Data(data) data2.setName(Name("/A/E/F")) self.assertEqual(interest.matchesData(data2), False) interest2 = Interest(interest) interest2.setMaxSuffixComponents(3) self.assertEqual(interest2.matchesData(data2), True) # Check violating PublisherPublicKeyLocator. data3 = Data(data) signature3 = Sha256WithRsaSignature() signature3.getKeyLocator().setType(KeyLocatorType.KEYNAME) signature3.getKeyLocator().setKeyName(Name("/G")) data3.setSignature(signature3) self.assertEqual(interest.matchesData(data3), False) interest3 = Interest(interest) interest3.getKeyLocator().setType(KeyLocatorType.KEYNAME) interest3.getKeyLocator().setKeyName(Name("/G")) self.assertEqual(interest3.matchesData(data3), True) data4 = Data(data) data4.setSignature(DigestSha256Signature()) self.assertEqual(interest.matchesData(data4), False) interest4 = Interest(interest) interest4.setKeyLocator(KeyLocator()) self.assertEqual(interest4.matchesData(data4), True) # Check violating Exclude. data5 = Data(data) data5.setName(Name("/A/J")) self.assertEqual(interest.matchesData(data5), False) interest5 = Interest(interest) interest5.getExclude().clear() interest5.getExclude().appendComponent(Name.Component("K")) interest5.getExclude().appendAny() self.assertEqual(interest5.matchesData(data5), True) # Check violating Name. data6 = Data(data) data6.setName(Name("/H/I")) self.assertEqual(interest.matchesData(data6), False) data7 = Data(data) data7.setName(Name("/A/B")) interest7 = Interest( Name("/A/B/sha256digest=" + "54008e240a7eea2714a161dfddf0dd6ced223b3856e9da96792151e180f3b128")) self.assertEqual(interest7.matchesData(data7), True) # Check violating the implicit digest. interest7b = Interest( Name("/A/B/%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00" + "%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00")) self.assertEqual(interest7b.matchesData(data7), False) # Check excluding the implicit digest. interest8 = Interest(Name("/A/B")) interest8.getExclude().appendComponent(interest7.getName().get(2)) self.assertEqual(interest8.matchesData(data7), False)
def onSetupComplete(defaultCertificateName, keyChain): testInt = Interest(Name("/abc")) keyChain.sign(testInt, defaultCertificateName) print(testInt.getName().toUri())
rp.setStartBlockId(0) interest = Interest(Name("/example/repo/1").append("insert").append(rp.wireEncode())) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) # 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) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, certificateName) face.makeCommandInterest(interest) callbacks = Callbacks() print interest.getName().toUri() face.expressInterest(interest, callbacks.onData, callbacks.onTimeout) face.registerPrefix(dataPrefix, callbacks.onInterest, callbacks.onRegisterFailed) while True: face.processEvents() time.sleep(0.1)
def start(self): interest = Interest(self._dataPrefix) self._face.expressInterest(interest, self.onData, self.onTimeout) print "Interest expressed " + interest.getName().toUri() return