nostr_tools.Relay¶
- class nostr_tools.Relay[source]¶
Bases:
objectNostr relay configuration and representation.
This class handles validation and representation of Nostr relay configurations. It automatically detects and validates network type (clearnet or Tor) based on the WebSocket URL format. The URL is validated and normalized upon initialization.
Examples
Create a clearnet relay:
>>> relay = Relay("wss://relay.damus.io") >>> print(relay.network) clearnet
Create a Tor relay:
>>> tor_relay = Relay("wss://relay.onion") >>> print(tor_relay.network) tor
URL is normalized automatically:
>>> relay = Relay("relay.damus.io") # Missing wss:// >>> print(relay.url) wss://relay.damus.io
Create from dictionary:
>>> relay_data = {"url": "wss://relay.damus.io"} >>> relay = Relay.from_dict(relay_data)
Validate a relay:
>>> try: ... relay.validate() ... print("Relay is valid") ... except RelayValidationError as e: ... print(f"Validation failed: {e}")
- Raises:
RelayValidationError – If URL is not a valid WebSocket URL or network type doesn’t match the URL.
Methods
__init__(url[, network])from_dict(data)Create a Relay instance from a dictionary representation.
to_dict()Convert the Relay object to a dictionary representation.
validate()Validate the Relay instance against protocol requirements.
Attributes
Check if the Relay is valid without raising exceptions.
Network type, automatically detected from URL.
// or ws://).
- url: str¶
// or ws://). Must be a valid WebSocket URL. Automatically normalized. Examples: “wss://relay.damus.io”, “wss://nostr.wine”
- Type:
WebSocket URL of the relay (wss
- network: str | None = None¶
Network type, automatically detected from URL. “clearnet” for standard internet relays, “tor” for .onion Tor hidden service relays.
- __post_init__()[source]¶
Validate and normalize the Relay instance after initialization.
This method is automatically called after the dataclass is created. It normalizes the URL, auto-detects the network type if not provided, and validates the relay configuration.
- Raises:
RelayValidationError – If URL or network configuration is invalid.
- Return type:
None
- validate()[source]¶
Validate the Relay instance against protocol requirements.
Performs comprehensive validation including: - Type checking for url and network attributes - WebSocket URL format validation (must be ws:// or wss://) - Network type consistency with URL (.onion for Tor) - URL normalization and format compliance
- Raises:
RelayValidationError – If url is not a valid WebSocket URL, or network type doesn’t match the URL pattern.
- Return type:
None
Examples
>>> relay = Relay("wss://relay.damus.io") >>> relay.validate() # Passes validation
>>> invalid_relay = Relay("https://not-a-websocket.com") >>> invalid_relay.validate() # Raises RelayValidationError
- property is_valid: bool¶
Check if the Relay 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 the relay passes all validation checks,
False if validation fails for any reason.
- Return type:
Examples
>>> relay = Relay("wss://relay.damus.io") >>> if relay.is_valid: ... client = Client(relay) ... else: ... print("Invalid relay configuration")
- classmethod from_dict(data)[source]¶
Create a Relay instance from a dictionary representation.
This class method constructs a Relay from a dictionary, typically used for deserialization from JSON or database records.
- Parameters:
data (
dict[str, Any]) – Dictionary containing relay configuration. Required keys: - url (str): WebSocket URL of the relay Optional keys: - network (str): Network type (auto-detected if omitted)- Returns:
A new Relay instance created from the dictionary data.
- Return type:
- Raises:
TypeError – If data is not a dictionary.
KeyError – If required ‘url’ key is missing.
RelayValidationError – If the resulting relay fails validation.
Examples
Create from configuration:
>>> config = {"url": "wss://relay.damus.io"} >>> relay = Relay.from_dict(config)
Parse from JSON:
>>> import json >>> json_str = '{"url": "wss://relay.damus.io", "network": "clearnet"}' >>> relay_dict = json.loads(json_str) >>> relay = Relay.from_dict(relay_dict)
Load from database:
>>> relay_data = db.relays.find_one({"name": "damus"}) >>> relay = Relay.from_dict(relay_data)
- to_dict()[source]¶
Convert the Relay object to a dictionary representation.
This method serializes the Relay instance into a dictionary format suitable for JSON encoding, storage, or transmission.
- Returns:
- Dictionary containing relay fields with keys:
url (str): WebSocket URL of the relay
network (str): Network type (“clearnet” or “tor”)
- Return type:
Examples
Serialize to JSON:
>>> relay = Relay("wss://relay.damus.io") >>> relay_dict = relay.to_dict() >>> import json >>> json_str = json.dumps(relay_dict) >>> print(json_str) {"url": "wss://relay.damus.io", "network": "clearnet"}
Store in database:
>>> relay_data = relay.to_dict() >>> db.relays.insert_one(relay_data)
Create client configuration:
>>> config = { ... "relay": relay.to_dict(), ... "timeout": 10 ... }