transport

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MailboxEventKind is the Nostr event kind for mailbox messages.
	MailboxEventKind = 20007

	// ReceiptEventKind is the Nostr event kind for delivery receipts.
	ReceiptEventKind = 20008

	// DefaultMailboxTTL is the default time-to-live for mailbox messages.
	DefaultMailboxTTL = 7 * 24 * time.Hour

	// DefaultSyncInterval is the default inbox polling interval.
	DefaultSyncInterval = 5 * time.Minute
)
View Source
const (
	// DefaultCacheTTL is the default time-to-live for cached messages.
	DefaultCacheTTL = 24 * time.Hour

	// MaxCachePerDest is the maximum number of messages cached per destination.
	MaxCachePerDest = 100

	// MaxCacheGlobal is the maximum total number of cached messages across all destinations.
	MaxCacheGlobal = 10000
)
View Source
const (
	// NostrEventKind is the event kind used for PeerClaw messages.
	NostrEventKind = 20004
)

Variables

This section is empty.

Functions

func SortICECandidates

func SortICECandidates(candidates []webrtc.ICECandidate) []webrtc.ICECandidate

SortICECandidates sorts ICE candidates by type priority: host > srflx > relay. This helps establish direct connections when possible while falling back to TURN.

Types

type ConnectionMonitor

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

ConnectionMonitor tracks connection quality metrics over time.

func NewConnectionMonitor

func NewConnectionMonitor(opts ...MonitorOption) *ConnectionMonitor

NewConnectionMonitor creates a new connection monitor.

func (*ConnectionMonitor) AvgRTT

func (m *ConnectionMonitor) AvgRTT() time.Duration

AvgRTT returns the rolling average RTT.

func (*ConnectionMonitor) PacketLoss

func (m *ConnectionMonitor) PacketLoss() float64

PacketLoss returns the current packet loss ratio.

func (*ConnectionMonitor) RecordLoss

func (m *ConnectionMonitor) RecordLoss()

RecordLoss records a packet loss event.

func (*ConnectionMonitor) RecordRTT

func (m *ConnectionMonitor) RecordRTT(rtt time.Duration)

RecordRTT records a round-trip time measurement.

func (*ConnectionMonitor) RecordRecv

func (m *ConnectionMonitor) RecordRecv(bytes int)

RecordRecv records a received message.

func (*ConnectionMonitor) RecordSend

func (m *ConnectionMonitor) RecordSend(bytes int)

RecordSend records a sent message.

func (*ConnectionMonitor) Stats

Stats returns the current connection statistics.

type ConnectionStateHandler

type ConnectionStateHandler func(state webrtc.ICEConnectionState)

ConnectionStateHandler is called when the ICE connection state changes.

type ConnectionStats

type ConnectionStats struct {
	RTT          time.Duration // round-trip time
	PacketLoss   float64       // 0.0 to 1.0
	BytesSent    int64
	BytesRecv    int64
	MessagesSent int64
	MessagesRecv int64
	Uptime       time.Duration
}

ConnectionStats holds point-in-time connection quality metrics.

type DeliveryReceipt

type DeliveryReceipt struct {
	EnvelopeID string    `json:"envelope_id"`
	Timestamp  time.Time `json:"timestamp"`
	Status     string    `json:"status"` // "delivered"
}

DeliveryReceipt is sent back by the recipient to confirm delivery.

type ICECandidateType

type ICECandidateType int

ICECandidateType represents the priority of an ICE candidate type.

const (
	ICECandidateHost  ICECandidateType = 3 // highest priority
	ICECandidateSrflx ICECandidateType = 2
	ICECandidateRelay ICECandidateType = 1 // lowest priority
)

type Mailbox

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

Mailbox provides encrypted offline message delivery via Nostr relays.

func NewMailbox

func NewMailbox(cfg MailboxConfig) (*Mailbox, error)

NewMailbox creates a new Mailbox.

func NewMailboxWithPool

func NewMailboxWithPool(cfg MailboxConfig, pool RelayPool) (*Mailbox, error)

NewMailboxWithPool creates a Mailbox with a custom relay pool (for testing).

func (*Mailbox) NostrPublicKeyHex

func (m *Mailbox) NostrPublicKeyHex() string

NostrPublicKeyHex returns this mailbox's Nostr public key.

func (*Mailbox) OnMessage

func (m *Mailbox) OnMessage(handler MailboxMessageHandler)

OnMessage registers a callback for incoming inbox messages.

func (*Mailbox) OnReceipt

func (m *Mailbox) OnReceipt(handler MailboxReceiptHandler)

OnReceipt registers a callback for delivery receipts.

func (*Mailbox) OutboxEntries

func (m *Mailbox) OutboxEntries() []OutboxEntry

OutboxEntries returns a copy of the outbox entries (for testing).

func (*Mailbox) OutboxLen

func (m *Mailbox) OutboxLen() int

OutboxLen returns the number of entries in the outbox (for testing).

func (*Mailbox) SendToInbox

func (m *Mailbox) SendToInbox(ctx context.Context, env *envelope.Envelope, destRelays []string, destNostrPub string) error

SendToInbox encrypts and publishes an envelope to the recipient's inbox relays.

func (*Mailbox) Start

func (m *Mailbox) Start(ctx context.Context)

Start begins inbox sync and outbox retry goroutines.

func (*Mailbox) Stop

func (m *Mailbox) Stop()

Stop saves state and shuts down.

func (*Mailbox) SyncInbox

func (m *Mailbox) SyncInbox(ctx context.Context)

SyncInbox queries inbox relays for new messages since last sync.

type MailboxConfig

type MailboxConfig struct {
	InboxRelays  []string      // This agent's inbox relay URLs
	Ed25519Seed  []byte        // 32-byte seed for deriving Nostr keypair
	AgentID      string        // This agent's ID
	TTL          time.Duration // Message expiration (default 7 days)
	SyncInterval time.Duration // Inbox poll interval (default 5 minutes)
	OutboxPath   string        // Outbox persistence path
	LastSyncPath string        // Last sync timestamp persistence path
	Logger       *slog.Logger
}

MailboxConfig holds configuration for the Mailbox.

type MailboxMessageHandler

type MailboxMessageHandler func(ctx context.Context, env *envelope.Envelope)

MailboxMessageHandler is called when an inbox message is received.

type MailboxReceiptHandler

type MailboxReceiptHandler func(envID string)

MailboxReceiptHandler is called when a delivery receipt is received.

type MessageCache

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

MessageCache stores messages for offline peers and delivers them when the peer comes online.

func NewMessageCache

func NewMessageCache() *MessageCache

NewMessageCache creates a new offline message cache.

func (*MessageCache) CleanExpired

func (mc *MessageCache) CleanExpired() int

CleanExpired removes all expired messages from all queues.

func (*MessageCache) Destinations

func (mc *MessageCache) Destinations() []string

Destinations returns all destinations with pending messages.

func (*MessageCache) Enqueue

func (mc *MessageCache) Enqueue(destination string, env *envelope.Envelope) error

Enqueue adds a message to the cache for a destination. Returns an error if the global cache limit is exceeded.

func (*MessageCache) Flush

func (mc *MessageCache) Flush(destination string) []*envelope.Envelope

Flush returns and removes all cached messages for a destination.

func (*MessageCache) LoadFromFile

func (mc *MessageCache) LoadFromFile(path string) error

LoadFromFile loads the cache from a JSON file.

func (*MessageCache) PendingCount

func (mc *MessageCache) PendingCount(destination string) int

PendingCount returns the number of pending messages for a destination.

func (*MessageCache) SaveToFile

func (mc *MessageCache) SaveToFile(path string) error

SaveToFile persists the cache to a JSON file.

func (*MessageCache) TotalPending

func (mc *MessageCache) TotalPending() int

TotalPending returns the total number of pending messages across all destinations.

type MonitorOption

type MonitorOption func(*ConnectionMonitor)

MonitorOption configures a ConnectionMonitor.

func WithDegradationCallback

func WithDegradationCallback(rttThreshold time.Duration, lossThreshold float64, cb func(ConnectionStats)) MonitorOption

WithDegradationCallback sets a callback for quality degradation events.

func WithMaxSamples

func WithMaxSamples(n int) MonitorOption

WithMaxSamples sets the maximum number of RTT samples to keep.

type NostrConfig

type NostrConfig struct {
	RelayURLs   []string
	AgentID     string
	Ed25519Seed []byte // 32-byte seed for deriving Nostr secp256k1 keys
	Logger      *slog.Logger
}

NostrConfig holds configuration for the Nostr fallback transport.

type NostrKeypair

type NostrKeypair struct {
	PrivateKey *btcec.PrivateKey
	PublicKey  *btcec.PublicKey
}

NostrKeypair holds a secp256k1 keypair for Nostr protocol usage.

func DeriveNostrKeypair

func DeriveNostrKeypair(ed25519Seed []byte) (*NostrKeypair, error)

DeriveNostrKeypair deterministically derives a secp256k1 keypair from an Ed25519 seed using HKDF-SHA256 with domain-specific info.

func (*NostrKeypair) PrivateKeyHex

func (nk *NostrKeypair) PrivateKeyHex() string

PrivateKeyHex returns the hex-encoded private key (for Nostr signing).

func (*NostrKeypair) PubKeyTyped

func (nk *NostrKeypair) PubKeyTyped() nostr.PubKey

PubKeyTyped returns the x-only public key as a nostr.PubKey ([32]byte).

func (*NostrKeypair) PublicKeyHex

func (nk *NostrKeypair) PublicKeyHex() string

PublicKeyHex returns the hex-encoded x-only public key (Nostr npub format internal).

func (*NostrKeypair) SecretKeyTyped

func (nk *NostrKeypair) SecretKeyTyped() nostr.SecretKey

SecretKeyTyped returns the private key as a nostr.SecretKey ([32]byte).

type NostrTransport

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

NostrTransport implements Transport using Nostr relays as a fallback when WebRTC direct connections fail.

func NewNostrTransport

func NewNostrTransport(cfg NostrConfig) (*NostrTransport, error)

NewNostrTransport creates a new Nostr relay transport.

func (*NostrTransport) Close

func (t *NostrTransport) Close() error

Close shuts down all relay connections.

func (*NostrTransport) Connect

func (t *NostrTransport) Connect(ctx context.Context) error

Connect establishes connections to all configured relays and starts subscription loops.

func (*NostrTransport) ConnectedRelays

func (t *NostrTransport) ConnectedRelays() int

ConnectedRelays returns the number of currently connected relays.

func (*NostrTransport) NostrPublicKeyHex

func (t *NostrTransport) NostrPublicKeyHex() string

NostrPublicKeyHex returns the Nostr public key for this transport.

func (*NostrTransport) Receive

func (t *NostrTransport) Receive(ctx context.Context) (<-chan *envelope.Envelope, error)

Receive returns a channel that yields incoming envelopes.

func (*NostrTransport) Send

func (t *NostrTransport) Send(ctx context.Context, env *envelope.Envelope) error

Send publishes an envelope as a NIP-44 encrypted Nostr event to all healthy relays.

type OutboxEntry

type OutboxEntry struct {
	Envelope     *envelope.Envelope `json:"envelope"`
	DestRelays   []string           `json:"dest_relays"`
	DestNostrPub string             `json:"dest_nostr_pub"`
	CreatedAt    time.Time          `json:"created_at"`
	ExpiresAt    time.Time          `json:"expires_at"`
	Retries      int                `json:"retries"`
	NextRetryAt  time.Time          `json:"next_retry_at"`
	Confirmed    bool               `json:"confirmed"`
	NostrEventID string             `json:"nostr_event_id"`
}

OutboxEntry tracks a sent mailbox message awaiting delivery confirmation.

type RelayPool

type RelayPool interface {
	Publish(ctx context.Context, relayURL string, event nostr.Event) error
	Subscribe(ctx context.Context, relayURL string, filter nostr.Filter) (<-chan nostr.Event, func(), error)
}

RelayPool abstracts Nostr relay connections for testability.

type Transport

type Transport interface {
	// Send delivers an envelope to the connected peer.
	Send(ctx context.Context, env *envelope.Envelope) error

	// Receive returns a channel that yields incoming envelopes.
	Receive(ctx context.Context) (<-chan *envelope.Envelope, error)

	// Close releases resources held by this transport.
	Close() error
}

Transport defines the interface for sending and receiving envelopes over a network transport.

type WebRTCConfig

type WebRTCConfig struct {
	ICEServers    []webrtc.ICEServer
	Logger        *slog.Logger
	OnStateChange ConnectionStateHandler
}

WebRTCConfig holds configuration for creating a WebRTC transport.

type WebRTCTransport

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

WebRTCTransport implements Transport over a WebRTC DataChannel.

func NewWebRTCTransport

func NewWebRTCTransport(cfg WebRTCConfig) (*WebRTCTransport, error)

NewWebRTCTransport creates a new WebRTC transport with a PeerConnection.

func (*WebRTCTransport) AddICECandidate

func (t *WebRTCTransport) AddICECandidate(candidate webrtc.ICECandidateInit) error

AddICECandidate adds a remote ICE candidate.

func (*WebRTCTransport) Close

func (t *WebRTCTransport) Close() error

func (*WebRTCTransport) ConnectionState

func (t *WebRTCTransport) ConnectionState() webrtc.ICEConnectionState

ConnectionState returns the current ICE connection state.

func (*WebRTCTransport) CreateAnswer

CreateAnswer creates an SDP answer in response to an offer.

func (*WebRTCTransport) CreateOffer

func (t *WebRTCTransport) CreateOffer() (*webrtc.SessionDescription, error)

CreateOffer creates an SDP offer for initiating a connection.

func (*WebRTCTransport) DTLSFingerprint added in v0.2.0

func (t *WebRTCTransport) DTLSFingerprint() string

DTLSFingerprint returns the local DTLS certificate fingerprint in "sha-256 XX:XX:..." format. Must be called after SetLocalDescription (i.e., after CreateOffer or CreateAnswer).

func (*WebRTCTransport) HandleAnswer

func (t *WebRTCTransport) HandleAnswer(answer webrtc.SessionDescription) error

HandleAnswer processes an SDP answer from the remote peer.

func (*WebRTCTransport) Monitor

func (t *WebRTCTransport) Monitor() *ConnectionMonitor

Monitor returns the connection quality monitor.

func (*WebRTCTransport) OnICECandidate

func (t *WebRTCTransport) OnICECandidate(handler func(*webrtc.ICECandidate))

OnICECandidate sets a handler for local ICE candidates.

func (*WebRTCTransport) OnStateChange added in v0.2.0

func (t *WebRTCTransport) OnStateChange(handler ConnectionStateHandler)

OnStateChange registers a callback for ICE connection state changes. This can be called after creation to receive state change notifications without polling.

func (*WebRTCTransport) Receive

func (t *WebRTCTransport) Receive(ctx context.Context) (<-chan *envelope.Envelope, error)

func (*WebRTCTransport) Send

func (*WebRTCTransport) VerifyRemoteDTLSFingerprint added in v0.2.0

func (t *WebRTCTransport) VerifyRemoteDTLSFingerprint(expected string) error

VerifyRemoteDTLSFingerprint checks that the expected fingerprint matches the remote SDP. Returns nil if matched or if expected is empty (backward compatible).

Jump to

Keyboard shortcuts

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