graphdb

package
v0.19.0-beta.rc1 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2025 License: MIT Imports: 28 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")
)

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 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 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 ChannelGraph

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

ChannelGraph 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 MakeTestGraph

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

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

func NewChannelGraph

func NewChannelGraph(db kvdb.Backend, options ...OptionModifier) (*ChannelGraph,
	error)

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

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) AddEdgeProof

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

AddEdgeProof sets the proof of an existing edge in the graph 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.

TODO(roasbeef): also need sig of announcement

func (*ChannelGraph) AddrsForNode

func (c *ChannelGraph) 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 (*ChannelGraph) ChanUpdatesInHorizon

func (c *ChannelGraph) 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 (*ChannelGraph) ChannelID

func (c *ChannelGraph) 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 (*ChannelGraph) ChannelView

func (c *ChannelGraph) 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 (*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 or not 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) DisabledChannelIDs

func (c *ChannelGraph) 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 (*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) FetchChanInfos

func (c *ChannelGraph) 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 (*ChannelGraph) FetchChannelEdgesByID

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 (*ChannelGraph) FetchChannelEdgesByOutpoint

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 (*ChannelGraph) FetchLightningNode

func (c *ChannelGraph) 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 (*ChannelGraph) FetchLightningNodeTx

func (c *ChannelGraph) 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 (*ChannelGraph) FetchNodeFeatures

func (c *ChannelGraph) 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. 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) FetchOtherNode

func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx,
	channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
	*models.LightningNode, error)

FetchOtherNode attempts to fetch the full LightningNode that's opposite of the target node in the channel. This is useful when one knows the pubkey of one of the nodes, and wishes to obtain the full LightningNode for the other end of the channel.

func (*ChannelGraph) FilterChannelRange

func (c *ChannelGraph) 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 (*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) 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 (*ChannelGraph) ForEachNode

func (c *ChannelGraph) 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 (*ChannelGraph) ForEachNodeCacheable

func (c *ChannelGraph) 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 (*ChannelGraph) ForEachNodeCached

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

ForEachNodeCached is similar to forEachNode, but it utilizes the channel graph cache instead. Note that this doesn't return all the information the regular forEachNode method does.

NOTE: The callback contents MUST not be modified.

func (*ChannelGraph) ForEachNodeChannel

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 (*ChannelGraph) ForEachNodeChannelTx

func (c *ChannelGraph) ForEachNodeChannelTx(tx kvdb.RTx,
	nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
		*models.ChannelEdgePolicy,
		*models.ChannelEdgePolicy) error) error

ForEachNodeChannelTx 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.

If the caller wishes to re-use an existing boltdb transaction, then it should be passed as the first argument. Otherwise, the first argument should be nil and a fresh transaction will be created to execute the graph traversal.

func (*ChannelGraph) ForEachNodeDirectedChannel

func (c *ChannelGraph) 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. 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) HasChannelEdge

func (c *ChannelGraph) 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 (*ChannelGraph) HasLightningNode

func (c *ChannelGraph) 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 (*ChannelGraph) HighestChanID

func (c *ChannelGraph) 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 (*ChannelGraph) IsClosedScid

func (c *ChannelGraph) 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 (*ChannelGraph) IsPublicNode

func (c *ChannelGraph) 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 (*ChannelGraph) IsZombieEdge

func (c *ChannelGraph) 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 (*ChannelGraph) LookupAlias

func (c *ChannelGraph) 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 (*ChannelGraph) MarkEdgeLive

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

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

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) NodeUpdatesInHorizon

func (c *ChannelGraph) 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 (*ChannelGraph) NumZombies

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

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

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) PruneTip

func (c *ChannelGraph) 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 (*ChannelGraph) PutClosedScid

func (c *ChannelGraph) 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 (*ChannelGraph) SetSourceNode

func (c *ChannelGraph) 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 (*ChannelGraph) SourceNode

func (c *ChannelGraph) 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 (*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.

func (*ChannelGraph) Wipe

func (c *ChannelGraph) Wipe() error

Wipe completely deletes all saved state within all used buckets within the database. The deletion is done in a single transaction, therefore this operation is fully atomic.

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 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 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 OptionModifier

type OptionModifier func(*Options)

OptionModifier is a function signature for modifying the default Options.

func WithBatchCommitInterval

func WithBatchCommitInterval(interval time.Duration) OptionModifier

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

func WithChannelCacheSize

func WithChannelCacheSize(n int) OptionModifier

WithChannelCacheSize sets the ChannelCacheSize to n.

func WithPreAllocCacheNumNodes

func WithPreAllocCacheNumNodes(n int) OptionModifier

WithPreAllocCacheNumNodes sets the PreAllocCacheNumNodes to n.

func WithRejectCacheSize

func WithRejectCacheSize(n int) OptionModifier

WithRejectCacheSize sets the RejectCacheSize to n.

func WithUseGraphCache

func WithUseGraphCache(use bool) OptionModifier

WithUseGraphCache sets the UseGraphCache option to the given value.

type Options

type Options 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

	// PreAllocCacheNumNodes is the number of nodes we expect to be in the
	// graph cache, so we can pre-allocate the map accordingly.
	PreAllocCacheNumNodes int

	// UseGraphCache denotes whether the in-memory graph cache should be
	// used or a fallback version that uses the underlying database for
	// path finding.
	UseGraphCache bool

	// 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
}

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

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns an Options populated with default values.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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