nips/Nostr-Spaces.md
2024-02-27 01:39:51 -05:00

46 KiB

Nostr Spaces Protocol

Introduction

Purpose and Scope

The Nostr Spaces Protocol (NIP) is designed to extend the capabilities of the Nostr ecosystem by introducing a framework for real-time peer-to-peer audio broadcasting. Leveraging the power of WebRTC for media transmission and utilizing Nostr for signaling, the protocol facilitates decentralized, secure, and scalable audio communication channels. This document outlines the specifications of the Nostr Spaces Protocol, detailing its architectural design, operational mechanisms, event types, and interactions between entities within the system. The objective is to provide developers, relay operators, and users with a clear understanding of how to implement, interact with, and benefit from Nostr spaces dedicated to audio broadcasting.

Background

The NOSTR protocol enables decentralized, censorship-resistant social networking and communication. It uses cryptographic keys for identities, relays for data transmission, and client applications for user interfaces, fostering a user-owned and operated network. Nostr's simplicity and adaptability have led to its application in various domains, including social media and messaging.

Building upon Nostr's foundational principles, the Nostr Spaces Protocol introduces the concept of "spaces" — virtual environments where individuals can engage in live audio broadcasting and listening sessions. These spaces operate within a decentralized framework, ensuring user control over content and interactions without central oversight. This specification aims to equip developers with the necessary information to create applications that utilize decentralized spaces for live audio experiences, promoting innovation, interoperability, and a rich ecosystem of Nostr-based applications that prioritize user autonomy and privacy.

Protocol Overview

Core Concepts

Understanding the foundational building blocks of the Nostr Spaces protocol is essential for grasping its functionality. These core concepts, such as space, host, co-host, speaker, and peer, define the roles and relationships within the network, setting the stage for efficient communication and collaboration.

Space: A virtual room or channel where audio broadcasting takes place. Spaces serve as the primary context for peer interactions and audio communication. Host: The creator of a space, possessing the highest level of control over it, including managing peer roles, and space settings. Co-Host: A role designated by the host that carries certain administrative privileges such as managing peers, but with limitations compared to the host. Speaker: A peer with the right to broadcast audio within a space. This role can be assigned by the host or co-hosts. Peer: Any participant in a space, with the default capability to listen. Peers can request or be granted the role of a speaker.

Event Types

The Nostr Spaces protocol leverages a diverse set of event types to enable real-time interactions and state changes within the network. Each event type serves a specific purpose, from establishing connections to managing roles, thereby ensuring a robust framework for peer-to-peer audio broadcasting.

CREATE_SPACE (1000): Generated by a host to create a new space. It contains the space's metadata, such as its name and description. JOIN_SPACE (31101): Sent by a peer to indicate their entry into a space. This event can be used to notify others of a new participant. LEAVE_SPACE (31102): Sent by a peer to signal their departure from a space, allowing for clean disconnection and resource reallocation. CLOSE_SPACE (1001): Initiated by the host to permanently close a space. This event signals all participants to terminate their connections. RESERVE_CONNECTION (31103): Used by a peer to initiate a WebRTC connection with another peer, typically for upgrading to a speaker role. CONFIRM_CONNECTION (31104): A response to RESERVE_CONNECTION, indicating acceptance of the WebRTC connection and proceeding with the handshake.
SDP_OFFER (21102) and SDP_ANSWER (21103): Part of the WebRTC signaling process, these events exchange session description protocol (SDP) data to establish media connections.
ICE_CANDIDATE (21104): Exchanges network information to find the best path for media stream between peers in the WebRTC connection
DROP_CONNECTION (31105): Indicates the termination of an existing WebRTC connection, either due to a peer leaving or being disconnected
REMOVE_PEER (31106), PROMOTE_SPEAKER (31107), PROMOTE_COHOST (31108), DEMOTE_TO_PEER (31109): Manage peer roles within a space, adjusting their permissions and capabilities.

CREATE_SPACE

Description

The "Create Space" event is the first step in establishing a new audio broadcasting space within the Nostr network. Initiated by a host, this event encapsulates all necessary metadata to define the space's characteristics and rules.

Event Generation

Initiator: The host, who wishes to create a new space.
Trigger: The host generates a CREATE_SPACE event when they decide to create a new space for audio broadcasting.

Event Data

The CREATE_SPACE event includes the following key pieces of information:

Kind: 1000, which is used to indicate the creation of a new space.

Content: The event content is a JSON string that includes:

  • id: A unique identifier for the space.
  • name: The name of the space.
  • host: An object containing information about the host of the space, which includes:
    • publicKey: The public key of the host.
    • networkMetrics: An object detailing network metrics relevant to the host, which includes:
      • downloadSpeedKbps: The download speed in Kbps.
      • uploadSpeedKbps: The upload speed in Kbps.
      • maxAudioOutputs: The maximum number of audio outputs supported.
      • networkConnectionType: The type of network connection.

Example of event content structure:

{
  "id": "unique_space_id",
  "name": "Example Space Name",
  "host": {
    "publicKey": "host_public_key",
    "networkMetrics": {
      "downloadSpeedKbps": 1000,
      "uploadSpeedKbps": 500,
      "maxAudioOutputs": 10,
      "networkConnectionType": "wifi"
    }
  }
}

Tags: The event includes two tags:

['webrtc', 'spaces']: Categorizes the event under the Nostr Spaces application, specifically indicating that it's related to WebRTC-based spaces.
['h', space.host.publicKey]: The tag uses the 'h' key to denote the "host" of the space. The value is the public key of the host, establishing the event's origin and providing a way to trace back to the space's creator for any administrative purposes or queries.

Event Broadcasting

Upon creation, the host broadcasts the CREATE_SPACE event to the Nostr network via their connected relays. This event is then propagated to other peers and relays, making the space discoverable to potential participants.

Handling by Peers and Relays

Peers: Upon receiving a CREATE_SPACE event, client applications can update their UI to reflect the new space, allowing users to join if interested.
Relays: Relays store and disseminate CREATE_SPACE events to interested subscribers, facilitating space discovery and participation.

Security and Privacy Considerations

To ensure the authenticity of a space, peers should verify that the CREATE_SPACE event is signed by the host's private key corresponding to the public key in the event. Additionally, hosts might employ mechanisms to control access to the space, such as invitation-only entry or password protection, to enhance privacy and security.

Lifecycle

The CREATE_SPACE event marks the beginning of a space's lifecycle. The space remains active until the host sends a CLOSE_SPACE event, which signals the space's termination and the release of all associated resources.

JOIN_SPACE

Description

The JOIN_SPACE event marks a peer's entry into an existing space for audio broadcasting. It plays a crucial role in signaling the peer's presence to others within the space, allowing for the dynamic adaptation of the broadcast based on the participants' capabilities.

Event Generation

Initiator: Any peer desiring to join a space.
Trigger: Initiated when a peer decides to enter a space, facilitated through the application interface.

Event Data

Kind: 31101, designating the JOIN_SPACE event.

Content: Contains details about the joining peer in a JSON structure:

  • name: The display name of the peer.
  • publicKey: The Nostr public key of the peer, serving as their identifier within the network.
  • networkMetrics: An object detailing the peer's network capabilities, which includes:
    • downloadSpeedKbps: The download speed in Kbps, indicating the peer's ability to receive streams.
    • uploadSpeedKbps: The upload speed in Kbps, relevant for peers who might broadcast audio.
    • maxAudioOutputs: The maximum number of concurrent audio streams the peer can handle, influencing their participation in multi-speaker spaces.
    • networkConnectionType: The type of network connection (e.g., WiFi, 4G), which can affect the quality and reliability of the peer's connection.

Example of event content structure:

{
  "name": "John Doe",
  "publicKey": "host_public_key",
  "networkMetrics": {
    "downloadSpeedKbps": 1000,
    "uploadSpeedKbps": 500,
    "maxAudioOutputs": 10,
    "networkConnectionType": "wifi"
  }
}

Tags:

['s', space.id]: Links the event to the specific space the peer is joining.
['d', space.id + '||' + space.host.publicKey + '||'+publicKey]: Utilizes the Nostr protocol's parametrized replaceable feature, enabling efficient update and management of peer statuses within a space. The tag's value concatenates the space ID, the host's public key, and the user's public key, offering a unique identifier for replaceable events related to a peer's participation in the space.
['h', space.host.publicKey]: Similar to the CREATE_SPACE event, this tag indicates the public key of the host or creator of the space, providing a reference to the administrative authority within the space.
['webrtc', 'spaces']: Identifies the event as part of the Nostr Spaces application, specifically for WebRTC-based audio spaces.

Event Broadcasting

The peer broadcasts the JOIN_SPACE event to the network through connected Nostr relays. This ensures that the host, co-hosts, and other peers within the space are informed of the new participant.

Handling by Peers and Relays

Peers: Current members of the space update their participant lists and may adjust the broadcast logic to accommodate the new peer's network capabilities.
Relays: Nostr relays propagate the JOIN_SPACE event to all subscribers within the space, ensuring that every participant is aware of the new addition.

Security and Privacy Considerations

Peers should verify the signature of the JOIN_SPACE event to ensure its authenticity. Spaces with access controls, such as invite-only or password-protected spaces, need to enforce these rules at the application level, maintaining the space's security and privacy.

Lifecycle Implications

The JOIN_SPACE event signifies the beginning of a peer's participation in a space. This status continues until the peer either leaves the space (via LEAVE_SPACE) or the space is closed (via CLOSE_SPACE), at which point their active participation ends.

LEAVE_SPACE

Description

The LEAVE_SPACE event indicates that a peer is exiting a space. It's essential for maintaining an accurate count of active participants and managing the distribution of audio streams within the space.

Event Generation

Initiator: A peer who wishes to leave a space.
Trigger: Occurs when a peer chooses to exit a space, typically through a user action in the client application.

Event Data

Kind: 31102, which identifies the event as a LEAVE_SPACE action.

Content: Typically, this event does not require detailed content beyond identifying the leaving peer, as the primary purpose is to signal the departure.

Tags:

['s', space.id]: Associates the event with the specific space from which the peer is leaving.
['d', space.id + '||' + space.host.publicKey + '||' + publicKey]: Uses the Nostr protocol's parametrized replaceable feature, allowing for efficient management of peer statuses. It enables the system to replace older JOIN_SPACE events with the latest state, reflecting the peer's departure.
['h', space.host.publicKey]: Indicates the public key of the host, maintaining a reference to the administrative authority of the space.
['webrtc', 'spaces']: Continues to identify the event as part of the Nostr Spaces application, reinforcing the context of WebRTC-based audio communication.

Event Broadcasting

The peer sends the LEAVE_SPACE event through their connected relays, notifying the space's host, co-hosts, and peers of their departure.

Handling by Peers and Relays

Peers: The remaining participants in the space update their lists to remove the leaving peer, potentially adjusting the audio stream distribution accordingly.
Relays: Propagate the LEAVE_SPACE event to ensure all participants are aware of the change in the space's composition.

Security and Privacy Considerations

While the LEAVE_SPACE event might not carry sensitive information, the integrity of the event should still be verified to prevent spoofing and ensure that only genuine departure signals are processed.

Lifecycle Implications

The LEAVE_SPACE event concludes a peer's active participation in a space. It triggers cleanup processes, such as the removal of the peer from participant lists and the reevaluation of audio stream distributions to remaining peers.

Following the LEAVE_SPACE event, we could move on to describing the CLOSE_SPACE event, which denotes the host's action to terminate a space, signaling the end of the space's lifecycle and the disconnection of all participants.

CLOSE_SPACE

Description

The CLOSE_SPACE event signifies the host's decision to terminate an existing space. This event is critical for formally ending the space's lifecycle and ensuring that all participants disconnect appropriately.

Event Generation

Initiator: The host of the space.
Trigger: Occurs when the host decides to close the space, which could be due to various reasons such as the end of the scheduled session, management decisions, or other operational considerations. Event Data

Kind: 1001, uniquely identifying this event as a CLOSE_SPACE action. Content: Typically, this event does not require detailed content, as the primary purpose is to signal the signal the closure of the space.

Tags:

['s', space.id]: Directly ties the event to the specific space being closed. This ensures that all participants and relays can accurately identify the space in question.
['h', space.host.publicKey]: Denotes the public key of the host, reaffirming their authority to close the space. This tag is crucial for validating the authenticity of the closure event.
['webrtc', 'spaces']: Maintains the association with the Nostr Spaces application, particularly within the WebRTC-based communication context.

Event Broadcasting

Upon deciding to close the space, the host broadcasts the CLOSE_SPACE event through the connected relays. This widespread dissemination ensures that all current participants and potential future joiners are aware that the space is no longer active.

Handling by Peers and Relays

Peers: Upon receiving a CLOSE_SPACE event, participants within the space initiate disconnection procedures, leaving the space and freeing up resources associated with their participation. Client applications may also update their interfaces to reflect the space's closure.
Relays: Play a crucial role in ensuring the CLOSE_SPACE event reaches all current and future interested parties.

Security and Privacy Considerations

Ensuring the CLOSE_SPACE event's integrity is paramount, as it leads to the termination of the space and the disconnection of all participants. Verification of the event's origin, specifically that it is issued by the legitimate host, is essential to prevent unauthorized or malicious closures.

Lifecycle Implications

The issuance of a CLOSE_SPACE event represents the definitive end of a space's lifecycle. It transitions the space from an active state, capable of hosting real-time audio communication, to a closed state, where no further interactions can occur. This event necessitates the cleanup of all related data and states within client applications.

RESERVE_CONNECTION

Description

RESERVE_CONNECTION is used by a peer to demand the authorization to initiate a WebRTC connection with another peer, typically for establishing a direct communication channel. This event is transient and should not be persisted by the relay, only broadcasted to the intended recipient.

Event Generation

Initiator: Any peer within a space wishing to establish a direct WebRTC connection with another peer.
Trigger: Triggered when a peer decides to connect directly with another peer, either for sending or receiving audio streams.

Event Data

Kind: 31103, indicating a RESERVE_CONNECTION event.
Content: Includes details necessary for initiating a WebRTC connection, such as:

  • type: Specifies the connection type, such as "provider" or "consumer," indicating the role the initiating peer is taking in the WebRTC negotiation process.

['s', space.id]: Associates the event with the space where the connection is being established.
['p', targetPeerPublicKey]: Specifies the public key of the peer with whom the connection is being reserved.
['h', space.host.publicKey]: Identifies the host of the space, providing a layer of authorization and context to the connection attempt.
['webrtc', 'spaces']: Categorizes the event under the Nostr Spaces application, emphasizing its role in facilitating WebRTC-based communications.
['d', space.id + '||' + hostPublicKey + '||' + requestingPeerPublicKey + '||' + confirmingPeerPublicKey]: Utilizes the Nostr protocol's parametrized replaceable feature for efficient event management, particularly in the context of connection statuses within the space.

Event Broadcasting

The RESERVE_CONNECTION event is broadcast to the specified peer and relevant entities within the space, signaling the intent to establish a direct connection.

Handling by Peers and Relays

Peers: The targeted peer, upon receiving a RESERVE_CONNECTION event, evaluates the request and may proceed with the WebRTC handshake process by generating a corresponding SDP_OFFER or SDP_ANSWER, depending on the connection type specified.
Relays: Play a crucial role in delivering the RESERVE_CONNECTION event from the sender to the intended recipient.

Security and Privacy Considerations

The security of the RESERVE_CONNECTION event hinges on the authentication of the initiating peer and the integrity of the transmitted network metrics. Peers should verify the authenticity of these events to prevent unauthorized connection attempts.

Lifecycle Implications

The RESERVE_CONNECTION event serves as an initial handshake signal between peers willing to establish a direct communication channel. However, the actual WebRTC communication setup, including the exchange of media streams, only commences upon the receipt and processing of the CONFIRM_CONNECTION event by the initiating peer. This event, therefore, marks a preliminary stage in the WebRTC lifecycle within the Nostr Spaces protocol, setting the groundwork for subsequent steps like the exchange of SDP offers/answers and ICE candidates.

CONFIRM_CONNECTION

Description

The CONFIRM_CONNECTION event is sent by a peer in response to receiving a RESERVE_CONNECTION request from another peer. It signifies the acceptance of the connection request and readiness to proceed with the WebRTC handshake process.

Event Generation

Initiator: A peer who has received a RESERVE_CONNECTION request and wishes to establish a WebRTC connection.
Trigger: The decision by the receiving peer to accept the connection request and engage in direct communication.

Event Data

Kind: 31104, identifying the event as a CONFIRM_CONNECTION action.

Content: Includes details necessary for initiating a WebRTC connection, such as:

  • type: Specifies the connection type, such as "provider" or "consumer," indicating the role the peer that reserved the connection is taking in the WebRTC negotiation process.

Tags:

['s', space.id]: Associates the event with the specific space within which the connection is being established.
['p', initiatingPeerPublicKey]: Identifies the peer who initiated the connection, ensuring the event is directed appropriately.
['d', space.id + '||' + hostPublicKey + '||' + initiatingPeerPublicKey + '||' + confirmingPeerPublicKey]: Utilizes the Nostr protocol's parametrized replaceable feature for efficient event management, particularly in the context of connection statuses within the space.
['h', space.host.publicKey]: Maintains a reference to the host of the space, denoting administrative context.
['webrtc', 'spaces']: Categorizes the event within the Nostr Spaces application, with a focus on WebRTC-based connections.

Event Broadcasting

Upon generating a CONFIRM_CONNECTION event, the confirming peer broadcasts it through their connected Nostr relays. This ensures that the initiating peer, and potentially other interested parties within the space, are aware of the confirmed connection.

Handling by Peers and Relays

Peers: The initiating peer, upon receiving a CONFIRM_CONNECTION event, proceeds with the WebRTC handshake process, exchanging SDP offers and answers to establish the media stream.
Relays: While relays facilitate the delivery of CONFIRM_CONNECTION events, they should treat these events as transient and not store them, focusing instead on real-time broadcasting to relevant peers.

Security and Privacy Considerations

The integrity of the CONFIRM_CONNECTION event is paramount to prevent unauthorized or spoofed connection confirmations. Peers should verify the event's authenticity and ensure it corresponds to an existing RESERVE_CONNECTION request.

Lifecycle Implications

The receipt of a CONFIRM_CONNECTION event marks the transition from preliminary connection setup to active WebRTC communication setup. Following this event, peers engage in the exchange of SDP offers/answers and ICE candidates to establish the media stream, fully activating the direct communication channel.

SDP_OFFER

Description:

The SDP_OFFER event is used by a peer to send a WebRTC session description offer to another peer within a Nostr space. This offer includes information about the media formats and protocols supported by the offering peer, initiating the negotiation for a WebRTC connection.

Event Generation:

Initiator: A peer willing to establish a direct communication channel with another peer.
Trigger: The creation of a WebRTC offer, typically after a CONFIRM_CONNECTION event has been received, signaling readiness to establish a WebRTC connection.

Event Data:

Kind: 21102, identifying the event as an SDP_OFFER.
Content: Contains the SDP offer data in a JSON structure. The SDP data is encoded as a string and includes details about the media streams, codecs, encryption schemes, and other connection parameters.

Tags:

['s', space.id]: Associates the event with the space in which the connection is being established.
['p', recipientPeerPublicKey]: Specifies the public key of the peer intended to receive the offer, directing the event appropriately.
['h', space.host.publicKey]: Maintains a reference to the host of the space, denoting administrative context.
['webrtc', 'spaces']: Indicates that the event is part of the WebRTC connection process within the Nostr Spaces application.

Event Broadcasting:

The offering peer sends the SDP_OFFER event through the Nostr network, targeting the specific peer with whom they wish to establish the connection. This event is crucial for negotiating the media communication parameters.

Handling by Peers and Relays:

Peers: The recipient peer processes the SDP_OFFER, generating an SDP_ANSWER in response if they accept the proposed media parameters. This answer is then sent back to the offering peer, continuing the negotiation process.
Relays: Given the direct nature of the communication and the potentially sensitive content of SDP data, SDP_OFFER events should be treated with priority in real-time broadcasting but do not necessarily need to be stored long-term by relays.

Security and Privacy Considerations:

Ensuring the confidentiality and integrity of the SDP data is crucial, as it contains sensitive information about the peer's media capabilities and network configuration. Encryption of SDP data and verification of the event's authenticity are recommended practices.

Lifecycle Implications:

The SDP_OFFER event initiates the SDP negotiation phase of the WebRTC connection setup. It is followed by the SDP_ANSWER event, which either confirms the acceptance of the proposed media parameters or suggests modifications, facilitating the establishment of the media communication channel.

SDP_ANSWER

Description:

Following an SDP_OFFER, the SDP_ANSWER event carries the response from the recipient peer, containing the accepted media session parameters. This event finalizes the negotiation phase of the WebRTC connection setup.

Event Generation:

Initiator: The peer responding to an SDP_OFFER.
Trigger: The generation of an SDP answer in response to a received offer, indicating agreement on the media session parameters or proposing adjustments.

Event Data:

Kind: 21103, denoting the event as an SDP_ANSWER. Content: Includes the SDP answer data, detailing the agreed-upon media formats, protocols, and other connection parameters necessary for establishing the WebRTC communication channel.

Tags:

['s', space.id], ['p', offeringPeerPublicKey], ['webrtc', 'spaces'], ['h', space.host.publicKey]:: Similar to the SDP_OFFER, these tags link the event to the specific space and peer, and categorize it within the WebRTC setup process in Nostr Spaces.

Event Broadcasting and Handling:

The SDP_ANSWER event is broadcasted to the offering peer, continuing the WebRTC setup process. Both peers, upon agreeing on the session parameters, proceed with the ICE candidate exchange (ICE_CANDIDATE events) to establish the connection.

Security and Privacy Considerations and Lifecycle Implications:

Similar to the SDP_OFFER, the SDP_ANSWER requires careful handling to protect the sensitive information it contains. The successful exchange of SDP_OFFER and SDP_ANSWER events concludes the SDP negotiation phase, transitioning into the ICE gathering and exchange phase to finalize the establishment of the WebRTC connection.

ICE_CANDIDATE

Description:

The ICE_CANDIDATE event carries information about the network endpoints (candidates) that can be used to establish the WebRTC connection. ICE (Interactive Connectivity Establishment) candidates represent potential points of communication that allow peers to discover the most efficient path for their media streams.

Event Generation:

Initiator: Both peers involved in setting up a WebRTC connection.
Trigger: Generated as part of the WebRTC ICE gathering process, where each peer collects and sends its available network candidates.

Event Data:

Kind: 21104, identifying the event as an ICE_CANDIDATE.
Content: Contains the ICE candidate information, typically including the candidate's network address, port, transport protocol, and priority. This data is encoded within a JSON structure.

Tags:

['s', space.id]: Links the event to the space where the WebRTC connection is being established.
['p', targetPeerPublicKey]: Directs the ICE candidate information to the specific peer involved in the connection setup.
['h', hostPublicKey]: Specifies the public key of the space's host, maintaining a connection to the space's administrative authority and ensuring that the event is contextualized within the correct space.
['webrtc', 'spaces']: Indicates the event's role in the WebRTC setup process within the Nostr Spaces application.

Event Broadcasting:

Each peer sends ICE_CANDIDATE events to the other as they gather ICE candidates. This exchange is crucial for determining the best possible network path for the WebRTC connection.

Handling by Peers and Relays:

Peers: Upon receiving an ICE_CANDIDATE event, a peer adds the candidate to its ICE agent, which assesses the viability of each candidate path. The WebRTC infrastructure then attempts to establish the connection using the most efficient path available.
Relays: Given that ICE_CANDIDATE events are part of the real-time connection setup process, relays should prioritize their immediate broadcasting. However, these events may not need long-term storage, as they are relevant only during the connection establishment phase.

Security and Privacy Considerations:

The exchange of ICE candidates should be secure to prevent eavesdropping or tampering. Encrypting the candidate information can help protect against potential interception.

Lifecycle Implications:

The ICE_CANDIDATE exchange is a dynamic and iterative process, continuing until an optimal network path is established or the connection setup times out. Successful ICE negotiation leads to the finalization of the WebRTC connection, allowing for the start of media streaming.

Once the ICE negotiation is successfully completed, and the optimal network path is established, the peers can begin the media transmission, marking the operational phase of the WebRTC connection within the Nostr Space. This phase includes the management of the connection, handling any disconnections, and eventually closing the connection when it's no longer needed.

DROP_CONNECTION

Description:

The DROP_CONNECTION event signals the intentional termination of an existing WebRTC connection between peers within a Nostr Space. It is an essential mechanism for maintaining the health and efficiency of the network by clearing up connections that are no longer needed or are malfunctioning.

Event Generation:

Initiator: Any peer within a space that wishes to terminate an existing WebRTC connection. This can be the result of a user action, such as leaving a space or ending a broadcast, or an automated response to network conditions.
Trigger: Triggered when a peer decides to close a WebRTC connection, either as part of normal operation (e.g., leaving a space) or due to error conditions (e.g., network failure).

Event Data:

Kind: 31105, identifying the event as a DROP_CONNECTION action.
Content: Typically, this event does not require detailed content as its primary purpose is to signal the termination of the connection between two peers.

Tags:

['s', space.id]: Connects the event to the specific space from which the connection is being dropped, ensuring clear contextualization within the ongoing audio broadcast.
['p', peerPublicKey]: Specifies the target peer of the connection that is being terminated, ensuring the message reaches the intended recipient.
['h', hostPublicKey]: Indicates the public key of the space's host, maintaining a link to the space's administrative context.
['webrtc', 'spaces']: Marks the event as part of the WebRTC lifecycle within the Nostr Spaces application, specifically related to connection management.
['d', uniqueIdentifier]: Utilizes the D tag for making the event replaceable if needed, enhancing the management and updating of connection states within the space. The unique identifier could include a combination of space ID, peer public keys, and a timestamp or sequence number to ensure uniqueness.

Event Broadcasting:

The DROP_CONNECTION event is broadcast to the involved peers through the Nostr network, using relays to ensure rapid dissemination. The focus is on timely communication to prompt the immediate release of connection resources.

Handling by Peers and Relays:

Peers: Upon receiving a DROP_CONNECTION event, the targeted peer(s) proceed to close the specified WebRTC connection, releasing any allocated resources and potentially adjusting their participation in the ongoing audio broadcast.
Relays: Play a critical role in delivering the DROP_CONNECTION event.

Security and Privacy Considerations:

Ensuring the authenticity of DROP_CONNECTION events is crucial to prevent malicious attempts to disrupt ongoing communications. Peers should verify the event's origin and integrity before acting on it.

Lifecycle Implications:

The issuance of a DROP_CONNECTION event marks the conclusion of a WebRTC connection's lifecycle within a Nostr Space, transitioning the involved peers into a state where they are either disconnected or ready to establish new connections as needed. This event underscores the dynamic nature of peer-to-peer communications in Nostr Spaces, where connections are continually formed, managed, and terminated in response to user actions and network conditions.

REMOVE_PEER

Description:

The REMOVE_PEER event facilitates the removal of a peer from a space by the host or co-hosts, typically due to moderation needs or rule violations.

Event Generation:

Initiator: Host or co-host of the space.
Trigger: Decision to remove a peer based on moderation policies or disruptive behavior.

Event Data:

Kind: 31106, indicating a REMOVE_PEER event.
Content: This event does not require any additional data.

Tags:

['s', space.id]: Associates the event with the specific space.
['p', removedPeerPublicKey]: Specifies the public key of the peer being removed.
['h', hostPublicKey]: Indicates the public key of the host or co-host who is removing the peer.
['d', space.id+'||'+hostPublicKey+'||'+removedPeerPublicKey]: Utilizes Nostr's parametrized replaceable feature for efficient state management. The composite identifier can include the space ID, the host's public key, and the removed peer's public key, creating a unique reference for the event.
['webrtc', 'spaces']: Categorizes the event within the WebRTC-based Nostr Spaces framework.

Event Broadcasting and Storage:

The event is broadcast to all current participants to update the space's state and is stored by relays for historical and audit purposes.

Handling by Peers and Relays:

Peers: Update UI and state to exclude the removed peer. The client of the removed peer handles the disconnection process.
Relays: Disseminate the REMOVE_PEER event to subscribed clients and retain it in the space's event log.

Security and Privacy Considerations:

Authenticating the event is crucial to ensure that only authorized individuals can execute removals, maintaining the space's integrity and security.

Lifecycle Implications:

Marks the termination of the removed peer's participation in the space, enforced by moderation actions. This event underscores the importance of community management within Nostr Spaces.

PROMOTE_SPEAKER

Description:

The PROMOTE_SPEAKER event is used to elevate a peer's role to a speaker within a space, granting them the ability to broadcast audio.

Event Generation:

Initiator: Host or co-host of the space.
Trigger: Decision to grant a peer speaker privileges, often based on the flow of the conversation or at the peer's request.

Event Data:

Kind: 31107, identifying a PROMOTE_SPEAKER event.
Content: This event does not require any additional data.

Tags:

['s', space.id]: Links the event to the specific space.
['p', promotedPeerPublicKey]: Identifies the peer being promoted to a speaker.
['h', hostPublicKey]: Indicates the host initiating the promotion.
['d', space.id + '||' + hostPublicKey + '||' + promotedPeerPublicKey]: Utilizes the parametrized replaceable feature, creating a unique identifier for this event related to the peer's role change.
['webrtc', 'spaces']: Categorizes the event within the Nostr Spaces application, specifically for WebRTC-based audio spaces.

Event Broadcasting:

The event is broadcast to all participants in the space to update the peer's role visually and functionally within the UI.

Handling by Peers and Relays:

Peers: Update the UI to reflect the new speaker role for the promoted peer, potentially adjusting the audio stream setup.
Relays: Disseminate the PROMOTE_SPEAKER event to ensure all clients within the space are aware of the role change.

Security and Privacy Considerations:

Verifying the event's authenticity is crucial to ensure that only authorized hosts or co-hosts can alter roles within the space.

Lifecycle Implications:

Marks a transition in the peer's participation level within the space, enhancing the interactive and dynamic nature of the audio experience.

PROMOTE_COHOST

Description:

The PROMOTE_COHOST event allows a host to delegate co-hosting responsibilities to a peer, providing them with administrative capabilities.

Event Generation:

Initiator: Host of the space.
Trigger: The host's decision to share or delegate administrative responsibilities within the space.

Event Data:

Kind: 31108, signifying a PROMOTE_COHOST event.
Content: This event does not require any additional data.

Tags:

['s', space.id]: Associates the event with the space.
['p', promotedPeerPublicKey]: Identifies the peer being promoted to a co-host.
['h', hostPublicKey]: Indicates the host responsible for the promotion.
['d', space.id + '||' + hostPublicKey + '||' + promotedPeerPublicKey]: Uses the parametrized replaceable feature to manage the state of co-host promotions efficiently.
['webrtc', 'spaces']: Categorizes the event within the Nostr Spaces application, specifically for WebRTC-based audio spaces.

Event Broadcasting and Handling:

Broadcast and handling procedures follow the same pattern as PROMOTE_SPEAKER, ensuring that all participants are informed of the new co-host and that the space's UI is updated accordingly.

DEMOTE_TO_PEER

Description:

The DEMOTE_TO_PEER event is used to revert a speaker or co-host back to a standard peer role, typically due to the end of their speaking turn or administrative duties.

Event Generation:

Initiator: Host or co-host of the space.
Trigger: Decision to remove speaker or co-host privileges from a peer.

Event Data:

Kind: 31109, indicating a DEMOTE_TO_PEER event.
Content: This event does not require any additional data.

Tags:

['s', space.id]: Connects the event to the space from which the peer is being demoted.
['p', demotedPeerPublicKey]: Identifies the peer being demoted to a standard role.
['h', hostPublicKey]: Indicates the host or co-host initiating the demotion.
['d', space.id + '||' + hostPublicKey + '||' + demotedPeerPublicKey]: Applies the parametrized replaceable feature, facilitating the efficient update of the peer's role within the space.
['webrtc', 'spaces']: Categorizes the event within the Nostr Spaces application, specifically for WebRTC-based audio spaces.

Event Broadcasting and Handling:

The event is disseminated to all space participants to update the demoted peer's status, with client applications adjusting the UI and functionalities to reflect the peer's standard role.

REQUEST_SPEECH

Description

The REQUEST_SPEECH event is used by a peer to formally request the right to speak in a space. This is particularly useful in moderated spaces where speaking rights are controlled by the host or co-hosts.

Event Generation

Initiator: A peer who wishes to speak in a space.
Trigger: The peer sends a REQUEST_SPEECH event when they want to request speaking rights, usually through an action in the client application.

Event Data

Kind: 21105, identifying the event as a speech request.
Content: This event does not require any additional data.

Tags

['s', space.id]: Links the event to the specific space where speech is requested.
['p', requestingPeerPublicKey]: Identifies the peer requesting to speak.
['h', hostPublicKey]: Indicates the host of the space, to whom the request is directed.
['d', space.id + '||' + hostPublicKey + '||' + requestingPeerPublicKey]: Utilizes the parametrized replaceable feature, ensuring that only the most recent speech request by the peer in the space is considered.
['webrtc', 'spaces']: Categorizes the event within the Nostr Spaces application, specifically for WebRTC-based audio spaces.

Event Broadcasting

This event is broadcasted through the connected Nostr relays but is not intended to be stored permanently by the relays. It serves as a real-time signal to the host or co-hosts.

Handling by Peers and Relays

Peers: The host or co-hosts receive the request and can decide to grant speaking rights based on their discretion and the space's rules
Relays: Relay the REQUEST_SPEECH event to the host or co-hosts but do not store it, as it is relevant only in real-time.

PROPOSE_SPEECH

Description

The PROPOSE_SPEECH event is used by the host or a co-host to suggest that a peer in the space may want to speak. This event serves as an invitation or encouragement for the peer to formally request speaking rights by sending a REQUEST_SPEECH event.

Event Generation

Initiator: The host or a co-host of the space.
Trigger: Sent when a host or co-host identifies a peer who could contribute to the conversation and wants to encourage them to request speaking rights.

Event Data

Kind: 21105, marking the event as a speech proposal.
Content: The content can include a message or indication that the peer is being proposed to speak. This is more of an invitation rather than an automatic promotion to speaker status.

Tags

['s', space.id]: Associates the event with the specific space.
['p', proposedPeerPublicKey]: Identifies the peer being suggested for speech.
['h', hostPublicKey]: Indicates the host or co-host making the proposal.
['d', space.id + '||' + hostPublicKey + '||' + proposedPeerPublicKey]: Utilizes the parametrized replaceable feature to manage speech proposals efficiently.
['webrtc', 'spaces']: Categorizes the event within the Nostr Spaces application, specifically for WebRTC-based audio spaces.

Event Broadcasting

This event is broadcasted through the connected Nostr relays to the proposed peer, serving as a real-time suggestion or invitation to speak.

Handling by Peers and Relays

Peers: The proposed peer receives the proposal and, if willing to speak, should then send a REQUEST_SPEECH event to formally request speaking rights.
Relays: Relay the PROPOSE_SPEECH event to the proposed peer without storing it, as it's intended for real-time interaction. Following the PROPOSE_SPEECH event and the peer's decision to speak, the sequence continues as follows: The proposed peer sends a REQUEST_SPEECH event, formally requesting speaking rights. The host or co-host reviews the request and, if approved, sends a PROMOTE_SPEAKER event to grant the peer speaking rights. This process ensures that speaking rights are managed transparently and consensually within Nostr Spaces, maintaining the interactive and participatory nature of the platform.

Peers collaboration Rules:

To ensure optimal performance within the Nostr Spaces Protocol, particularly for peer connections and audio broadcasting, a sophisticated approach to decision-making and behavior management is essential. Here's a detailed explanation incorporating the specific function provided:

Decision-Making for Peer Connections

Evaluating Connection Requests

Upon receiving a RESERVE_CONNECTION request, a peer evaluates the request based on several key criteria:

Proximity Score: Reflects the peer's network distance from the host, with closer peers preferred to minimize latency.
Network Score: Assesses the peer's network quality, considering both the upload/download speeds and the number of allowed consumers, ensuring the peer can handle the data throughput.
Load Score: Evaluates the current load on the peer, favoring peers with fewer active connections to distribute the network load evenly. Scoring System.
A composite score is calculated for each peer considering the above criteria, using the provided formula:

Score = { 1 if both peers are speakers, co-hosts, or hosts Proximity Score * Distance Weight + Network Score * Speed Weight + Load Score * Load Weight otherwise }

This scoring system ensures that priority is given to maintaining strong connections between key participants (speakers, co-hosts, hosts) while also considering the overall network efficiency and balance.

Connection Graph

The network structure is maintained as a graph, enabling efficient scanning and decision-making. This graph-based approach allows for quick identification of potential connections and optimization of the overall network topology.

Managing Connection Failures and Timeouts

Handling Dropped Connections

In the event of a dropped connection, the affected peer should immediately seek a new connection to maintain network stability. The graph structure facilitates identifying the next best connection based on the scoring system.

Dealing with Unresponsive Connection Requests

If a peer does not respond to a RESERVE_CONNECTION request within a certain timeout, the initiating peer should:

  • Issue a DROP_CONNECTION event to terminate the attempted connection.
  • Utilize the graph to find the next best peer based on the scoring criteria and initiate a new connection request.

Adaptive Behavior

The system is designed to be adaptive, adjusting to changes in network conditions, participant roles, and overall space dynamics. Regular reassessment of connections ensures optimal network configuration. The graph-based structure supports dynamic updates and reconfigurations, allowing the system to maintain optimal connectivity among participants.

Implementation Considerations

Implementing these behaviors requires continuous monitoring of the network state, peer statuses, and space dynamics, facilitated by the graph-based network structure. Efficient algorithms are essential for scoring and decision-making processes to ensure the system can rapidly adapt to changing conditions and maintain high-quality audio broadcasting for all participants. This refined approach highlights the importance of a multi-faceted evaluation system and a dynamic, graph-based network structure for decision-making in the Nostr Spaces Protocol, aiming to enhance the resilience, efficiency, and user experience in decentralized audio spaces.