nostr_tools.RelayMetadata

class nostr_tools.RelayMetadata[source]

Bases: object

Comprehensive metadata for a Nostr relay.

This class stores complete metadata about a relay, combining information from multiple Nostr Improvement Proposals (NIPs). It includes: - Relay connection and configuration (Relay object) - NIP-11: Relay information document (name, description, capabilities) - NIP-66: Connection performance metrics (RTT, read/write capabilities) - Generation timestamp for tracking when metadata was collected

The metadata provides a comprehensive view of relay capabilities and performance, useful for relay selection, monitoring, and health checks.

Examples

Fetch complete relay metadata:

>>> relay = Relay("wss://relay.damus.io")
>>> client = Client(relay)
>>> metadata = await fetch_relay_metadata(client, private_key, public_key)
>>> print(f"Relay: {metadata.relay.url}")
>>> print(f"Name: {metadata.nip11.name if metadata.nip11 else 'Unknown'}")
>>> print(f"Readable: {metadata.nip66.readable if metadata.nip66 else False}")

Access NIP-11 information:

>>> if metadata.nip11:
...     print(f"Software: {metadata.nip11.software}")
...     print(f"Supported NIPs: {metadata.nip11.supported_nips}")

Check connection metrics:

>>> if metadata.nip66:
...     print(f"Connection time: {metadata.nip66.rtt_open}ms")
...     print(f"Read capable: {metadata.nip66.readable}")
...     print(f"Write capable: {metadata.nip66.writable}")
Raises:

RelayMetadataValidationError – If metadata validation fails during initialization or when invalid data is provided.

Methods

__init__(relay, generated_at[, nip11, nip66])

from_dict(data)

Create RelayMetadata from dictionary representation.

to_dict()

Convert RelayMetadata to dictionary representation.

validate()

Validate the RelayMetadata instance.

Attributes

is_valid

Check if all metadata is valid without raising exceptions.

nip11

NIP-11 relay information document data

nip66

NIP-66 connection and performance data

relay

The relay object this metadata describes

generated_at

Timestamp when the metadata was generated

relay: Relay

The relay object this metadata describes

generated_at: int

Timestamp when the metadata was generated

nip11: Nip11 | None = None

NIP-11 relay information document data

nip66: Nip66 | None = None

NIP-66 connection and performance data

__post_init__()[source]

Validate RelayMetadata after initialization.

This method is automatically called after the dataclass is created. It performs validation to ensure all metadata is properly formatted.

Raises:

RelayMetadataValidationError – If metadata validation fails

Return type:

None

validate()[source]

Validate the RelayMetadata instance.

Raises:

RelayMetadataValidationError – If relay metadata is invalid

Return type:

None

property is_valid: bool

Check if all metadata is valid without raising exceptions.

This property attempts validation and returns True if successful, False otherwise. Unlike validate(), this method does not raise exceptions, making it safe for conditional checks.

Returns:

True if all metadata passes validation checks,

False if validation fails for any reason.

Return type:

bool

Examples

>>> metadata = await fetch_relay_metadata(client, sec, pub)
>>> if metadata.is_valid:
...     print("Metadata is valid")
...     store_metadata(metadata)
... else:
...     print("Invalid metadata")
>>> # Validate before processing
>>> if not metadata.is_valid:
...     logger.warning(f"Invalid metadata for {metadata.relay.url}")
classmethod from_dict(data)[source]

Create RelayMetadata from dictionary representation.

This method reconstructs a RelayMetadata instance from a dictionary, typically used for deserialization from storage or network transmission.

Parameters:

data (dict[str, Any]) – Dictionary containing relay metadata with keys: - relay (dict): Relay configuration dictionary - generated_at (int): Unix timestamp when metadata was generated - nip11 (Optional[dict]): NIP-11 relay information or None - nip66 (Optional[dict]): NIP-66 connection metrics or None

Returns:

An instance of RelayMetadata created from the dictionary.

Return type:

RelayMetadata

Raises:

Examples

Load from JSON:

>>> import json
>>> with open('relay_metadata.json') as f:
...     data = json.load(f)
>>> metadata = RelayMetadata.from_dict(data)

Deserialize from database:

>>> metadata_dict = db.relay_metadata.find_one({"relay.url": url})
>>> metadata = RelayMetadata.from_dict(metadata_dict)

Parse API response:

>>> response = requests.get(f"{api_url}/relay/metadata")
>>> metadata = RelayMetadata.from_dict(response.json())
to_dict()[source]

Convert RelayMetadata to dictionary representation.

This method serializes the RelayMetadata instance into a dictionary format suitable for JSON encoding, storage, or network transmission.

Returns:

Dictionary representation of RelayMetadata with keys:
  • relay (dict): Relay configuration dictionary

  • generated_at (int): Unix timestamp when metadata was generated

  • nip11 (Optional[dict]): NIP-11 relay information or None

  • nip66 (Optional[dict]): NIP-66 connection metrics or None

Return type:

dict[str, Any]

Examples

Serialize to JSON:

>>> metadata = await fetch_relay_metadata(client, sec, pub)
>>> metadata_dict = metadata.to_dict()
>>> import json
>>> json_str = json.dumps(metadata_dict, indent=2)
>>> with open('relay_metadata.json', 'w') as f:
...     f.write(json_str)

Store in database:

>>> metadata_dict = metadata.to_dict()
>>> db.relay_metadata.insert_one(metadata_dict)

Send via API:

>>> response = requests.post(
...     f"{api_url}/relay/metadata",
...     json=metadata.to_dict()
... )
class Nip11[source]

Bases: object

NIP-11: Relay Information Document

This module defines the Nip11 class for handling relay information documents as specified in NIP-11. It includes validation, normalization, and conversion to/from dictionary representations.

name: str | None = None

Relay name

description: str | None = None

Relay description

banner: str | None = None

URL to banner image

icon: str | None = None

URL to icon image

pubkey: str | None = None

Relay public key

contact: str | None = None

Contact information

supported_nips: list[int | str] | None = None

List of supported NIPs

software: str | None = None

Software name

version: str | None = None

Software version

privacy_policy: str | None = None

URL to privacy policy

terms_of_service: str | None = None

URL to terms of service

limitation: dict[str, Any] | None = None

Limitation information

extra_fields: dict[str, Any] | None = None

Additional fields

__post_init__()[source]

Normalize and validate data after initialization.

This method is automatically called after the dataclass is created. It normalizes empty collections to None and validates the NIP-11 data.

Raises:

Nip11ValidationError – If NIP-11 data validation fails

Return type:

None

validate()[source]

Validate NIP-11 data.

Raises:

Nip11ValidationError – If NIP-11 data is invalid

Return type:

None

property is_valid: bool

Check if the NIP-11 data is valid.

Returns:

True if valid, False otherwise

Return type:

bool

classmethod from_dict(data)[source]

Create Nip11 from dictionary.

Parameters:

data (dict[str, Any]) – Dictionary containing NIP-11 data

Returns:

An instance of Nip11

Return type:

RelayMetadata.Nip11

Raises:
to_dict()[source]

Convert Nip11 to dictionary.

Returns:

Dictionary representation of Nip11

Return type:

dict[str, Any]

__init__(name=None, description=None, banner=None, icon=None, pubkey=None, contact=None, supported_nips=None, software=None, version=None, privacy_policy=None, terms_of_service=None, limitation=None, extra_fields=None)
Parameters:
  • name (str | None)

  • description (str | None)

  • banner (str | None)

  • icon (str | None)

  • pubkey (str | None)

  • contact (str | None)

  • supported_nips (list[int | str] | None)

  • software (str | None)

  • version (str | None)

  • privacy_policy (str | None)

  • terms_of_service (str | None)

  • limitation (dict[str, Any] | None)

  • extra_fields (dict[str, Any] | None)

Return type:

None

class Nip66[source]

Bases: object

NIP-66: Relay Connection and Performance Data

This module defines the Nip66 class for handling relay connection and performance data as specified in NIP-66. It includes validation, conversion to/from dictionary representations, and a property to check data validity.

openable: bool = False

Whether the relay is openable

readable: bool = False

Whether the relay is readable

writable: bool = False

Whether the relay is writable

rtt_open: int | None = None

Round-trip time to open connection in ms

rtt_read: int | None = None

Round-trip time to read data in ms

rtt_write: int | None = None

Round-trip time to write data in ms

__post_init__()[source]

Validate data after initialization.

This method is automatically called after the dataclass is created. It validates the NIP-66 connection and performance data.

Raises:

Nip66ValidationError – If NIP-66 data validation fails

Return type:

None

validate()[source]

Validate NIP-66 data.

Raises:

Nip66ValidationError – If NIP-66 data is invalid

Return type:

None

property is_valid: bool

Check if the NIP-66 data is valid.

Returns:

True if valid, False otherwise

Return type:

bool

classmethod from_dict(data)[source]

Create Nip66 from dictionary.

Parameters:

data (dict[str, Any]) – Dictionary containing NIP-66 data

Returns:

An instance of Nip66

Return type:

RelayMetadata.Nip66

Raises:
to_dict()[source]

Convert Nip66 to dictionary.

Returns:

Dictionary representation of Nip66

Return type:

dict[str, Any]

__init__(openable=False, readable=False, writable=False, rtt_open=None, rtt_read=None, rtt_write=None)
Parameters:
  • openable (bool)

  • readable (bool)

  • writable (bool)

  • rtt_open (int | None)

  • rtt_read (int | None)

  • rtt_write (int | None)

Return type:

None

__init__(relay, generated_at, nip11=None, nip66=None)
Parameters:
Return type:

None