relayer

package module
v2.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2026 License: Unlicense Imports: 26 Imported by: 13

README

Nostr Relay Framework -- use it to implement your own custom relay.

There is an example/reference implementation at basic. Binaries for that are also available under Releases.

GoDoc

Supported NIPs

These are handled by the framework itself, so every relay built on it gets them:

NIP
01 Basic protocol flow (EVENT, REQ, CLOSE, EOSE, OK, CLOSED, NOTICE), including what used to be NIPs 12, 15, 16, 20 and 33
09 Event deletion request
11 Relay information document
67 EOSE completeness hint
77 Negentropy syncing (NEG-OPEN, NEG-MSG, NEG-CLOSE)

These depend on what your relay implements:

NIP requires
42 Auther — authentication of clients to relays
17, 59 Auther — gift-wrapped events are only served to the pubkey they are addressed to
45 a storage implementing EventCounter — COUNT

The default NIP-11 document reports exactly this set. A relay implementing Informationer replaces the document wholesale and is responsible for its own supported_nips.

Note that the numbers 12, 15, 16, 20 and 33 still appear in that document for the benefit of older clients; those NIPs were merged into NIP-01 and no longer exist on their own.

Running several instances on one storage

Live subscriptions are tracked in memory, so out of the box an event published to one instance is only pushed to the clients of that instance. To run several instances (behind a load balancer, say) against one shared storage, implement Notifier on your relay or on your storage:

type Notifier interface {
	Notify(context.Context, *nostr.Event) error
	Notifications(context.Context) (<-chan *nostr.Event, error)
}

Notify is called for every accepted event; Notifications must deliver the events accepted by every instance, this one included. With a Notifier present, events reach local subscribers only through Notifications, so there is a single delivery path and no duplicates.

Notifier is eventstore.Notifier, and the postgresql storage implements it with LISTEN/NOTIFY, so a relay on PostgreSQL gets this for free. For any other storage the transport is up to you — Redis pub/sub, NATS, anything that carries events from Notify on one instance to Notifications on all of them; see multi-instance for SQLite kept in sync over Redis.

Documentation

Overview

NIP-77 Negentropy set-reconciliation server-side handling. The relay replies to NEG-OPEN / NEG-MSG exchanges by iteratively calling negentropy.Reconcile on a frozen snapshot of the events matching the filter.

Index

Constants

View Source
const (
	AUTH_CONTEXT_KEY = iota
	SERVER_CONTEXT_KEY
)

Variables

This section is empty.

Functions

func AddEvent

func AddEvent(ctx context.Context, relay Relay, evt *nostr.Event) (accepted bool, message string)

AddEvent has a business rule to add an event to the relayer

func BroadcastEvent added in v2.1.17

func BroadcastEvent(evt *nostr.Event)

func GetAuthStatus added in v2.1.0

func GetAuthStatus(ctx context.Context) (pubkey string, ok bool)

func GetIP added in v2.3.0

func GetIP(ctx context.Context) (ip string, ok bool)

GetIP reports the address the connection handling ctx came from, resolved the same way as the "connected from" log line.

func GetListeningFilters

func GetListeningFilters() nostr.Filters

Types

type AdvancedDeleter

type AdvancedDeleter interface {
	BeforeDelete(ctx context.Context, id string, pubkey string)
	AfterDelete(id string, pubkey string)
}

AdvancedDeleter methods are called before and after [Storage.DeleteEvent].

type AdvancedSaver

type AdvancedSaver interface {
	BeforeSave(context.Context, *nostr.Event)
	AfterSave(*nostr.Event)
}

AdvancedSaver methods are called before and after [Storage.SaveEvent].

type Auther

type Auther interface {
	ServiceURL() string
}

Auther is the interface for implementing NIP-42. ServiceURL() returns the URL used to verify the "AUTH" event from clients.

type CustomWebSocketHandler

type CustomWebSocketHandler interface {
	HandleUnknownType(ws *WebSocket, typ string, request []json.RawMessage)
}

CustomWebSocketHandler, if implemented, is passed nostr message types unrecognized by the server. The server handles "EVENT", "REQ" and "CLOSE" messages, as described in NIP-01.

type EventCounter

type EventCounter interface {
	CountEvents(ctx context.Context, filter nostr.Filter) (int64, error)
}

type FiltersCounter added in v2.2.19

type FiltersCounter interface {
	CountEventsFilters(ctx context.Context, filters nostr.Filters) (int64, error)
}

FiltersCounter counts the events matching any of several filters for NIP-45, which asks for the filters to be OR'd together into a single count. Summing CountEvents over each filter separately counts an event that matches more than one of them once per filter, so a store that can evaluate the union itself — a SQL backend counting over a UNION, say — should implement this. Stores that do not are still summed, which is exact as long as the filters do not overlap.

type Informationer

type Informationer interface {
	GetNIP11InformationDocument() nip11.RelayInformationDocument
}

Informationer is called to compose NIP-11 response to an HTTP request with application/nostr+json mime type. See also Relay.Name.

type Injector

type Injector interface {
	InjectEvents() chan nostr.Event
}

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

type Logger

type Logger interface {
	Infof(format string, v ...any)
	Warningf(format string, v ...any)
	Errorf(format string, v ...any)
}

Logger is what Server uses to log messages.

type Notice

type Notice struct {
	Kind    string `json:"kind"`
	Message string `json:"message"`
}

type Notifier added in v2.3.0

type Notifier = eventstore.Notifier

Notifier propagates accepted events between multiple relay instances that share the same storage, so that clients subscribed on one instance receive events published on another. It is eventstore.Notifier, so a storage can provide one natively (see postgresql.PostgresBackend) and a relay can provide one on top of any storage.

It is looked up first on the Relay and then on the eventstore.Store returned by Relay.Storage; the first one found is used. When a Notifier is present, AddEvent no longer delivers events to local subscribers directly: every accepted event is passed to Notify, and only events arriving from Notifications are delivered. An implementation must therefore also send back the events it was asked to Notify about, including to the instance that published them. Ephemeral events are passed to Notify as well, even though they are not saved.

type Option added in v2.1.1

type Option func(*Options)

func WithPerConnectionLimiter added in v2.1.1

func WithPerConnectionLimiter(rps rate.Limit, burst int) Option

func WithSkipEventFunc added in v2.1.13

func WithSkipEventFunc(skipEventFunc func(*nostr.Event) bool) Option

func WithTrustedProxyHeader added in v2.3.0

func WithTrustedProxyHeader(header string) Option

WithTrustedProxyHeader names the header carrying the client address, for a relay that only ever receives connections through a proxy that sets it — "CF-Connecting-IP" behind Cloudflare, "X-Forwarded-For" behind an ingress that appends to it. Leave it unset when clients can reach the relay directly: any client can send whichever header it likes, so reading one that nothing overwrites records an address of the client's choosing.

type Options added in v2.1.1

type Options struct {
	// contains filtered or unexported fields
}

func DefaultOptions added in v2.1.1

func DefaultOptions() *Options

type Relay

type Relay interface {
	// Name is used as the "name" field in NIP-11 and as a prefix in default Server logging.
	// For other NIP-11 fields, see [Informationer].
	Name() string
	// Init is called at the very beginning by [Server.Start], allowing a relay
	// to initialize its internal resources.
	// Also see [eventstore.Store.Init].
	Init() error
	// AcceptEvent is called for every nostr event received by the server.
	// If the returned value is true, the event is passed on to [Storage.SaveEvent].
	// Otherwise, the server responds with a negative and "blocked" message as described
	// in NIP-20.
	AcceptEvent(context.Context, *nostr.Event) (bool, string)
	// Storage returns the relay storage implementation.
	Storage(context.Context) eventstore.Store
}

Relay is the main interface for implementing a nostr relay.

type ReqAccepter added in v2.1.4

type ReqAccepter interface {
	// AcceptReq is called for every nostr request filters received by the
	// server. If the returned value is true, the filtres is passed on to
	// [Storage.QueryEvent].
	AcceptReq(ctx context.Context, id string, filters nostr.Filters, authedPubkey string) bool
}

ReqAccepter is the main interface for implementing a nostr relay.

type Server

type Server struct {
	// Default logger, as set by NewServer, is a stdlib logger prefixed with [Relay.Name],
	// outputting to stderr.
	Log Logger

	// in case you call Server.Start
	Addr string
	// contains filtered or unexported fields
}

Server is a base for package users to implement nostr relays. It can serve HTTP requests and websockets, passing control over to a relay implementation.

To implement a relay, it is enough to satisfy Relay interface. Other interfaces are Informationer, CustomWebSocketHandler, ShutdownAware, Injector, Notifier and AdvancedXxx types. See their respective doc comments.

The basic usage is to call Start or StartConf, which starts serving immediately. For a more fine-grained control, use NewServer. See basic/main.go, whitelisted/main.go, expensive/main.go and rss-bridge/main.go for example implementations.

The following resource is a good starting point for details on what nostr protocol is and how it works: https://github.com/nostr-protocol/nostr

func NewServer

func NewServer(relay Relay, opts ...Option) (*Server, error)

NewServer initializes the relay and its storage using their respective Init methods, returning any non-nil errors, and returns a Server ready to listen for HTTP requests.

func (*Server) BroadcastEvent added in v2.2.10

func (s *Server) BroadcastEvent(evt *nostr.Event)

func (*Server) ClientsNum added in v2.2.9

func (s *Server) ClientsNum() int

func (*Server) GetListeningFilters added in v2.2.10

func (s *Server) GetListeningFilters() nostr.Filters

func (*Server) HandleNIP11

func (s *Server) HandleNIP11(w http.ResponseWriter, r *http.Request)

func (*Server) HandleWebsocket

func (s *Server) HandleWebsocket(w http.ResponseWriter, r *http.Request)

func (*Server) Router

func (s *Server) Router() *http.ServeMux

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler interface.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context)

Shutdown sends a websocket close control message to all connected clients.

If the relay is ShutdownAware, Shutdown calls its OnShutdown, passing the context as is. Note that the HTTP server make some time to shutdown and so the context deadline, if any, may have been shortened by the time OnShutdown is called.

func (*Server) Start

func (s *Server) Start(host string, port int, started ...chan bool) error

type ShutdownAware

type ShutdownAware interface {
	OnShutdown(context.Context)
}

ShutdownAware is called during the server shutdown. See Server.Shutdown for details.

type WebSocket

type WebSocket struct {
	// contains filtered or unexported fields
}

func (*WebSocket) WriteJSON

func (ws *WebSocket) WriteJSON(any interface{}) error

func (*WebSocket) WriteMessage

func (ws *WebSocket) WriteMessage(t int, b []byte) error

Directories

Path Synopsis
examples
basic command
expensive command
multi-instance command
rss-bridge command
search command
whitelisted command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址