ndn.app package

Introduction

The ndn.app package contains the class NDNApp , which connects an NDN application and an NFD node.

NDNApp provides the functionalities similar to application Face in ndn-cxx, which include:

  • Establish a connection to an NFD node.

  • Express Interests and handle the Data coming back.

  • Register and unregister a route with an Interest handling function.

This package does not support PIT token. To use PIT token, consider using ndn.appv2 package.

Keyword Arguments

Some functions which create a Interest or Data packet accept a kwargs, which can be used to support diversity in arguments provided to create a packet.

MetaInfo

These arguments are used to fill in the MetaInfo field of a Data packet.

  • meta_info (MetaInfo) - the MetaInfo field of Data. All other related parameters will be ignored.

  • content_type (int) - ContentType. ContentType.BLOB by default.

  • freshness_period (int) - FreshnessPeriod in milliseconds. None by default.

  • final_block_id (BinaryStr) - FinalBlockId. It should be an encoded Component. None by default.

InterestParameters

These arguments are used to fill in fields of an Interest packet.

  • interest_param (InterestParam) - a dataclass containing all parameters. All other related parameters will be ignored.

  • can_be_prefix (bool) - CanBePrefix. False by default.

  • must_be_fresh (bool) - MustBeFresh. False by default.

  • nonce (int) - Nonce. A random number will be generated by default. To omit Nonce, please explicitly pass None to this argument.

  • lifetime (int) - InterestLifetime in milliseconds. 4000 by default.

    Warning

    On Windows, a too small number may cause a memory failure of the NameTrie. Currently, >=10 is safe.

  • hop_limit (int) - HopLimit. None by default.

  • forwarding_hint (list[NonStrictName]) - see InterestParam.

Signature

These arguments are used to decide how the Interest or Data packet is signed and by which Signer. Supported arguments are different with each Keychain. Only those supported by the default Keychain are listed here. If there is a conflict, the earlier an argument is listed the higher priority it has.

Note

Only Interests with ApplicationParameters are signed. b'' can be used if that field is not needed by the application.

  • signer (Signer) - the Signer used to sign this packet. All other related parameters will be ignored. The Keychain will not be used.

  • no_signature (bool) - not signed. Not recommended.

  • digest_sha256 (bool) - using SHA-256 digest to protect integrity only. False by default.

  • cert (NonStrictName) - using the speficied Certificate to sign this packet. The Key name will be derived from the certificate name.

  • key - using the specified Key to sign this packet. Either a Key object or the NonStrictName of a Key is acceptable. KeyLocator will be set to the default Certificate name of this Key unless specified.

  • identity - using the default Key of the specified Identity to sign this packet. Either an Identity object or the NonStrictName of an Identity is acceptable. The default Identity will be used if all of the above arguments are omitted.

  • key_locator (NonStrictName) - using the specified KeyLocator Name regardless of which Key is used.

Reference

class ndn.app.NDNApp(face=None, keychain=None)

An NDN application.

Variables:
  • face – the Face used to connection to a NFD node.

  • keychain – the Keychain to store Identities and Keys, providing Signers.

  • int_validator – the default validator for Interest packets.

  • data_validator – the default validator for Data packets.

express_interest(name, app_param=None, validator=None, need_raw_packet=False, **kwargs)

Express an Interest packet.

The Interest packet is sent immediately and a coroutine used to get the result is returned. Awaiting on what is returned will block until the Data is received and return that Data. An exception is raised if unable to receive the Data.

Parameters:
  • name (NonStrictName) – the Name.

  • app_param (Optional[BinaryStr]) – the ApplicationParameters.

  • validator (Optional[Validator]) – the Validator used to verify the Data received.

  • need_raw_packet (bool) – if True, return the raw Data packet with TL.

  • kwargsKeyword Arguments.

Returns:

A tuple of (Name, MetaInfo, Content) after await. If need_raw_packet is True, return a tuple (Name, MetaInfo, Content, RawPacket).

Return type:

Coroutine[Any, None, Tuple[FormalName, MetaInfo, Optional[BinaryStr]]]

The following exception is raised by express_interest:

Raises:

NetworkError – the face to NFD is down before sending this Interest.

The following exceptions are raised by the coroutine returned:

Raises:
async main_loop(after_start=None)

The main loop of NDNApp.

Parameters:

after_start (Awaitable) – the coroutine to start after connection to NFD is established.

Return type:

bool

Returns:

True if the connection is shutdown not by Ctrl+C. For example, manually or by the other side.

prepare_data(name, content=None, **kwargs)

Prepare a Data packet by generating, encoding and signing it.

Parameters:
Returns:

TLV encoded Data packet.

put_data(name, content=None, **kwargs)

Publish a Data packet.

Parameters:
Returns:

TLV encoded Data packet.

put_raw_packet(data)

Send a raw Data packet.

Parameters:

data (BinaryStr) – TLV encoded Data packet.

Raises:

NetworkError – the face to NFD is down.

async register(name, func, validator=None, need_raw_packet=False, need_sig_ptrs=False)

Register a route for a specific prefix dynamically.

Parameters:
  • name (NonStrictName) – the Name prefix for this route.

  • func (Optional[Callable[[FormalName, InterestParam, Optional[BinaryStr]], None]]) – the onInterest function for the specified route. If None, the NDNApp will only send the register command to forwarder, without setting any callback function.

  • validator (Optional[Validator]) – the Validator used to validate coming Interests.

  • need_raw_packet (bool) – if True, pass the raw Interest packet to the callback as a keyword argument raw_packet.

  • need_sig_ptrs (bool) – if True, pass the Signature pointers to the callback as a keyword argument sig_ptrs.

Return type:

bool

Returns:

True if the registration succeeded.

Raises:
  • ValueError – the prefix is already registered.

  • NetworkError – the face to NFD is down now.

route(name, validator=None, need_raw_packet=False, need_sig_ptrs=False)

A decorator used to register a permanent route for a specific prefix.

This function is non-blocking and can be called at any time. If it is called before connecting to NFD, NDNApp will remember this route and automatically register it every time when a connection is established. Failure in registering this route to NFD will be ignored.

The decorated function should accept 3 arguments: Name, Interest parameters and ApplicationParameters.

Parameters:
  • name (NonStrictName) – the Name prefix for this route.

  • validator (Optional[Validator]) – the Validator used to validate coming Interests. An Interest without ApplicationParameters and SignatureInfo will be considered valid without calling validator. Interests with malformed ParametersSha256DigestComponent will be dropped before going into the validator. Otherwise NDNApp will try to validate the Interest with the validator. Interests which fail to be validated will be dropped without raising any exception.

  • need_raw_packet (bool) – if True, pass the raw Interest packet to the callback as a keyword argument raw_packet.

  • need_sig_ptrs (bool) – if True, pass the Signature pointers to the callback as a keyword argument sig_ptrs.

Examples:
app = NDNApp()

@app.route('/example/rpc')
def on_interest(name: FormalName, param: InterestParam, app_param):
    pass

Note

The route function must be a normal function instead of an async one. This is on purpose, because an Interest is supposed to be replied ASAP, even it cannot finish the request in time. To provide some feedback, a better practice is replying with an Application NACK (or some equivalent Data packet saying the operation cannot be finished in time). If you want to use await in the handler, please use asyncio.create_task to create a new coroutine.

Note

Currently, python-ndn does not handle PIT Tokens.

run_forever(after_start=None)

A non-async wrapper of main_loop().

Parameters:

after_start (Awaitable) – the coroutine to start after connection to NFD is established.

Examples:
app = NDNApp()

if __name__ == '__main__':
    app.run_forever(after_start=main())
set_interest_filter(name, func, validator=None, need_raw_packet=False, need_sig_ptrs=False)

Set the callback function for an Interest prefix without sending a register command to the forwarder.

Note

All callbacks registered by set_interest_filter are removed when disconnected from the the forwarder, and will not be added back after reconnection. This behaviour is the same as register. Therefore, it is strongly recommended to use route for static routes.

shutdown()

Manually shutdown the face to NFD.

async unregister(name)

Unregister a route for a specific prefix.

Parameters:

name (NonStrictName) – the Name prefix.

Return type:

bool

unset_interest_filter(name)

Remove the callback function for an Interest prefix without sending an unregister command.

Note

unregister will only remove the callback if the callback’s name matches exactly the route’s name. This is because there may be one route whose name is the prefix of another. To avoid cancelling unexpected routes, neither unregister nor unset_interest_filter behaves in a cascading manner. Please remove callbacks manually.