migration_01_to_11

package
v0.10.2-beta-rc2-branch Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2020 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxMemoSize is maximum size of the memo field within invoices stored
	// in the database.
	MaxMemoSize = 1024

	// MaxReceiptSize is the maximum size of the payment receipt stored
	// within the database along side incoming/outgoing invoices.
	MaxReceiptSize = 1024

	// MaxPaymentRequestSize is the max size of a payment request for
	// this invoice.
	// TODO(halseth): determine the max length payment request when field
	// lengths are final.
	MaxPaymentRequestSize = 4096
)
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
)
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 VertexSize = 33

VertexSize is the size of the array to store a vertex.

Variables

View Source
var (
	// ErrNoInvoicesCreated is returned when we don't have invoices in
	// our database to return.
	ErrNoInvoicesCreated = fmt.Errorf("there are no existing invoices")

	// ErrNoPaymentsCreated is returned when bucket of payments hasn't been
	// created.
	ErrNoPaymentsCreated = fmt.Errorf("there are no existing payments")

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

	// 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")

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

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

	// ErrUnknownAddressType is returned when a node's addressType is not
	// an expected value.
	ErrUnknownAddressType = fmt.Errorf("address type cannot be resolved")

	// ErrNoClosedChannels is returned when a node is queries for all the
	// channels it has closed, but it hasn't yet closed any channels.
	ErrNoClosedChannels = fmt.Errorf("no channel have been closed yet")

	// 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")
)
View Source
var ErrNoRouteHopsProvided = fmt.Errorf("empty route hops provided")

ErrNoRouteHopsProvided is returned when a caller attempts to construct a new sphinx packet, but provides an empty set of hops for each route.

Functions

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 MigrateEdgePolicies

func MigrateEdgePolicies(tx kvdb.RwTx) error

MigrateEdgePolicies is a migration function that will update the edges bucket. It ensure that edges with unknown policies will also have an entry in the bucket. After the migration, there will be two edge entries for every channel, regardless of whether the policies are known.

func MigrateGossipMessageStoreKeys

func MigrateGossipMessageStoreKeys(tx kvdb.RwTx) error

MigrateGossipMessageStoreKeys migrates the key format for gossip messages found in the message store to a new one that takes into consideration the of the message being stored.

func MigrateInvoiceTimeSeries

func MigrateInvoiceTimeSeries(tx kvdb.RwTx) error

MigrateInvoiceTimeSeries is a database migration that assigns all existing invoices an index in the add and/or the settle index. Additionally, all existing invoices will have their bytes padded out in order to encode the add+settle index as well as the amount paid.

func MigrateInvoiceTimeSeriesOutgoingPayments

func MigrateInvoiceTimeSeriesOutgoingPayments(tx kvdb.RwTx) error

MigrateInvoiceTimeSeriesOutgoingPayments is a follow up to the migrateInvoiceTimeSeries migration. As at the time of writing, the OutgoingPayment struct embeddeds an instance of the Invoice struct. As a result, we also need to migrate the internal invoice to the new format.

func MigrateInvoices

func MigrateInvoices(tx kvdb.RwTx) error

MigrateInvoices adds invoice htlcs and a separate cltv delta field to the invoices.

func MigrateNodeAndEdgeUpdateIndex

func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error

MigrateNodeAndEdgeUpdateIndex is a migration function that will update the database from version 0 to version 1. In version 1, we add two new indexes (one for nodes and one for edges) to keep track of the last time a node or edge was updated on the network. These new indexes allow us to implement the new graph sync protocol added.

func MigrateOptionalChannelCloseSummaryFields

func MigrateOptionalChannelCloseSummaryFields(tx kvdb.RwTx) error

MigrateOptionalChannelCloseSummaryFields migrates the serialized format of ChannelCloseSummary to a format where optional fields' presence is indicated with boolean markers.

func MigrateOutgoingPayments

func MigrateOutgoingPayments(tx kvdb.RwTx) error

MigrateOutgoingPayments moves the OutgoingPayments into a new bucket format where they all reside in a top-level bucket indexed by the payment hash. In this sub-bucket we store information relevant to this payment, such as the payment status.

Since the router cannot handle resumed payments that have the status InFlight (we have no PaymentAttemptInfo available for pre-migration payments) we delete those statuses, so only Completed payments remain in the new bucket structure.

func MigratePruneEdgeUpdateIndex

func MigratePruneEdgeUpdateIndex(tx kvdb.RwTx) error

MigratePruneEdgeUpdateIndex is a database migration that attempts to resolve some lingering bugs with regards to edge policies and their update index. Stale entries within the edge update index were not being properly pruned due to a miscalculation on the offset of an edge's policy last update. This migration also fixes the case where the public keys within edge policies were being serialized with an extra byte, causing an even greater error when attempting to perform the offset calculation described earlier.

func MigrateRouteSerialization

func MigrateRouteSerialization(tx kvdb.RwTx) error

MigrateRouteSerialization migrates the way we serialize routes across the entire database. At the time of writing of this migration, this includes our payment attempts, as well as the payment results in mission control.

func PaymentStatusesMigration

func PaymentStatusesMigration(tx kvdb.RwTx) error

PaymentStatusesMigration is a database migration intended for adding payment statuses for each existing payment entity in bucket to be able control transitions of statuses and prevent cases such as double payment

func ReadElement

func ReadElement(r io.Reader, element interface{}) error

ReadElement is a one-stop utility function to deserialize any datastructure encoded using the serialization format of the database.

func ReadElements

func ReadElements(r io.Reader, elements ...interface{}) error

ReadElements deserializes a variable number of elements into the passed io.Reader, with each element being deserialized according to the ReadElement function.

func SerializeRoute

func SerializeRoute(w io.Writer, r Route) error

SerializeRoute serializes a route.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info.

func WriteElement

func WriteElement(w io.Writer, element interface{}) error

WriteElement is a one-stop shop to write the big endian representation of any element which is to be serialized for storage on disk. The passed io.Writer should be backed by an appropriately sized byte slice, or be able to dynamically expand to accommodate additional data.

func WriteElements

func WriteElements(w io.Writer, elements ...interface{}) error

WriteElements is writes each element in the elements slice to the passed io.Writer using WriteElement.

Types

type ChannelAuthProof

type ChannelAuthProof struct {
	// NodeSig1Bytes are the raw bytes of the first node signature encoded
	// in DER format.
	NodeSig1Bytes []byte

	// NodeSig2Bytes are the raw bytes of the second node signature
	// encoded in DER format.
	NodeSig2Bytes []byte

	// BitcoinSig1Bytes are the raw bytes of the first bitcoin signature
	// encoded in DER format.
	BitcoinSig1Bytes []byte

	// BitcoinSig2Bytes are the raw bytes of the second bitcoin signature
	// encoded in DER format.
	BitcoinSig2Bytes []byte
}

ChannelAuthProof is the authentication proof (the signature portion) for a channel. Using the four signatures contained in the struct, and some auxiliary knowledge (the funding script, node identities, and outpoint) nodes on the network are able to validate the authenticity and existence of a channel. Each of these signatures signs the following digest: chanID || nodeID1 || nodeID2 || bitcoinKey1|| bitcoinKey2 || 2-byte-feature-len || features.

func (*ChannelAuthProof) IsEmpty

func (c *ChannelAuthProof) IsEmpty() bool

IsEmpty check is the authentication proof is empty Proof is empty if at least one of the signatures are equal to nil.

type ChannelCloseSummary

type ChannelCloseSummary struct {
	// ChanPoint is the outpoint for this channel's funding transaction,
	// and is used as a unique identifier for the channel.
	ChanPoint wire.OutPoint

	// ShortChanID encodes the exact location in the chain in which the
	// channel was initially confirmed. This includes: the block height,
	// transaction index, and the output within the target transaction.
	ShortChanID lnwire.ShortChannelID

	// ChainHash is the hash of the genesis block that this channel resides
	// within.
	ChainHash chainhash.Hash

	// ClosingTXID is the txid of the transaction which ultimately closed
	// this channel.
	ClosingTXID chainhash.Hash

	// RemotePub is the public key of the remote peer that we formerly had
	// a channel with.
	RemotePub *btcec.PublicKey

	// Capacity was the total capacity of the channel.
	Capacity btcutil.Amount

	// CloseHeight is the height at which the funding transaction was
	// spent.
	CloseHeight uint32

	// SettledBalance is our total balance settled balance at the time of
	// channel closure. This _does not_ include the sum of any outputs that
	// have been time-locked as a result of the unilateral channel closure.
	SettledBalance btcutil.Amount

	// TimeLockedBalance is the sum of all the time-locked outputs at the
	// time of channel closure. If we triggered the force closure of this
	// channel, then this value will be non-zero if our settled output is
	// above the dust limit. If we were on the receiving side of a channel
	// force closure, then this value will be non-zero if we had any
	// outstanding outgoing HTLC's at the time of channel closure.
	TimeLockedBalance btcutil.Amount

	// CloseType details exactly _how_ the channel was closed. Five closure
	// types are possible: cooperative, local force, remote force, breach
	// and funding canceled.
	CloseType ClosureType

	// IsPending indicates whether this channel is in the 'pending close'
	// state, which means the channel closing transaction has been
	// confirmed, but not yet been fully resolved. In the case of a channel
	// that has been cooperatively closed, it will go straight into the
	// fully resolved state as soon as the closing transaction has been
	// confirmed. However, for channels that have been force closed, they'll
	// stay marked as "pending" until _all_ the pending funds have been
	// swept.
	IsPending bool

	// RemoteCurrentRevocation is the current revocation for their
	// commitment transaction. However, since this is the derived public key,
	// we don't yet have the private key so we aren't yet able to verify
	// that it's actually in the hash chain.
	RemoteCurrentRevocation *btcec.PublicKey

	// RemoteNextRevocation is the revocation key to be used for the *next*
	// commitment transaction we create for the local node. Within the
	// specification, this value is referred to as the
	// per-commitment-point.
	RemoteNextRevocation *btcec.PublicKey

	// LocalChanCfg is the channel configuration for the local node.
	LocalChanConfig ChannelConfig

	// LastChanSyncMsg is the ChannelReestablish message for this channel
	// for the state at the point where it was closed.
	LastChanSyncMsg *lnwire.ChannelReestablish
}

ChannelCloseSummary contains the final state of a channel at the point it was closed. Once a channel is closed, all the information pertaining to that channel within the openChannelBucket is deleted, and a compact summary is put in place instead.

type ChannelCommitment

type ChannelCommitment struct {
	// CommitHeight is the update number that this ChannelDelta represents
	// the total number of commitment updates to this point. This can be
	// viewed as sort of a "commitment height" as this number is
	// monotonically increasing.
	CommitHeight uint64

	// LocalLogIndex is the cumulative log index index of the local node at
	// this point in the commitment chain. This value will be incremented
	// for each _update_ added to the local update log.
	LocalLogIndex uint64

	// LocalHtlcIndex is the current local running HTLC index. This value
	// will be incremented for each outgoing HTLC the local node offers.
	LocalHtlcIndex uint64

	// RemoteLogIndex is the cumulative log index index of the remote node
	// at this point in the commitment chain. This value will be
	// incremented for each _update_ added to the remote update log.
	RemoteLogIndex uint64

	// RemoteHtlcIndex is the current remote running HTLC index. This value
	// will be incremented for each outgoing HTLC the remote node offers.
	RemoteHtlcIndex uint64

	// LocalBalance is the current available settled balance within the
	// channel directly spendable by us.
	LocalBalance lnwire.MilliSatoshi

	// RemoteBalance is the current available settled balance within the
	// channel directly spendable by the remote node.
	RemoteBalance lnwire.MilliSatoshi

	// CommitFee is the amount calculated to be paid in fees for the
	// current set of commitment transactions. The fee amount is persisted
	// with the channel in order to allow the fee amount to be removed and
	// recalculated with each channel state update, including updates that
	// happen after a system restart.
	CommitFee btcutil.Amount

	// FeePerKw is the min satoshis/kilo-weight that should be paid within
	// the commitment transaction for the entire duration of the channel's
	// lifetime. This field may be updated during normal operation of the
	// channel as on-chain conditions change.
	//
	// TODO(halseth): make this SatPerKWeight. Cannot be done atm because
	// this will cause the import cycle lnwallet<->channeldb. Fee
	// estimation stuff should be in its own package.
	FeePerKw btcutil.Amount

	// CommitTx is the latest version of the commitment state, broadcast
	// able by us.
	CommitTx *wire.MsgTx

	// CommitSig is one half of the signature required to fully complete
	// the script for the commitment transaction above. This is the
	// signature signed by the remote party for our version of the
	// commitment transactions.
	CommitSig []byte

	// Htlcs is the set of HTLC's that are pending at this particular
	// commitment height.
	Htlcs []HTLC
}

ChannelCommitment is a snapshot of the commitment state at a particular point in the commitment chain. With each state transition, a snapshot of the current state along with all non-settled HTLCs are recorded. These snapshots detail the state of the _remote_ party's commitment at a particular state number. For ourselves (the local node) we ONLY store our most recent (unrevoked) state for safety purposes.

type ChannelConfig

type ChannelConfig struct {
	// ChannelConstraints is the set of constraints that must be upheld for
	// the duration of the channel for the owner of this channel
	// configuration. Constraints govern a number of flow control related
	// parameters, also including the smallest HTLC that will be accepted
	// by a participant.
	ChannelConstraints

	// MultiSigKey is the key to be used within the 2-of-2 output script
	// for the owner of this channel config.
	MultiSigKey keychain.KeyDescriptor

	// RevocationBasePoint is the base public key to be used when deriving
	// revocation keys for the remote node's commitment transaction. This
	// will be combined along with a per commitment secret to derive a
	// unique revocation key for each state.
	RevocationBasePoint keychain.KeyDescriptor

	// PaymentBasePoint is the base public key to be used when deriving
	// the key used within the non-delayed pay-to-self output on the
	// commitment transaction for a node. This will be combined with a
	// tweak derived from the per-commitment point to ensure unique keys
	// for each commitment transaction.
	PaymentBasePoint keychain.KeyDescriptor

	// DelayBasePoint is the base public key to be used when deriving the
	// key used within the delayed pay-to-self output on the commitment
	// transaction for a node. This will be combined with a tweak derived
	// from the per-commitment point to ensure unique keys for each
	// commitment transaction.
	DelayBasePoint keychain.KeyDescriptor

	// HtlcBasePoint is the base public key to be used when deriving the
	// local HTLC key. The derived key (combined with the tweak derived
	// from the per-commitment point) is used within the "to self" clause
	// within any HTLC output scripts.
	HtlcBasePoint keychain.KeyDescriptor
}

ChannelConfig is a struct that houses the various configuration opens for channels. Each side maintains an instance of this configuration file as it governs: how the funding and commitment transaction to be created, the nature of HTLC's allotted, the keys to be used for delivery, and relative time lock parameters.

type ChannelConstraints

type ChannelConstraints struct {
	// DustLimit is the threshold (in satoshis) below which any outputs
	// should be trimmed. When an output is trimmed, it isn't materialized
	// as an actual output, but is instead burned to miner's fees.
	DustLimit btcutil.Amount

	// ChanReserve is an absolute reservation on the channel for the
	// owner of this set of constraints. This means that the current
	// settled balance for this node CANNOT dip below the reservation
	// amount. This acts as a defense against costless attacks when
	// either side no longer has any skin in the game.
	ChanReserve btcutil.Amount

	// MaxPendingAmount is the maximum pending HTLC value that the
	// owner of these constraints can offer the remote node at a
	// particular time.
	MaxPendingAmount lnwire.MilliSatoshi

	// MinHTLC is the minimum HTLC value that the owner of these
	// constraints can offer the remote node. If any HTLCs below this
	// amount are offered, then the HTLC will be rejected. This, in
	// tandem with the dust limit allows a node to regulate the
	// smallest HTLC that it deems economically relevant.
	MinHTLC lnwire.MilliSatoshi

	// MaxAcceptedHtlcs is the maximum number of HTLCs that the owner of
	// this set of constraints can offer the remote node. This allows each
	// node to limit their over all exposure to HTLCs that may need to be
	// acted upon in the case of a unilateral channel closure or a contract
	// breach.
	MaxAcceptedHtlcs uint16

	// CsvDelay is the relative time lock delay expressed in blocks. Any
	// settled outputs that pay to the owner of this channel configuration
	// MUST ensure that the delay branch uses this value as the relative
	// time lock. Similarly, any HTLC's offered by this node should use
	// this value as well.
	CsvDelay uint16
}

ChannelConstraints represents a set of constraints meant to allow a node to limit their exposure, enact flow control and ensure that all HTLCs are economically relevant. This struct will be mirrored for both sides of the channel, as each side will enforce various constraints that MUST be adhered to for the life time of the channel. The parameters for each of these constraints are static for the duration of the channel, meaning the channel must be torn down for them to change.

type ChannelEdgeInfo

type ChannelEdgeInfo struct {
	// ChannelID is the unique channel ID for the channel. The first 3
	// bytes are the block height, the next 3 the index within the block,
	// and the last 2 bytes are the output index for the channel.
	ChannelID uint64

	// ChainHash is the hash that uniquely identifies the chain that this
	// channel was opened within.
	//
	// TODO(roasbeef): need to modify db keying for multi-chain
	//  * must add chain hash to prefix as well
	ChainHash chainhash.Hash

	// NodeKey1Bytes is the raw public key of the first node.
	NodeKey1Bytes [33]byte

	// NodeKey2Bytes is the raw public key of the first node.
	NodeKey2Bytes [33]byte

	// BitcoinKey1Bytes is the raw public key of the first node.
	BitcoinKey1Bytes [33]byte

	// BitcoinKey2Bytes is the raw public key of the first node.
	BitcoinKey2Bytes [33]byte

	// Features is an opaque byte slice that encodes the set of channel
	// specific features that this channel edge supports.
	Features []byte

	// AuthProof is the authentication proof for this channel. This proof
	// contains a set of signatures binding four identities, which attests
	// to the legitimacy of the advertised channel.
	AuthProof *ChannelAuthProof

	// ChannelPoint is the funding outpoint of the channel. This can be
	// used to uniquely identify the channel within the channel graph.
	ChannelPoint wire.OutPoint

	// Capacity is the total capacity of the channel, this is determined by
	// the value output in the outpoint that created this channel.
	Capacity btcutil.Amount

	// ExtraOpaqueData is the set of data that was appended to this
	// message, some of which we may not actually know how to iterate or
	// parse. By holding onto this data, we ensure that we're able to
	// properly validate the set of signatures that cover these new fields,
	// and ensure we're able to make upgrades to the network in a forwards
	// compatible manner.
	ExtraOpaqueData []byte
}

ChannelEdgeInfo represents a fully authenticated channel along with all its unique attributes. Once an authenticated channel announcement has been processed on the network, then an instance of ChannelEdgeInfo encapsulating the channels attributes is stored. The other portions relevant to routing policy of a channel are stored within a ChannelEdgePolicy for each direction of the channel.

type ChannelEdgePolicy

type ChannelEdgePolicy struct {
	// SigBytes is the raw bytes of the signature of the channel edge
	// policy. We'll only parse these if the caller needs to access the
	// signature for validation purposes. Do not set SigBytes directly, but
	// use SetSigBytes instead to make sure that the cache is invalidated.
	SigBytes []byte

	// ChannelID is the unique channel ID for the channel. The first 3
	// bytes are the block height, the next 3 the index within the block,
	// and the last 2 bytes are the output index for the channel.
	ChannelID uint64

	// LastUpdate is the last time an authenticated edge for this channel
	// was received.
	LastUpdate time.Time

	// MessageFlags is a bitfield which indicates the presence of optional
	// fields (like max_htlc) in the policy.
	MessageFlags lnwire.ChanUpdateMsgFlags

	// ChannelFlags is a bitfield which signals the capabilities of the
	// channel as well as the directed edge this update applies to.
	ChannelFlags lnwire.ChanUpdateChanFlags

	// TimeLockDelta is the number of blocks this node will subtract from
	// the expiry of an incoming HTLC. This value expresses the time buffer
	// the node would like to HTLC exchanges.
	TimeLockDelta uint16

	// MinHTLC is the smallest value HTLC this node will accept, expressed
	// in millisatoshi.
	MinHTLC lnwire.MilliSatoshi

	// MaxHTLC is the largest value HTLC this node will accept, expressed
	// in millisatoshi.
	MaxHTLC lnwire.MilliSatoshi

	// FeeBaseMSat is the base HTLC fee that will be charged for forwarding
	// ANY HTLC, expressed in mSAT's.
	FeeBaseMSat lnwire.MilliSatoshi

	// FeeProportionalMillionths is the rate that the node will charge for
	// HTLCs for each millionth of a satoshi forwarded.
	FeeProportionalMillionths lnwire.MilliSatoshi

	// Node is the LightningNode that this directed edge leads to. Using
	// this pointer the channel graph can further be traversed.
	Node *LightningNode

	// ExtraOpaqueData is the set of data that was appended to this
	// message, some of which we may not actually know how to iterate or
	// parse. By holding onto this data, we ensure that we're able to
	// properly validate the set of signatures that cover these new fields,
	// and ensure we're able to make upgrades to the network in a forwards
	// compatible manner.
	ExtraOpaqueData []byte
}

ChannelEdgePolicy represents a *directed* edge within the channel graph. For each channel in the database, there are two distinct edges: one for each possible direction of travel along the channel. The edges themselves hold information concerning fees, and minimum time-lock information which is utilized during path finding.

func (*ChannelEdgePolicy) IsDisabled

func (c *ChannelEdgePolicy) IsDisabled() bool

IsDisabled determines whether the edge has the disabled bit set.

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

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

type ChannelStatus

type ChannelStatus uint8

ChannelStatus is a bit vector used to indicate whether an OpenChannel is in the default usable state, or a state where it shouldn't be used.

var (
	// ChanStatusDefault is the normal state of an open channel.
	ChanStatusDefault ChannelStatus

	// ChanStatusBorked indicates that the channel has entered an
	// irreconcilable state, triggered by a state desynchronization or
	// channel breach.  Channels in this state should never be added to the
	// htlc switch.
	ChanStatusBorked ChannelStatus = 1

	// ChanStatusCommitBroadcasted indicates that a commitment for this
	// channel has been broadcasted.
	ChanStatusCommitBroadcasted ChannelStatus = 1 << 1

	// ChanStatusLocalDataLoss indicates that we have lost channel state
	// for this channel, and broadcasting our latest commitment might be
	// considered a breach.
	//
	// TODO(halseh): actually enforce that we are not force closing such a
	// channel.
	ChanStatusLocalDataLoss ChannelStatus = 1 << 2

	// ChanStatusRestored is a status flag that signals that the channel
	// has been restored, and doesn't have all the fields a typical channel
	// will have.
	ChanStatusRestored ChannelStatus = 1 << 3
)

func (ChannelStatus) String

func (c ChannelStatus) String() string

String returns a human-readable representation of the ChannelStatus.

type ChannelType

type ChannelType uint8

ChannelType is an enum-like type that describes one of several possible channel types. Each open channel is associated with a particular type as the channel type may determine how higher level operations are conducted such as fee negotiation, channel closing, the format of HTLCs, etc. TODO(roasbeef): split up per-chain?

const (

	// SingleFunder represents a channel wherein one party solely funds the
	// entire capacity of the channel.
	SingleFunder ChannelType = 0
)

type CircuitKey

type CircuitKey struct {
	// ChanID is the short chanid indicating the HTLC's origin.
	//
	// NOTE: It is fine for this value to be blank, as this indicates a
	// locally-sourced payment.
	ChanID lnwire.ShortChannelID

	// HtlcID is the unique htlc index predominately assigned by links,
	// though can also be assigned by switch in the case of locally-sourced
	// payments.
	HtlcID uint64
}

CircuitKey is used by a channel to uniquely identify the HTLCs it receives from the switch, and is used to purge our in-memory state of HTLCs that have already been processed by a link. Two list of CircuitKeys are included in each CommitDiff to allow a link to determine which in-memory htlcs directed the opening and closing of circuits in the switch's circuit map.

func (CircuitKey) String

func (k CircuitKey) String() string

String returns a string representation of the CircuitKey.

type ClosureType

type ClosureType uint8

ClosureType is an enum like structure that details exactly _how_ a channel was closed. Three closure types are currently possible: none, cooperative, local force close, remote force close, and (remote) breach.

const (
	// RemoteForceClose indicates that the remote peer has unilaterally
	// broadcast their current commitment state on-chain.
	RemoteForceClose ClosureType = 4
)

type ContractState

type ContractState uint8

ContractState describes the state the invoice is in.

const (
	// ContractOpen means the invoice has only been created.
	ContractOpen ContractState = 0

	// ContractSettled means the htlc is settled and the invoice has been
	// paid.
	ContractSettled ContractState = 1

	// ContractCanceled means the invoice has been canceled.
	ContractCanceled ContractState = 2

	// ContractAccepted means the HTLC has been accepted but not settled
	// yet.
	ContractAccepted ContractState = 3
)

func (ContractState) String

func (c ContractState) String() string

String returns a human readable identifier for the ContractState type.

type ContractTerm

type ContractTerm struct {
	// PaymentPreimage is the preimage which is to be revealed in the
	// occasion that an HTLC paying to the hash of this preimage is
	// extended.
	PaymentPreimage lntypes.Preimage

	// Value is the expected amount of milli-satoshis to be paid to an HTLC
	// which can be satisfied by the above preimage.
	Value lnwire.MilliSatoshi

	// State describes the state the invoice is in.
	State ContractState
}

ContractTerm is a companion struct to the Invoice struct. This struct houses the necessary conditions required before the invoice can be considered fully settled by the payee.

type DB

type DB struct {
	kvdb.Backend
	// contains filtered or unexported fields
}

DB is the primary datastore for the lnd daemon. The database stores information related to nodes, routing data, open/closed channels, fee schedules, and reputation data.

func Open

func Open(dbPath string, modifiers ...OptionModifier) (*DB, error)

Open opens an existing channeldb. Any necessary schemas migrations due to updates will take place as necessary.

func (*DB) ChannelGraph

func (d *DB) ChannelGraph() *ChannelGraph

ChannelGraph returns a new instance of the directed channel graph.

func (*DB) FetchAllInvoices

func (d *DB) FetchAllInvoices(pendingOnly bool) ([]Invoice, error)

FetchAllInvoices returns all invoices currently stored within the database. If the pendingOnly param is true, then only unsettled invoices will be returned, skipping all invoices that are fully settled.

func (*DB) FetchClosedChannels

func (d *DB) FetchClosedChannels(pendingOnly bool) ([]*ChannelCloseSummary, error)

FetchClosedChannels attempts to fetch all closed channels from the database. The pendingOnly bool toggles if channels that aren't yet fully closed should be returned in the response or not. When a channel was cooperatively closed, it becomes fully closed after a single confirmation. When a channel was forcibly closed, it will become fully closed after _all_ the pending funds (if any) have been swept.

func (*DB) FetchPayments

func (db *DB) FetchPayments() ([]*Payment, error)

FetchPayments returns all sent payments found in the DB.

type FailureReason

type FailureReason byte

FailureReason encodes the reason a payment ultimately failed.

const (
	// FailureReasonTimeout indicates that the payment did timeout before a
	// successful payment attempt was made.
	FailureReasonTimeout FailureReason = 0

	// FailureReasonNoRoute indicates no successful route to the
	// destination was found during path finding.
	FailureReasonNoRoute FailureReason = 1

	// FailureReasonError indicates that an unexpected error happened during
	// payment.
	FailureReasonError FailureReason = 2

	// FailureReasonIncorrectPaymentDetails indicates that either the hash
	// is unknown or the final cltv delta or amount is incorrect.
	FailureReasonIncorrectPaymentDetails FailureReason = 3
)

func (FailureReason) String

func (r FailureReason) String() string

String returns a human readable FailureReason

type HTLC

type HTLC struct {
	// Signature is the signature for the second level covenant transaction
	// for this HTLC. The second level transaction is a timeout tx in the
	// case that this is an outgoing HTLC, and a success tx in the case
	// that this is an incoming HTLC.
	//
	// TODO(roasbeef): make [64]byte instead?
	Signature []byte

	// RHash is the payment hash of the HTLC.
	RHash [32]byte

	// Amt is the amount of milli-satoshis this HTLC escrows.
	Amt lnwire.MilliSatoshi

	// RefundTimeout is the absolute timeout on the HTLC that the sender
	// must wait before reclaiming the funds in limbo.
	RefundTimeout uint32

	// OutputIndex is the output index for this particular HTLC output
	// within the commitment transaction.
	OutputIndex int32

	// Incoming denotes whether we're the receiver or the sender of this
	// HTLC.
	Incoming bool

	// OnionBlob is an opaque blob which is used to complete multi-hop
	// routing.
	OnionBlob []byte

	// HtlcIndex is the HTLC counter index of this active, outstanding
	// HTLC. This differs from the LogIndex, as the HtlcIndex is only
	// incremented for each offered HTLC, while they LogIndex is
	// incremented for each update (includes settle+fail).
	HtlcIndex uint64

	// LogIndex is the cumulative log index of this HTLC. This differs
	// from the HtlcIndex as this will be incremented for each new log
	// update added.
	LogIndex uint64
}

HTLC is the on-disk representation of a hash time-locked contract. HTLCs are contained within ChannelDeltas which encode the current state of the commitment between state updates.

TODO(roasbeef): save space by using smaller ints at tail end?

type Hop

type Hop struct {
	// PubKeyBytes is the raw bytes of the public key of the target node.
	PubKeyBytes Vertex

	// ChannelID is the unique channel ID for the channel. The first 3
	// bytes are the block height, the next 3 the index within the block,
	// and the last 2 bytes are the output index for the channel.
	ChannelID uint64

	// OutgoingTimeLock is the timelock value that should be used when
	// crafting the _outgoing_ HTLC from this hop.
	OutgoingTimeLock uint32

	// AmtToForward is the amount that this hop will forward to the next
	// hop. This value is less than the value that the incoming HTLC
	// carries as a fee will be subtracted by the hop.
	AmtToForward lnwire.MilliSatoshi

	// TLVRecords if non-nil are a set of additional TLV records that
	// should be included in the forwarding instructions for this node.
	TLVRecords []tlv.Record

	// LegacyPayload if true, then this signals that this node doesn't
	// understand the new TLV payload, so we must instead use the legacy
	// payload.
	LegacyPayload bool
}

Hop represents an intermediate or final node of the route. This naming is in line with the definition given in BOLT #4: Onion Routing Protocol. The struct houses the channel along which this hop can be reached and the values necessary to create the HTLC that needs to be sent to the next hop. It is also used to encode the per-hop payload included within the Sphinx packet.

func (*Hop) PackHopPayload

func (h *Hop) PackHopPayload(w io.Writer, nextChanID uint64) error

PackHopPayload writes to the passed io.Writer, the series of byes that can be placed directly into the per-hop payload (EOB) for this hop. This will include the required routing fields, as well as serializing any of the passed optional TLVRecords. nextChanID is the unique channel ID that references the _outgoing_ channel ID that follows this hop. This field follows the same semantics as the NextAddress field in the onion: it should be set to zero to indicate the terminal hop.

type HtlcState

type HtlcState uint8

HtlcState defines the states an htlc paying to an invoice can be in.

type Invoice

type Invoice struct {
	// Memo is an optional memo to be stored along side an invoice.  The
	// memo may contain further details pertaining to the invoice itself,
	// or any other message which fits within the size constraints.
	Memo []byte

	// Receipt is an optional field dedicated for storing a
	// cryptographically binding receipt of payment.
	//
	// TODO(roasbeef): document scheme.
	Receipt []byte

	// PaymentRequest is an optional field where a payment request created
	// for this invoice can be stored.
	PaymentRequest []byte

	// FinalCltvDelta is the minimum required number of blocks before htlc
	// expiry when the invoice is accepted.
	FinalCltvDelta int32

	// Expiry defines how long after creation this invoice should expire.
	Expiry time.Duration

	// CreationDate is the exact time the invoice was created.
	CreationDate time.Time

	// SettleDate is the exact time the invoice was settled.
	SettleDate time.Time

	// Terms are the contractual payment terms of the invoice. Once all the
	// terms have been satisfied by the payer, then the invoice can be
	// considered fully fulfilled.
	//
	// TODO(roasbeef): later allow for multiple terms to fulfill the final
	// invoice: payment fragmentation, etc.
	Terms ContractTerm

	// AddIndex is an auto-incrementing integer that acts as a
	// monotonically increasing sequence number for all invoices created.
	// Clients can then use this field as a "checkpoint" of sorts when
	// implementing a streaming RPC to notify consumers of instances where
	// an invoice has been added before they re-connected.
	//
	// NOTE: This index starts at 1.
	AddIndex uint64

	// SettleIndex is an auto-incrementing integer that acts as a
	// monotonically increasing sequence number for all settled invoices.
	// Clients can then use this field as a "checkpoint" of sorts when
	// implementing a streaming RPC to notify consumers of instances where
	// an invoice has been settled before they re-connected.
	//
	// NOTE: This index starts at 1.
	SettleIndex uint64

	// AmtPaid is the final amount that we ultimately accepted for pay for
	// this invoice. We specify this value independently as it's possible
	// that the invoice originally didn't specify an amount, or the sender
	// overpaid.
	AmtPaid lnwire.MilliSatoshi

	// Htlcs records all htlcs that paid to this invoice. Some of these
	// htlcs may have been marked as canceled.
	Htlcs map[CircuitKey]*InvoiceHTLC
}

Invoice is a payment invoice generated by a payee in order to request payment for some good or service. The inclusion of invoices within Lightning creates a payment work flow for merchants very similar to that of the existing financial system within PayPal, etc. Invoices are added to the database when a payment is requested, then can be settled manually once the payment is received at the upper layer. For record keeping purposes, invoices are never deleted from the database, instead a bit is toggled denoting the invoice has been fully settled. Within the database, all invoices must have a unique payment hash which is generated by taking the sha256 of the payment preimage.

type InvoiceHTLC

type InvoiceHTLC struct {
	// Amt is the amount that is carried by this htlc.
	Amt lnwire.MilliSatoshi

	// AcceptHeight is the block height at which the invoice registry
	// decided to accept this htlc as a payment to the invoice. At this
	// height, the invoice cltv delay must have been met.
	AcceptHeight uint32

	// AcceptTime is the wall clock time at which the invoice registry
	// decided to accept the htlc.
	AcceptTime time.Time

	// ResolveTime is the wall clock time at which the invoice registry
	// decided to settle the htlc.
	ResolveTime time.Time

	// Expiry is the expiry height of this htlc.
	Expiry uint32

	// State indicates the state the invoice htlc is currently in. A
	// canceled htlc isn't just removed from the invoice htlcs map, because
	// we need AcceptHeight to properly cancel the htlc back.
	State HtlcState
}

InvoiceHTLC contains details about an htlc paying to this invoice.

type LightningNode

type LightningNode struct {
	// PubKeyBytes is the raw bytes of the public key of the target node.
	PubKeyBytes [33]byte

	// HaveNodeAnnouncement indicates whether we received a node
	// announcement for this particular node. If true, the remaining fields
	// will be set, if false only the PubKey is known for this node.
	HaveNodeAnnouncement bool

	// LastUpdate is the last time the vertex information for this node has
	// been updated.
	LastUpdate time.Time

	// Address is the TCP address this node is reachable over.
	Addresses []net.Addr

	// Color is the selected color for the node.
	Color color.RGBA

	// Alias is a nick-name for the node. The alias can be used to confirm
	// a node's identity or to serve as a short ID for an address book.
	Alias string

	// AuthSigBytes is the raw signature under the advertised public key
	// which serves to authenticate the attributes announced by this node.
	AuthSigBytes []byte

	// Features is the list of protocol features supported by this node.
	Features *lnwire.FeatureVector

	// ExtraOpaqueData is the set of data that was appended to this
	// message, some of which we may not actually know how to iterate or
	// parse. By holding onto this data, we ensure that we're able to
	// properly validate the set of signatures that cover these new fields,
	// and ensure we're able to make upgrades to the network in a forwards
	// compatible manner.
	ExtraOpaqueData []byte
	// contains filtered or unexported fields
}

LightningNode represents an individual vertex/node within the channel graph. A node is connected to other nodes by one or more channel edges emanating from it. As the graph is directed, a node will also have an incoming edge attached to it for each outgoing edge.

func (*LightningNode) PubKey

func (l *LightningNode) PubKey() (*btcec.PublicKey, error)

PubKey is the node's long-term identity public key. This key will be used to authenticated any advertisements/updates sent by the node.

NOTE: By having this method to access an attribute, we ensure we only need to fully deserialize the pubkey if absolutely necessary.

type Meta

type Meta struct {
	// DbVersionNumber is the current schema version of the database.
	DbVersionNumber uint32
}

Meta structure holds the database meta information.

type OpenChannel

type OpenChannel struct {
	// ChanType denotes which type of channel this is.
	ChanType ChannelType

	// ChainHash is a hash which represents the blockchain that this
	// channel will be opened within. This value is typically the genesis
	// hash. In the case that the original chain went through a contentious
	// hard-fork, then this value will be tweaked using the unique fork
	// point on each branch.
	ChainHash chainhash.Hash

	// FundingOutpoint is the outpoint of the final funding transaction.
	// This value uniquely and globally identifies the channel within the
	// target blockchain as specified by the chain hash parameter.
	FundingOutpoint wire.OutPoint

	// ShortChannelID encodes the exact location in the chain in which the
	// channel was initially confirmed. This includes: the block height,
	// transaction index, and the output within the target transaction.
	ShortChannelID lnwire.ShortChannelID

	// IsPending indicates whether a channel's funding transaction has been
	// confirmed.
	IsPending bool

	// IsInitiator is a bool which indicates if we were the original
	// initiator for the channel. This value may affect how higher levels
	// negotiate fees, or close the channel.
	IsInitiator bool

	// FundingBroadcastHeight is the height in which the funding
	// transaction was broadcast. This value can be used by higher level
	// sub-systems to determine if a channel is stale and/or should have
	// been confirmed before a certain height.
	FundingBroadcastHeight uint32

	// NumConfsRequired is the number of confirmations a channel's funding
	// transaction must have received in order to be considered available
	// for normal transactional use.
	NumConfsRequired uint16

	// ChannelFlags holds the flags that were sent as part of the
	// open_channel message.
	ChannelFlags lnwire.FundingFlag

	// IdentityPub is the identity public key of the remote node this
	// channel has been established with.
	IdentityPub *btcec.PublicKey

	// Capacity is the total capacity of this channel.
	Capacity btcutil.Amount

	// TotalMSatSent is the total number of milli-satoshis we've sent
	// within this channel.
	TotalMSatSent lnwire.MilliSatoshi

	// TotalMSatReceived is the total number of milli-satoshis we've
	// received within this channel.
	TotalMSatReceived lnwire.MilliSatoshi

	// LocalChanCfg is the channel configuration for the local node.
	LocalChanCfg ChannelConfig

	// RemoteChanCfg is the channel configuration for the remote node.
	RemoteChanCfg ChannelConfig

	// LocalCommitment is the current local commitment state for the local
	// party. This is stored distinct from the state of the remote party
	// as there are certain asymmetric parameters which affect the
	// structure of each commitment.
	LocalCommitment ChannelCommitment

	// RemoteCommitment is the current remote commitment state for the
	// remote party. This is stored distinct from the state of the local
	// party as there are certain asymmetric parameters which affect the
	// structure of each commitment.
	RemoteCommitment ChannelCommitment

	// RemoteCurrentRevocation is the current revocation for their
	// commitment transaction. However, since this the derived public key,
	// we don't yet have the private key so we aren't yet able to verify
	// that it's actually in the hash chain.
	RemoteCurrentRevocation *btcec.PublicKey

	// RemoteNextRevocation is the revocation key to be used for the *next*
	// commitment transaction we create for the local node. Within the
	// specification, this value is referred to as the
	// per-commitment-point.
	RemoteNextRevocation *btcec.PublicKey

	// RevocationProducer is used to generate the revocation in such a way
	// that remote side might store it efficiently and have the ability to
	// restore the revocation by index if needed. Current implementation of
	// secret producer is shachain producer.
	RevocationProducer shachain.Producer

	// RevocationStore is used to efficiently store the revocations for
	// previous channels states sent to us by remote side. Current
	// implementation of secret store is shachain store.
	RevocationStore shachain.Store

	// FundingTxn is the transaction containing this channel's funding
	// outpoint. Upon restarts, this txn will be rebroadcast if the channel
	// is found to be pending.
	//
	// NOTE: This value will only be populated for single-funder channels
	// for which we are the initiator.
	FundingTxn *wire.MsgTx

	// TODO(roasbeef): eww
	Db *DB

	sync.RWMutex
}

OpenChannel encapsulates the persistent and dynamic state of an open channel with a remote node. An open channel supports several options for on-disk serialization depending on the exact context. Full (upon channel creation) state commitments, and partial (due to a commitment update) writes are supported. Each partial write due to a state update appends the new update to an on-disk log, which can then subsequently be queried in order to "time-travel" to a prior state.

func (*OpenChannel) ShortChanID

func (c *OpenChannel) ShortChanID() lnwire.ShortChannelID

ShortChanID returns the current ShortChannelID of this channel.

type OptionModifier

type OptionModifier func(*Options)

OptionModifier is a function signature for modifying the default Options.

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

	// NoFreelistSync, if true, prevents the database from syncing its
	// freelist to disk, resulting in improved performance at the expense of
	// increased startup time.
	NoFreelistSync bool
}

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

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns an Options populated with default values.

type Payment

type Payment struct {

	// Status is the current PaymentStatus of this payment.
	Status PaymentStatus

	// Info holds all static information about this payment, and is
	// populated when the payment is initiated.
	Info *PaymentCreationInfo

	// Attempt is the information about the last payment attempt made.
	//
	// NOTE: Can be nil if no attempt is yet made.
	Attempt *PaymentAttemptInfo

	// PaymentPreimage is the preimage of a successful payment. This serves
	// as a proof of payment. It will only be non-nil for settled payments.
	//
	// NOTE: Can be nil if payment is not settled.
	PaymentPreimage *lntypes.Preimage

	// Failure is a failure reason code indicating the reason the payment
	// failed. It is only non-nil for failed payments.
	//
	// NOTE: Can be nil if payment is not failed.
	Failure *FailureReason
	// contains filtered or unexported fields
}

Payment is a wrapper around a payment's PaymentCreationInfo, PaymentAttemptInfo, and preimage. All payments will have the PaymentCreationInfo set, the PaymentAttemptInfo will be set only if at least one payment attempt has been made, while only completed payments will have a non-zero payment preimage.

type PaymentAttemptInfo

type PaymentAttemptInfo struct {
	// PaymentID is the unique ID used for this attempt.
	PaymentID uint64

	// SessionKey is the ephemeral key used for this payment attempt.
	SessionKey *btcec.PrivateKey

	// Route is the route attempted to send the HTLC.
	Route Route
}

PaymentAttemptInfo contains information about a specific payment attempt for a given payment. This information is used by the router to handle any errors coming back after an attempt is made, and to query the switch about the status of a payment. For settled payment this will be the information for the succeeding payment attempt.

type PaymentCreationInfo

type PaymentCreationInfo struct {
	// PaymentHash is the hash this payment is paying to.
	PaymentHash lntypes.Hash

	// Value is the amount we are paying.
	Value lnwire.MilliSatoshi

	// CreatingDate is the time when this payment was initiated.
	CreationDate time.Time

	// PaymentRequest is the full payment request, if any.
	PaymentRequest []byte
}

PaymentCreationInfo is the information necessary to have ready when initiating a payment, moving it into state InFlight.

type PaymentStatus

type PaymentStatus byte

PaymentStatus represent current status of payment

const (
	// StatusUnknown is the status where a payment has never been initiated
	// and hence is unknown.
	StatusUnknown PaymentStatus = 0

	// StatusInFlight is the status where a payment has been initiated, but
	// a response has not been received.
	StatusInFlight PaymentStatus = 1

	// StatusSucceeded is the status where a payment has been initiated and
	// the payment was completed successfully.
	StatusSucceeded PaymentStatus = 2

	// StatusFailed is the status where a payment has been initiated and a
	// failure result has come back.
	StatusFailed PaymentStatus = 3
)

func (PaymentStatus) Bytes

func (ps PaymentStatus) Bytes() []byte

Bytes returns status as slice of bytes.

func (*PaymentStatus) FromBytes

func (ps *PaymentStatus) FromBytes(status []byte) error

FromBytes sets status from slice of bytes.

func (PaymentStatus) String

func (ps PaymentStatus) String() string

String returns readable representation of payment status.

type Route

type Route struct {
	// TotalTimeLock is the cumulative (final) time lock across the entire
	// route. This is the CLTV value that should be extended to the first
	// hop in the route. All other hops will decrement the time-lock as
	// advertised, leaving enough time for all hops to wait for or present
	// the payment preimage to complete the payment.
	TotalTimeLock uint32

	// TotalAmount is the total amount of funds required to complete a
	// payment over this route. This value includes the cumulative fees at
	// each hop. As a result, the HTLC extended to the first-hop in the
	// route will need to have at least this many satoshis, otherwise the
	// route will fail at an intermediate node due to an insufficient
	// amount of fees.
	TotalAmount lnwire.MilliSatoshi

	// SourcePubKey is the pubkey of the node where this route originates
	// from.
	SourcePubKey Vertex

	// Hops contains details concerning the specific forwarding details at
	// each hop.
	Hops []*Hop
}

Route represents a path through the channel graph which runs over one or more channels in succession. This struct carries all the information required to craft the Sphinx onion packet, and send the payment along the first hop in the path. A route is only selected as valid if all the channels have sufficient capacity to carry the initial payment amount after fees are accounted for.

func DeserializeRoute

func DeserializeRoute(r io.Reader) (Route, error)

DeserializeRoute deserializes a route.

func NewRouteFromHops

func NewRouteFromHops(amtToSend lnwire.MilliSatoshi, timeLock uint32,
	sourceVertex Vertex, hops []*Hop) (*Route, error)

NewRouteFromHops creates a new Route structure from the minimally required information to perform the payment. It infers fee amounts and populates the node, chan and prev/next hop maps.

func (*Route) HopFee

func (r *Route) HopFee(hopIndex int) lnwire.MilliSatoshi

HopFee returns the fee charged by the route hop indicated by hopIndex.

func (*Route) String

func (r *Route) String() string

String returns a human readable representation of the route.

func (*Route) ToSphinxPath

func (r *Route) ToSphinxPath() (*sphinx.PaymentPath, error)

ToSphinxPath converts a complete route into a sphinx PaymentPath that contains the per-hop paylods used to encoding the HTLC routing data for each hop in the route. This method also accepts an optional EOB payload for the final hop.

func (*Route) TotalFees

func (r *Route) TotalFees() lnwire.MilliSatoshi

TotalFees is the sum of the fees paid at each hop within the final route. In the case of a one-hop payment, this value will be zero as we don't need to pay a fee to ourself.

type UnknownElementType

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

UnknownElementType is an error returned when the codec is unable to encode or decode a particular type.

func (UnknownElementType) Error

func (e UnknownElementType) Error() string

Error returns the name of the method that encountered the error, as well as the type that was unsupported.

type Vertex

type Vertex [VertexSize]byte

Vertex is a simple alias for the serialization of a compressed Bitcoin public key.

func NewVertex

func NewVertex(pub *btcec.PublicKey) Vertex

NewVertex returns a new Vertex given a public key.

func NewVertexFromBytes

func NewVertexFromBytes(b []byte) (Vertex, error)

NewVertexFromBytes returns a new Vertex based on a serialized pubkey in a byte slice.

func NewVertexFromStr

func NewVertexFromStr(v string) (Vertex, error)

NewVertexFromStr returns a new Vertex given its hex-encoded string format.

func (Vertex) String

func (v Vertex) String() string

String returns a human readable version of the Vertex which is the hex-encoding of the serialized compressed public key.

Jump to

Keyboard shortcuts

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