graphdb

package
v0.19.3-beta.rc2 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// DefaultRejectCacheSize is the default number of rejectCacheEntries to
	// cache for use in the rejection cache of incoming gossip traffic. This
	// produces a cache size of around 1MB.
	DefaultRejectCacheSize = 50000

	// DefaultChannelCacheSize is the default number of ChannelEdges cached
	// in order to reply to gossip queries. This produces a cache size of
	// around 40MB.
	DefaultChannelCacheSize = 20000

	// DefaultPreAllocCacheNumNodes is the default number of channels we
	// assume for mainnet for pre-allocating the graph cache. As of
	// September 2021, there currently are 14k nodes in a strictly pruned
	// graph, so we choose a number that is slightly higher.
	DefaultPreAllocCacheNumNodes = 15000
)
View Source
const (
	// MaxAllowedExtraOpaqueBytes is the largest amount of opaque bytes that
	// we'll permit to be written to disk. We limit this as otherwise, it
	// would be possible for a node to create a ton of updates and slowly
	// fill our disk, and also waste bandwidth due to relaying.
	MaxAllowedExtraOpaqueBytes = 10000
)
View Source
const Subsystem = "GRDB"

Subsystem defines the logging code for this subsystem.

Variables

View Source
var (
	// ErrEdgePolicyOptionalFieldNotFound is an error returned if a channel
	// policy field is not found in the db even though its message flags
	// indicate it should be.
	ErrEdgePolicyOptionalFieldNotFound = fmt.Errorf("optional field not " +
		"present")

	// ErrGraphNotFound is returned when at least one of the components of
	// graph doesn't exist.
	ErrGraphNotFound = fmt.Errorf("graph bucket not initialized")

	// ErrGraphNeverPruned is returned when graph was never pruned.
	ErrGraphNeverPruned = fmt.Errorf("graph never pruned")

	// ErrSourceNodeNotSet is returned if the source node of the graph
	// hasn't been added The source node is the center node within a
	// star-graph.
	ErrSourceNodeNotSet = fmt.Errorf("source node does not exist")

	// ErrGraphNodesNotFound is returned in case none of the nodes has
	// been added in graph node bucket.
	ErrGraphNodesNotFound = fmt.Errorf("no graph nodes exist")

	// ErrGraphNoEdgesFound is returned in case of none of the channel/edges
	// has been added in graph edge bucket.
	ErrGraphNoEdgesFound = fmt.Errorf("no graph edges exist")

	// ErrGraphNodeNotFound is returned when we're unable to find the target
	// node.
	ErrGraphNodeNotFound = fmt.Errorf("unable to find node")

	// ErrZombieEdge is an error returned when we attempt to look up an edge
	// but it is marked as a zombie within the zombie index.
	ErrZombieEdge = errors.New("edge marked as zombie")

	// ErrEdgeNotFound is returned when an edge for the target chanID
	// can't be found.
	ErrEdgeNotFound = fmt.Errorf("edge not found")

	// ErrEdgeAlreadyExist is returned when edge with specific
	// channel id can't be added because it already exist.
	ErrEdgeAlreadyExist = fmt.Errorf("edge already exist")

	// ErrNodeAliasNotFound is returned when alias for node can't be found.
	ErrNodeAliasNotFound = fmt.Errorf("alias for node not found")

	// ErrClosedScidsNotFound is returned when the closed scid bucket
	// hasn't been created.
	ErrClosedScidsNotFound = fmt.Errorf("closed scid bucket doesn't exist")

	// ErrZombieEdgeNotFound is an error returned when we attempt to find an
	// edge in the zombie index which is not there.
	ErrZombieEdgeNotFound = errors.New("edge not found in zombie index")

	// ErrUnknownAddressType is returned when a node's addressType is not
	// an expected value.
	ErrUnknownAddressType = fmt.Errorf("address type cannot be resolved")
)
View Source
var ErrChanGraphShuttingDown = fmt.Errorf("ChannelGraph shutting down")

ErrChanGraphShuttingDown indicates that the ChannelGraph has shutdown or is busy shutting down.

Functions

func DeserializeAddr

func DeserializeAddr(r io.Reader) (net.Addr, error)

DeserializeAddr reads the serialized raw representation of an address and deserializes it into the actual address. This allows us to avoid address resolution within the channeldb package.

func DisableLog

func DisableLog()

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

func EncodeHexColor

func EncodeHexColor(color color.RGBA) string

EncodeHexColor takes a color and returns it in hex code format.

func ErrTooManyExtraOpaqueBytes

func ErrTooManyExtraOpaqueBytes(numBytes int) error

ErrTooManyExtraOpaqueBytes creates an error which should be returned if the caller attempts to write an announcement message which bares too many extra opaque bytes. We limit this value in order to ensure that we don't waste disk space due to nodes unnecessarily padding out their announcements with garbage data.

func ReadOutpoint

func ReadOutpoint(r io.Reader, o *wire.OutPoint) error

ReadOutpoint reads an outpoint from the passed reader that was previously written using the WriteOutpoint struct.

func SerializeAddr

func SerializeAddr(w io.Writer, address net.Addr) error

SerializeAddr serializes an address into its raw bytes representation so that it can be deserialized without requiring address resolution.

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.

func WriteOutpoint

func WriteOutpoint(w io.Writer, o *wire.OutPoint) error

WriteOutpoint writes an outpoint to the passed writer using the minimal amount of bytes possible.

Types

type BlockChannelRange

type BlockChannelRange struct {
	// Height is the height of the block all of the channels below were
	// included in.
	Height uint32

	// Channels is the list of channels identified by their short ID
	// representation known to us that were included in the block height
	// above. The list may include channel update timestamp information if
	// requested.
	Channels []ChannelUpdateInfo
}

BlockChannelRange represents a range of channels for a given block height.

type ChanGraphOption

type ChanGraphOption func(*chanGraphOptions)

ChanGraphOption describes the signature of a functional option that can be used to customize a ChannelGraph instance.

func WithPreAllocCacheNumNodes

func WithPreAllocCacheNumNodes(n int) ChanGraphOption

WithPreAllocCacheNumNodes sets the number of nodes we expect to be in the graph cache, so we can pre-allocate the map accordingly.

func WithUseGraphCache

func WithUseGraphCache(use bool) ChanGraphOption

WithUseGraphCache sets whether the in-memory graph cache should be used.

type ChannelEdge

type ChannelEdge struct {
	// Info contains all the static information describing the channel.
	Info *models.ChannelEdgeInfo

	// Policy1 points to the "first" edge policy of the channel containing
	// the dynamic information required to properly route through the edge.
	Policy1 *models.ChannelEdgePolicy

	// Policy2 points to the "second" edge policy of the channel containing
	// the dynamic information required to properly route through the edge.
	Policy2 *models.ChannelEdgePolicy

	// Node1 is "node 1" in the channel. This is the node that would have
	// produced Policy1 if it exists.
	Node1 *models.LightningNode

	// Node2 is "node 2" in the channel. This is the node that would have
	// produced Policy2 if it exists.
	Node2 *models.LightningNode
}

ChannelEdge represents the complete set of information for a channel edge in the known channel graph. This struct couples the core information of the edge as well as each of the known advertised edge policies.

type ChannelEdgeUpdate

type ChannelEdgeUpdate struct {
	// ChanID is the unique short channel ID for the channel. This encodes
	// where in the blockchain the channel's funding transaction was
	// originally confirmed.
	ChanID uint64

	// ChanPoint is the outpoint which represents the multi-sig funding
	// output for the channel.
	ChanPoint wire.OutPoint

	// Capacity is the capacity of the newly created channel.
	Capacity btcutil.Amount

	// MinHTLC is the minimum HTLC amount that this channel will forward.
	MinHTLC lnwire.MilliSatoshi

	// MaxHTLC is the maximum HTLC amount that this channel will forward.
	MaxHTLC lnwire.MilliSatoshi

	// BaseFee is the base fee that will charged for all HTLC's forwarded
	// across the this channel direction.
	BaseFee lnwire.MilliSatoshi

	// FeeRate is the fee rate that will be shared for all HTLC's forwarded
	// across this channel direction.
	FeeRate lnwire.MilliSatoshi

	// TimeLockDelta is the time-lock expressed in blocks that will be
	// added to outgoing HTLC's from incoming HTLC's. This value is the
	// difference of the incoming and outgoing HTLC's time-locks routed
	// through this hop.
	TimeLockDelta uint16

	// AdvertisingNode is the node that's advertising this edge.
	AdvertisingNode *btcec.PublicKey

	// ConnectingNode is the node that the advertising node connects to.
	ConnectingNode *btcec.PublicKey

	// Disabled, if true, signals that the channel is unavailable to relay
	// payments.
	Disabled bool

	// ExtraOpaqueData is the set of data that was appended to this message
	// to fill out the full maximum transport message size. These fields can
	// be used to specify optional data such as custom TLV fields.
	ExtraOpaqueData lnwire.ExtraOpaqueData
}

ChannelEdgeUpdate is an update for a new channel within the ChannelGraph. This update is sent out once a new authenticated channel edge is discovered within the network. These updates are directional, so if a channel is fully public, then there will be two updates sent out: one for each direction within the channel. Each update will carry that particular routing edge policy for the channel direction.

An edge is a channel in the direction of AdvertisingNode -> ConnectingNode.

type ChannelGraph

type ChannelGraph struct {
	*KVStore
	// contains filtered or unexported fields
}

ChannelGraph is a layer above the graph's CRUD layer.

NOTE: currently, this is purely a pass-through layer directly to the backing KVStore. Upcoming commits will move the graph cache out of the KVStore and into this layer so that the KVStore is only responsible for CRUD operations.

func MakeTestGraph

func MakeTestGraph(t testing.TB, modifiers ...KVStoreOptionModifier) (
	*ChannelGraph, error)

MakeTestGraph creates a new instance of the KVStore for testing purposes.

func NewChannelGraph

func NewChannelGraph(cfg *Config, options ...ChanGraphOption) (*ChannelGraph,
	error)

NewChannelGraph creates a new ChannelGraph instance with the given backend.

func (*ChannelGraph) AddChannelEdge

func (c *ChannelGraph) AddChannelEdge(edge *models.ChannelEdgeInfo,
	op ...batch.SchedulerOption) error

AddChannelEdge adds a new (undirected, blank) edge to the graph database. An undirected edge from the two target nodes are created. The information stored denotes the static attributes of the channel, such as the channelID, the keys involved in creation of the channel, and the set of features that the channel supports. The chanPoint and chanID are used to uniquely identify the edge globally within the database.

func (*ChannelGraph) AddLightningNode

func (c *ChannelGraph) AddLightningNode(node *models.LightningNode,
	op ...batch.SchedulerOption) error

AddLightningNode adds a vertex/node to the graph database. If the node is not in the database from before, this will add a new, unconnected one to the graph. If it is present from before, this will update that node's information. Note that this method is expected to only be called to update an already present node from a node announcement, or to insert a node found in a channel update.

func (*ChannelGraph) DeleteChannelEdges

func (c *ChannelGraph) DeleteChannelEdges(strictZombiePruning, markZombie bool,
	chanIDs ...uint64) error

DeleteChannelEdges removes edges with the given channel IDs from the database and marks them as zombies. This ensures that we're unable to re-add it to our database once again. If an edge does not exist within the database, then ErrEdgeNotFound will be returned. If strictZombiePruning is true, then when we mark these edges as zombies, we'll set up the keys such that we require the node that failed to send the fresh update to be the one that resurrects the channel from its zombie state. The markZombie bool denotes whether to mark the channel as a zombie.

func (*ChannelGraph) DeleteLightningNode

func (c *ChannelGraph) DeleteLightningNode(nodePub route.Vertex) error

DeleteLightningNode starts a new database transaction to remove a vertex/node from the database according to the node's public key.

func (*ChannelGraph) DisconnectBlockAtHeight

func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) (
	[]*models.ChannelEdgeInfo, error)

DisconnectBlockAtHeight is used to indicate that the block specified by the passed height has been disconnected from the main chain. This will "rewind" the graph back to the height below, deleting channels that are no longer confirmed from the graph. The prune log will be set to the last prune height valid for the remaining chain. Channels that were removed from the graph resulting from the disconnected block are returned.

func (*ChannelGraph) FetchNodeFeatures

func (c *ChannelGraph) FetchNodeFeatures(node route.Vertex) (
	*lnwire.FeatureVector, error)

FetchNodeFeatures returns the features of the given node. If no features are known for the node, an empty feature vector is returned. If the graphCache is available, then it will be used to retrieve the node's features instead of the database.

NOTE: this is part of the graphdb.NodeTraverser interface.

func (*ChannelGraph) FilterKnownChanIDs

func (c *ChannelGraph) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo,
	isZombieChan func(time.Time, time.Time) bool) ([]uint64, error)

FilterKnownChanIDs takes a set of channel IDs and return the subset of chan ID's that we don't know and are not known zombies of the passed set. In other words, we perform a set difference of our set of chan ID's and the ones passed in. This method can be used by callers to determine the set of channels another peer knows of that we don't.

func (*ChannelGraph) ForEachNodeCached

func (c *ChannelGraph) ForEachNodeCached(cb func(node route.Vertex,
	chans map[uint64]*DirectedChannel) error) error

ForEachNodeCached iterates through all the stored vertices/nodes in the graph, executing the passed callback with each node encountered.

NOTE: The callback contents MUST not be modified.

func (*ChannelGraph) ForEachNodeDirectedChannel

func (c *ChannelGraph) ForEachNodeDirectedChannel(node route.Vertex,
	cb func(channel *DirectedChannel) error) error

ForEachNodeDirectedChannel iterates through all channels of a given node, executing the passed callback on the directed edge representing the channel and its incoming policy. If the callback returns an error, then the iteration is halted with the error propagated back up to the caller. If the graphCache is available, then it will be used to retrieve the node's channels instead of the database.

Unknown policies are passed into the callback as nil values.

NOTE: this is part of the graphdb.NodeTraverser interface.

func (*ChannelGraph) GraphSession

func (c *ChannelGraph) GraphSession(cb func(graph NodeTraverser) error) error

GraphSession will provide the call-back with access to a NodeTraverser instance which can be used to perform queries against the channel graph. If the graph cache is not enabled, then the call-back will be provided with access to the graph via a consistent read-only transaction.

func (*ChannelGraph) MarkEdgeLive

func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error

MarkEdgeLive clears an edge from our zombie index, deeming it as live. If the cache is enabled, the edge will be added back to the graph cache if we still have a record of this channel in the DB.

func (*ChannelGraph) MarkEdgeZombie

func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
	pubKey1, pubKey2 [33]byte) error

MarkEdgeZombie attempts to mark a channel identified by its channel ID as a zombie. This method is used on an ad-hoc basis, when channels need to be marked as zombies outside the normal pruning cycle.

func (*ChannelGraph) PruneGraph

func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint,
	blockHash *chainhash.Hash, blockHeight uint32) (
	[]*models.ChannelEdgeInfo, error)

PruneGraph prunes newly closed channels from the channel graph in response to a new block being solved on the network. Any transactions which spend the funding output of any known channels within he graph will be deleted. Additionally, the "prune tip", or the last block which has been used to prune the graph is stored so callers can ensure the graph is fully in sync with the current UTXO state. A slice of channels that have been closed by the target block are returned if the function succeeds without error.

func (*ChannelGraph) PruneGraphNodes

func (c *ChannelGraph) PruneGraphNodes() error

PruneGraphNodes is a garbage collection method which attempts to prune out any nodes from the channel graph that are currently unconnected. This ensure that we only maintain a graph of reachable nodes. In the event that a pruned node gains more channels, it will be re-added back to the graph.

func (*ChannelGraph) Start

func (c *ChannelGraph) Start() error

Start kicks off any goroutines required for the ChannelGraph to function. If the graph cache is enabled, then it will be populated with the contents of the database.

func (*ChannelGraph) Stop

func (c *ChannelGraph) Stop() error

Stop signals any active goroutines for a graceful closure.

func (*ChannelGraph) SubscribeTopology

func (c *ChannelGraph) SubscribeTopology() (*TopologyClient, error)

SubscribeTopology returns a new topology client which can be used by the caller to receive notifications whenever a change in the channel graph topology occurs. Changes that will be sent at notifications include: new nodes appearing, node updating their attributes, new channels, channels closing, and updates in the routing policies of a channel's directed edges.

func (*ChannelGraph) UpdateEdgePolicy

func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
	op ...batch.SchedulerOption) error

UpdateEdgePolicy updates the edge routing policy for a single directed edge within the database for the referenced channel. The `flags` attribute within the ChannelEdgePolicy determines which of the directed edges are being updated. If the flag is 1, then the first node's information is being updated, otherwise it's the second node's information. The node ordering is determined by the lexicographical ordering of the identity public keys of the nodes on either side of the channel.

type ChannelUpdateInfo

type ChannelUpdateInfo struct {
	// ShortChannelID is the SCID identifier of the channel.
	ShortChannelID lnwire.ShortChannelID

	// Node1UpdateTimestamp is the timestamp of the latest received update
	// from the node 1 channel peer. This will be set to zero time if no
	// update has yet been received from this node.
	Node1UpdateTimestamp time.Time

	// Node2UpdateTimestamp is the timestamp of the latest received update
	// from the node 2 channel peer. This will be set to zero time if no
	// update has yet been received from this node.
	Node2UpdateTimestamp time.Time
}

ChannelUpdateInfo couples the SCID of a channel with the timestamps of the latest received channel updates for the channel.

func NewChannelUpdateInfo

func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
	node2Timestamp time.Time) ChannelUpdateInfo

NewChannelUpdateInfo is a constructor which makes sure we initialize the timestamps with zero seconds unix timestamp which equals `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.

type ClosedChanSummary

type ClosedChanSummary struct {
	// ChanID is the short-channel ID which uniquely identifies the
	// channel.
	ChanID uint64

	// Capacity was the total capacity of the channel before it was closed.
	Capacity btcutil.Amount

	// ClosedHeight is the height in the chain that the channel was closed
	// at.
	ClosedHeight uint32

	// ChanPoint is the funding point, or the multi-sig utxo which
	// previously represented the channel.
	ChanPoint wire.OutPoint
}

ClosedChanSummary is a summary of a channel that was detected as being closed by monitoring the blockchain. Once a channel's funding point has been spent, the channel will automatically be marked as closed by the ChainNotifier.

TODO(roasbeef): add nodes involved?

type Config

type Config struct {
	// KVDB is the kvdb.Backend that will be used for initializing the
	// KVStore CRUD layer.
	KVDB kvdb.Backend

	// KVStoreOpts is a list of functional options that will be used when
	// initializing the KVStore.
	KVStoreOpts []KVStoreOptionModifier
}

Config is a struct that holds all the necessary dependencies for a ChannelGraph.

type DirectedChannel

type DirectedChannel struct {
	// ChannelID is the unique identifier of this channel.
	ChannelID uint64

	// IsNode1 indicates if this is the node with the smaller public key.
	IsNode1 bool

	// OtherNode is the public key of the node on the other end of this
	// channel.
	OtherNode route.Vertex

	// Capacity is the announced capacity of this channel in satoshis.
	Capacity btcutil.Amount

	// OutPolicySet is a boolean that indicates whether the node has an
	// outgoing policy set. For pathfinding only the existence of the policy
	// is important to know, not the actual content.
	OutPolicySet bool

	// InPolicy is the incoming policy *from* the other node to this node.
	// In path finding, we're walking backward from the destination to the
	// source, so we're always interested in the edge that arrives to us
	// from the other node.
	InPolicy *models.CachedEdgePolicy

	// Inbound fees of this node.
	InboundFee lnwire.Fee
}

DirectedChannel is a type that stores the channel information as seen from one side of the channel.

func (*DirectedChannel) DeepCopy

func (c *DirectedChannel) DeepCopy() *DirectedChannel

DeepCopy creates a deep copy of the channel, including the incoming policy.

type EdgePoint

type EdgePoint struct {
	// FundingPkScript is the p2wsh multi-sig script of the target channel.
	FundingPkScript []byte

	// OutPoint is the outpoint of the target channel.
	OutPoint wire.OutPoint
}

EdgePoint couples the outpoint of a channel with the funding script that it creates. The FilteredChainView will use this to watch for spends of this edge point on chain. We require both of these values as depending on the concrete implementation, either the pkScript, or the out point will be used.

func (*EdgePoint) String

func (e *EdgePoint) String() string

String returns a human readable version of the target EdgePoint. We return the outpoint directly as it is enough to uniquely identify the edge point.

type GraphCache

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

GraphCache is a type that holds a minimal set of information of the public channel graph that can be used for pathfinding.

func NewGraphCache

func NewGraphCache(preAllocNumNodes int) *GraphCache

NewGraphCache creates a new graphCache.

func (*GraphCache) AddChannel

func (c *GraphCache) AddChannel(info *models.ChannelEdgeInfo,
	policy1 *models.ChannelEdgePolicy, policy2 *models.ChannelEdgePolicy)

AddChannel adds a non-directed channel, meaning that the order of policy 1 and policy 2 does not matter, the directionality is extracted from the info and policy flags automatically. The policy will be set as the outgoing policy on one node and the incoming policy on the peer's side.

func (*GraphCache) AddNodeFeatures

func (c *GraphCache) AddNodeFeatures(node route.Vertex,
	features *lnwire.FeatureVector)

AddNodeFeatures adds a graph node and its features to the cache.

func (*GraphCache) ForEachChannel

func (c *GraphCache) ForEachChannel(node route.Vertex,
	cb func(channel *DirectedChannel) error) error

ForEachChannel invokes the given callback for each channel of the given node.

func (*GraphCache) ForEachNode

func (c *GraphCache) ForEachNode(cb func(node route.Vertex,
	channels map[uint64]*DirectedChannel) error) error

ForEachNode iterates over the adjacency list of the graph, executing the call back for each node and the set of channels that emanate from the given node.

NOTE: This method should be considered _read only_, the channels or nodes passed in MUST NOT be modified.

func (*GraphCache) GetFeatures

func (c *GraphCache) GetFeatures(node route.Vertex) *lnwire.FeatureVector

GetFeatures returns the features of the node with the given ID. If no features are known for the node, an empty feature vector is returned.

func (*GraphCache) RemoveChannel

func (c *GraphCache) RemoveChannel(node1, node2 route.Vertex, chanID uint64)

RemoveChannel removes a single channel between two nodes.

func (*GraphCache) RemoveNode

func (c *GraphCache) RemoveNode(node route.Vertex)

RemoveNode completely removes a node and all its channels (including the peer's side).

func (*GraphCache) Stats

func (c *GraphCache) Stats() string

Stats returns statistics about the current cache size.

func (*GraphCache) UpdateChannel

func (c *GraphCache) UpdateChannel(info *models.ChannelEdgeInfo)

UpdateChannel updates the channel edge information for a specific edge. We expect the edge to already exist and be known. If it does not yet exist, this call is a no-op.

func (*GraphCache) UpdatePolicy

func (c *GraphCache) UpdatePolicy(policy *models.ChannelEdgePolicy, fromNode,
	toNode route.Vertex, edge1 bool)

UpdatePolicy updates a single policy on both the from and to node. The order of the from and to node is not strictly important. But we assume that a channel edge was added beforehand so that the directed channel struct already exists in the cache.

type KVStore

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

KVStore is a persistent, on-disk graph representation of the Lightning Network. This struct can be used to implement path finding algorithms on top of, and also to update a node's view based on information received from the p2p network. Internally, the graph is stored using a modified adjacency list representation with some added object interaction possible with each serialized edge/node. The graph is stored is directed, meaning that are two edges stored for each channel: an inbound/outbound edge for each node pair. Nodes, edges, and edge information can all be added to the graph independently. Edge removal results in the deletion of all edge information for that edge.

func NewKVStore

func NewKVStore(db kvdb.Backend, options ...KVStoreOptionModifier) (*KVStore,
	error)

NewKVStore allocates a new KVStore backed by a DB instance. The returned instance has its own unique reject cache and channel cache.

func (*KVStore) AddChannelEdge

func (c *KVStore) AddChannelEdge(edge *models.ChannelEdgeInfo,
	op ...batch.SchedulerOption) error

AddChannelEdge adds a new (undirected, blank) edge to the graph database. An undirected edge from the two target nodes are created. The information stored denotes the static attributes of the channel, such as the channelID, the keys involved in creation of the channel, and the set of features that the channel supports. The chanPoint and chanID are used to uniquely identify the edge globally within the database.

func (*KVStore) AddEdgeProof

func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
	proof *models.ChannelAuthProof) error

AddEdgeProof sets the proof of an existing edge in the graph database.

func (*KVStore) AddLightningNode

func (c *KVStore) AddLightningNode(node *models.LightningNode,
	op ...batch.SchedulerOption) error

AddLightningNode adds a vertex/node to the graph database. If the node is not in the database from before, this will add a new, unconnected one to the graph. If it is present from before, this will update that node's information. Note that this method is expected to only be called to update an already present node from a node announcement, or to insert a node found in a channel update.

TODO(roasbeef): also need sig of announcement.

func (*KVStore) AddrsForNode

func (c *KVStore) AddrsForNode(nodePub *btcec.PublicKey) (bool, []net.Addr,
	error)

AddrsForNode returns all known addresses for the target node public key that the graph DB is aware of. The returned boolean indicates if the given node is unknown to the graph DB or not.

NOTE: this is part of the channeldb.AddrSource interface.

func (*KVStore) ChanUpdatesInHorizon

func (c *KVStore) ChanUpdatesInHorizon(startTime,
	endTime time.Time) ([]ChannelEdge, error)

ChanUpdatesInHorizon returns all the known channel edges which have at least one edge that has an update timestamp within the specified horizon.

func (*KVStore) ChannelID

func (c *KVStore) ChannelID(chanPoint *wire.OutPoint) (uint64, error)

ChannelID attempt to lookup the 8-byte compact channel ID which maps to the passed channel point (outpoint). If the passed channel doesn't exist within the database, then ErrEdgeNotFound is returned.

func (*KVStore) ChannelView

func (c *KVStore) ChannelView() ([]EdgePoint, error)

ChannelView returns the verifiable edge information for each active channel within the known channel graph. The set of UTXO's (along with their scripts) returned are the ones that need to be watched on chain to detect channel closes on the resident blockchain.

func (*KVStore) DeleteChannelEdges

func (c *KVStore) DeleteChannelEdges(strictZombiePruning, markZombie bool,
	chanIDs ...uint64) ([]*models.ChannelEdgeInfo, error)

DeleteChannelEdges removes edges with the given channel IDs from the database and marks them as zombies. This ensures that we're unable to re-add it to our database once again. If an edge does not exist within the database, then ErrEdgeNotFound will be returned. If strictZombiePruning is true, then when we mark these edges as zombies, we'll set up the keys such that we require the node that failed to send the fresh update to be the one that resurrects the channel from its zombie state. The markZombie bool denotes whether or not to mark the channel as a zombie.

func (*KVStore) DeleteLightningNode

func (c *KVStore) DeleteLightningNode(nodePub route.Vertex) error

DeleteLightningNode starts a new database transaction to remove a vertex/node from the database according to the node's public key.

func (*KVStore) DisabledChannelIDs

func (c *KVStore) DisabledChannelIDs() ([]uint64, error)

DisabledChannelIDs returns the channel ids of disabled channels. A channel is disabled when two of the associated ChanelEdgePolicies have their disabled bit on.

func (*KVStore) DisconnectBlockAtHeight

func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
	[]*models.ChannelEdgeInfo, error)

DisconnectBlockAtHeight is used to indicate that the block specified by the passed height has been disconnected from the main chain. This will "rewind" the graph back to the height below, deleting channels that are no longer confirmed from the graph. The prune log will be set to the last prune height valid for the remaining chain. Channels that were removed from the graph resulting from the disconnected block are returned.

func (*KVStore) FetchChanInfos

func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error)

FetchChanInfos returns the set of channel edges that correspond to the passed channel ID's. If an edge is the query is unknown to the database, it will skipped and the result will contain only those edges that exist at the time of the query. This can be used to respond to peer queries that are seeking to fill in gaps in their view of the channel graph.

func (*KVStore) FetchChannelEdgesByID

func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
	*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
	*models.ChannelEdgePolicy, error)

FetchChannelEdgesByID attempts to lookup the two directed edges for the channel identified by the channel ID. If the channel can't be found, then ErrEdgeNotFound is returned. A struct which houses the general information for the channel itself is returned as well as two structs that contain the routing policies for the channel in either direction.

ErrZombieEdge an be returned if the edge is currently marked as a zombie within the database. In this case, the ChannelEdgePolicy's will be nil, and the ChannelEdgeInfo will only include the public keys of each node.

func (*KVStore) FetchChannelEdgesByOutpoint

func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
	*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
	*models.ChannelEdgePolicy, error)

FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for the channel identified by the funding outpoint. If the channel can't be found, then ErrEdgeNotFound is returned. A struct which houses the general information for the channel itself is returned as well as two structs that contain the routing policies for the channel in either direction.

func (*KVStore) FetchLightningNode

func (c *KVStore) FetchLightningNode(nodePub route.Vertex) (
	*models.LightningNode, error)

FetchLightningNode attempts to look up a target node by its identity public key. If the node isn't found in the database, then ErrGraphNodeNotFound is returned.

func (*KVStore) FetchLightningNodeTx

func (c *KVStore) FetchLightningNodeTx(tx kvdb.RTx, nodePub route.Vertex) (
	*models.LightningNode, error)

FetchLightningNodeTx attempts to look up a target node by its identity public key. If the node isn't found in the database, then ErrGraphNodeNotFound is returned. An optional transaction may be provided. If none is provided, then a new one will be created.

func (*KVStore) FetchNodeFeatures

func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
	*lnwire.FeatureVector, error)

FetchNodeFeatures returns the features of the given node. If no features are known for the node, an empty feature vector is returned.

NOTE: this is part of the graphdb.NodeTraverser interface.

func (*KVStore) FilterChannelRange

func (c *KVStore) FilterChannelRange(startHeight,
	endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error)

FilterChannelRange returns the channel ID's of all known channels which were mined in a block height within the passed range. The channel IDs are grouped by their common block height. This method can be used to quickly share with a peer the set of channels we know of within a particular range to catch them up after a period of time offline. If withTimestamps is true then the timestamp info of the latest received channel update messages of the channel will be included in the response.

func (*KVStore) FilterKnownChanIDs

func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
	[]ChannelUpdateInfo, error)

FilterKnownChanIDs takes a set of channel IDs and return the subset of chan ID's that we don't know and are not known zombies of the passed set. In other words, we perform a set difference of our set of chan ID's and the ones passed in. This method can be used by callers to determine the set of channels another peer knows of that we don't. The ChannelUpdateInfos for the known zombies is also returned.

func (*KVStore) ForEachChannel

ForEachChannel iterates through all the channel edges stored within the graph and invokes the passed callback for each edge. The callback takes two edges as since this is a directed graph, both the in/out edges are visited. If the callback returns an error, then the transaction is aborted and the iteration stops early.

NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer for that particular channel edge routing policy will be passed into the callback.

func (*KVStore) ForEachNode

func (c *KVStore) ForEachNode(cb func(tx NodeRTx) error) error

ForEachNode iterates through all the stored vertices/nodes in the graph, executing the passed callback with each node encountered. If the callback returns an error, then the transaction is aborted and the iteration stops early. Any operations performed on the NodeTx passed to the call-back are executed under the same read transaction and so, methods on the NodeTx object _MUST_ only be called from within the call-back.

func (*KVStore) ForEachNodeCacheable

func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
	*lnwire.FeatureVector) error) error

ForEachNodeCacheable iterates through all the stored vertices/nodes in the graph, executing the passed callback with each node encountered. If the callback returns an error, then the transaction is aborted and the iteration stops early.

func (*KVStore) ForEachNodeCached

func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
	chans map[uint64]*DirectedChannel) error) error

ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel data to the call-back.

NOTE: The callback contents MUST not be modified.

func (*KVStore) ForEachNodeChannel

func (c *KVStore) ForEachNodeChannel(nodePub route.Vertex,
	cb func(*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
		*models.ChannelEdgePolicy) error) error

ForEachNodeChannel iterates through all channels of the given node, executing the passed callback with an edge info structure and the policies of each end of the channel. The first edge policy is the outgoing edge *to* the connecting node, while the second is the incoming edge *from* the connecting node. If the callback returns an error, then the iteration is halted with the error propagated back up to the caller.

Unknown policies are passed into the callback as nil values.

func (*KVStore) ForEachNodeDirectedChannel

func (c *KVStore) ForEachNodeDirectedChannel(nodePub route.Vertex,
	cb func(channel *DirectedChannel) error) error

ForEachNodeDirectedChannel iterates through all channels of a given node, executing the passed callback on the directed edge representing the channel and its incoming policy. If the callback returns an error, then the iteration is halted with the error propagated back up to the caller.

Unknown policies are passed into the callback as nil values.

NOTE: this is part of the graphdb.NodeTraverser interface.

func (*KVStore) ForEachSourceNodeChannel

func (c *KVStore) ForEachSourceNodeChannel(cb func(chanPoint wire.OutPoint,
	havePolicy bool, otherNode *models.LightningNode) error) error

ForEachSourceNodeChannel iterates through all channels of the source node, executing the passed callback on each. The callback is provided with the channel's outpoint, whether we have a policy for the channel and the channel peer's node information.

func (*KVStore) GraphSession

func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error

GraphSession will provide the call-back with access to a NodeTraverser instance which can be used to perform queries against the channel graph.

func (*KVStore) HasChannelEdge

func (c *KVStore) HasChannelEdge(
	chanID uint64) (time.Time, time.Time, bool, bool, error)

HasChannelEdge returns true if the database knows of a channel edge with the passed channel ID, and false otherwise. If an edge with that ID is found within the graph, then two time stamps representing the last time the edge was updated for both directed edges are returned along with the boolean. If it is not found, then the zombie index is checked and its result is returned as the second boolean.

func (*KVStore) HasLightningNode

func (c *KVStore) HasLightningNode(nodePub [33]byte) (time.Time, bool,
	error)

HasLightningNode determines if the graph has a vertex identified by the target node identity public key. If the node exists in the database, a timestamp of when the data for the node was lasted updated is returned along with a true boolean. Otherwise, an empty time.Time is returned with a false boolean.

func (*KVStore) HighestChanID

func (c *KVStore) HighestChanID() (uint64, error)

HighestChanID returns the "highest" known channel ID in the channel graph. This represents the "newest" channel from the PoV of the chain. This method can be used by peers to quickly determine if they're graphs are in sync.

func (*KVStore) IsClosedScid

func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error)

IsClosedScid checks whether a channel identified by the passed in scid is closed. This helps avoid having to perform expensive validation checks. TODO: Add an LRU cache to cut down on disc reads.

func (*KVStore) IsPublicNode

func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error)

IsPublicNode is a helper method that determines whether the node with the given public key is seen as a public node in the graph from the graph's source node's point of view.

func (*KVStore) IsZombieEdge

func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte)

IsZombieEdge returns whether the edge is considered zombie. If it is a zombie, then the two node public keys corresponding to this edge are also returned.

func (*KVStore) LookupAlias

func (c *KVStore) LookupAlias(pub *btcec.PublicKey) (string, error)

LookupAlias attempts to return the alias as advertised by the target node. TODO(roasbeef): currently assumes that aliases are unique...

func (*KVStore) MarkEdgeLive

func (c *KVStore) MarkEdgeLive(chanID uint64) error

MarkEdgeLive clears an edge from our zombie index, deeming it as live.

func (*KVStore) MarkEdgeZombie

func (c *KVStore) MarkEdgeZombie(chanID uint64,
	pubKey1, pubKey2 [33]byte) error

MarkEdgeZombie attempts to mark a channel identified by its channel ID as a zombie. This method is used on an ad-hoc basis, when channels need to be marked as zombies outside the normal pruning cycle.

func (*KVStore) NodeUpdatesInHorizon

func (c *KVStore) NodeUpdatesInHorizon(startTime,
	endTime time.Time) ([]models.LightningNode, error)

NodeUpdatesInHorizon returns all the known lightning node which have an update timestamp within the passed range. This method can be used by two nodes to quickly determine if they have the same set of up to date node announcements.

func (*KVStore) NumZombies

func (c *KVStore) NumZombies() (uint64, error)

NumZombies returns the current number of zombie channels in the graph.

func (*KVStore) PruneGraph

func (c *KVStore) PruneGraph(spentOutputs []*wire.OutPoint,
	blockHash *chainhash.Hash, blockHeight uint32) (
	[]*models.ChannelEdgeInfo, []route.Vertex, error)

PruneGraph prunes newly closed channels from the channel graph in response to a new block being solved on the network. Any transactions which spend the funding output of any known channels within he graph will be deleted. Additionally, the "prune tip", or the last block which has been used to prune the graph is stored so callers can ensure the graph is fully in sync with the current UTXO state. A slice of channels that have been closed by the target block along with any pruned nodes are returned if the function succeeds without error.

func (*KVStore) PruneGraphNodes

func (c *KVStore) PruneGraphNodes() ([]route.Vertex, error)

PruneGraphNodes is a garbage collection method which attempts to prune out any nodes from the channel graph that are currently unconnected. This ensure that we only maintain a graph of reachable nodes. In the event that a pruned node gains more channels, it will be re-added back to the graph.

func (*KVStore) PruneTip

func (c *KVStore) PruneTip() (*chainhash.Hash, uint32, error)

PruneTip returns the block height and hash of the latest block that has been used to prune channels in the graph. Knowing the "prune tip" allows callers to tell if the graph is currently in sync with the current best known UTXO state.

func (*KVStore) PutClosedScid

func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error

PutClosedScid stores a SCID for a closed channel in the database. This is so that we can ignore channel announcements that we know to be closed without having to validate them and fetch a block.

func (*KVStore) SetSourceNode

func (c *KVStore) SetSourceNode(node *models.LightningNode) error

SetSourceNode sets the source node within the graph database. The source node is to be used as the center of a star-graph within path finding algorithms.

func (*KVStore) SourceNode

func (c *KVStore) SourceNode() (*models.LightningNode, error)

SourceNode returns the source node of the graph. The source node is treated as the center node within a star-graph. This method may be used to kick off a path finding algorithm in order to explore the reachability of another node based off the source node.

func (*KVStore) UpdateEdgePolicy

func (c *KVStore) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
	op ...batch.SchedulerOption) (route.Vertex, route.Vertex, error)

UpdateEdgePolicy updates the edge routing policy for a single directed edge within the database for the referenced channel. The `flags` attribute within the ChannelEdgePolicy determines which of the directed edges are being updated. If the flag is 1, then the first node's information is being updated, otherwise it's the second node's information. The node ordering is determined by the lexicographical ordering of the identity public keys of the nodes on either side of the channel.

type KVStoreOptionModifier

type KVStoreOptionModifier func(*KVStoreOptions)

KVStoreOptionModifier is a function signature for modifying the default KVStoreOptions.

func WithBatchCommitInterval

func WithBatchCommitInterval(interval time.Duration) KVStoreOptionModifier

WithBatchCommitInterval sets the batch commit interval for the interval batch schedulers.

func WithChannelCacheSize

func WithChannelCacheSize(n int) KVStoreOptionModifier

WithChannelCacheSize sets the ChannelCacheSize to n.

func WithRejectCacheSize

func WithRejectCacheSize(n int) KVStoreOptionModifier

WithRejectCacheSize sets the RejectCacheSize to n.

type KVStoreOptions

type KVStoreOptions struct {
	// RejectCacheSize is the maximum number of rejectCacheEntries to hold
	// in the rejection cache.
	RejectCacheSize int

	// ChannelCacheSize is the maximum number of ChannelEdges to hold in the
	// channel cache.
	ChannelCacheSize int

	// BatchCommitInterval is the maximum duration the batch schedulers will
	// wait before attempting to commit a pending set of updates.
	BatchCommitInterval time.Duration

	// NoMigration specifies that underlying backend was opened in read-only
	// mode and migrations shouldn't be performed. This can be useful for
	// applications that use the channeldb package as a library.
	NoMigration bool
}

KVStoreOptions holds parameters for tuning and customizing a graph.DB.

func DefaultOptions

func DefaultOptions() *KVStoreOptions

DefaultOptions returns a KVStoreOptions populated with default values.

type NetworkNodeUpdate

type NetworkNodeUpdate struct {
	// Addresses is a slice of all the node's known addresses.
	Addresses []net.Addr

	// IdentityKey is the identity public key of the target node. This is
	// used to encrypt onion blobs as well as to authenticate any new
	// updates.
	IdentityKey *btcec.PublicKey

	// Alias is the alias or nick name of the node.
	Alias string

	// Color is the node's color in hex code format.
	Color string

	// Features holds the set of features the node supports.
	Features *lnwire.FeatureVector
}

NetworkNodeUpdate is an update for a node within the Lightning Network. A NetworkNodeUpdate is sent out either when a new node joins the network, or a node broadcasts a new update with a newer time stamp that supersedes its old update. All updates are properly authenticated.

type NodeRTx

type NodeRTx interface {
	// Node returns the raw information of the node.
	Node() *models.LightningNode

	// ForEachChannel can be used to iterate over the node's channels under
	// the same transaction used to fetch the node.
	ForEachChannel(func(*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
		*models.ChannelEdgePolicy) error) error

	// FetchNode fetches the node with the given pub key under the same
	// transaction used to fetch the current node. The returned node is also
	// a NodeRTx and any operations on that NodeRTx will also be done under
	// the same transaction.
	FetchNode(node route.Vertex) (NodeRTx, error)
}

NodeRTx represents transaction object with an underlying node associated that can be used to make further queries to the graph under the same transaction. This is useful for consistency during graph traversal and queries.

type NodeTraverser

type NodeTraverser interface {
	// ForEachNodeDirectedChannel calls the callback for every channel of
	// the given node.
	ForEachNodeDirectedChannel(nodePub route.Vertex,
		cb func(channel *DirectedChannel) error) error

	// FetchNodeFeatures returns the features of the given node.
	FetchNodeFeatures(nodePub route.Vertex) (*lnwire.FeatureVector, error)
}

NodeTraverser is an abstract read only interface that provides information about nodes and their edges. The interface is about providing fast read-only access to the graph and so if a cache is available, it should be used.

type TopologyChange

type TopologyChange struct {
	// NodeUpdates is a slice of nodes which are either new to the channel
	// graph, or have had their attributes updated in an authenticated
	// manner.
	NodeUpdates []*NetworkNodeUpdate

	// ChanelEdgeUpdates is a slice of channel edges which are either newly
	// opened and authenticated, or have had their routing policies
	// updated.
	ChannelEdgeUpdates []*ChannelEdgeUpdate

	// ClosedChannels contains a slice of close channel summaries which
	// described which block a channel was closed at, and also carry
	// supplemental information such as the capacity of the former channel.
	ClosedChannels []*ClosedChanSummary
}

TopologyChange represents a new set of modifications to the channel graph. Topology changes will be dispatched in real-time as the ChannelGraph validates and process modifications to the authenticated channel graph.

type TopologyClient

type TopologyClient struct {
	// TopologyChanges is a receive only channel that new channel graph
	// updates will be sent over.
	//
	// TODO(roasbeef): chan for each update type instead?
	TopologyChanges <-chan *TopologyChange

	// Cancel is a function closure that should be executed when the client
	// wishes to cancel their notification intent. Doing so allows the
	// ChannelRouter to free up resources.
	Cancel func()
}

TopologyClient represents an intent to receive notifications from the channel router regarding changes to the topology of the channel graph. The TopologyChanges channel will be sent upon with new updates to the channel graph in real-time as they're encountered.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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