core

package
v0.4.12 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

client/core/eventSerializer.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComputeEventID

func ComputeEventID(event *nostr.Event) (string, error)

ComputeEventID computes the event ID according to NIP-01

func ContactListFilter

func ContactListFilter(pubkey string) nostr.Filter

ContactListFilter creates a filter for contact lists (kind 3)

func CreateNostrMessage

func CreateNostrMessage(messageType string, args ...interface{}) ([]byte, error)

CreateNostrMessage creates a properly formatted Nostr protocol message

func DerivePublicKey

func DerivePublicKey(privateKeyHex string) (string, error)

DerivePublicKey derives a public key from a private key hex

func DeserializeEvent

func DeserializeEvent(data []byte) (*nostr.Event, error)

DeserializeEvent deserializes JSON bytes to an event

func EventFromJSON

func EventFromJSON(data []byte) (*nostr.Event, error)

EventFromJSON parses an event from JSON

func EventToJSON

func EventToJSON(event *nostr.Event) ([]byte, error)

EventToJSON converts an event to pretty-printed JSON

func GeneratePrivateKey

func GeneratePrivateKey() (string, error)

GeneratePrivateKey generates a new random private key

func GetPublicKeyFromExtension

func GetPublicKeyFromExtension() (string, error)

GetPublicKeyFromExtension attempts to get public key from browser extension

func NotesFilter

func NotesFilter(authors []string, limit int) nostr.Filter

NotesFilter creates a filter for notes from specific authors

func ParseNostrMessage

func ParseNostrMessage(data []byte) (messageType string, args []interface{}, err error)

ParseNostrMessage parses a Nostr protocol message

func ProfileFilter

func ProfileFilter(pubkey string) nostr.Filter

ProfileFilter creates a filter for user profiles (kind 0)

func ReactionsFilter

func ReactionsFilter(eventID string) nostr.Filter

ReactionsFilter creates a filter for reactions to a specific event

func RecentNotesFilter

func RecentNotesFilter(limit int, maxAge time.Duration) nostr.Filter

RecentNotesFilter creates a filter for recent notes

func RelayListFilter

func RelayListFilter(pubkey string) nostr.Filter

RelayListFilter creates a filter for relay lists (kind 10002)

func SerializeEvent

func SerializeEvent(evt nostr.Event) string

SerializeEvent manually constructs the JSON string for event serialization according to NIP-01

func SerializeEventArray

func SerializeEventArray(events []*nostr.Event) ([]byte, error)

SerializeEventArray serializes an event for inclusion in a Nostr message array

func SignEventWithExtension

func SignEventWithExtension(event *nostr.Event) error

SignEventWithExtension attempts to sign an event using browser extension (NIP-07)

func TimeRangeFilter

func TimeRangeFilter(since, until time.Time, kinds []int) nostr.Filter

TimeRangeFilter creates a filter for events within a specific time range

func ValidateEventStructure

func ValidateEventStructure(event *nostr.Event) error

ValidateEventStructure validates the basic structure of an event

func VerifyEventSignature

func VerifyEventSignature(event *nostr.Event) bool

VerifyEventSignature verifies an event's signature

Types

type BroadcastResult

type BroadcastResult struct {
	RelayURL string
	Success  bool
	Error    error
	Message  string
	Duration time.Duration
}

BroadcastResult represents the result of broadcasting to a single relay

func BroadcastEvent

func BroadcastEvent(event *nostr.Event, relays []string, pool *RelayPool) []BroadcastResult

BroadcastEvent sends an event to multiple relays using the relay pool

func BroadcastToUserRelays

func BroadcastToUserRelays(event *nostr.Event, pubkey string, client *Client) []BroadcastResult

BroadcastToUserRelays broadcasts an event to a user's preferred relays

func BroadcastWithRetry

func BroadcastWithRetry(event *nostr.Event, relays []string, pool *RelayPool, maxRetries int) []BroadcastResult

BroadcastWithRetry broadcasts an event with retry logic

func PublishEvent

func PublishEvent(client *Client, signer *EventSigner, eventBuilder *EventBuilder, targetRelays []string) (*nostr.Event, []BroadcastResult, error)

PublishEvent is a high-level function to build, sign, and broadcast an event

func PublishEventWithRetry

func PublishEventWithRetry(client *Client, signer *EventSigner, eventBuilder *EventBuilder, targetRelays []string, maxRetries int) (*nostr.Event, []BroadcastResult, error)

PublishEventWithRetry publishes an event with retry logic

type BroadcastSummary

type BroadcastSummary struct {
	TotalRelays     int
	Successful      int
	Failed          int
	SuccessRate     float64
	AverageDuration time.Duration
	Errors          []string
}

BroadcastSummary provides a summary of broadcast results

func SummarizeBroadcast

func SummarizeBroadcast(results []BroadcastResult) BroadcastSummary

SummarizeBroadcast creates a summary of broadcast results

type Client

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

Client represents the main Nostr client with connection pooling

func NewClient

func NewClient(config *Config) *Client

NewClient creates a new Nostr client instance

func (*Client) Close

func (c *Client) Close() error

func (*Client) ConnectToRelays

func (c *Client) ConnectToRelays(urls []string) error

ConnectToRelays establishes connections to multiple relay URLs

func (*Client) ConnectToRelaysWithRetry

func (c *Client) ConnectToRelaysWithRetry(urls []string, maxRetries int) error

ConnectToRelaysWithRetry establishes connections with retry logic

func (*Client) DisconnectFromRelay added in v0.4.12

func (c *Client) DisconnectFromRelay(relayURL string) error

DisconnectFromRelay closes a specific relay connection

func (*Client) DisconnectFromRelays added in v0.4.12

func (c *Client) DisconnectFromRelays(relayURLs []string) error

DisconnectFromRelays closes connections to multiple relays

func (*Client) GetConnectedRelays

func (c *Client) GetConnectedRelays() []string

GetConnectedRelays returns a list of currently connected relay URLs

func (*Client) GetRelayStatus

func (c *Client) GetRelayStatus() map[string]string

GetRelayStatus returns detailed status of all relay connections

func (*Client) GetUserProfile

func (c *Client) GetUserProfile(pubkey string, relayHints []string) (*nostr.Event, error)

func (*Client) GetUserRelays

func (c *Client) GetUserRelays(pubkey string) (*Mailboxes, error)

GetUserRelays retrieves user relay list (kind 10002)

func (*Client) PublishEvent

func (c *Client) PublishEvent(event *nostr.Event, targetRelays []string) ([]BroadcastResult, error)

PublishEvent publishes an event to specified relays

func (*Client) PublishEventWithRetry

func (c *Client) PublishEventWithRetry(event *nostr.Event, targetRelays []string, maxRetries int) ([]BroadcastResult, error)

PublishEventWithRetry publishes an event with retry logic

func (*Client) ReplaceRelayConnections added in v0.4.12

func (c *Client) ReplaceRelayConnections(newRelays []RelayConfig) error

ReplaceRelayConnections replaces current relay connections with a new set

func (*Client) Subscribe

func (c *Client) Subscribe(filters []nostr.Filter, relayHints []string) (*Subscription, error)

Subscribe creates a new subscription with filters and relay hints

func (*Client) SwitchToDefaultRelays added in v0.4.12

func (c *Client) SwitchToDefaultRelays() error

SwitchToDefaultRelays switches the client back to default app relays

func (*Client) SwitchToUserRelays added in v0.4.12

func (c *Client) SwitchToUserRelays(userRelays []RelayConfig) error

SwitchToUserRelays switches the client to use user's cached relays

type ClientError

type ClientError struct {
	Message string
}

ClientError represents client-specific errors

func (*ClientError) Error

func (e *ClientError) Error() string

type Config

type Config struct {
	DefaultRelays     []string      `json:"default_relays"`
	ConnectionTimeout time.Duration `json:"connection_timeout"`
	ReadTimeout       time.Duration `json:"read_timeout"`
	WriteTimeout      time.Duration `json:"write_timeout"`
	MaxConnections    int           `json:"max_connections"`
	RetryAttempts     int           `json:"retry_attempts"`
	RetryDelay        time.Duration `json:"retry_delay"`
	KeepAlive         bool          `json:"keep_alive"`
	UserAgent         string        `json:"user_agent"`
}

Config holds client-specific configuration

func ConfigFromServerConfig added in v0.4.11

func ConfigFromServerConfig(serverCfg *cfgType.ServerConfig) *Config

ConfigFromServerConfig creates a client config from server configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a sensible default configuration

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid

type ConnectionStatus

type ConnectionStatus int

ConnectionStatus represents the state of a relay connection

const (
	StatusDisconnected ConnectionStatus = iota
	StatusConnecting
	StatusConnected
	StatusError
)

type EventBuilder

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

EventBuilder provides a fluent interface for building Nostr events

func NewContactList

func NewContactList() *EventBuilder

NewContactList creates a builder for a contact list (kind 3)

func NewDeletion

func NewDeletion(eventIDs []string, reason string) *EventBuilder

NewDeletion creates a builder for a deletion event (kind 5)

func NewEventBuilder

func NewEventBuilder(kind int) *EventBuilder

NewEventBuilder creates a new event builder with the specified kind

func NewProfile

func NewProfile() *EventBuilder

NewProfile creates a builder for a profile event (kind 0)

func NewReaction

func NewReaction(eventID string, content string) *EventBuilder

NewReaction creates a builder for a reaction (kind 7)

func NewRelayList

func NewRelayList() *EventBuilder

NewRelayList creates a builder for a relay list (kind 10002)

func NewRepost

func NewRepost(eventID string, relayHint string) *EventBuilder

NewRepost creates a builder for a repost (kind 6)

func NewTextNote

func NewTextNote(content string) *EventBuilder

NewTextNote creates a builder for a text note (kind 1)

func (*EventBuilder) ATag

func (eb *EventBuilder) ATag(kind int, pubkey string, dTag string, relayHint ...string) *EventBuilder

ATag adds an 'a' tag (address reference) to the event

func (*EventBuilder) Build

func (eb *EventBuilder) Build() *nostr.Event

Build constructs the final Event struct (without signing)

func (*EventBuilder) Content

func (eb *EventBuilder) Content(content string) *EventBuilder

Content sets the content of the event

func (*EventBuilder) CreatedAt

func (eb *EventBuilder) CreatedAt(t time.Time) *EventBuilder

CreatedAt sets the created_at timestamp for the event

func (*EventBuilder) DTag

func (eb *EventBuilder) DTag(identifier string) *EventBuilder

DTag adds a 'd' tag (identifier) to the event

func (*EventBuilder) ETag

func (eb *EventBuilder) ETag(eventID string, relayHint, marker string) *EventBuilder

ETag adds an 'e' tag (event reference) to the event

func (*EventBuilder) PTag

func (eb *EventBuilder) PTag(pubkey string, relayHint ...string) *EventBuilder

PTag adds a 'p' tag (pubkey reference) to the event

func (*EventBuilder) RTag

func (eb *EventBuilder) RTag(relayURL string, marker string) *EventBuilder

RTag adds an 'r' tag (relay reference) to the event

func (*EventBuilder) TTag

func (eb *EventBuilder) TTag(hashtag string) *EventBuilder

TTag adds a 't' tag (hashtag) to the event

func (*EventBuilder) Tag

func (eb *EventBuilder) Tag(name string, values ...string) *EventBuilder

Tag adds a generic tag to the event

type EventSigner

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

EventSigner handles event signing with private keys

func NewEventSigner

func NewEventSigner(privateKeyHex string) (*EventSigner, error)

NewEventSigner creates a new event signer from a hex private key

func NewEventSignerFromRandom

func NewEventSignerFromRandom() (*EventSigner, error)

NewEventSignerFromRandom creates a new event signer with a random private key

func (*EventSigner) GetPrivateKeyHex

func (es *EventSigner) GetPrivateKeyHex() string

GetPrivateKeyHex returns the private key in hex format (use carefully!)

func (*EventSigner) GetPublicKey

func (es *EventSigner) GetPublicKey() string

GetPublicKey returns the public key in hex format

func (*EventSigner) SignEvent

func (es *EventSigner) SignEvent(event *nostr.Event) error

SignEvent signs an event and sets the ID, PubKey, and Sig fields

type FilterBuilder

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

FilterBuilder provides a fluent interface for building Nostr filters

func NewFilterBuilder

func NewFilterBuilder() *FilterBuilder

NewFilterBuilder creates a new filter builder

func (*FilterBuilder) Authors

func (fb *FilterBuilder) Authors(pubkeys ...string) *FilterBuilder

Authors sets the authors filter

func (*FilterBuilder) Build

func (fb *FilterBuilder) Build() nostr.Filter

Build returns the constructed filter

func (*FilterBuilder) IDs

func (fb *FilterBuilder) IDs(ids ...string) *FilterBuilder

IDs sets the event IDs filter

func (*FilterBuilder) Kinds

func (fb *FilterBuilder) Kinds(kinds ...int) *FilterBuilder

Kinds sets the kinds filter

func (*FilterBuilder) Limit

func (fb *FilterBuilder) Limit(limit int) *FilterBuilder

Limit sets the limit filter

func (*FilterBuilder) Since

func (fb *FilterBuilder) Since(timestamp time.Time) *FilterBuilder

Since sets the since timestamp filter

func (*FilterBuilder) Tag

func (fb *FilterBuilder) Tag(name string, values ...string) *FilterBuilder

Tag adds a tag filter

func (*FilterBuilder) Until

func (fb *FilterBuilder) Until(timestamp time.Time) *FilterBuilder

Until sets the until timestamp filter

type Mailboxes

type Mailboxes struct {
	Read  []string `json:"read"`
	Write []string `json:"write"`
	Both  []string `json:"both"`
}

Mailboxes represents a user's relay preferences from NIP-65

func (Mailboxes) ToStringSlice

func (m Mailboxes) ToStringSlice() []string

ToStringSlice combines Read, Write, and Both into a single []string

type MessageRouter

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

MessageRouter handles routing messages to subscriptions

func NewMessageRouter

func NewMessageRouter() *MessageRouter

NewMessageRouter creates a new message router

func (*MessageRouter) RegisterSubscription

func (mr *MessageRouter) RegisterSubscription(subID string, sub *Subscription)

RegisterSubscription registers a subscription for message routing

func (*MessageRouter) RouteMessage

func (mr *MessageRouter) RouteMessage(subID string, messageType string, data interface{})

RouteMessage routes a message to the appropriate subscription

func (*MessageRouter) UnregisterSubscription

func (mr *MessageRouter) UnregisterSubscription(subID string)

UnregisterSubscription removes a subscription from message routing

type RelayConfig added in v0.4.12

type RelayConfig struct {
	URL   string `json:"url"`
	Read  bool   `json:"read"`
	Write bool   `json:"write"`
}

RelayConfig represents relay configuration with permissions

type RelayConnection

type RelayConnection struct {
	URL           string
	Conn          *websocket.Conn
	Status        ConnectionStatus
	LastPing      time.Time
	Subscriptions map[string]bool
	// contains filtered or unexported fields
}

RelayConnection represents a single relay connection

type RelayPool

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

RelayPool manages multiple relay connections

func NewRelayPool

func NewRelayPool(config *Config) *RelayPool

NewRelayPool creates a new relay pool

func (*RelayPool) BroadcastMessage

func (rp *RelayPool) BroadcastMessage(message interface{}, urls []string) error

BroadcastMessage sends a message to multiple relays

func (*RelayPool) Close

func (rp *RelayPool) Close() error

Close shuts down all relay connections

func (*RelayPool) CloseConnection

func (rp *RelayPool) CloseConnection(url string) error

CloseConnection closes a specific relay connection

func (*RelayPool) Connect

func (rp *RelayPool) Connect(url string) error

Connect establishes a connection to a relay

func (*RelayPool) GetConnectedRelays

func (rp *RelayPool) GetConnectedRelays() []string

GetConnectedRelays returns a list of connected relay URLs

func (*RelayPool) GetConnection

func (rp *RelayPool) GetConnection(url string) (*RelayConnection, error)

GetConnection returns a specific relay connection

func (*RelayPool) RegisterSubscription

func (rp *RelayPool) RegisterSubscription(subID string, sub *Subscription)

RegisterSubscription registers a subscription for message routing

func (*RelayPool) SendMessage

func (rp *RelayPool) SendMessage(url string, message interface{}) error

SendMessage sends a message to a specific relay

func (*RelayPool) UnregisterSubscription

func (rp *RelayPool) UnregisterSubscription(subID string)

UnregisterSubscription removes a subscription from message routing

type Subscription

type Subscription struct {
	ID      string
	Filters []nostr.Filter
	Relays  []string
	Events  chan *nostr.Event
	Errors  chan error
	Done    chan struct{}
	// contains filtered or unexported fields
}

Subscription manages a Nostr subscription across multiple relays

func NewSubscription

func NewSubscription(id string, filters []nostr.Filter, relays []string, client *Client) *Subscription

NewSubscription creates a new subscription instance

func (*Subscription) AddRelay

func (s *Subscription) AddRelay(url string) error

AddRelay adds a new relay to an active subscription

func (*Subscription) Close

func (s *Subscription) Close() error

Close terminates the subscription

func (*Subscription) GetFilters

func (s *Subscription) GetFilters() []nostr.Filter

GetFilters returns a copy of the subscription filters

func (*Subscription) GetRelayCount

func (s *Subscription) GetRelayCount() int

GetRelayCount returns the number of relays in this subscription

func (*Subscription) IsActive

func (s *Subscription) IsActive() bool

IsActive returns whether the subscription is currently active

func (*Subscription) RemoveRelay

func (s *Subscription) RemoveRelay(url string) error

RemoveRelay removes a relay from the subscription

func (*Subscription) Start

func (s *Subscription) Start() error

Start begins the subscription on all specified relays

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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