Core components
RelayPool
TheRelayPool manages multiple relay connections and subscriptions across all relays:
- Maintain WebSocket connections to multiple relays
- Track global subscriptions that apply to all relays
- Coordinate reconnection and keepalive operations
- Handle NIP-42 authentication state and retry logic
Relay
Individual relay connection using theewebsock library:
- WebSocket reader/writer pair with wake-up callbacks for UI repaints
- Connection status tracking
- Authentication state (challenge and authenticated keys)
Subscription
A subscription represents a Nostr filter set sent to relays:- Assigned random 7-character alphanumeric IDs by default
- Stored in the RelayPool and sent to all connected relays
- Automatically resubscribed when relays reconnect
Reconnection logic
Thekeepalive() method runs periodically to maintain connections:
- Reconnection attempts happen every
RELAY_RECONNECT_SECONDS(5 seconds) - Keepalive pings sent every 30 seconds to maintain connections
- When a relay reconnects, all subscriptions are automatically resubmitted
Message handling
The relay system handles both inbound and outbound messages:Outbound (ClientMessage)
Inbound (RelayMessage)
try_recv() method polls all relays for incoming messages:
NIP-42 authentication
The relay system supports NIP-42 authentication for relays that require it:- Relay sends
AUTHchallenge message - Challenge stored in relay’s
auth_state - Application creates auth event using
AccountManager::create_auth_event() - Auth event sent via
send_auth()method - Relay marks key as authenticated in
authenticated_keysset - Pending subscriptions that failed due to auth are retried
Event loop integration
The relay pool integrates with the main application event loop:- Wake-up callbacks: Each relay connection has a wake-up callback that triggers UI repaints when messages arrive
- Non-blocking:
try_recv()polls for messages without blocking - Automatic resubscription: When connections open, all subscriptions are resent
- Status tracking: Each relay maintains connection status for UI display