本文整理汇总了Python中pyndn.data.Data类的典型用法代码示例。如果您正苦于以下问题:Python Data类的具体用法?Python Data怎么用?Python Data使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Data类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: onReceivedElement
def onReceivedElement(self, element):
"""
This is called by the transport's ElementReader to process an
entire received Data or Interest element.
:param element: The bytes of the incoming element.
:type element: An array type with int elements
"""
lpPacket = None
if element[0] == Tlv.LpPacket_LpPacket:
# Decode the LpPacket and replace element with the fragment.
lpPacket = LpPacket()
# Set copy False so that the fragment is a slice which will be
# copied below. The header fields are all integers and don't need to
# be copied.
TlvWireFormat.get().decodeLpPacket(lpPacket, element, False)
element = lpPacket.getFragmentWireEncoding().buf()
# First, decode as Interest or Data.
data = None
decoder = TlvDecoder(element)
if decoder.peekType(Tlv.Data, len(element)):
data = Data()
data.wireDecode(element, TlvWireFormat.get())
if lpPacket != None:
data.setLpPacket(lpPacket)
# Now process as Interest or Data.
if data != None:
if self._onBtleData:
self._onBtleData(data)
开发者ID:remap,项目名称:ndn-flow,代码行数:32,代码来源:btle_node.py
示例2: onReceivedElement
def onReceivedElement(self, element):
"""
This is called by the transport's ElementReader to process an
entire received Data or Interest element.
:param element: The bytes of the incoming element.
:type element: An array type with int elements
"""
# First, decode as Interest or Data.
interest = None
data = None
decoder = TlvDecoder(element)
if decoder.peekType(Tlv.Interest, len(element)):
interest = Interest()
interest.wireDecode(element, TlvWireFormat.get())
elif decoder.peekType(Tlv.Data, len(element)):
data = Data()
data.wireDecode(element, TlvWireFormat.get())
# Now process as Interest or Data.
if interest != None:
# Call all interest filter callbacks which match.
for i in range(len(self._interestFilterTable)):
entry = self._interestFilterTable[i]
if entry.getFilter().doesMatch(interest.getName()):
includeFilter = True
# Use getcallargs to test if onInterest accepts 5 args.
try:
inspect.getcallargs(entry.getOnInterest(),
None, None, None, None, None)
except TypeError:
# Assume onInterest is old-style with 4 arguments.
includeFilter = False
if includeFilter:
try:
entry.getOnInterest()(
entry.getFilter().getPrefix(), interest,
entry.getFace(), entry.getInterestFilterId(),
entry.getFilter())
except:
logging.exception("Error in onInterest")
else:
# Old-style onInterest without the filter argument. We
# still pass a Face instead of Transport since Face also
# has a send method.
try:
entry.getOnInterest()(
entry.getFilter().getPrefix(), interest,
entry.getFace(), entry.getInterestFilterId())
except:
logging.exception("Error in onInterest")
elif data != None:
pendingInterests = self._extractEntriesForExpressedInterest(
data.getName())
for pendingInterest in pendingInterests:
try:
pendingInterest.getOnData()(pendingInterest.getInterest(), data)
except:
logging.exception("Error in onData")
开发者ID:MAHIS,项目名称:PyNDN2,代码行数:60,代码来源:node.py
示例3: _processRecoveryInterest
def _processRecoveryInterest(self, interest, syncDigest, face):
logging.getLogger(__name__).info("processRecoveryInterest")
if self._logFind(syncDigest) != -1:
tempContent = SyncStateMsg()
for i in range(self._digestTree.size()):
content = getattr(tempContent, "ss").add()
content.name = self._digestTree.get(i).getDataPrefix()
content.type = SyncState_UPDATE
content.seqno.seq = self._digestTree.get(i).getSequenceNo()
content.seqno.session = self._digestTree.get(i).getSessionNo()
if len(getattr(tempContent, "ss")) != 0:
# TODO: Check if this works in Python 3.
#pylint: disable=E1103
array = tempContent.SerializeToString()
#pylint: enable=E1103
data = Data(interest.getName())
data.setContent(Blob(array))
if interest.getName().get(-1).toEscapedString() == "00":
# Limit the lifetime of replies to interest for "00" since
# they can be different.
data.getMetaInfo().setFreshnessPeriod(1000)
self._keyChain.sign(data, self._certificateName)
try:
face.putData(data)
except Exception as ex:
logging.getLogger(__name__).error(
"Error in face.putData: %s", str(ex))
return
logging.getLogger(__name__).info("send recovery data back")
logging.getLogger(__name__).info("%s", interest.getName().toUri())
开发者ID:named-data,项目名称:PyNDN2,代码行数:33,代码来源:chrono_sync2013.py
示例4: _processRecoveryInterest
def _processRecoveryInterest(self, interest, syncDigest, transport):
logging.getLogger(__name__).info("processRecoveryInterest")
if self._logFind(syncDigest) != -1:
tempContent = sync_state_pb2.SyncStateMsg()
for i in range(self._digestTree.size()):
content = getattr(tempContent, "ss").add()
content.name = self._applicationDataPrefixUri
content.type = SyncState_UPDATE
content.seqno.seq = self._sequenceNo
content.seqno.session = self._digestTree.get(i).getSessionNo()
if len(getattr(tempContent, "ss")) != 0:
# TODO: Check if this works in Python 3.
#pylint: disable=E1103
array = tempContent.SerializeToString()
#pylint: enable=E1103
data = Data(interest.getName())
data.setContent(Blob(array))
self._keyChain.sign(data, self._certificateName)
try:
transport.send(data.wireEncode().toBuffer())
except Exception as ex:
logging.getLogger(__name__).error(
"Error in transport.send: %s", str(ex))
return
logging.getLogger(__name__).info("send recovery data back")
logging.getLogger(__name__).info("%s", interest.getName().toUri())
开发者ID:WeiqiJust,项目名称:NDN-total,代码行数:28,代码来源:chrono_sync2013.py
示例5: _createDKeyData
def _createDKeyData(self, startTimeStamp, endTimeStamp, keyName,
privateKeyBlob, certificateKey):
"""
Create a D-KEY Data packet with an EncryptedContent for the given
private key, encrypted with the certificate key.
:param str startTimeStamp: The start time stamp string to put in the name.
:param str endTimeStamp: The end time stamp string to put in the name.
:param Name keyName The key name to put in the data packet name and the
EncryptedContent key locator.
:param Blob privateKeyBlob: A Blob of the encoded private key.
:param Blob certificateKey: The certificate key encoding, used to
encrypt the private key.
:return: The Data packet.
:rtype: Data
"""
name = Name(self._namespace)
name.append(Encryptor.NAME_COMPONENT_D_KEY)
name.append(startTimeStamp).append(endTimeStamp)
data = Data(name)
data.getMetaInfo().setFreshnessPeriod(
self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR)
encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
Encryptor.encryptData(
data, privateKeyBlob, keyName, certificateKey, encryptParams)
self._keyChain.sign(data)
return data
开发者ID:named-data,项目名称:PyNDN2,代码行数:27,代码来源:group_manager.py
示例6: setName
def setName(self, name):
"""
Overrides Data.setName() to ensure that the new name is a valid identity
certificate name.
:param name: The new name for this IdentityCertificate
:type name: Name
"""
if (not self._isCorrectName(name)):
raise SecurityException("Bad format for identity certificate name!")
Data.setName(self, name)
self._setPublicKeyName()
开发者ID:MAHIS,项目名称:PyNDN2,代码行数:12,代码来源:identity_certificate.py
示例7: _broadcastSyncState
def _broadcastSyncState(self, digest, syncMessage):
"""
Make a data packet with the syncMessage and with name
applicationBroadcastPrefix_ + digest. Sign and send.
:param str digest: The root digest as a hex string for the data packet
name.
:param sync_state_pb2.SyncState syncMessage:
"""
data = Data(self._applicationBroadcastPrefix)
data.getName().append(digest)
# TODO: Check if this works in Python 3.
data.setContent(Blob(syncMessage.SerializeToString()))
self._keyChain.sign(data, self._certificateName)
self._contentCache.add(data)
开发者ID:named-data,项目名称:PyNDN2,代码行数:15,代码来源:chrono_sync2013.py
示例8: wireDecode
def wireDecode(self, buf, wireFormat = None):
"""
Override to call the base class wireDecode then check the certificate
format.
:param input: The array with the bytes to decode. If input is not a
Blob, then copy the bytes to save the defaultWireEncoding (otherwise
take another pointer to the same Blob).
:type input: A Blob or an array type with int elements
:param wireFormat: (optional) A WireFormat object used to decode this
Data object. If omitted, use WireFormat.getDefaultWireFormat().
:type wireFormat: A subclass of WireFormat
"""
Data.wireDecode(self, buf, wireFormat)
self._checkFormat()
开发者ID:named-data,项目名称:PyNDN2,代码行数:15,代码来源:certificate_v2.py
示例9: wireDecode
def wireDecode(self, input):
"""
Decode the input as an NDN-TLV SafeBag and update this object.
:param input: The array with the bytes to decode.
:type input: A Blob or an array type with int elements
"""
if isinstance(input, Blob):
input = input.buf()
# Decode directly as TLV. We don't support the WireFormat abstraction
# because this isn't meant to go directly on the wire.
decoder = TlvDecoder(input)
endOffset = decoder.readNestedTlvsStart(Tlv.SafeBag_SafeBag)
# Get the bytes of the certificate and decode.
certificateBeginOffset = decoder.getOffset()
certificateEndOffset = decoder.readNestedTlvsStart(Tlv.Data)
decoder.seek(certificateEndOffset)
self._certificate = Data()
self._certificate.wireDecode(
decoder.getSlice(certificateBeginOffset, certificateEndOffset),
TlvWireFormat.get())
self._privateKeyBag = Blob(
decoder.readBlobTlv(Tlv.SafeBag_EncryptedKeyBag), True)
decoder.finishNestedTlvs(endOffset)
开发者ID:named-data,项目名称:PyNDN2,代码行数:28,代码来源:safe_bag.py
示例10: _encryptContentKey
def _encryptContentKey(self, encryptionKey, eKeyName, timeSlot,
onEncryptedKeys, onError):
"""
Get the content key from the database_ and encrypt it for the timeSlot
using encryptionKey.
:param Blob encryptionKey: The encryption key value.
:param Name eKeyName: The key name for the EncryptedContent.
:param float timeSlot: The time slot as milliseconds since Jan 1, 1970 UTC.
:param onEncryptedKeys: When there are no more interests to process,
this calls onEncryptedKeys(keys) where keys is a list of encrypted
content key Data packets. If onEncryptedKeys is None, this does not
use it.
:type onEncryptedKeys: function object
:param onError: This calls onError(errorCode, message) for an error.
:type onError: function object
:return: True if encryption succeeds, otherwise False.
:rtype: bool
"""
timeCount = round(timeSlot)
keyRequest = self._keyRequests[timeCount]
keyName = Name(self._namespace)
keyName.append(Encryptor.NAME_COMPONENT_C_KEY)
keyName.append(
Schedule.toIsoString(Producer._getRoundedTimeSlot(timeSlot)))
contentKey = self._database.getContentKey(timeSlot)
cKeyData = Data()
cKeyData.setName(keyName)
params = EncryptParams(EncryptAlgorithmType.RsaOaep)
try:
Encryptor.encryptData(
cKeyData, contentKey, eKeyName, encryptionKey, params)
except Exception as ex:
try:
onError(EncryptError.ErrorCode.EncryptionFailure,
"encryptData error: " + repr(ex))
except:
logging.exception("Error in onError")
return False
self._keyChain.sign(cKeyData)
keyRequest.encryptedKeys.append(cKeyData)
self._updateKeyRequest(keyRequest, timeCount, onEncryptedKeys)
return True
开发者ID:MAHIS,项目名称:PyNDN2,代码行数:47,代码来源:producer.py
示例11: _createEKeyData
def _createEKeyData(self, startTimeStamp, endTimeStamp, publicKeyBlob):
"""
Create an E-KEY Data packet for the given public key.
:param str startTimeStamp: The start time stamp string to put in the name.
:param str endTimeStamp: The end time stamp string to put in the name.
:param Blob publicKeyBlob: A Blob of the public key DER.
:return: The Data packet.
:rtype: Data
"""
name = Name(self._namespace)
name.append(Encryptor.NAME_COMPONENT_E_KEY).append(startTimeStamp).append(endTimeStamp)
data = Data(name)
data.getMetaInfo().setFreshnessPeriod(self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR)
data.setContent(publicKeyBlob)
self._keyChain.sign(data)
return data
开发者ID:named-data,项目名称:PyNDN2,代码行数:18,代码来源:group_manager.py
示例12: __init__
def __init__(self, data, successCallback, failureCallback):
super(DataValidationState, self).__init__()
# Make a copy.
self._data = Data(data)
self._successCallback = successCallback
self._failureCallback = failureCallback
if self._successCallback == None:
raise ValueError("The successCallback is None")
if self._failureCallback == None:
raise ValueError("The failureCallback is None")
开发者ID:named-data,项目名称:PyNDN2,代码行数:12,代码来源:data_validation_state.py
示例13: onReceivedElement
def onReceivedElement(self, element):
"""
This is called by the transport's ElementReader to process an
entire received Data or Interest element.
:param element: The bytes of the incoming element.
:type element: An array type with int elements
"""
# The type codes for TLV Interest and Data packets are chosen to not
# conflict with the first byte of a binary XML packet, so we canjust
# look at the first byte.
if not (element[0] == Tlv.Interest or element[0] == Tlv.Data):
# Ignore non-TLV elements.
return
# First, decode as Interest or Data.
interest = None
data = None
decoder = TlvDecoder(element)
if decoder.peekType(Tlv.Interest, len(element)):
interest = Interest()
interest.wireDecode(element, TlvWireFormat.get())
elif decoder.peekType(Tlv.Data, len(element)):
data = Data()
data.wireDecode(element, TlvWireFormat.get())
# Now process as Interest or Data.
if interest != None:
entry = self._getEntryForRegisteredPrefix(interest.getName())
if entry != None:
entry.getOnInterest()(
entry.getPrefix(), interest, self._transport,
entry.getRegisteredPrefixId())
elif data != None:
pendingInterests = self._extractEntriesForExpressedInterest(
data.getName())
for pendingInterest in pendingInterests:
pendingInterest.getOnData()(pendingInterest.getInterest(), data)
开发者ID:WeiqiJust,项目名称:NDN-total,代码行数:38,代码来源:node.py
示例14: __init__
def __init__(self, arg1, privateKeyBag = None,
publicKeyEncoding = None, password = None,
digestAlgorithm = DigestAlgorithm.SHA256, wireFormat = None):
if isinstance(arg1, Name):
keyName = arg1
if wireFormat == None:
# Don't use a default argument since getDefaultWireFormat can change.
wireFormat = WireFormat.getDefaultWireFormat()
self._certificate = SafeBag._makeSelfSignedCertificate(
keyName, privateKeyBag, publicKeyEncoding, password,
digestAlgorithm, wireFormat)
self._privateKeyBag = privateKeyBag
elif isinstance(arg1, Data):
# The certificate is supplied.
self._certificate = Data(arg1)
self._privateKeyBag = privateKeyBag
else:
# Assume the first argument is the encoded SafeBag.
self.wireDecode(arg1)
开发者ID:named-data,项目名称:PyNDN2,代码行数:20,代码来源:safe_bag.py
示例15: _makeAndPublishCkData
def _makeAndPublishCkData(self, onError):
"""
Make a CK Data packet for _ckName encrypted by the KEK in _kekData and
insert it in the _storage.
:param onError: On failure, this calls onError(errorCode, message) where
errorCode is from EncryptError.ErrorCode, and message is an error
string.
:type onError: function object
:return: True on success, else False.
:rtype: bool
"""
try:
kek = PublicKey(self._kekData.getContent())
content = EncryptedContent()
content.setPayload(kek.encrypt
(Blob(self._ckBits, False), EncryptAlgorithmType.RsaOaep))
ckData = Data(
Name(self._ckName).append(EncryptorV2.NAME_COMPONENT_ENCRYPTED_BY)
.append(self._kekData.getName()))
ckData.setContent(content.wireEncodeV2())
# FreshnessPeriod can serve as a soft access control for revoking access.
ckData.getMetaInfo().setFreshnessPeriod(
EncryptorV2.DEFAULT_CK_FRESHNESS_PERIOD_MS)
self._keyChain.sign(ckData, self._ckDataSigningInfo)
self._storage.insert(ckData)
logging.getLogger(__name__).info("Publishing CK data: " +
ckData.getName().toUri())
return True
except Exception as ex:
onError(EncryptError.ErrorCode.EncryptionFailure,
"Failed to encrypt generated CK with KEK " +
self._kekData.getName().toUri())
return False
开发者ID:named-data,项目名称:PyNDN2,代码行数:37,代码来源:encryptor_v2.py
示例16: DataValidationState
class DataValidationState(ValidationState):
"""
Create a DataValidationState for the Data packet. The caller must ensure
that the state instance is valid until the validation finishes (i.e., until
validateCertificateChain() and validateOriginalPacket() have been called).
:param Data data: The Date packet being validated, which is copied.
:param successCallback: This calls successCallback(data) to report a
successful Data validation.
:type successCallback: function object
:param failureCallback: This calls failureCallback(data, error) to report a
failed Data validation, where error is a ValidationError.
:type failureCallback: function object
"""
def __init__(self, data, successCallback, failureCallback):
super(DataValidationState, self).__init__()
# Make a copy.
self._data = Data(data)
self._successCallback = successCallback
self._failureCallback = failureCallback
if self._successCallback == None:
raise ValueError("The successCallback is None")
if self._failureCallback == None:
raise ValueError("The failureCallback is None")
def fail(self, error):
"""
Call the failure callback.
:param ValidationError error:
"""
logging.getLogger(__name__).info("" + str(error))
try:
self._failureCallback(self._data, error)
except:
logging.exception("Error in failureCallback")
self.setOutcome(False)
def getOriginalData(self):
"""
Get the original Data packet being validated which was given to the
constructor.
:return: The original Data packet.
:rtype: Data
"""
return self._data
def _verifyOriginalPacket(self, trustedCertificate):
"""
Verify the signature of the original packet. This is only called by the
Validator class.
:param CertificateV2 trustedCertificate: The certificate that signs the
original packet.
"""
if VerificationHelpers.verifyDataSignature(self._data, trustedCertificate):
logging.getLogger(__name__).info("OK signature for data `" +
self._data.getName().toUri() + "`")
try:
self._successCallback(self._data)
except:
logging.exception("Error in successCallback")
self.setOutcome(True)
else:
self.fail(ValidationError(ValidationError.INVALID_SIGNATURE,
"Invalid signature of data `" + self._data.getName().toUri() + "`"))
def _bypassValidation(self):
"""
Call the success callback of the original packet without signature
validation. This is only called by the Validator class.
"""
logging.getLogger(__name__).info("Signature verification bypassed for data `" +
self._data.getName().toUri() + "`")
try:
self._successCallback(self._data)
except:
logging.exception("Error in successCallback")
self.setOutcome(True)
开发者ID:named-data,项目名称:PyNDN2,代码行数:85,代码来源:data_validation_state.py
示例17: _registerPrefixHelper
def _registerPrefixHelper(
self, registeredPrefixId, prefix, onInterest, onRegisterFailed, flags,
wireFormat, face):
"""
Do the work of registerPrefix to register with NDNx once we have an
_ndndId.
: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 not WireFormat.ENABLE_NDNX:
# We can get here if the command signing info is set, but running NDNx.
raise RuntimeError(
"registerPrefix with NDNx is deprecated. To enable while you upgrade your code to use NFD, set WireFormat.ENABLE_NDNX = True")
# Create a ForwardingEntry.
# Note: ndnd ignores any freshness that is larger than 3600 seconds and
# sets 300 seconds instead. To register "forever", (=2000000000 sec),
# the freshness period must be omitted.
forwardingEntry = ForwardingEntry()
forwardingEntry.setAction("selfreg")
forwardingEntry.setPrefix(prefix)
forwardingEntry.setForwardingFlags(flags)
content = forwardingEntry.wireEncode(wireFormat)
# Set the ForwardingEntry as the content of a Data packet and sign.
data = Data()
data.setContent(content)
# Set the name to a random value so that each request is unique.
nonce = bytearray(4)
for i in range(len(nonce)):
nonce[i] = _systemRandom.randint(0, 0xff)
data.getName().append(nonce)
# The ndnd ignores the signature, so set to blank values.
data.getSignature().getKeyLocator().setType(
KeyLocatorType.KEY_LOCATOR_DIGEST)
data.getSignature().getKeyLocator().setKeyData(
Blob(bytearray(32), False))
data.getSignature().setSignature(Blob(bytearray(128), False))
encodedData = data.wireEncode(wireFormat)
# Create an interest where the name has the encoded Data packet.
interestName = Name().append("ndnx").append(self._ndndId).append(
"selfreg").append(encodedData)
interest = Interest(interestName)
interest.setInterestLifetimeMilliseconds(4000.0)
interest.setScope(1)
if registeredPrefixId != 0:
interestFilterId = 0
if onInterest != None:
# registerPrefix was called with the "combined" form that includes
# the callback, so add an InterestFilterEntry.
interestFilterId = self.getNextEntryId()
self.setInterestFilter(
interestFilterId, InterestFilter(prefix), onInterest, face)
self._registeredPrefixTable.append(Node._RegisteredPrefix(
registeredPrefixId, prefix, interestFilterId))
# Send the registration interest.
response = Node._RegisterResponse(
self, prefix, onInterest, onRegisterFailed, flags, wireFormat, False,
face)
self.expressInterest(
self.getNextEntryId(), interest, response.onData, response.onTimeout,
wireFormat, face)
开发者ID:mjycom,项目名称:PyNDN2,代码行数:69,代码来源:node.py
示例18: onReceivedElement
def onReceivedElement(self, element):
"""
This is called by the transport's ElementReader to process an
entire received Data or Interest element.
:param element: The bytes of the incoming element.
:type element: An array type with int elements
"""
# The type codes for TLV Interest and Data packets are chosen to not
# conflict with the first byte of a binary XML packet, so we canjust
# look at the first byte.
if not (element[0] == Tlv.Interest or element[0] == Tlv.Data):
# Ignore non-TLV elements.
# Assume it is Binary XML.
if not WireFormat.ENABLE_NDNX:
raise RuntimeError(
"BinaryXmlWireFormat (NDNx) is deprecated. To enable while you upgrade your network to use NDN-TLV, set WireFormat.ENABLE_NDNX = True")
return
# First, decode as Interest or Data.
interest = None
data = None
decoder = TlvDecoder(element)
if decoder.peekType(Tlv.Interest, len(element)):
interest = Interest()
interest.wireDecode(element, TlvWireFormat.get())
elif decoder.peekType(Tlv.Data, len(element)):
data = Data()
data.wireDecode(element, TlvWireFormat.get())
# Now process as Interest or Data.
if interest != None:
# Call all interest filter callbacks which match.
for i in range(len(self._interestFilterTable)):
entry = self._interestFilterTable[i]
if entry.getFilter().doesMatch(interest.getName()):
includeFilter = True
# Use getcallargs to test if onInterest accepts 5 args.
try:
inspect.getcallargs(entry.getOnInterest(),
None, None, None, None, None)
except TypeError:
# Assume onInterest is old-style with 4 arguments.
includeFilter = False
if includeFilter:
entry.getOnInterest()(
entry.getFilter().getPrefix(), interest,
entry.getFace(), entry.getInterestFilterId(),
entry.getFilter())
else:
# Old-style onInterest without the filter argument. We
# still pass a Face instead of Transport since Face also
# has a send method.
entry.getOnInterest()(
entry.getFilter().getPrefix(), interest,
entry.getFace(), entry.getInterestFilterId())
elif data != None:
pendingInterests = self._extractEntriesForExpressedInterest(
data.getName())
for pendingInterest in pendingInterests:
pendingInterest.getOnData()(pendingInterest.getInterest(), data)
开发者ID:mjycom,项目名称:PyNDN2,代码行数:63,代码来源:node.py
示例19: onReceivedElement
def onReceivedElement(self, element):
"""
This is called by the transport's ElementReader to process an
entire received Data or Interest element.
:param element: The bytes of the incoming element.
:type element: An array type with int elements
"""
lpPacket = None
if element[0] == Tlv.LpPacket_LpPacket:
# Decode the LpPacket and replace element with the fragment.
lpPacket = LpPacket()
# Set copy False so that the fragment is a slice which will be
# copied below. The header fields are all integers and don't need to
# be copied.
TlvWireFormat.get().decodeLpPacket(lpPacket, element, False)
element = lpPacket.getFragmentWireEncoding().buf()
# First, decode as Interest or Data.
interest = None
data = None
decoder = TlvDecoder(element)
if decoder.peekType(Tlv.Interest, len(element)):
interest = Interest()
interest.wireDecode(element, TlvWireFormat.get())
if lpPacket != None:
interest.setLpPacket(lpPacket)
elif decoder.peekType(Tlv.Data, len(element)):
data = Data()
data.wireDecode(element, TlvWireFormat.get())
if lpPacket != None:
data.setLpPacket(lpPacket)
if lpPacket != None:
# We have decoded the fragment, so remove the wire encoding to save
# memory.
lpPacket.setFragmentWireEncoding(Blob())
networkNack = NetworkNack.getFirstHeader(lpPacket)
if networkNack != None:
if interest == None:
# We got a Nack but not for an Interest, so drop the packet.
return
pendingInterests = []
self._pendingInterestTable.extractEntriesForNackInterest(
interest, pendingInterests)
for pendingInterest in pendingInterests:
try:
pendingInterest.getOnNetworkNack()(
pendingInterest.getInterest(), networkNack)
except:
logging.exception("Error in onNetworkNack")
# We have processed the network Nack packet.
return
# Now process as Interest or Data.
if interest != None:
self._dispatchInterest(interest)
elif data != None:
self._satisfyPendingInterests(data)
开发者ID:named-data,项目名称:PyNDN2,代码行数:65,代码来源:node.py
示例20: _processSyncInterest
def _processSyncInterest(self, index, syncDigest, face):
"""
Common interest processing, using digest log to find the difference
after syncDigest.
:return: True if sent a data packet to satisfy the interest, otherwise
False.
:rtype: bool
"""
nameList = [] # of str
sequenceNoList = [] # of int
sessionNoList = [] # of int
for j in range(index + 1, len(self._digestLog)):
temp = self._digestLog[j].getData() # array of sync_state_pb2.SyncState.
for i in range(len(temp)):
syncState = temp[i]
if syncState.type != SyncState_UPDATE:
continue
if self._digestTree.find(
syncState.name, syncState.seqno.session) != -1:
n = -1
for k in range(len(nameList)):
if nameList[k] == syncState.name:
n = k
break
if n == -1:
nameList.append(syncState.name)
sequenceNoList.append(syncState.seqno.seq)
sessionNoList.append(syncState.seqno.session)
else:
sequenceNoList[n] = syncState.seqno.seq
sessionNoList[n] = syncState.seqno.session
tempContent = SyncStateMsg()
for i in range(len(nameList)):
content = getattr(tempContent, "ss").add()
content.name = nameList[i]
content.type = SyncState_UPDATE
content.seqno.seq = sequenceNoList[i]
content.seqno.session = sessionNoList[i]
sent = False
if len(getattr(tempContent, "ss")) != 0:
name = Name(self._applicationBroadcastPrefix)
name.append(syncDigest)
# TODO: Check if this works in Python 3.
#pylint: disable=E1103
array = tempContent.SerializeToString()
#pylint: enable=E1103
data = Data(name)
data.setContent(Blob(array))
self._keyChain.sign(data, self._certificateName)
try:
face.putData(data)
except Exception as ex:
logging.getLogger(__name__).error(
"Error in face.putData: %s", str(ex))
return
sent = True
logging.getLogger(__name__).info("Sync Data send")
logging.getLogger(__name__).info("%s", name.toUri())
return sent
开发者ID:named-data,项目名称:PyNDN2,代码行数:67,代码来源:chrono_sync2013.py
注:本文中的pyndn.data.Data类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论