wtclient

package
v0.18.0-beta.rc2 Latest Latest
Warning

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

Go to latest
Published: May 7, 2024 License: MIT Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultReadTimeout specifies the default duration we will wait during
	// a read before breaking out of a blocking read.
	DefaultReadTimeout = 15 * time.Second

	// DefaultWriteTimeout specifies the default duration we will wait
	// during a write before breaking out of a blocking write.
	DefaultWriteTimeout = 15 * time.Second

	// DefaultStatInterval specifies the default interval between logging
	// metrics about the client's operation.
	DefaultStatInterval = time.Minute

	// DefaultSessionCloseRange is the range over which we will generate a
	// random number of blocks to delay closing a session after its last
	// channel has been closed.
	DefaultSessionCloseRange = 288

	// DefaultMaxTasksInMemQueue is the maximum number of items to be held
	// in the in-memory queue.
	DefaultMaxTasksInMemQueue = 2000
)

Variables

View Source
var (
	// ErrAddressesExhausted signals that a addressIterator has cycled
	// through all available addresses.
	ErrAddressesExhausted = errors.New("exhausted all addresses")

	// ErrAddrInUse indicates that an address is locked and cannot be
	// removed from the addressIterator.
	ErrAddrInUse = errors.New("address in use")
)
View Source
var (
	// ErrClientExiting signals that the watchtower client is shutting down.
	ErrClientExiting = errors.New("watchtower client shutting down")

	// ErrTowerCandidatesExhausted signals that a TowerCandidateIterator has
	// cycled through all available candidates.
	ErrTowerCandidatesExhausted = errors.New("exhausted all tower " +
		"candidates")

	// ErrTowerNotInIterator is returned when a requested tower was not
	// found in the iterator.
	ErrTowerNotInIterator = errors.New("tower not in iterator")

	// ErrPermanentTowerFailure signals that the tower has reported that it
	// has permanently failed or the client believes this has happened based
	// on the tower's behavior.
	ErrPermanentTowerFailure = errors.New("permanent tower failure")

	// ErrNegotiatorExiting signals that the SessionNegotiator is shutting
	// down.
	ErrNegotiatorExiting = errors.New("negotiator exiting")

	// ErrFailedNegotiation signals that the session negotiator could not
	// acquire a new session as requested.
	ErrFailedNegotiation = errors.New("session negotiation unsuccessful")

	// ErrUnregisteredChannel signals that the client was unable to backup a
	// revoked state because the channel had not been previously registered
	// with the client.
	ErrUnregisteredChannel = errors.New("channel is not registered")

	// ErrSessionKeyAlreadyUsed indicates that the client attempted to
	// create a new session with a tower with a session key that has already
	// been used in the past.
	ErrSessionKeyAlreadyUsed = errors.New("session key already used")
)

Functions

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func ExhaustedSessionFilter

func ExhaustedSessionFilter() wtdb.ClientSessWithNumCommittedUpdatesFilterFn

ExhaustedSessionFilter constructs a wtdb.ClientSessionFilterFn filter function that will filter out any sessions that have been exhausted. A session is considered exhausted only if it has no un-acked updates and the sequence number of the session is equal to the max updates of the session policy.

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 AddressIterator

type AddressIterator interface {
	// Next returns the next candidate address. This iterator will always
	// return candidates in the order given when the iterator was
	// instantiated. If no more candidates are available,
	// ErrAddressesExhausted is returned.
	Next() (net.Addr, error)

	// NextAndLock does the same as described for Next, and it also places a
	// lock on the returned address so that the address can not be removed
	// until the lock on it has been released via ReleaseLock.
	NextAndLock() (net.Addr, error)

	// Peek returns the currently selected address in the iterator. If the
	// end of the iterator has been reached then it is reset and the first
	// item in the iterator is returned. Since the AddressIterator will
	// never have an empty address list, this function will never return a
	// nil value.
	Peek() net.Addr

	// PeekAndLock does the same as described for Peek, and it also places
	// a lock on the returned address so that the address can not be removed
	// until the lock on it has been released via ReleaseLock.
	PeekAndLock() net.Addr

	// ReleaseLock releases the lock held on the given address.
	ReleaseLock(addr net.Addr)

	// Add adds a new address to the iterator.
	Add(addr net.Addr)

	// Remove removes an existing address from the iterator. It disallows
	// the address from being removed if it is the last address in the
	// iterator or if there is currently a lock on the address.
	Remove(addr net.Addr) error

	// HasLocked returns true if the addressIterator has any locked
	// addresses.
	HasLocked() bool

	// GetAll returns a copy of all the addresses in the iterator.
	GetAll() []net.Addr

	// Reset clears the iterators state, and makes the address at the front
	// of the list the next item to be returned.
	Reset()

	// Copy constructs a new AddressIterator that has the same addresses
	// as this iterator.
	//
	// NOTE that the address locks are not expected to be copied.
	Copy() AddressIterator
}

AddressIterator handles iteration over a list of addresses. It strictly disallows the list of addresses it holds to be empty. It also allows callers to place locks on certain addresses in order to prevent other callers from removing the addresses in question from the iterator.

type AuthDialer

type AuthDialer func(localKey keychain.SingleKeyECDH,
	netAddr *lnwire.NetAddress,
	dialer tor.DialFunc) (wtserver.Peer, error)

AuthDialer connects to a remote node using an authenticated transport, such as brontide. The dialer argument is used to specify a resolver, which allows this method to be used over Tor or clear net connections.

type BreachRetributionBuilder

type BreachRetributionBuilder func(id lnwire.ChannelID,
	commitHeight uint64) (*lnwallet.BreachRetribution,
	channeldb.ChannelType, error)

BreachRetributionBuilder is a function that can be used to construct a BreachRetribution from a channel ID and a commitment height.

type ClientManager

type ClientManager interface {
	// AddTower adds a new watchtower reachable at the given address and
	// considers it for new sessions. If the watchtower already exists, then
	// any new addresses included will be considered when dialing it for
	// session negotiations and backups.
	AddTower(*lnwire.NetAddress) error

	// RemoveTower removes a watchtower from being considered for future
	// session negotiations and from being used for any subsequent backups
	// until it's added again. If an address is provided, then this call
	// only serves as a way of removing the address from the watchtower
	// instead.
	RemoveTower(*btcec.PublicKey, net.Addr) error

	// DeactivateTower sets the given tower's status to inactive so that it
	// is not considered for session negotiation. Its sessions will also not
	// be used while the tower is inactive.
	DeactivateTower(pubKey *btcec.PublicKey) error

	// TerminateSession sets the given session's status to CSessionTerminal
	// meaning that it will not be used again.
	TerminateSession(id wtdb.SessionID) error

	// Stats returns the in-memory statistics of the client since startup.
	Stats() ClientStats

	// Policy returns the active client policy configuration.
	Policy(blob.Type) (wtpolicy.Policy, error)

	// RegisteredTowers retrieves the list of watchtowers registered with
	// the client. It returns a set of registered towers per client policy
	// type.
	RegisteredTowers(opts ...wtdb.ClientSessionListOption) (
		map[blob.Type][]*RegisteredTower, error)

	// LookupTower retrieves a registered watchtower through its public key.
	LookupTower(*btcec.PublicKey, ...wtdb.ClientSessionListOption) (
		map[blob.Type]*RegisteredTower, error)

	// RegisterChannel persistently initializes any channel-dependent
	// parameters within the client. This should be called during link
	// startup to ensure that the client is able to support the link during
	// operation.
	RegisterChannel(lnwire.ChannelID, channeldb.ChannelType) error

	// BackupState initiates a request to back up a particular revoked
	// state. If the method returns nil, the backup is guaranteed to be
	// successful unless the justice transaction would create dust outputs
	// when trying to abide by the negotiated policy.
	BackupState(chanID *lnwire.ChannelID, stateNum uint64) error
}

ClientManager is the primary interface used by the daemon to control a client's lifecycle and backup revoked states.

type ClientSession

type ClientSession struct {
	// ID is the client's public key used when authenticating with the
	// tower.
	ID wtdb.SessionID

	wtdb.ClientSessionBody

	// Tower represents the tower that the client session has been made
	// with.
	Tower *Tower

	// SessionKeyECDH is the ECDH capable wrapper of the ephemeral secret
	// key used to connect to the watchtower.
	SessionKeyECDH keychain.SingleKeyECDH
}

ClientSession represents the session that a tower client has with a server.

func NewClientSessionFromDBSession

func NewClientSessionFromDBSession(s *wtdb.ClientSession, tower *Tower,
	keyRing ECDHKeyRing) (*ClientSession, error)

NewClientSessionFromDBSession converts a wtdb.ClientSession to a ClientSession.

type ClientStats

type ClientStats struct {
	// NumTasksPending is the total number of backups that are pending to
	// be acknowledged by all active and exhausted watchtower sessions.
	NumTasksPending int

	// NumTasksAccepted is the total number of backups made to all active
	// and exhausted watchtower sessions.
	NumTasksAccepted int

	// NumTasksIneligible is the total number of backups that all active and
	// exhausted watchtower sessions have failed to acknowledge.
	NumTasksIneligible int

	// NumSessionsAcquired is the total number of new sessions made to
	// watchtowers.
	NumSessionsAcquired int

	// NumSessionsExhausted is the total number of watchtower sessions that
	// have been exhausted.
	NumSessionsExhausted int
}

ClientStats is a collection of in-memory statistics of the actions the client has performed since its creation.

type Config

type Config struct {
	// Signer provides access to the wallet so that the client can sign
	// justice transactions that spend from a remote party's commitment
	// transaction.
	Signer input.Signer

	// SubscribeChannelEvents can be used to subscribe to channel event
	// notifications.
	SubscribeChannelEvents func() (subscribe.Subscription, error)

	// FetchClosedChannel can be used to fetch the info about a closed
	// channel. If the channel is not found or not yet closed then
	// channeldb.ErrClosedChannelNotFound will be returned.
	FetchClosedChannel func(cid lnwire.ChannelID) (
		*channeldb.ChannelCloseSummary, error)

	// ChainNotifier can be used to subscribe to block notifications.
	ChainNotifier chainntnfs.ChainNotifier

	// BuildBreachRetribution is a function closure that allows the client
	// fetch the breach retribution info for a certain channel at a certain
	// revoked commitment height.
	BuildBreachRetribution BreachRetributionBuilder

	// NewAddress generates a new on-chain sweep pkscript.
	NewAddress func() ([]byte, error)

	// SecretKeyRing is used to derive the session keys used to communicate
	// with the tower. The client only stores the KeyLocators internally so
	// that we never store private keys on disk.
	SecretKeyRing ECDHKeyRing

	// Dial connects to an addr using the specified net and returns the
	// connection object.
	Dial tor.DialFunc

	// AuthDialer establishes a brontide connection over an onion or clear
	// network.
	AuthDial AuthDialer

	// DB provides access to the client's stable storage medium.
	DB DB

	// ChainHash identifies the chain that the client is on and for which
	// the tower must be watching to monitor for breaches.
	ChainHash chainhash.Hash

	// ReadTimeout is the duration we will wait during a read before
	// breaking out of a blocking read. If the value is less than or equal
	// to zero, the default will be used instead.
	ReadTimeout time.Duration

	// WriteTimeout is the duration we will wait during a write before
	// breaking out of a blocking write. If the value is less than or equal
	// to zero, the default will be used instead.
	WriteTimeout time.Duration

	// MinBackoff defines the initial backoff applied to connections with
	// watchtowers. Subsequent backoff durations will grow exponentially up
	// until MaxBackoff.
	MinBackoff time.Duration

	// MaxBackoff defines the maximum backoff applied to connections with
	// watchtowers. If the exponential backoff produces a timeout greater
	// than this value, the backoff will be clamped to MaxBackoff.
	MaxBackoff time.Duration

	// SessionCloseRange is the range over which we will generate a random
	// number of blocks to delay closing a session after its last channel
	// has been closed.
	SessionCloseRange uint32

	// MaxTasksInMemQueue is the maximum number of backup tasks that should
	// be kept in-memory. Any more tasks will overflow to disk.
	MaxTasksInMemQueue uint64
}

Config provides the client with access to the resources it requires to perform its duty. All nillable fields must be non-nil for the tower to be initialized properly.

type DB

type DB interface {
	// CreateTower initialize an address record used to communicate with a
	// watchtower. Each Tower is assigned a unique ID, that is used to
	// amortize storage costs of the public key when used by multiple
	// sessions. If the tower already exists, the address is appended to the
	// list of all addresses used to that tower previously and its
	// corresponding sessions are marked as active.
	CreateTower(*lnwire.NetAddress) (*wtdb.Tower, error)

	// RemoveTower modifies a tower's record within the database. If an
	// address is provided, then _only_ the address record should be removed
	// from the tower's persisted state. Otherwise, we'll attempt to mark
	// the tower as inactive. If any of its sessions have unacked updates,
	// then ErrTowerUnackedUpdates is returned. If the tower doesn't have
	// any sessions at all, it'll be completely removed from the database.
	//
	// NOTE: An error is not returned if the tower doesn't exist.
	RemoveTower(*btcec.PublicKey, net.Addr) error

	// TerminateSession sets the given session's status to CSessionTerminal
	// meaning that it will not be usable again.
	TerminateSession(id wtdb.SessionID) error

	// LoadTower retrieves a tower by its public key.
	LoadTower(*btcec.PublicKey) (*wtdb.Tower, error)

	// LoadTowerByID retrieves a tower by its tower ID.
	LoadTowerByID(wtdb.TowerID) (*wtdb.Tower, error)

	// ListTowers retrieves the list of towers available within the
	// database. The filter function may be set in order to filter out the
	// towers to be returned.
	ListTowers(filter wtdb.TowerFilterFn) ([]*wtdb.Tower, error)

	// NextSessionKeyIndex reserves a new session key derivation index for a
	// particular tower id and blob type. The index is reserved for that
	// (tower, blob type) pair until CreateClientSession is invoked for that
	// tower and index, at which point a new index for that tower can be
	// reserved. Multiple calls to this method before CreateClientSession is
	// invoked should return the same index unless forceNext is true.
	NextSessionKeyIndex(wtdb.TowerID, blob.Type, bool) (uint32, error)

	// CreateClientSession saves a newly negotiated client session to the
	// client's database. This enables the session to be used across
	// restarts.
	CreateClientSession(*wtdb.ClientSession) error

	// ListClientSessions returns the set of all client sessions known to
	// the db. An optional tower ID can be used to filter out any client
	// sessions in the response that do not correspond to this tower.
	ListClientSessions(*wtdb.TowerID, ...wtdb.ClientSessionListOption) (
		map[wtdb.SessionID]*wtdb.ClientSession, error)

	// GetClientSession loads the ClientSession with the given ID from the
	// DB.
	GetClientSession(wtdb.SessionID,
		...wtdb.ClientSessionListOption) (*wtdb.ClientSession, error)

	// FetchSessionCommittedUpdates retrieves the current set of un-acked
	// updates of the given session.
	FetchSessionCommittedUpdates(id *wtdb.SessionID) (
		[]wtdb.CommittedUpdate, error)

	// IsAcked returns true if the given backup has been backed up using
	// the given session.
	IsAcked(id *wtdb.SessionID, backupID *wtdb.BackupID) (bool, error)

	// NumAckedUpdates returns the number of backups that have been
	// successfully backed up using the given session.
	NumAckedUpdates(id *wtdb.SessionID) (uint64, error)

	// FetchChanInfos loads a mapping from all registered channels to
	// their wtdb.ChannelInfo. Only the channels that have not yet been
	// marked as closed will be loaded.
	FetchChanInfos() (wtdb.ChannelInfos, error)

	// MarkChannelClosed will mark a registered channel as closed by setting
	// its closed-height as the given block height. It returns a list of
	// session IDs for sessions that are now considered closable due to the
	// close of this channel. The details for this channel will be deleted
	// from the DB if there are no more sessions in the DB that contain
	// updates for this channel.
	MarkChannelClosed(chanID lnwire.ChannelID, blockHeight uint32) (
		[]wtdb.SessionID, error)

	// ListClosableSessions fetches and returns the IDs for all sessions
	// marked as closable.
	ListClosableSessions() (map[wtdb.SessionID]uint32, error)

	// DeleteSession can be called when a session should be deleted from the
	// DB. All references to the session will also be deleted from the DB.
	// A session will only be deleted if it was previously marked as
	// closable.
	DeleteSession(id wtdb.SessionID) error

	// RegisterChannel registers a channel for use within the client
	// database. For now, all that is stored in the channel summary is the
	// sweep pkscript that we'd like any tower sweeps to pay into. In the
	// future, this will be extended to contain more info to allow the
	// client efficiently request historical states to be backed up under
	// the client's active policy.
	RegisterChannel(lnwire.ChannelID, []byte) error

	// MarkBackupIneligible records that the state identified by the
	// (channel id, commit height) tuple was ineligible for being backed up
	// under the current policy. This state can be retried later under a
	// different policy.
	MarkBackupIneligible(chanID lnwire.ChannelID, commitHeight uint64) error

	// CommitUpdate writes the next state update for a particular
	// session, so that we can be sure to resend it after a restart if it
	// hasn't been ACK'd by the tower. The sequence number of the update
	// should be exactly one greater than the existing entry, and less that
	// or equal to the session's MaxUpdates.
	CommitUpdate(id *wtdb.SessionID,
		update *wtdb.CommittedUpdate) (uint16, error)

	// AckUpdate records an acknowledgment from the watchtower that the
	// update identified by seqNum was received and saved. The returned
	// lastApplied will be recorded.
	AckUpdate(id *wtdb.SessionID, seqNum, lastApplied uint16) error

	// GetDBQueue returns a BackupID Queue instance under the given name
	// space.
	GetDBQueue(namespace []byte) wtdb.Queue[*wtdb.BackupID]

	// DeleteCommittedUpdates deletes all the committed updates belonging to
	// the given session from the db.
	DeleteCommittedUpdates(id *wtdb.SessionID) error

	// DeactivateTower sets the given tower's status to inactive. This means
	// that this tower's sessions won't be loaded and used for backups.
	// CreateTower can be used to reactivate the tower again.
	DeactivateTower(pubKey *btcec.PublicKey) error
}

DB abstracts the required database operations required by the watchtower client.

type DiskOverflowQueue

type DiskOverflowQueue[T any] struct {
	// contains filtered or unexported fields
}

DiskOverflowQueue is a queue that must be initialised with a certain maximum buffer size which represents the maximum number of elements that the queue should hold in memory. If the queue is full, then any new elements added to the queue will be persisted to disk instead. Once a consumer starts reading from the front of the queue again then items on disk will be moved into the queue again. The queue is also re-start safe. When it is stopped, any items in the memory queue, will be persisted to disk. On start up, the queue will be re-initialised with the items on disk.

func NewDiskOverflowQueue

func NewDiskOverflowQueue[T any](db wtdb.Queue[T], maxQueueSize uint64,
	logger btclog.Logger) (*DiskOverflowQueue[T], error)

NewDiskOverflowQueue constructs a new DiskOverflowQueue.

func (*DiskOverflowQueue[T]) NextBackupID

func (q *DiskOverflowQueue[T]) NextBackupID() <-chan T

NextBackupID can be used to read from the head of the DiskOverflowQueue.

func (*DiskOverflowQueue[T]) QueueBackupID

func (q *DiskOverflowQueue[T]) QueueBackupID(item *wtdb.BackupID) error

QueueBackupID adds a wtdb.BackupID to the queue. It will only return an error if the queue has been stopped. It is non-blocking.

func (*DiskOverflowQueue[T]) Start

func (q *DiskOverflowQueue[T]) Start() error

Start kicks off all the goroutines that are required to manage the queue.

func (*DiskOverflowQueue[T]) Stop

func (q *DiskOverflowQueue[T]) Stop() error

Stop stops the queue and persists any items in the memory queue to disk.

type ECDHKeyRing

type ECDHKeyRing interface {
	keychain.ECDHRing

	// DeriveKey attempts to derive an arbitrary key specified by the
	// passed KeyLocator. This may be used in several recovery scenarios,
	// or when manually rotating something like our current default node
	// key.
	DeriveKey(keyLoc keychain.KeyLocator) (keychain.KeyDescriptor, error)
}

ECDHKeyRing abstracts the ability to derive shared ECDH keys given a description of the derivation path of a private key.

type Manager

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

Manager manages the various tower clients that are active. A client is required for each different commitment transaction type. The Manager acts as a tower client multiplexer.

func NewManager

func NewManager(config *Config, policies ...wtpolicy.Policy) (*Manager, error)

NewManager constructs a new Manager.

func (*Manager) AddTower

func (m *Manager) AddTower(address *lnwire.NetAddress) error

AddTower adds a new watchtower reachable at the given address and considers it for new sessions. If the watchtower already exists, then any new addresses included will be considered when dialing it for session negotiations and backups.

func (*Manager) BackupState

func (m *Manager) BackupState(chanID *lnwire.ChannelID, stateNum uint64) error

BackupState initiates a request to back up a particular revoked state. If the method returns nil, the backup is guaranteed to be successful unless the justice transaction would create dust outputs when trying to abide by the negotiated policy.

func (*Manager) DeactivateTower

func (m *Manager) DeactivateTower(key *btcec.PublicKey) error

DeactivateTower sets the given tower's status to inactive so that it is not considered for session negotiation. Its sessions will also not be used while the tower is inactive.

func (*Manager) LookupTower

func (m *Manager) LookupTower(key *btcec.PublicKey,
	opts ...wtdb.ClientSessionListOption) (map[blob.Type]*RegisteredTower,
	error)

LookupTower retrieves a registered watchtower through its public key.

func (*Manager) Policy

func (m *Manager) Policy(blobType blob.Type) (wtpolicy.Policy, error)

Policy returns the active client policy configuration for the client using the given blob type.

func (*Manager) RegisterChannel

func (m *Manager) RegisterChannel(id lnwire.ChannelID,
	chanType channeldb.ChannelType) error

RegisterChannel persistently initializes any channel-dependent parameters within the client. This should be called during link startup to ensure that the client is able to support the link during operation.

func (*Manager) RegisteredTowers

func (m *Manager) RegisteredTowers(opts ...wtdb.ClientSessionListOption) (
	map[blob.Type][]*RegisteredTower, error)

RegisteredTowers retrieves the list of watchtowers being used by the various clients.

func (*Manager) RemoveTower

func (m *Manager) RemoveTower(key *btcec.PublicKey, addr net.Addr) error

RemoveTower removes a watchtower from being considered for future session negotiations and from being used for any subsequent backups until it's added again. If an address is provided, then this call only serves as a way of removing the address from the watchtower instead.

func (*Manager) Start

func (m *Manager) Start() error

Start starts all the clients that have been registered with the Manager.

func (*Manager) Stats

func (m *Manager) Stats() ClientStats

Stats returns the in-memory statistics of the clients managed by the Manager since startup.

func (*Manager) Stop

func (m *Manager) Stop() error

Stop stops all the clients that the Manger is managing.

func (*Manager) TerminateSession

func (m *Manager) TerminateSession(id wtdb.SessionID) error

TerminateSession sets the given session's status to CSessionTerminal meaning that it will not be used again.

type NegotiatorConfig

type NegotiatorConfig struct {
	// DB provides access to a persistent storage medium used by the tower
	// to properly allocate session ephemeral keys and record successfully
	// negotiated sessions.
	DB DB

	// SecretKeyRing allows the client to derive new session private keys
	// when attempting to negotiate session with a tower.
	SecretKeyRing ECDHKeyRing

	// Candidates is an abstract set of tower candidates that the negotiator
	// will traverse serially when attempting to negotiate a new session.
	Candidates TowerCandidateIterator

	// Policy defines the session policy that will be proposed to towers
	// when attempting to negotiate a new session. This policy will be used
	// across all negotiation proposals for the lifetime of the negotiator.
	Policy wtpolicy.Policy

	// Dial initiates an outbound brontide connection to the given address
	// using a specified private key. The peer is returned in the event of a
	// successful connection.
	Dial func(keychain.SingleKeyECDH, *lnwire.NetAddress) (wtserver.Peer,
		error)

	// SendMessage writes a wtwire message to remote peer.
	SendMessage func(wtserver.Peer, wtwire.Message) error

	// ReadMessage reads a message from a remote peer and returns the
	// decoded wtwire message.
	ReadMessage func(wtserver.Peer) (wtwire.Message, error)

	// ChainHash the genesis hash identifying the chain for any negotiated
	// sessions. Any state updates sent to that session should also
	// originate from this chain.
	ChainHash chainhash.Hash

	// MinBackoff defines the initial backoff applied by the session
	// negotiator after all tower candidates have been exhausted and
	// reattempting negotiation with the same set of candidates. Subsequent
	// backoff durations will grow exponentially.
	MinBackoff time.Duration

	// MaxBackoff defines the maximum backoff applied by the session
	// negotiator after all tower candidates have been exhausted and
	// reattempting negotiation with the same set of candidates. If the
	// exponential backoff produces a timeout greater than this value, the
	// backoff duration will be clamped to MaxBackoff.
	MaxBackoff time.Duration

	// Log specifies the desired log output, which should be prefixed by the
	// client type, e.g. anchor or legacy.
	Log btclog.Logger
}

NegotiatorConfig provides access to the resources required by a SessionNegotiator to faithfully carry out its duties. All nil-able field must be initialized.

type RegisteredTower

type RegisteredTower struct {
	*wtdb.Tower

	// Sessions is the set of sessions corresponding to the watchtower.
	Sessions map[wtdb.SessionID]*wtdb.ClientSession

	// ActiveSessionCandidate determines whether the watchtower is currently
	// being considered for new sessions.
	ActiveSessionCandidate bool
}

RegisteredTower encompasses information about a registered watchtower with the client.

type SessionNegotiator

type SessionNegotiator interface {
	// RequestSession signals to the session negotiator that the client
	// needs another session. Once the session is negotiated, it should be
	// returned via NewSessions.
	RequestSession()

	// NewSessions is a read-only channel where newly negotiated sessions
	// will be delivered.
	NewSessions() <-chan *ClientSession

	// Start safely initializes the session negotiator.
	Start() error

	// Stop safely shuts down the session negotiator.
	Stop() error
}

SessionNegotiator is an interface for asynchronously requesting new sessions.

type Tower

type Tower struct {
	// ID is the unique, db-assigned, identifier for this tower.
	ID wtdb.TowerID

	// IdentityKey is the public key of the remote node, used to
	// authenticate the brontide transport.
	IdentityKey *btcec.PublicKey

	// Addresses is an AddressIterator that can be used to manage the
	// addresses for this tower.
	Addresses AddressIterator
}

Tower represents the info about a watchtower server that a watchtower client needs in order to connect to it.

func NewTowerFromDBTower

func NewTowerFromDBTower(t *wtdb.Tower) (*Tower, error)

NewTowerFromDBTower converts a wtdb.Tower, which uses a static address list, into a Tower which uses an address iterator.

type TowerCandidateIterator

type TowerCandidateIterator interface {
	// AddCandidate adds a new candidate tower to the iterator. If the
	// candidate already exists, then any new addresses are added to it.
	AddCandidate(*Tower)

	// RemoveCandidate removes an existing candidate tower from the
	// iterator. An optional address can be provided to indicate a stale
	// tower address to remove it. If it isn't provided, then the tower is
	// completely removed from the iterator.
	RemoveCandidate(wtdb.TowerID, net.Addr) error

	// IsActive determines whether a given tower is exists within the
	// iterator.
	IsActive(wtdb.TowerID) bool

	// Reset clears any internal iterator state, making previously taken
	// candidates available as long as they remain in the set.
	Reset() error

	// GetTower gets the tower with the given ID from the iterator. If no
	// such tower is found then ErrTowerNotInIterator is returned.
	GetTower(id wtdb.TowerID) (*Tower, error)

	// Next returns the next candidate tower. The iterator is not required
	// to return results in any particular order.  If no more candidates are
	// available, ErrTowerCandidatesExhausted is returned.
	Next() (*Tower, error)
}

TowerCandidateIterator provides an abstraction for iterating through possible watchtower addresses when attempting to create a new session.

Jump to

Keyboard shortcuts

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