Esempio n. 1
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Create an in-memory key chain with default keys.
    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)))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    # Enable Interest loopback so that the EncryptorV2 can fetch Data packets
    # from the AccessManagerV2.
    face.setInterestLoopbackEnabled(True)

    contentPrefix = Name("/testname/content")
    contentNamespace = Namespace(contentPrefix, keyChain)

    # We know the content has two segments.
    metaInfo = MetaInfo()
    metaInfo.setFinalBlockId(Name().appendSegment(1)[0])
    contentNamespace.setNewDataMetaInfo(metaInfo)

    ckPrefix = Name("/some/ck/prefix")
    encryptor = prepareData(ckPrefix, keyChain, face)

    # Make the callback to produce a Data packet for a content segment.
    def onObjectNeeded(namespace, neededNamespace, id):
        if not (len(neededNamespace.name) == len(contentPrefix) + 1
                and contentPrefix.isPrefixOf(neededNamespace.name)
                and neededNamespace.name[-1].isSegment()):
            # Not a content segment, ignore.
            return False

        # Get the segment number.
        segment = neededNamespace.name[-1].toSegment()
        if not (segment >= 0 and segment <= 1):
            # An invalid segment was requested.
            return False

        segmentContent = ("This test message was decrypted"
                          if segment == 0 else " from segments.")
        # Now call serializeObject which will answer the pending incoming Interest.
        dump("Producing Data", neededNamespace.name)
        neededNamespace.serializeObject(
            encryptor.encrypt(Blob(segmentContent)).wireEncodeV2())

        return True

    contentNamespace.addOnObjectNeeded(onObjectNeeded)

    dump("Register prefix", contentNamespace.name)
    # Set the face and register to receive Interests.
    contentNamespace.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName))

    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)