chanevents

package
v0.2.18-alpha Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package chanevents contains functions for monitoring and storing channel events such as online/offline and balance updates.

Index

Constants

View Source
const Subsystem = "CHEV"

Variables

View Source
var (

	// ErrUnknownChannel signals that the requested channel is not
	// present in the store.
	ErrUnknownChannel = errors.New("unknown channel")
)

Functions

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

Types

type BatchedSQLQueries

type BatchedSQLQueries interface {
	SQLQueries

	sqldb.BatchedTx[SQLQueries]
}

BatchedSQLQueries combines the SQLQueries interface with the BatchedTx interface, allowing for multiple queries to be executed in single SQL transaction.

type Channel

type Channel struct {
	// ID is the database ID of the channel.
	ID int64

	// ChannelPoint is the channel point of the channel.
	ChannelPoint string

	// ShortChannelID is the short channel ID of the channel.
	ShortChannelID uint64

	// PeerID is the database ID of the peer that this channel is with.
	PeerID int64
}

Channel is the application-level representation of a channel.

type ChannelEvent

type ChannelEvent struct {
	// ID is the database ID of the event.
	ID int64

	// ChannelID is the database ID of the channel that this event is
	// associated with.
	ChannelID int64

	// EventType is the type of the event.
	EventType EventType

	// Timestamp is the time that the event occurred.
	Timestamp time.Time

	// LocalBalance is the local balance of the channel at the time of the
	// event. This is only populated for balance update events.
	LocalBalance fn.Option[btcutil.Amount]

	// RemoteBalance is the remote balance of the channel at the time of the
	// event. This is only populated for balance update events.
	RemoteBalance fn.Option[btcutil.Amount]

	// IsSync indicates whether this event was recorded during an initial
	// sync rather than from a live subscription.
	IsSync bool
}

ChannelEvent is the application-level representation of a channel event.

type Config

type Config struct {
	// MaxEvents is the maximum number of channel events to retain. Once the
	// table exceeds this count, the oldest events are pruned. This operates
	// as a hard ceiling on database size to prevent disk filling. A value
	// of 0 disables this limit.
	MaxEvents uint64 `` /* 232-byte string literal not displayed */

	// Retention is the minimum duration of channel events to keep. Events
	// older than this window are pruned, even if the max-events limit is
	// not exceeded. If max-events is exceeded, newer events can still be
	// pruned to enforce the size ceiling. A value of 0 disables this limit.
	Retention time.Duration `` /* 210-byte string literal not displayed */
}

Config holds the configuration options for channel event pruning. See the README for storage sizing guidance.

type EventType

type EventType int16

EventType is an enum for the different types of channel events.

const (
	// EventTypeUnknown is the unknown event type.
	EventTypeUnknown EventType = 0

	// EventTypeOnline is the online event type.
	EventTypeOnline EventType = 1

	// EventTypeOffline is the offline event type.
	EventTypeOffline EventType = 2

	// EventTypeUpdate is the balance update event type.
	EventTypeUpdate EventType = 3
)

func EventTypeFromString

func EventTypeFromString(s string) EventType

EventTypeFromString returns the event type from a string.

func (EventType) String

func (e EventType) String() string

String returns the string representation of the event type.

type EventsSource

type EventsSource interface {
	// GetLatestChannelUpdateBefore returns the latest channel event before
	// the given time, or (nil, nil) if no event predates it.
	GetLatestChannelUpdateBefore(ctx context.Context, channelID int64,
		before time.Time) (*ChannelEvent, error)

	// GetChannelEvents fetches up to limit events for a channel with id >
	// afterID and timestamp in [startTime, endTime), ordered by id ASC.
	// Callers page through a range by passing the last returned id as
	// afterID until a short page comes back.
	GetChannelEvents(ctx context.Context, channelID, afterID int64,
		startTime, endTime time.Time,
		limit int32) ([]*ChannelEvent, error)

	// GetChannelByShortChanID resolves an scid to a Channel, returning
	// ErrUnknownChannel when no row matches.
	GetChannelByShortChanID(ctx context.Context,
		shortChannelID uint64) (*Channel, error)

	// ScidToPeerMap returns the historically recorded scid→peer index,
	// including closed channels.
	ScidToPeerMap(ctx context.Context) (map[uint64]string, error)
}

EventsSource abstracts the chanevents store so ForwardingAnalyzer can derive uptime metrics without coupling to a specific storage backend.

type ForwardingAbility

type ForwardingAbility struct {
	// EffectiveUptime is the time the pair held at least the liquidity floor
	// of directional forwardable liquidity over the window.
	EffectiveUptime time.Duration

	// ForwardedMsat is the total successfully forwarded amount over the
	// window, in millisatoshis.
	ForwardedMsat lnwire.MilliSatoshi

	// FeeMsat is the total fee earned on the pair's forwards over the
	// window.
	FeeMsat lnwire.MilliSatoshi

	// Forwards is how many successful forwards the pair carried. It decides
	// whether the pair forwarded at all, since the fee total can be zero
	// for one that did under a zero-fee policy.
	Forwards int64
}

ForwardingAbility holds the raw forwarding facts for one direction of a peer pair over the analysis window. It carries no derived rates or categories. The consumer derives velocity and uptime fraction from these and the window, and reconstructs any categorization (such as forwards observed without qualifying uptime) from EffectiveUptime and ForwardedMsat.

type ForwardingAnalyzer

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

ForwardingAnalyzer computes forwarding velocity and effective uptime for every (peerIn, peerOut) pair.

func NewForwardingAnalyzer

func NewForwardingAnalyzer(store EventsSource,
	lnd lndclient.LndServices) *ForwardingAnalyzer

NewForwardingAnalyzer returns a ready-to-use analyzer.

func (*ForwardingAnalyzer) EffectiveUptime

func (a *ForwardingAnalyzer) EffectiveUptime(ctx context.Context, startTime,
	endTime time.Time, liquidityFloor btcutil.Amount) (
	map[PeerPair]ForwardingAbility, error)

EffectiveUptime returns a ForwardingAbility for every (peerIn, peerOut) pair over [startTime, endTime). Closed channels are folded into the considered set so survivorship bias does not skew the uptime denominator. A single liquidityFloor is applied uniformly to every pair, so effective uptime is the time each pair held at least that much directional forwardable liquidity.

type Monitor

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

Monitor is an active component that listens to LND channel events and records them in the database.

func NewMonitor

func NewMonitor(lnd lndclient.LightningClient, store *Store,
	cfg Config) *Monitor

NewMonitor creates a new channel events monitor.

func (*Monitor) Start

func (m *Monitor) Start(ctx context.Context) error

Start starts the channel events monitor.

func (*Monitor) Stop

func (m *Monitor) Stop() error

Stop stops the channel events monitor.

type Peer

type Peer struct {
	// ID is the database ID of the peer.
	ID int64

	// PubKey is the public key of the peer.
	PubKey string
}

Peer is the application-level representation of a peer.

type PeerPair

type PeerPair struct {
	PeerIn  string
	PeerOut string
}

PeerPair identifies a unidirectional routing edge from PeerIn to PeerOut. PeerIn names the source-side peer (the incoming channel's far end in lnd's forwarding vocabulary) and PeerOut names the sink-side peer.

type Queries

type Queries interface {
	InsertPeer(ctx context.Context, pubkey string) (int64, error)

	GetPeerByPubKey(ctx context.Context, pubkey string) (sqlc.Peer, error)

	InsertChannel(ctx context.Context,
		arg sqlc.InsertChannelParams) (int64, error)

	GetChannelByChanPoint(ctx context.Context,
		channelPoint string) (sqlc.Channel, error)

	GetChannelByShortChanID(ctx context.Context,
		shortChannelID int64) (sqlc.Channel, error)

	InsertChannelEvent(ctx context.Context,
		arg sqlc.InsertChannelEventParams) error

	GetChannelEvents(ctx context.Context,
		arg sqlc.GetChannelEventsParams) ([]sqlc.ChannelEvent, error)

	GetLatestChannelEventBefore(ctx context.Context,
		arg sqlc.GetLatestChannelEventBeforeParams) (
		sqlc.ChannelEvent,
		error,
	)

	GetChannels(ctx context.Context) ([]sqlc.GetChannelsRow, error)

	PruneChannelEventsBySize(ctx context.Context, offset int32) (int64,
		error)

	PruneChannelEventsByAge(ctx context.Context, timestamp time.Time) (
		int64, error)
}

Queries is a subset of the sqlc.Queries interface that can be used to interact with the peers, channels and channel_events tables.

type SQLQueries

type SQLQueries interface {
	Queries
}

SQLQueries is a subset of the sqlc.Queries interface that can be used to interact with various chanevents tables.

type SQLQueriesExecutor

type SQLQueriesExecutor[T any] struct {
	*sqldb.TransactionExecutor[T]

	SQLQueries
}

type Store

type Store struct {

	// BaseDB represents the underlying database connection.
	*sqldb.BaseDB
	// contains filtered or unexported fields
}

Store provides access to the db for channel events.

func NewStore

func NewStore(sqlDB *sqldb.BaseDB, queries *sqlc.Queries,
	clock clock.Clock) *Store

NewStore creates a new SQLStore instance given an open SQLQueries storage backend.

func NewTestDB

func NewTestDB(t testing.TB, clock clock.Clock) *Store

NewTestDB creates a new test chanevents.Store backed by a sqlite DB.

func (*Store) AddChannel

func (s *Store) AddChannel(ctx context.Context, channelPoint string,
	shortChannelID uint64, peerID int64) (int64, error)

AddChannel adds a new channel for a peer.

func (*Store) AddChannelEvent

func (s *Store) AddChannelEvent(ctx context.Context,
	event *ChannelEvent) error

AddChannelEvent adds a new channel event.

func (*Store) AddPeer

func (s *Store) AddPeer(ctx context.Context, pubkey string) (int64, error)

AddPeer adds a new peer to the database.

func (*Store) GetChannel

func (s *Store) GetChannel(ctx context.Context, channelPoint string) (*Channel,
	error)

GetChannel retrieves a channel by its channel point.

func (*Store) GetChannelByShortChanID

func (s *Store) GetChannelByShortChanID(ctx context.Context,
	shortChannelID uint64) (*Channel, error)

GetChannelByShortChanID retrieves a channel by its short channel ID, returning ErrUnknownChannel if no row matches.

func (*Store) GetChannelEvents

func (s *Store) GetChannelEvents(ctx context.Context, channelID, afterID int64,
	startTime, endTime time.Time, limit int32) ([]*ChannelEvent, error)

GetChannelEvents returns up to limit events for a channel where id > afterID AND startTime <= timestamp < endTime, ordered by id ASC. Pass afterID = 0 on the first call; for subsequent calls pass the previous page's last event id. The (startTime, endTime) bounds are independent filters and do not need to advance between pages.

func (*Store) GetLatestChannelUpdateBefore

func (s *Store) GetLatestChannelUpdateBefore(ctx context.Context,
	channelID int64, before time.Time) (*ChannelEvent, error)

GetLatestChannelUpdateBefore returns the latest channel event before a given time (exclusive). If no event is found, it returns (nil, nil).

func (*Store) GetPeer

func (s *Store) GetPeer(ctx context.Context, pubkey string) (*Peer, error)

GetPeer retrieves a peer by their public key.

func (*Store) PruneEvents

func (s *Store) PruneEvents(ctx context.Context, maxEvents uint64,
	retention time.Duration) (int64, error)

PruneEvents enforces the size and age storage limits independently, returning the number of events deleted. A zero maxEvents or retention disables the corresponding limit, and zero for both disables pruning.

func (*Store) ScidToPeerMap

func (s *Store) ScidToPeerMap(ctx context.Context) (map[uint64]string, error)

ScidToPeerMap returns the historic scid→peer index, including channels that have since closed. Unconfirmed channels (scid still zero) are not part of the contract.

Jump to

Keyboard shortcuts

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