channeldb

package
v0.10.1-beta-rc1-branch Latest Latest
Warning

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

Go to latest
Published: May 19, 2020 License: MIT Imports: 39 Imported by: 281

README

channeldb

Build Status MIT licensed GoDoc

The channeldb implements the persistent storage engine for lnd and generically a data storage layer for the required state within the Lightning Network. The backing storage engine is boltdb, an embedded pure-go key-value store based off of LMDB.

The package implements an object-oriented storage model with queries and mutations flowing through a particular object instance rather than the database itself. The storage implemented by the objects includes: open channels, past commitment revocation states, the channel graph which includes authenticated node and channel announcements, outgoing payments, and invoices

Installation and Updating

$ go get -u github.com/lightningnetwork/lnd/channeldb

Documentation

Index

Constants

View Source
const (
	// MaxMemoSize is maximum size of the memo field within invoices stored
	// in the database.
	MaxMemoSize = 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 (

	// MaxResponseEvents is the max number of forwarding events that will
	// be returned by a single query response. This size was selected to
	// safely remain under gRPC's 4MiB message size response limit. As each
	// full forwarding event (including the timestamp) is 40 bytes, we can
	// safely return 50k entries in a single response.
	MaxResponseEvents = 50000
)

Variables

View Source
var (
	// ErrNoCommitmentsFound is returned when a channel has not set
	// commitment states.
	ErrNoCommitmentsFound = fmt.Errorf("no commitments found")

	// ErrNoChanInfoFound is returned when a particular channel does not
	// have any channels state.
	ErrNoChanInfoFound = fmt.Errorf("no chan info found")

	// ErrNoRevocationsFound is returned when revocation state for a
	// particular channel cannot be found.
	ErrNoRevocationsFound = fmt.Errorf("no revocations found")

	// ErrNoPendingCommit is returned when there is not a pending
	// commitment for a remote party. A new commitment is written to disk
	// each time we write a new state in order to be properly fault
	// tolerant.
	ErrNoPendingCommit = fmt.Errorf("no pending commits found")

	// ErrInvalidCircuitKeyLen signals that a circuit key could not be
	// decoded because the byte slice is of an invalid length.
	ErrInvalidCircuitKeyLen = fmt.Errorf(
		"length of serialized circuit key must be 16 bytes")

	// ErrNoCommitPoint is returned when no data loss commit point is found
	// in the database.
	ErrNoCommitPoint = fmt.Errorf("no commit point found")

	// ErrNoCloseTx is returned when no closing tx is found for a channel
	// in the state CommitBroadcasted.
	ErrNoCloseTx = fmt.Errorf("no closing tx found")

	// ErrNoRestoredChannelMutation is returned when a caller attempts to
	// mutate a channel that's been recovered.
	ErrNoRestoredChannelMutation = fmt.Errorf("cannot mutate restored " +
		"channel state")

	// ErrChanBorked is returned when a caller attempts to mutate a borked
	// channel.
	ErrChanBorked = fmt.Errorf("cannot mutate borked channel")
)
View Source
var (
	// ErrNoChanDBExists is returned when a channel bucket hasn't been
	// created.
	ErrNoChanDBExists = fmt.Errorf("channel db has not yet been created")

	// ErrNoHistoricalBucket is returned when the historical channel bucket
	// not been created yet.
	ErrNoHistoricalBucket = fmt.Errorf("historical channel bucket has " +
		"not yet been created")

	// ErrDBReversion is returned when detecting an attempt to revert to a
	// prior database version.
	ErrDBReversion = fmt.Errorf("channel db cannot revert to prior version")

	// ErrLinkNodesNotFound is returned when node info bucket hasn't been
	// created.
	ErrLinkNodesNotFound = fmt.Errorf("no link nodes exist")

	// ErrNoActiveChannels  is returned when there is no active (open)
	// channels within the database.
	ErrNoActiveChannels = fmt.Errorf("no active channels exist")

	// ErrNoPastDeltas is returned when the channel delta bucket hasn't been
	// created.
	ErrNoPastDeltas = fmt.Errorf("channel has no recorded deltas")

	// ErrInvoiceNotFound is returned when a targeted invoice can't be
	// found.
	ErrInvoiceNotFound = fmt.Errorf("unable to locate invoice")

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

	// ErrDuplicateInvoice is returned when an invoice with the target
	// payment hash already exists.
	ErrDuplicateInvoice = fmt.Errorf("invoice with payment hash already exists")

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

	// ErrNodeNotFound is returned when node bucket exists, but node with
	// specific identity can't be found.
	ErrNodeNotFound = fmt.Errorf("link node with target identity not found")

	// ErrChannelNotFound is returned when we attempt to locate a channel
	// for a specific chain, but it is not found.
	ErrChannelNotFound = fmt.Errorf("channel not found")

	// ErrMetaNotFound is returned when meta bucket hasn't been
	// created.
	ErrMetaNotFound = fmt.Errorf("unable to locate meta information")

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

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

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

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

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

	// ErrNoForwardingEvents is returned in the case that a query fails due
	// to the log not having any recorded events.
	ErrNoForwardingEvents = fmt.Errorf("no recorded forwarding events")

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

	// ErrChanAlreadyExists is return when the caller attempts to create a
	// channel with a channel point that is already present in the
	// database.
	ErrChanAlreadyExists = fmt.Errorf("channel already exists")
)
View Source
var (
	// UnknownPreimage is an all-zeroes preimage that indicates that the
	// preimage for this invoice is not yet known.
	UnknownPreimage lntypes.Preimage

	// ErrInvoiceAlreadySettled is returned when the invoice is already
	// settled.
	ErrInvoiceAlreadySettled = errors.New("invoice already settled")

	// ErrInvoiceAlreadyCanceled is returned when the invoice is already
	// canceled.
	ErrInvoiceAlreadyCanceled = errors.New("invoice already canceled")

	// ErrInvoiceAlreadyAccepted is returned when the invoice is already
	// accepted.
	ErrInvoiceAlreadyAccepted = errors.New("invoice already accepted")

	// ErrInvoiceStillOpen is returned when the invoice is still open.
	ErrInvoiceStillOpen = errors.New("invoice still open")

	// ErrInvoiceCannotOpen is returned when an attempt is made to move an
	// invoice to the open state.
	ErrInvoiceCannotOpen = errors.New("cannot move invoice to open")

	// ErrInvoiceCannotAccept is returned when an attempt is made to accept
	// an invoice while the invoice is not in the open state.
	ErrInvoiceCannotAccept = errors.New("cannot accept invoice")

	// ErrInvoicePreimageMismatch is returned when the preimage doesn't
	// match the invoice hash.
	ErrInvoicePreimageMismatch = errors.New("preimage does not match")
)
View Source
var (
	// ErrAlreadyPaid signals we have already paid this payment hash.
	ErrAlreadyPaid = errors.New("invoice is already paid")

	// ErrPaymentInFlight signals that payment for this payment hash is
	// already "in flight" on the network.
	ErrPaymentInFlight = errors.New("payment is in transition")

	// ErrPaymentNotInitiated is returned if the payment wasn't initiated.
	ErrPaymentNotInitiated = errors.New("payment isn't initiated")

	// ErrPaymentAlreadySucceeded is returned in the event we attempt to
	// change the status of a payment already succeeded.
	ErrPaymentAlreadySucceeded = errors.New("payment is already succeeded")

	// ErrPaymentAlreadyFailed is returned in the event we attempt to alter
	// a failed payment.
	ErrPaymentAlreadyFailed = errors.New("payment has already failed")

	// ErrUnknownPaymentStatus is returned when we do not recognize the
	// existing state of a payment.
	ErrUnknownPaymentStatus = errors.New("unknown payment status")

	// ErrPaymentTerminal is returned if we attempt to alter a payment that
	// already has reached a terminal condition.
	ErrPaymentTerminal = errors.New("payment has reached terminal condition")

	// ErrAttemptAlreadySettled is returned if we try to alter an already
	// settled HTLC attempt.
	ErrAttemptAlreadySettled = errors.New("attempt already settled")

	// ErrAttemptAlreadyFailed is returned if we try to alter an already
	// failed HTLC attempt.
	ErrAttemptAlreadyFailed = errors.New("attempt already failed")

	// ErrValueMismatch is returned if we try to register a non-MPP attempt
	// with an amount that doesn't match the payment amount.
	ErrValueMismatch = errors.New("attempted value doesn't match payment" +
		"amount")

	// ErrValueExceedsAmt is returned if we try to register an attempt that
	// would take the total sent amount above the payment amount.
	ErrValueExceedsAmt = errors.New("attempted value exceeds payment" +
		"amount")

	// ErrNonMPPayment is returned if we try to register an MPP attempt for
	// a payment that already has a non-MPP attempt regitered.
	ErrNonMPPayment = errors.New("payment has non-MPP attempts")

	// ErrMPPayment is returned if we try to register a non-MPP attempt for
	// a payment that already has an MPP attempt regitered.
	ErrMPPayment = errors.New("payment has MPP attempts")

	// ErrMPPPaymentAddrMismatch is returned if we try to register an MPP
	// shard where the payment address doesn't match existing shards.
	ErrMPPPaymentAddrMismatch = errors.New("payment address mismatch")

	// ErrMPPTotalAmountMismatch is returned if we try to register an MPP
	// shard where the total amount doesn't match existing shards.
	ErrMPPTotalAmountMismatch = errors.New("mp payment total amount mismatch")
)
View Source
var (

	// ErrWaitingProofNotFound is returned if waiting proofs haven't been
	// found by db.
	ErrWaitingProofNotFound = errors.New("waiting proofs haven't been " +
		"found")

	// ErrWaitingProofAlreadyExist is returned if waiting proofs haven't been
	// found by db.
	ErrWaitingProofAlreadyExist = errors.New("waiting proof with such " +
		"key already exist")
)
View Source
var (
	// ErrNoWitnesses is an error that's returned when no new witnesses have
	// been added to the WitnessCache.
	ErrNoWitnesses = fmt.Errorf("no witnesses")

	// ErrUnknownWitnessType is returned if a caller attempts to
	ErrUnknownWitnessType = fmt.Errorf("unknown witness type")
)
View Source
var ErrClosedChannelNotFound = errors.New("unable to find closed channel summary")

ErrClosedChannelNotFound signals that a closed channel could not be found in the channeldb.

View Source
var ErrCorruptedFwdPkg = errors.New("fwding package db has been corrupted")

ErrCorruptedFwdPkg signals that the on-disk structure of the forwarding package has potentially been mangled.

View Source
var (
	// ErrDryRunMigrationOK signals that a migration executed successful,
	// but we intentionally did not commit the result.
	ErrDryRunMigrationOK = errors.New("Dry run migration successful")
)

Functions

func DeserializeRoute

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

DeserializeRoute deserializes a route.

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

func SerializeHtlcs(b io.Writer, htlcs ...HTLC) error

SerializeHtlcs writes out the passed set of HTLC's into the passed writer using the current default on-disk serialization format.

NOTE: This API is NOT stable, the on-disk format will likely change in the future.

func SerializeRoute

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

SerializeRoute serializes a route.

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

type AddRef struct {
	// Height is the remote commitment height that locked in the Add.
	Height uint64

	// Index is the index of the Add within the fwd pkg's Adds.
	//
	// NOTE: This index is static over the lifetime of a forwarding package.
	Index uint16
}

AddRef is used to identify a particular Add in a FwdPkg. The short channel ID is assumed to be that of the packager.

func (*AddRef) Decode

func (a *AddRef) Decode(r io.Reader) error

Decode deserializes the AddRef from the given io.Reader.

func (*AddRef) Encode

func (a *AddRef) Encode(w io.Writer) error

Encode serializes the AddRef to the given io.Writer.

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
	// contains filtered or unexported fields
}

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

func (c *ChannelAuthProof) BitcoinSig1() (*btcec.Signature, error)

BitcoinSig1 is the signature using the public key of the first node that was used in the channel's multi-sig output.

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

func (*ChannelAuthProof) BitcoinSig2

func (c *ChannelAuthProof) BitcoinSig2() (*btcec.Signature, error)

BitcoinSig2 is the signature using the public key of the second node that was used in the channel's multi-sig output.

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

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.

func (*ChannelAuthProof) Node1Sig

func (c *ChannelAuthProof) Node1Sig() (*btcec.Signature, error)

Node1Sig is the signature using the identity key of the node that is first in a lexicographical ordering of the serialized public keys of the two nodes that created the channel.

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

func (*ChannelAuthProof) Node2Sig

func (c *ChannelAuthProof) Node2Sig() (*btcec.Signature, error)

Node2Sig is the signature using the identity key of the node that is second in a lexicographical ordering of the serialized public keys of the two nodes that created the channel.

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

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.
	//
	// NOTE: This is the balance *after* subtracting any commitment fee,
	// AND anchor output values.
	LocalBalance lnwire.MilliSatoshi

	// RemoteBalance is the current available settled balance within the
	// channel directly spendable by the remote node.
	//
	// NOTE: This is the balance *after* subtracting any commitment fee,
	// AND anchor output values.
	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 ChannelEdge

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

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

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

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 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
	// contains filtered or unexported fields
}

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.

func (*ChannelEdgeInfo) AddNodeKeys

func (c *ChannelEdgeInfo) AddNodeKeys(nodeKey1, nodeKey2, bitcoinKey1,
	bitcoinKey2 *btcec.PublicKey)

AddNodeKeys is a setter-like method that can be used to replace the set of keys for the target ChannelEdgeInfo.

func (*ChannelEdgeInfo) BitcoinKey1

func (c *ChannelEdgeInfo) BitcoinKey1() (*btcec.PublicKey, error)

BitcoinKey1 is the Bitcoin multi-sig key belonging to the first node, that was involved in the funding transaction that originally created the channel that this struct represents.

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

func (*ChannelEdgeInfo) BitcoinKey2

func (c *ChannelEdgeInfo) BitcoinKey2() (*btcec.PublicKey, error)

BitcoinKey2 is the Bitcoin multi-sig key belonging to the second node, that was involved in the funding transaction that originally created the channel that this struct represents.

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

func (*ChannelEdgeInfo) FetchOtherNode

func (c *ChannelEdgeInfo) FetchOtherNode(tx kvdb.ReadTx, thisNodeKey []byte) (*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 (*ChannelEdgeInfo) NodeKey1

func (c *ChannelEdgeInfo) NodeKey1() (*btcec.PublicKey, error)

NodeKey1 is the identity public key of the "first" node that was involved in the creation of this channel. A node is considered "first" if the lexicographical ordering the its serialized public key is "smaller" than that of the other node involved in channel creation.

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

func (*ChannelEdgeInfo) NodeKey2

func (c *ChannelEdgeInfo) NodeKey2() (*btcec.PublicKey, error)

NodeKey2 is the identity public key of the "second" node that was involved in the creation of this channel. A node is considered "second" if the lexicographical ordering the its serialized public key is "larger" than that of the other node involved in channel creation.

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

func (*ChannelEdgeInfo) OtherNodeKeyBytes

func (c *ChannelEdgeInfo) OtherNodeKeyBytes(thisNodeKey []byte) (
	[33]byte, error)

OtherNodeKeyBytes returns the node key bytes of the other end 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 forward, expressed
	// in millisatoshi.
	MinHTLC lnwire.MilliSatoshi

	// MaxHTLC is the largest value HTLC this node will forward, 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
	// contains filtered or unexported fields
}

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

ComputeFee computes the fee to forward an HTLC of `amt` milli-satoshis over the passed active payment channel. This value is currently computed as specified in BOLT07, but will likely change in the near future.

func (*ChannelEdgePolicy) ComputeFeeFromIncoming

func (c *ChannelEdgePolicy) ComputeFeeFromIncoming(
	incomingAmt lnwire.MilliSatoshi) lnwire.MilliSatoshi

ComputeFeeFromIncoming computes the fee to forward an HTLC given the incoming amount.

func (*ChannelEdgePolicy) IsDisabled

func (c *ChannelEdgePolicy) IsDisabled() bool

IsDisabled determines whether the edge has the disabled bit set.

func (*ChannelEdgePolicy) SetSigBytes

func (c *ChannelEdgePolicy) SetSigBytes(sig []byte)

SetSigBytes updates the signature and invalidates the cached parsed signature.

func (*ChannelEdgePolicy) Signature

func (c *ChannelEdgePolicy) Signature() (*btcec.Signature, error)

Signature is a channel announcement signature, which is needed for proper edge policy announcement.

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

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

func (c *ChannelGraph) AddChannelEdge(edge *ChannelEdgeInfo) error

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

func (*ChannelGraph) AddLightningNode

func (c *ChannelGraph) AddLightningNode(node *LightningNode) 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) 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) Database

func (c *ChannelGraph) Database() *DB

Database returns a pointer to the underlying database.

func (*ChannelGraph) DeleteChannelEdges

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

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) ([]*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

func (c *ChannelGraph) FetchChannelEdgesByID(chanID uint64,
) (*ChannelEdgeInfo, *ChannelEdgePolicy, *ChannelEdgePolicy, error)

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

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

func (*ChannelGraph) FetchChannelEdgesByOutpoint

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

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

func (*ChannelGraph) FetchLightningNode

func (c *ChannelGraph) FetchLightningNode(tx kvdb.ReadTx, nodePub route.Vertex) (
	*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.

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

func (c *ChannelGraph) FilterChannelRange(startHeight, endHeight uint32) ([]uint64, error)

FilterChannelRange returns the channel ID's of all known channels which were mined in a block height within the passed range. 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.

func (*ChannelGraph) FilterKnownChanIDs

func (c *ChannelGraph) FilterKnownChanIDs(chanIDs []uint64) ([]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(tx kvdb.RwTx, cb func(kvdb.ReadTx, *LightningNode) 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.

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

TODO(roasbeef): add iterator interface to allow for memory efficient graph traversal when graph gets mega

func (*ChannelGraph) ForEachNodeChannel

func (c *ChannelGraph) ForEachNodeChannel(tx kvdb.ReadTx, nodePub []byte,
	cb func(kvdb.ReadTx, *ChannelEdgeInfo, *ChannelEdgePolicy,
		*ChannelEdgePolicy) error) error

ForEachNodeChannel iterates through all channels of a 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 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) 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) 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) NewChannelEdgePolicy

func (c *ChannelGraph) NewChannelEdgePolicy() *ChannelEdgePolicy

NewChannelEdgePolicy returns a new blank ChannelEdgePolicy.

func (*ChannelGraph) NodeUpdatesInHorizon

func (c *ChannelGraph) NodeUpdatesInHorizon(startTime, endTime time.Time) ([]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) ([]*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) 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.

func (*ChannelGraph) UpdateChannelEdge

func (c *ChannelGraph) UpdateChannelEdge(edge *ChannelEdgeInfo) error

UpdateChannelEdge retrieves and update edge of the graph database. Method only reserved for updating an edge info after its already been created. In order to maintain this constraints, we return an error in the scenario that an edge info hasn't yet been created yet, but someone attempts to update it.

func (*ChannelGraph) UpdateEdgePolicy

func (c *ChannelGraph) UpdateEdgePolicy(edge *ChannelEdgePolicy) error

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

type ChannelPackager

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

ChannelPackager is used by a channel to manage the lifecycle of its forwarding packages. The packager is tied to a particular source channel ID, allowing it to create and edit its own packages. Each packager also has the ability to remove fail/settle htlcs that correspond to an add contained in one of source's packages.

func NewChannelPackager

func NewChannelPackager(source lnwire.ShortChannelID) *ChannelPackager

NewChannelPackager creates a new packager for a single channel.

func (*ChannelPackager) AckAddHtlcs

func (p *ChannelPackager) AckAddHtlcs(tx kvdb.RwTx, addRefs ...AddRef) error

AckAddHtlcs accepts a list of references to add htlcs, and updates the AckAddFilter of those forwarding packages to indicate that a settle or fail has been received in response to the add.

func (*ChannelPackager) AckSettleFails

func (p *ChannelPackager) AckSettleFails(tx kvdb.RwTx, settleFailRefs ...SettleFailRef) error

AckSettleFails persistently acknowledges settles or fails from a remote forwarding package. This should only be called after the source of the Add has locked in the settle/fail, or it becomes otherwise safe to forgo retransmitting the settle/fail after a restart.

func (*ChannelPackager) AddFwdPkg

func (*ChannelPackager) AddFwdPkg(tx kvdb.RwTx, fwdPkg *FwdPkg) error

AddFwdPkg writes a newly locked in forwarding package to disk.

func (*ChannelPackager) LoadFwdPkgs

func (p *ChannelPackager) LoadFwdPkgs(tx kvdb.ReadTx) ([]*FwdPkg, error)

LoadFwdPkgs scans the forwarding log for any packages that haven't been processed, and returns their deserialized log updates in a map indexed by the remote commitment height at which the updates were locked in.

func (*ChannelPackager) RemovePkg

func (p *ChannelPackager) RemovePkg(tx kvdb.RwTx, height uint64) error

RemovePkg deletes the forwarding package at the given height from the packager's source bucket.

func (*ChannelPackager) SetFwdFilter

func (p *ChannelPackager) SetFwdFilter(tx kvdb.RwTx, height uint64,
	fwdFilter *PkgFilter) error

SetFwdFilter writes the set of indexes corresponding to Adds at the `height` that are to be forwarded to the switch. Calling this method causes the forwarding package at `height` to be in FwdStateProcessed. We write this forwarding decision so that we always arrive at the same behavior for HTLCs leaving this channel. After a restart, we skip validation of these Adds, since they are assumed to have already been validated, and make the switch or outgoing link responsible for handling replays.

type ChannelShell

type ChannelShell struct {
	// NodeAddrs the set of addresses that this node has known to be
	// reachable at in the past.
	NodeAddrs []net.Addr

	// Chan is a shell of an OpenChannel, it contains only the items
	// required to restore the channel on disk.
	Chan *OpenChannel
}

ChannelShell is a shell of a channel that is meant to be used for channel recovery purposes. It contains a minimal OpenChannel instance along with addresses for that target node.

type ChannelSnapshot

type ChannelSnapshot struct {
	// RemoteIdentity is the identity public key of the remote node that we
	// are maintaining the open channel with.
	RemoteIdentity btcec.PublicKey

	// ChanPoint is the outpoint that created the channel. This output is
	// found within the funding transaction and uniquely identified the
	// channel on the resident chain.
	ChannelPoint wire.OutPoint

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

	// Capacity is the total capacity of the 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

	// ChannelCommitment is the current up-to-date commitment for the
	// target channel.
	ChannelCommitment
}

ChannelSnapshot is a frozen snapshot of the current channel state. A snapshot is detached from the original channel that generated it, providing read-only access to the current or prior state of an active channel.

TODO(roasbeef): remove all together? pretty much just commitment

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

	// ChanStatusCoopBroadcasted indicates that a cooperative close for
	// this channel has been broadcasted. Older cooperatively closed
	// channels will only have this status set. Newer ones will also have
	// close initiator information stored using the local/remote initiator
	// status. This status is set in conjunction with the initiator status
	// so that we do not need to check multiple channel statues for
	// cooperative closes.
	ChanStatusCoopBroadcasted ChannelStatus = 1 << 4

	// ChanStatusLocalCloseInitiator indicates that we initiated closing
	// the channel.
	ChanStatusLocalCloseInitiator ChannelStatus = 1 << 5

	// ChanStatusRemoteCloseInitiator indicates that the remote node
	// initiated closing the channel.
	ChanStatusRemoteCloseInitiator ChannelStatus = 1 << 6
)

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. Structure-wise, a ChannelType is a bit field, with each bit denoting a modification from the base channel type of single funder.

const (

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

	// DualFunderBit represents a channel wherein both parties contribute
	// funds towards the total capacity of the channel. The channel may be
	// funded symmetrically or asymmetrically.
	DualFunderBit ChannelType = 1 << 0

	// SingleFunderTweakless is similar to the basic SingleFunder channel
	// type, but it omits the tweak for one's key in the commitment
	// transaction of the remote party.
	SingleFunderTweaklessBit ChannelType = 1 << 1

	// NoFundingTxBit denotes if we have the funding transaction locally on
	// disk. This bit may be on if the funding transaction was crafted by a
	// wallet external to the primary daemon.
	NoFundingTxBit ChannelType = 1 << 2

	// AnchorOutputsBit indicates that the channel makes use of anchor
	// outputs to bump the commitment transaction's effective feerate. This
	// channel type also uses a delayed to_remote output script. If bit is
	// set, we'll find the size of the anchor outputs in the database.
	AnchorOutputsBit ChannelType = 1 << 3

	// FrozenBit indicates that the channel is a frozen channel, meaning
	// that only the responder can decide to cooperatively close the
	// channel.
	FrozenBit ChannelType = 1 << 4
)

func (ChannelType) HasAnchors

func (c ChannelType) HasAnchors() bool

HasAnchors returns true if this channel type has anchor ouputs on its commitment.

func (ChannelType) HasFundingTx

func (c ChannelType) HasFundingTx() bool

HasFundingTx returns true if this channel type is one that has a funding transaction stored locally.

func (ChannelType) IsDualFunder

func (c ChannelType) IsDualFunder() bool

IsDualFunder returns true if the ChannelType has the DualFunderBit set.

func (ChannelType) IsFrozen

func (c ChannelType) IsFrozen() bool

IsFrozen returns true if the channel is considered to be "frozen". A frozen channel means that only the responder can initiate a cooperative channel closure.

func (ChannelType) IsSingleFunder

func (c ChannelType) IsSingleFunder() bool

IsSingleFunder returns true if the channel type if one of the known single funder variants.

func (ChannelType) IsTweakless

func (c ChannelType) IsTweakless() bool

IsTweakless returns true if the target channel uses a commitment that doesn't tweak the key for the remote party.

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

func (k CircuitKey) Bytes() []byte

Bytes returns the serialized bytes for this circuit key.

func (*CircuitKey) Decode

func (k *CircuitKey) Decode(r io.Reader) error

Decode reads a CircuitKey from the provided io.Reader.

func (*CircuitKey) Encode

func (k *CircuitKey) Encode(w io.Writer) error

Encode writes a CircuitKey to the provided io.Writer.

func (*CircuitKey) SetBytes

func (k *CircuitKey) SetBytes(bs []byte) error

SetBytes deserializes the given bytes into this CircuitKey.

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 (
	// CooperativeClose indicates that a channel has been closed
	// cooperatively.  This means that both channel peers were online and
	// signed a new transaction paying out the settled balance of the
	// contract.
	CooperativeClose ClosureType = 0

	// LocalForceClose indicates that we have unilaterally broadcast our
	// current commitment state on-chain.
	LocalForceClose ClosureType = 1

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

	// BreachClose indicates that the remote peer attempted to broadcast a
	// prior _revoked_ channel state.
	BreachClose ClosureType = 2

	// FundingCanceled indicates that the channel never was fully opened
	// before it was marked as closed in the database. This can happen if
	// we or the remote fail at some point during the opening workflow, or
	// we timeout waiting for the funding transaction to be confirmed.
	FundingCanceled ClosureType = 3

	// Abandoned indicates that the channel state was removed without
	// any further actions. This is intended to clean up unusable
	// channels during development.
	Abandoned ClosureType = 5
)

type CommitDiff

type CommitDiff struct {
	// ChannelCommitment is the full commitment state that one would arrive
	// at by applying the set of messages contained in the UpdateDiff to
	// the prior accepted commitment.
	Commitment ChannelCommitment

	// LogUpdates is the set of messages sent prior to the commitment state
	// transition in question. Upon reconnection, if we detect that they
	// don't have the commitment, then we re-send this along with the
	// proper signature.
	LogUpdates []LogUpdate

	// CommitSig is the exact CommitSig message that should be sent after
	// the set of LogUpdates above has been retransmitted. The signatures
	// within this message should properly cover the new commitment state
	// and also the HTLC's within the new commitment state.
	CommitSig *lnwire.CommitSig

	// OpenedCircuitKeys is a set of unique identifiers for any downstream
	// Add packets included in this commitment txn. After a restart, this
	// set of htlcs is acked from the link's incoming mailbox to ensure
	// there isn't an attempt to re-add them to this commitment txn.
	OpenedCircuitKeys []CircuitKey

	// ClosedCircuitKeys records the unique identifiers for any settle/fail
	// packets that were resolved by this commitment txn. After a restart,
	// this is used to ensure those circuits are removed from the circuit
	// map, and the downstream packets in the link's mailbox are removed.
	ClosedCircuitKeys []CircuitKey

	// AddAcks specifies the locations (commit height, pkg index) of any
	// Adds that were failed/settled in this commit diff. This will ack
	// entries in *this* channel's forwarding packages.
	//
	// NOTE: This value is not serialized, it is used to atomically mark the
	// resolution of adds, such that they will not be reprocessed after a
	// restart.
	AddAcks []AddRef

	// SettleFailAcks specifies the locations (chan id, commit height, pkg
	// index) of any Settles or Fails that were locked into this commit
	// diff, and originate from *another* channel, i.e. the outgoing link.
	//
	// NOTE: This value is not serialized, it is used to atomically acks
	// settles and fails from the forwarding packages of other channels,
	// such that they will not be reforwarded internally after a restart.
	SettleFailAcks []SettleFailRef
}

CommitDiff represents the delta needed to apply the state transition between two subsequent commitment states. Given state N and state N+1, one is able to apply the set of messages contained within the CommitDiff to N to arrive at state N+1. Each time a new commitment is extended, we'll write a new commitment (along with the full commitment state) to disk so we can re-transmit the state in the case of a connection loss or message drop.

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

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

	// PaymentAddr is a randomly generated value include in the MPP record
	// by the sender to prevent probing of the receiver.
	PaymentAddr [32]byte

	// Features is the feature vectors advertised on the payment request.
	Features *lnwire.FeatureVector
}

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.

func (ContractTerm) String

func (c ContractTerm) String() string

String returns a human-readable description of the prominent contract terms.

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

func (d *DB) AbandonChannel(chanPoint *wire.OutPoint, bestHeight uint32) error

AbandonChannel attempts to remove the target channel from the open channel database. If the channel was already removed (has a closed channel entry), then we'll return a nil error. Otherwise, we'll insert a new close summary into the database.

func (*DB) AddInvoice

func (d *DB) AddInvoice(newInvoice *Invoice, paymentHash lntypes.Hash) (
	uint64, error)

AddInvoice inserts the targeted invoice into the database. If the invoice has *any* payment hashes which already exists within the database, then the insertion will be aborted and rejected due to the strict policy banning any duplicate payment hashes. A side effect of this function is that it sets AddIndex on newInvoice.

func (*DB) AddrsForNode

func (d *DB) AddrsForNode(nodePub *btcec.PublicKey) ([]net.Addr, error)

AddrsForNode consults the graph and channel database for all addresses known to the passed node public key.

func (*DB) ChannelGraph

func (d *DB) ChannelGraph() *ChannelGraph

ChannelGraph returns a new instance of the directed channel graph.

func (*DB) DeleteLinkNode

func (db *DB) DeleteLinkNode(identity *btcec.PublicKey) error

DeleteLinkNode removes the link node with the given identity from the database.

func (*DB) DeletePayments

func (db *DB) DeletePayments() error

DeletePayments deletes all completed and failed payments from the DB.

func (*DB) FetchAllChannels

func (d *DB) FetchAllChannels() ([]*OpenChannel, error)

FetchAllChannels attempts to retrieve all open channels currently stored within the database, including pending open, fully open and channels waiting for a closing transaction to confirm.

func (*DB) FetchAllInvoicesWithPaymentHash

func (d *DB) FetchAllInvoicesWithPaymentHash(pendingOnly bool) (
	[]InvoiceWithPaymentHash, error)

FetchAllInvoicesWithPaymentHash returns all invoices and their payment hashes currently stored within the database. If the pendingOnly param is true, then only open or accepted invoices and their payment hashes will be returned, skipping all invoices that are fully settled or canceled. Note that the returned array is not ordered by add index.

func (*DB) FetchAllLinkNodes

func (db *DB) FetchAllLinkNodes() ([]*LinkNode, error)

FetchAllLinkNodes starts a new database transaction to fetch all nodes with whom we have active channels with.

func (*DB) FetchAllOpenChannels

func (d *DB) FetchAllOpenChannels() ([]*OpenChannel, error)

FetchAllOpenChannels will return all channels that have the funding transaction confirmed, and is not waiting for a closing transaction to be confirmed.

func (*DB) FetchChannel

func (d *DB) FetchChannel(chanPoint wire.OutPoint) (*OpenChannel, error)

FetchChannel attempts to locate a channel specified by the passed channel point. If the channel cannot be found, then an error will be returned.

func (*DB) FetchClosedChannel

func (d *DB) FetchClosedChannel(chanID *wire.OutPoint) (*ChannelCloseSummary, error)

FetchClosedChannel queries for a channel close summary using the channel point of the channel in question.

func (*DB) FetchClosedChannelForID

func (d *DB) FetchClosedChannelForID(cid lnwire.ChannelID) (
	*ChannelCloseSummary, error)

FetchClosedChannelForID queries for a channel close summary using the channel ID of the channel in question.

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

func (d *DB) FetchHistoricalChannel(outPoint *wire.OutPoint) (*OpenChannel, error)

FetchHistoricalChannel fetches open channel data from the historical channel bucket.

func (*DB) FetchLinkNode

func (db *DB) FetchLinkNode(identity *btcec.PublicKey) (*LinkNode, error)

FetchLinkNode attempts to lookup the data for a LinkNode based on a target identity public key. If a particular LinkNode for the passed identity public key cannot be found, then ErrNodeNotFound if returned.

func (*DB) FetchMeta

func (d *DB) FetchMeta(tx kvdb.ReadTx) (*Meta, error)

FetchMeta fetches the meta data from boltdb and returns filled meta structure.

func (*DB) FetchOpenChannels

func (d *DB) FetchOpenChannels(nodeID *btcec.PublicKey) ([]*OpenChannel, error)

FetchOpenChannels starts a new database transaction and returns all stored currently active/open channels associated with the target nodeID. In the case that no active channels are known to have been created with this node, then a zero-length slice is returned.

func (*DB) FetchPayments

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

FetchPayments returns all sent payments found in the DB.

nolint: dupl

func (*DB) FetchPendingChannels

func (d *DB) FetchPendingChannels() ([]*OpenChannel, error)

FetchPendingChannels will return channels that have completed the process of generating and broadcasting funding transactions, but whose funding transactions have yet to be confirmed on the blockchain.

func (*DB) FetchWaitingCloseChannels

func (d *DB) FetchWaitingCloseChannels() ([]*OpenChannel, error)

FetchWaitingCloseChannels will return all channels that have been opened, but are now waiting for a closing transaction to be confirmed.

NOTE: This includes channels that are also pending to be opened.

func (*DB) ForwardingLog

func (d *DB) ForwardingLog() *ForwardingLog

ForwardingLog returns an instance of the ForwardingLog object backed by the target database instance.

func (*DB) InvoicesAddedSince

func (d *DB) InvoicesAddedSince(sinceAddIndex uint64) ([]Invoice, error)

InvoicesAddedSince can be used by callers to seek into the event time series of all the invoices added in the database. The specified sinceAddIndex should be the highest add index that the caller knows of. This method will return all invoices with an add index greater than the specified sinceAddIndex.

NOTE: The index starts from 1, as a result. We enforce that specifying a value below the starting index value is a noop.

func (*DB) InvoicesSettledSince

func (d *DB) InvoicesSettledSince(sinceSettleIndex uint64) ([]Invoice, error)

InvoicesSettledSince can be used by callers to catch up any settled invoices they missed within the settled invoice time series. We'll return all known settled invoice that have a settle index higher than the passed sinceSettleIndex.

NOTE: The index starts from 1, as a result. We enforce that specifying a value below the starting index value is a noop.

func (*DB) LookupInvoice

func (d *DB) LookupInvoice(paymentHash [32]byte) (Invoice, error)

LookupInvoice attempts to look up an invoice according to its 32 byte payment hash. If an invoice which can settle the HTLC identified by the passed payment hash isn't found, then an error is returned. Otherwise, the full invoice is returned. Before setting the incoming HTLC, the values SHOULD be checked to ensure the payer meets the agreed upon contractual terms of the payment.

func (*DB) MarkChanFullyClosed

func (d *DB) MarkChanFullyClosed(chanPoint *wire.OutPoint) error

MarkChanFullyClosed marks a channel as fully closed within the database. A channel should be marked as fully closed if the channel was initially cooperatively closed and it's reached a single confirmation, or after all the pending funds in a channel that has been forcibly closed have been swept.

func (*DB) NewLinkNode

func (db *DB) NewLinkNode(bitNet wire.BitcoinNet, pub *btcec.PublicKey,
	addrs ...net.Addr) *LinkNode

NewLinkNode creates a new LinkNode from the provided parameters, which is backed by an instance of channeldb.

func (*DB) NewWitnessCache

func (d *DB) NewWitnessCache() *WitnessCache

NewWitnessCache returns a new instance of the witness cache.

func (*DB) Path

func (d *DB) Path() string

Path returns the file path to the channel database.

func (*DB) PruneLinkNodes

func (d *DB) PruneLinkNodes() error

PruneLinkNodes attempts to prune all link nodes found within the databse with whom we no longer have any open channels with.

func (*DB) PutMeta

func (d *DB) PutMeta(meta *Meta) error

PutMeta writes the passed instance of the database met-data struct to disk.

func (*DB) QueryInvoices

func (d *DB) QueryInvoices(q InvoiceQuery) (InvoiceSlice, error)

QueryInvoices allows a caller to query the invoice database for invoices within the specified add index range.

func (*DB) QueryPayments

func (db *DB) QueryPayments(query PaymentsQuery) (PaymentsResponse, error)

QueryPayments is a query to the payments database which is restricted to a subset of payments by the payments query, containing an offset index and a maximum number of returned payments.

func (*DB) RestoreChannelShells

func (d *DB) RestoreChannelShells(channelShells ...*ChannelShell) error

RestoreChannelShells is a method that allows the caller to reconstruct the state of an OpenChannel from the ChannelShell. We'll attempt to write the new channel to disk, create a LinkNode instance with the passed node addresses, and finally create an edge within the graph for the channel as well. This method is idempotent, so repeated calls with the same set of channel shells won't modify the database after the initial call.

func (*DB) UpdateInvoice

func (d *DB) UpdateInvoice(paymentHash lntypes.Hash,
	callback InvoiceUpdateCallback) (*Invoice, error)

UpdateInvoice attempts to update an invoice corresponding to the passed payment hash. If an invoice matching the passed payment hash doesn't exist within the database, then the action will fail with a "not found" error.

The update is performed inside the same database transaction that fetches the invoice and is therefore atomic. The fields to update are controlled by the supplied callback.

func (*DB) Wipe

func (d *DB) 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 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 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

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

	// FailureReasonInsufficientBalance indicates that we didn't have enough
	// balance to complete the payment.
	FailureReasonInsufficientBalance FailureReason = 4
)

func (FailureReason) Error

func (r FailureReason) Error() string

Error returns a human readable error string for the FailureReason.

func (FailureReason) String

func (r FailureReason) String() string

String returns a human readable FailureReason.

type ForwardingEvent

type ForwardingEvent struct {
	// Timestamp is the settlement time of this payment circuit.
	Timestamp time.Time

	// IncomingChanID is the incoming channel ID of the payment circuit.
	IncomingChanID lnwire.ShortChannelID

	// OutgoingChanID is the outgoing channel ID of the payment circuit.
	OutgoingChanID lnwire.ShortChannelID

	// AmtIn is the amount of the incoming HTLC. Subtracting this from the
	// outgoing amount gives the total fees of this payment circuit.
	AmtIn lnwire.MilliSatoshi

	// AmtOut is the amount of the outgoing HTLC. Subtracting the incoming
	// amount from this gives the total fees for this payment circuit.
	AmtOut lnwire.MilliSatoshi
}

ForwardingEvent is an event in the forwarding log's time series. Each forwarding event logs the creation and tear-down of a payment circuit. A circuit is created once an incoming HTLC has been fully forwarded, and destroyed once the payment has been settled.

type ForwardingEventQuery

type ForwardingEventQuery struct {
	// StartTime is the start time of the time slice.
	StartTime time.Time

	// EndTime is the end time of the time slice.
	EndTime time.Time

	// IndexOffset is the offset within the time slice to start at. This
	// can be used to start the response at a particular record.
	IndexOffset uint32

	// NumMaxEvents is the max number of events to return.
	NumMaxEvents uint32
}

ForwardingEventQuery represents a query to the forwarding log payment circuit time series database. The query allows a caller to retrieve all records for a particular time slice, offset in that time slice, limiting the total number of responses returned.

type ForwardingLog

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

ForwardingLog is a time series database that logs the fulfilment of payment circuits by a lightning network daemon. The log contains a series of forwarding events which map a timestamp to a forwarding event. A forwarding event describes which channels were used to create+settle a circuit, and the amount involved. Subtracting the outgoing amount from the incoming amount reveals the fee charged for the forwarding service.

func (*ForwardingLog) AddForwardingEvents

func (f *ForwardingLog) AddForwardingEvents(events []ForwardingEvent) error

AddForwardingEvents adds a series of forwarding events to the database. Before inserting, the set of events will be sorted according to their timestamp. This ensures that all writes to disk are sequential.

func (*ForwardingLog) Query

Query allows a caller to query the forwarding event time series for a particular time slice. The caller can control the precise time as well as the number of events to be returned.

TODO(roasbeef): rename?

type ForwardingLogTimeSlice

type ForwardingLogTimeSlice struct {
	ForwardingEventQuery

	// ForwardingEvents is the set of events in our time series that answer
	// the query embedded above.
	ForwardingEvents []ForwardingEvent

	// LastIndexOffset is the index of the last element in the set of
	// returned ForwardingEvents above. Callers can use this to resume
	// their query in the event that the time slice has too many events to
	// fit into a single response.
	LastIndexOffset uint32
}

ForwardingLogTimeSlice is the response to a forwarding query. It includes the original query, the set events that match the query, and an integer which represents the offset index of the last item in the set of retuned events. This integer allows callers to resume their query using this offset in the event that the query's response exceeds the max number of returnable events.

type FwdOperator

type FwdOperator interface {
	// GlobalFwdPkgReader provides read access to all known forwarding
	// packages
	GlobalFwdPkgReader

	// SettleFailAcker grants the ability to acknowledge settles or fails
	// residing in arbitrary forwarding packages.
	SettleFailAcker
}

FwdOperator defines the interfaces for managing forwarding packages that are external to a particular channel. This interface is used by the switch to read forwarding packages from arbitrary channels, and acknowledge settles and fails for locally-sourced payments.

type FwdPackager

type FwdPackager interface {
	// AddFwdPkg serializes and writes a FwdPkg for this channel at the
	// remote commitment height included in the forwarding package.
	AddFwdPkg(tx kvdb.RwTx, fwdPkg *FwdPkg) error

	// SetFwdFilter looks up the forwarding package at the remote `height`
	// and sets the `fwdFilter`, marking the Adds for which:
	// 1) We are not the exit node
	// 2) Passed all validation
	// 3) Should be forwarded to the switch immediately after a failure
	SetFwdFilter(tx kvdb.RwTx, height uint64, fwdFilter *PkgFilter) error

	// AckAddHtlcs atomically updates the add filters in this channel's
	// forwarding packages to mark the resolution of an Add that was
	// received from the remote party.
	AckAddHtlcs(tx kvdb.RwTx, addRefs ...AddRef) error

	// SettleFailAcker allows a link to acknowledge settle/fail HTLCs
	// belonging to other channels.
	SettleFailAcker

	// LoadFwdPkgs loads all known forwarding packages owned by this
	// channel.
	LoadFwdPkgs(tx kvdb.ReadTx) ([]*FwdPkg, error)

	// RemovePkg deletes a forwarding package owned by this channel at
	// the provided remote `height`.
	RemovePkg(tx kvdb.RwTx, height uint64) error
}

FwdPackager supports all operations required to modify fwd packages, such as creation, updates, reading, and removal. The interfaces are broken down in this way to support future delegation of the subinterfaces.

type FwdPkg

type FwdPkg struct {
	// Source identifies the channel that wrote this forwarding package.
	Source lnwire.ShortChannelID

	// Height is the height of the remote commitment chain that locked in
	// this forwarding package.
	Height uint64

	// State signals the persistent condition of the package and directs how
	// to reprocess the package in the event of failures.
	State FwdState

	// Adds contains all add messages which need to be processed and
	// forwarded to the switch. Adds does not change over the life of a
	// forwarding package.
	Adds []LogUpdate

	// FwdFilter is a filter containing the indices of all Adds that were
	// forwarded to the switch.
	FwdFilter *PkgFilter

	// AckFilter is a filter containing the indices of all Adds for which
	// the source has received a settle or fail and is reflected in the next
	// commitment txn. A package should not be removed until IsFull()
	// returns true.
	AckFilter *PkgFilter

	// SettleFails contains all settle and fail messages that should be
	// forwarded to the switch.
	SettleFails []LogUpdate

	// SettleFailFilter is a filter containing the indices of all Settle or
	// Fails originating in this package that have been received and locked
	// into the incoming link's commitment state.
	SettleFailFilter *PkgFilter
}

FwdPkg records all adds, settles, and fails that were locked in as a result of the remote peer sending us a revocation. Each package is identified by the short chanid and remote commitment height corresponding to the revocation that locked in the HTLCs. For everything except a locally initiated payment, settles and fails in a forwarding package must have a corresponding Add in another package, and can be removed individually once the source link has received the fail/settle.

Adds cannot be removed, as we need to present the same batch of Adds to properly handle replay protection. Instead, we use a PkgFilter to mark that we have finished processing a particular Add. A FwdPkg should only be deleted after the AckFilter is full and all settles and fails have been persistently removed.

func NewFwdPkg

func NewFwdPkg(source lnwire.ShortChannelID, height uint64,
	addUpdates, settleFailUpdates []LogUpdate) *FwdPkg

NewFwdPkg initializes a new forwarding package in FwdStateLockedIn. This should be used to create a package at the time we receive a revocation.

func (*FwdPkg) ID

func (f *FwdPkg) ID() []byte

ID returns an unique identifier for this package, used to ensure that sphinx replay processing of this batch is idempotent.

func (*FwdPkg) String

func (f *FwdPkg) String() string

String returns a human-readable description of the forwarding package.

type FwdState

type FwdState byte

FwdState is an enum used to describe the lifecycle of a FwdPkg.

const (
	// FwdStateLockedIn is the starting state for all forwarding packages.
	// Packages in this state have not yet committed to the exact set of
	// Adds to forward to the switch.
	FwdStateLockedIn FwdState = iota

	// FwdStateProcessed marks the state in which all Adds have been
	// locally processed and the forwarding decision to the switch has been
	// persisted.
	FwdStateProcessed

	// FwdStateCompleted signals that all Adds have been acked, and that all
	// settles and fails have been delivered to their sources. Packages in
	// this state can be removed permanently.
	FwdStateCompleted
)

type GlobalFwdPkgReader

type GlobalFwdPkgReader interface {
	// LoadChannelFwdPkgs loads all known forwarding packages for the given
	// channel.
	LoadChannelFwdPkgs(tx kvdb.RwTx,
		source lnwire.ShortChannelID) ([]*FwdPkg, error)
}

GlobalFwdPkgReader is an interface used to retrieve the forwarding packages of any active channel.

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?

func DeserializeHtlcs

func DeserializeHtlcs(r io.Reader) ([]HTLC, error)

DeserializeHtlcs attempts to read out a slice of HTLC's from the passed io.Reader. The bytes within the passed reader MUST have been previously written to using the SerializeHtlcs function.

NOTE: This API is NOT stable, the on-disk format will likely change in the future.

func (*HTLC) Copy

func (h *HTLC) Copy() HTLC

Copy returns a full copy of the target HTLC.

type HTLCAttempt

type HTLCAttempt struct {
	HTLCAttemptInfo

	// Settle 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.
	Settle *HTLCSettleInfo

	// Fail 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 *HTLCFailInfo
}

HTLCAttempt contains information about a specific HTLC attempt for a given payment. It contains the HTLCAttemptInfo used to send the HTLC, as well as a timestamp and any known outcome of the attempt.

type HTLCAttemptInfo

type HTLCAttemptInfo struct {
	// AttemptID is the unique ID used for this attempt.
	AttemptID uint64

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

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

	// AttemptTime is the time at which this HTLC was attempted.
	AttemptTime time.Time
}

HTLCAttemptInfo contains static information about a specific HTLC attempt for a 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 the attempt.

type HTLCFailInfo

type HTLCFailInfo struct {
	// FailTime is the time at which this HTLC was failed.
	FailTime time.Time

	// Message is the wire message that failed this HTLC. This field will be
	// populated when the failure reason is HTLCFailMessage.
	Message lnwire.FailureMessage

	// Reason is the failure reason for this HTLC.
	Reason HTLCFailReason

	// The position in the path of the intermediate or final node that
	// generated the failure message. Position zero is the sender node. This
	// field will be populated when the failure reason is either
	// HTLCFailMessage or HTLCFailUnknown.
	FailureSourceIndex uint32
}

HTLCFailInfo encapsulates the information that augments an HTLCAttempt in the event that the HTLC fails.

type HTLCFailReason

type HTLCFailReason byte

HTLCFailReason is the reason an htlc failed.

const (
	// HTLCFailUnknown is recorded for htlcs that failed with an unknown
	// reason.
	HTLCFailUnknown HTLCFailReason = 0

	// HTLCFailUnknown is recorded for htlcs that had a failure message that
	// couldn't be decrypted.
	HTLCFailUnreadable HTLCFailReason = 1

	// HTLCFailInternal is recorded for htlcs that failed because of an
	// internal error.
	HTLCFailInternal HTLCFailReason = 2

	// HTLCFailMessage is recorded for htlcs that failed with a network
	// failure message.
	HTLCFailMessage HTLCFailReason = 3
)

type HTLCSettleInfo

type HTLCSettleInfo struct {
	// Preimage is the preimage of a successful HTLC. This serves as a proof
	// of payment.
	Preimage lntypes.Preimage

	// SettleTime is the time at which this HTLC was settled.
	SettleTime time.Time
}

HTLCSettleInfo encapsulates the information that augments an HTLCAttempt in the event that the HTLC is successful.

type HtlcAcceptDesc

type HtlcAcceptDesc struct {
	// AcceptHeight is the block height at which this htlc was accepted.
	AcceptHeight int32

	// Amt is the amount that is carried by this htlc.
	Amt lnwire.MilliSatoshi

	// MppTotalAmt is a field for mpp that indicates the expected total
	// amount.
	MppTotalAmt lnwire.MilliSatoshi

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

	// CustomRecords contains the custom key/value pairs that accompanied
	// the htlc.
	CustomRecords record.CustomSet
}

HtlcAcceptDesc describes the details of a newly accepted htlc.

type HtlcState

type HtlcState uint8

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

const (
	// HtlcStateAccepted indicates the htlc is locked-in, but not resolved.
	HtlcStateAccepted HtlcState = iota

	// HtlcStateCanceled indicates the htlc is canceled back to the
	// sender.
	HtlcStateCanceled

	// HtlcStateSettled indicates the htlc is settled.
	HtlcStateSettled
)

type InFlightPayment

type InFlightPayment struct {
	// Info is the PaymentCreationInfo of the in-flight payment.
	Info *PaymentCreationInfo

	// Attempts is the set of payment attempts that was made to this
	// payment hash.
	//
	// NOTE: Might be empty.
	Attempts []HTLCAttemptInfo
}

InFlightPayment is a wrapper around a payment that has status InFlight.

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

	// PaymentRequest is the encoded payment request for this invoice. For
	// spontaneous (keysend) payments, this field will be empty.
	PaymentRequest []byte

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

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

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

func (*Invoice) IsPending

func (i *Invoice) IsPending() bool

IsPending returns ture if the invoice is in ContractOpen state.

type InvoiceHTLC

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

	// MppTotalAmt is a field for mpp that indicates the expected total
	// amount.
	MppTotalAmt 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

	// CustomRecords contains the custom key/value pairs that accompanied
	// the htlc.
	CustomRecords record.CustomSet
}

InvoiceHTLC contains details about an htlc paying to this invoice.

type InvoiceQuery

type InvoiceQuery struct {
	// IndexOffset is the offset within the add indices to start at. This
	// can be used to start the response at a particular invoice.
	IndexOffset uint64

	// NumMaxInvoices is the maximum number of invoices that should be
	// starting from the add index.
	NumMaxInvoices uint64

	// PendingOnly, if set, returns unsettled invoices starting from the
	// add index.
	PendingOnly bool

	// Reversed, if set, indicates that the invoices returned should start
	// from the IndexOffset and go backwards.
	Reversed bool
}

InvoiceQuery represents a query to the invoice database. The query allows a caller to retrieve all invoices starting from a particular add index and limit the number of results returned.

type InvoiceSlice

type InvoiceSlice struct {
	InvoiceQuery

	// Invoices is the set of invoices that matched the query above.
	Invoices []Invoice

	// FirstIndexOffset is the index of the first element in the set of
	// returned Invoices above. Callers can use this to resume their query
	// in the event that the slice has too many events to fit into a single
	// response.
	FirstIndexOffset uint64

	// LastIndexOffset is the index of the last element in the set of
	// returned Invoices above. Callers can use this to resume their query
	// in the event that the slice has too many events to fit into a single
	// response.
	LastIndexOffset uint64
}

InvoiceSlice is the response to a invoice query. It includes the original query, the set of invoices that match the query, and an integer which represents the offset index of the last item in the set of returned invoices. This integer allows callers to resume their query using this offset in the event that the query's response exceeds the maximum number of returnable invoices.

type InvoiceStateUpdateDesc

type InvoiceStateUpdateDesc struct {
	// NewState is the new state that this invoice should progress to.
	NewState ContractState

	// Preimage must be set to the preimage when NewState is settled.
	Preimage lntypes.Preimage
}

InvoiceStateUpdateDesc describes an invoice-level state transition.

type InvoiceUpdateCallback

type InvoiceUpdateCallback = func(invoice *Invoice) (*InvoiceUpdateDesc, error)

InvoiceUpdateCallback is a callback used in the db transaction to update the invoice.

type InvoiceUpdateDesc

type InvoiceUpdateDesc struct {
	// State is the new state that this invoice should progress to. If nil,
	// the state is left unchanged.
	State *InvoiceStateUpdateDesc

	// CancelHtlcs describes the htlcs that need to be canceled.
	CancelHtlcs map[CircuitKey]struct{}

	// AddHtlcs describes the newly accepted htlcs that need to be added to
	// the invoice.
	AddHtlcs map[CircuitKey]*HtlcAcceptDesc
}

InvoiceUpdateDesc describes the changes that should be applied to the invoice.

type InvoiceWithPaymentHash

type InvoiceWithPaymentHash struct {
	// Invoice holds the invoice as selected from the invoices bucket.
	Invoice Invoice

	// PaymentHash is the payment hash for the Invoice.
	PaymentHash lntypes.Hash
}

InvoiceWithPaymentHash is used to store an invoice and its corresponding payment hash. This struct is only used to store results of ChannelDB.FetchAllInvoicesWithPaymentHash() call.

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

func (l *LightningNode) AddPubKey(key *btcec.PublicKey)

AddPubKey is a setter-link method that can be used to swap out the public key for a node.

func (*LightningNode) AuthSig

func (l *LightningNode) AuthSig() (*btcec.Signature, error)

AuthSig is a signature under the advertised public key which serves to authenticate the attributes announced by this node.

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

func (*LightningNode) ForEachChannel

ForEachChannel iterates through all channels of this 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 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 (*LightningNode) NodeAnnouncement

func (l *LightningNode) NodeAnnouncement(signed bool) (*lnwire.NodeAnnouncement,
	error)

NodeAnnouncement retrieves the latest node announcement of the node.

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 LinkNode

type LinkNode struct {
	// Network indicates the Bitcoin network that the LinkNode advertises
	// for incoming channel creation.
	Network wire.BitcoinNet

	// IdentityPub is the node's current identity public key. Any
	// channel/topology related information received by this node MUST be
	// signed by this public key.
	IdentityPub *btcec.PublicKey

	// LastSeen tracks the last time this node was seen within the network.
	// A node should be marked as seen if the daemon either is able to
	// establish an outgoing connection to the node or receives a new
	// incoming connection from the node. This timestamp (stored in unix
	// epoch) may be used within a heuristic which aims to determine when a
	// channel should be unilaterally closed due to inactivity.
	//
	// TODO(roasbeef): replace with block hash/height?
	//  * possibly add a time-value metric into the heuristic?
	LastSeen time.Time

	// Addresses is a list of IP address in which either we were able to
	// reach the node over in the past, OR we received an incoming
	// authenticated connection for the stored identity public key.
	Addresses []net.Addr
	// contains filtered or unexported fields
}

LinkNode stores metadata related to node's that we have/had a direct channel open with. Information such as the Bitcoin network the node advertised, and its identity public key are also stored. Additionally, this struct and the bucket its stored within have store data similar to that of Bitcoin's addrmanager. The TCP address information stored within the struct can be used to establish persistent connections will all channel counterparties on daemon startup.

TODO(roasbeef): also add current OnionKey plus rotation schedule? TODO(roasbeef): add bitfield for supported services

  • possibly add a wire.NetAddress type, type

func (*LinkNode) AddAddress

func (l *LinkNode) AddAddress(addr net.Addr) error

AddAddress appends the specified TCP address to the list of known addresses this node is/was known to be reachable at.

func (*LinkNode) Sync

func (l *LinkNode) Sync() error

Sync performs a full database sync which writes the current up-to-date data within the struct to the database.

func (*LinkNode) UpdateLastSeen

func (l *LinkNode) UpdateLastSeen(lastSeen time.Time) error

UpdateLastSeen updates the last time this node was directly encountered on the Lightning Network.

type LogUpdate

type LogUpdate struct {
	// LogIndex is the log index of this proposed commitment update entry.
	LogIndex uint64

	// UpdateMsg is the update message that was included within the our
	// local update log. The LogIndex value denotes the log index of this
	// update which will be used when restoring our local update log if
	// we're left with a dangling update on restart.
	UpdateMsg lnwire.Message
}

LogUpdate represents a pending update to the remote commitment chain. The log update may be an add, fail, or settle entry. We maintain this data in order to be able to properly retransmit our proposed state if necessary.

func (*LogUpdate) Decode

func (l *LogUpdate) Decode(r io.Reader) error

Decode reads a log update from the provided io.Reader.

func (*LogUpdate) Encode

func (l *LogUpdate) Encode(w io.Writer) error

Encode writes a log update to the provided io.Writer.

type MPPayment

type MPPayment struct {
	// SequenceNum is a unique identifier used to sort the payments in
	// order of creation.
	SequenceNum uint64

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

	// HTLCs holds the information about individual HTLCs that we send in
	// order to make the payment.
	HTLCs []HTLCAttempt

	// FailureReason is the failure reason code indicating the reason the
	// payment failed.
	//
	// NOTE: Will only be set once the daemon has given up on the payment
	// altogether.
	FailureReason *FailureReason

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

MPPayment is a wrapper around a payment's PaymentCreationInfo and HTLCAttempts. All payments will have the PaymentCreationInfo set, any HTLCs made in attempts to be completed will populated in the HTLCs slice. Each populated HTLCAttempt represents an attempted HTLC, each of which may have the associated Settle or Fail struct populated if the HTLC is no longer in-flight.

func (*MPPayment) InFlightHTLCs

func (m *MPPayment) InFlightHTLCs() []HTLCAttempt

InFlightHTLCs returns the HTLCs that are still in-flight, meaning they have not been settled or failed.

func (*MPPayment) SentAmt

SentAmt returns the sum of sent amount and fees for HTLCs that are either settled or still in flight.

func (*MPPayment) TerminalInfo

func (m *MPPayment) TerminalInfo() (*HTLCSettleInfo, *FailureReason)

TerminalInfo returns any HTLC settle info recorded. If no settle info is recorded, any payment level failure will be returned. If neither a settle nor a failure is recorded, both return values will be nil.

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

	// Packager is used to create and update forwarding packages for this
	// channel, which encodes all necessary information to recover from
	// failures and reforward HTLCs that were not fully processed.
	Packager FwdPackager

	// 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, and that we also have the funding
	// transaction for. One can check this by using the HasFundingTx()
	// method on the ChanType field.
	FundingTxn *wire.MsgTx

	// LocalShutdownScript is set to a pre-set script if the channel was opened
	// by the local node with option_upfront_shutdown_script set. If the option
	// was not set, the field is empty.
	LocalShutdownScript lnwire.DeliveryAddress

	// RemoteShutdownScript is set to a pre-set script if the channel was opened
	// by the remote node with option_upfront_shutdown_script set. If the option
	// was not set, the field is empty.
	RemoteShutdownScript lnwire.DeliveryAddress

	// ThawHeight is the height when a frozen channel once again becomes a
	// normal channel. If this is zero, then there're no restrictions on
	// this channel.
	ThawHeight uint32

	// TODO(roasbeef): eww
	Db *DB

	sync.RWMutex
	// contains filtered or unexported fields
}

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

func (c *OpenChannel) AckAddHtlcs(addRefs ...AddRef) error

AckAddHtlcs updates the AckAddFilter containing any of the provided AddRefs indicating that a response to this Add has been committed to the remote party. Doing so will prevent these Add HTLCs from being reforwarded internally.

func (*OpenChannel) AckSettleFails

func (c *OpenChannel) AckSettleFails(settleFailRefs ...SettleFailRef) error

AckSettleFails updates the SettleFailFilter containing any of the provided SettleFailRefs, indicating that the response has been delivered to the incoming link, corresponding to a particular AddRef. Doing so will prevent the responses from being retransmitted internally.

func (*OpenChannel) ActiveHtlcs

func (c *OpenChannel) ActiveHtlcs() []HTLC

ActiveHtlcs returns a slice of HTLC's which are currently active on *both* commitment transactions.

func (*OpenChannel) AdvanceCommitChainTail

func (c *OpenChannel) AdvanceCommitChainTail(fwdPkg *FwdPkg) error

AdvanceCommitChainTail records the new state transition within an on-disk append-only log which records all state transitions by the remote peer. In the case of an uncooperative broadcast of a prior state by the remote peer, this log can be consulted in order to reconstruct the state needed to rectify the situation. This method will add the current commitment for the remote party to the revocation log, and promote the current pending commitment to the current remote commitment.

func (*OpenChannel) AppendRemoteCommitChain

func (c *OpenChannel) AppendRemoteCommitChain(diff *CommitDiff) error

AppendRemoteCommitChain appends a new CommitDiff to the end of the commitment chain for the remote party. This method is to be used once we have prepared a new commitment state for the remote party, but before we transmit it to the remote party. The contents of the argument should be sufficient to retransmit the updates and signature needed to reconstruct the state in full, in the case that we need to retransmit.

func (*OpenChannel) ApplyChanStatus

func (c *OpenChannel) ApplyChanStatus(status ChannelStatus) error

ApplyChanStatus allows the caller to modify the internal channel state in a thead-safe manner.

func (*OpenChannel) BalancesAtHeight

func (c *OpenChannel) BalancesAtHeight(height uint64) (lnwire.MilliSatoshi,
	lnwire.MilliSatoshi, error)

BalancesAtHeight returns the local and remote balances on our commitment transactions as of a given height.

NOTE: these are our balances *after* subtracting the commitment fee and anchor outputs.

func (*OpenChannel) BroadcastedCommitment

func (c *OpenChannel) BroadcastedCommitment() (*wire.MsgTx, error)

BroadcastedCommitment retrieves the stored unilateral closing tx set during MarkCommitmentBroadcasted. If not found ErrNoCloseTx is returned.

func (*OpenChannel) BroadcastedCooperative

func (c *OpenChannel) BroadcastedCooperative() (*wire.MsgTx, error)

BroadcastedCooperative retrieves the stored cooperative closing tx set during MarkCoopBroadcasted. If not found ErrNoCloseTx is returned.

func (*OpenChannel) ChanStatus

func (c *OpenChannel) ChanStatus() ChannelStatus

ChanStatus returns the current ChannelStatus of this channel.

func (*OpenChannel) ChanSyncMsg

func (c *OpenChannel) ChanSyncMsg() (*lnwire.ChannelReestablish, error)

ChanSyncMsg returns the ChannelReestablish message that should be sent upon reconnection with the remote peer that we're maintaining this channel with. The information contained within this message is necessary to re-sync our commitment chains in the case of a last or only partially processed message. When the remote party receiver this message one of three things may happen:

  1. We're fully synced and no messages need to be sent.
  2. We didn't get the last CommitSig message they sent, to they'll re-send it.
  3. We didn't get the last RevokeAndAck message they sent, so they'll re-send it.

If this is a restored channel, having status ChanStatusRestored, then we'll modify our typical chan sync message to ensure they force close even if we're on the very first state.

func (*OpenChannel) ClearChanStatus

func (c *OpenChannel) ClearChanStatus(status ChannelStatus) error

ClearChanStatus allows the caller to clear a particular channel status from the primary channel status bit field. After this method returns, a call to HasChanStatus(status) should return false.

func (*OpenChannel) CloseChannel

func (c *OpenChannel) CloseChannel(summary *ChannelCloseSummary,
	statuses ...ChannelStatus) error

CloseChannel closes a previously active Lightning channel. Closing a channel entails deleting all saved state within the database concerning this channel. This method also takes a struct that summarizes the state of the channel at closing, this compact representation will be the only component of a channel left over after a full closing. It takes an optional set of channel statuses which will be written to the historical channel bucket. These statuses are used to record close initiators.

func (*OpenChannel) CommitmentHeight

func (c *OpenChannel) CommitmentHeight() (uint64, error)

CommitmentHeight returns the current commitment height. The commitment height represents the number of updates to the commitment state to date. This value is always monotonically increasing. This method is provided in order to allow multiple instances of a particular open channel to obtain a consistent view of the number of channel updates to date.

func (*OpenChannel) DataLossCommitPoint

func (c *OpenChannel) DataLossCommitPoint() (*btcec.PublicKey, error)

DataLossCommitPoint retrieves the stored commit point set during MarkDataLoss. If not found ErrNoCommitPoint is returned.

func (*OpenChannel) FindPreviousState

func (c *OpenChannel) FindPreviousState(updateNum uint64) (*ChannelCommitment, error)

FindPreviousState scans through the append-only log in an attempt to recover the previous channel state indicated by the update number. This method is intended to be used for obtaining the relevant data needed to claim all funds rightfully spendable in the case of an on-chain broadcast of the commitment transaction.

func (*OpenChannel) HasChanStatus

func (c *OpenChannel) HasChanStatus(status ChannelStatus) bool

HasChanStatus returns true if the internal bitfield channel status of the target channel has the specified status bit set.

func (*OpenChannel) InsertNextRevocation

func (c *OpenChannel) InsertNextRevocation(revKey *btcec.PublicKey) error

InsertNextRevocation inserts the _next_ commitment point (revocation) into the database, and also modifies the internal RemoteNextRevocation attribute to point to the passed key. This method is to be using during final channel set up, _after_ the channel has been fully confirmed.

NOTE: If this method isn't called, then the target channel won't be able to propose new states for the commitment state of the remote party.

func (*OpenChannel) LatestCommitments

func (c *OpenChannel) LatestCommitments() (*ChannelCommitment, *ChannelCommitment, error)

LatestCommitments returns the two latest commitments for both the local and remote party. These commitments are read from disk to ensure that only the latest fully committed state is returned. The first commitment returned is the local commitment, and the second returned is the remote commitment.

func (*OpenChannel) LoadFwdPkgs

func (c *OpenChannel) LoadFwdPkgs() ([]*FwdPkg, error)

LoadFwdPkgs scans the forwarding log for any packages that haven't been processed, and returns their deserialized log updates in map indexed by the remote commitment height at which the updates were locked in.

func (*OpenChannel) MarkAsOpen

func (c *OpenChannel) MarkAsOpen(openLoc lnwire.ShortChannelID) error

MarkAsOpen marks a channel as fully open given a locator that uniquely describes its location within the chain.

func (*OpenChannel) MarkBorked

func (c *OpenChannel) MarkBorked() error

MarkBorked marks the event when the channel as reached an irreconcilable state, such as a channel breach or state desynchronization. Borked channels should never be added to the switch.

func (*OpenChannel) MarkCommitmentBroadcasted

func (c *OpenChannel) MarkCommitmentBroadcasted(closeTx *wire.MsgTx,
	locallyInitiated bool) error

MarkCommitmentBroadcasted marks the channel as a commitment transaction has been broadcast, either our own or the remote, and we should watch the chain for it to confirm before taking any further action. It takes as argument the closing tx _we believe_ will appear in the chain. This is only used to republish this tx at startup to ensure propagation, and we should still handle the case where a different tx actually hits the chain.

func (*OpenChannel) MarkCoopBroadcasted

func (c *OpenChannel) MarkCoopBroadcasted(closeTx *wire.MsgTx,
	locallyInitiated bool) error

MarkCoopBroadcasted marks the channel to indicate that a cooperative close transaction has been broadcast, either our own or the remote, and that we should watch the chain for it to confirm before taking further action. It takes as argument a cooperative close tx that could appear on chain, and should be rebroadcast upon startup. This is only used to republish and ensure propagation, and we should still handle the case where a different tx actually hits the chain.

func (*OpenChannel) MarkDataLoss

func (c *OpenChannel) MarkDataLoss(commitPoint *btcec.PublicKey) error

MarkDataLoss marks sets the channel status to LocalDataLoss and stores the passed commitPoint for use to retrieve funds in case the remote force closes the channel.

func (*OpenChannel) NextLocalHtlcIndex

func (c *OpenChannel) NextLocalHtlcIndex() (uint64, error)

NextLocalHtlcIndex returns the next unallocated local htlc index. To ensure this always returns the next index that has been not been allocated, this will first try to examine any pending commitments, before falling back to the last locked-in remote commitment.

func (*OpenChannel) RefreshShortChanID

func (c *OpenChannel) RefreshShortChanID() error

RefreshShortChanID updates the in-memory channel state using the latest value observed on disk.

TODO: the name of this function should be changed to reflect the fact that it is not only refreshing the short channel id but all the channel state. maybe Refresh/Reload?

func (*OpenChannel) RemoteCommitChainTip

func (c *OpenChannel) RemoteCommitChainTip() (*CommitDiff, error)

RemoteCommitChainTip returns the "tip" of the current remote commitment chain. This value will be non-nil iff, we've created a new commitment for the remote party that they haven't yet ACK'd. In this case, their commitment chain will have a length of two: their current unrevoked commitment, and this new pending commitment. Once they revoked their prior state, we'll swap these pointers, causing the tip and the tail to point to the same entry.

func (*OpenChannel) RemoteRevocationStore

func (c *OpenChannel) RemoteRevocationStore() (shachain.Store, error)

RemoteRevocationStore returns the most up to date commitment version of the revocation storage tree for the remote party. This method can be used when acting on a possible contract breach to ensure, that the caller has the most up to date information required to deliver justice.

func (*OpenChannel) RemoveFwdPkg

func (c *OpenChannel) RemoveFwdPkg(height uint64) error

RemoveFwdPkg atomically removes a forwarding package specified by the remote commitment height.

NOTE: This method should only be called on packages marked FwdStateCompleted.

func (*OpenChannel) RevocationLogTail

func (c *OpenChannel) RevocationLogTail() (*ChannelCommitment, error)

RevocationLogTail returns the "tail", or the end of the current revocation log. This entry represents the last previous state for the remote node's commitment chain. The ChannelDelta returned by this method will always lag one state behind the most current (unrevoked) state of the remote node's commitment chain.

func (*OpenChannel) SetFwdFilter

func (c *OpenChannel) SetFwdFilter(height uint64, fwdFilter *PkgFilter) error

SetFwdFilter atomically sets the forwarding filter for the forwarding package identified by `height`.

func (*OpenChannel) ShortChanID

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

ShortChanID returns the current ShortChannelID of this channel.

func (*OpenChannel) Snapshot

func (c *OpenChannel) Snapshot() *ChannelSnapshot

Snapshot returns a read-only snapshot of the current channel state. This snapshot includes information concerning the current settled balance within the channel, metadata detailing total flows, and any outstanding HTLCs.

func (*OpenChannel) SyncPending

func (c *OpenChannel) SyncPending(addr net.Addr, pendingHeight uint32) error

SyncPending writes the contents of the channel to the database while it's in the pending (waiting for funding confirmation) state. The IsPending flag will be set to true. When the channel's funding transaction is confirmed, the channel should be marked as "open" and the IsPending flag set to false. Note that this function also creates a LinkNode relationship between this newly created channel and a new LinkNode instance. This allows listing all channels in the database globally, or according to the LinkNode they were created with.

TODO(roasbeef): addr param should eventually be an lnwire.NetAddress type that includes service bits.

func (*OpenChannel) UnsignedAckedUpdates

func (c *OpenChannel) UnsignedAckedUpdates() ([]LogUpdate, error)

UnsignedAckedUpdates retrieves the persisted unsigned acked remote log updates that still need to be signed for.

func (*OpenChannel) UpdateCommitment

func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment,
	unsignedAckedUpdates []LogUpdate) error

UpdateCommitment updates the local commitment state. It locks in the pending local updates that were received by us from the remote party. The commitment state completely describes the balance state at this point in the commitment chain. In addition to that, it persists all the remote log updates that we have acked, but not signed a remote commitment for yet. These need to be persisted to be able to produce a valid commit signature if a restart would occur. This method its to be called when we revoke our prior commitment state.

type OptionModifier

type OptionModifier func(*Options)

OptionModifier is a function signature for modifying the default Options.

func OptionClock

func OptionClock(clock clock.Clock) OptionModifier

OptionClock sets a non-default clock dependency.

func OptionDryRunMigration

func OptionDryRunMigration(dryRun bool) OptionModifier

OptionDryRunMigration controls whether or not to intentially fail to commit a successful migration that occurs when opening the database.

func OptionSetChannelCacheSize

func OptionSetChannelCacheSize(n int) OptionModifier

OptionSetChannelCacheSize sets the ChannelCacheSize to n.

func OptionSetRejectCacheSize

func OptionSetRejectCacheSize(n int) OptionModifier

OptionSetRejectCacheSize sets the RejectCacheSize to n.

func OptionSetSyncFreelist

func OptionSetSyncFreelist(b bool) OptionModifier

OptionSetSyncFreelist allows the database to sync its freelist.

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
	// contains filtered or unexported fields
}

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

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns an Options populated with default values.

type PaymentControl

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

PaymentControl implements persistence for payments and payment attempts.

func NewPaymentControl

func NewPaymentControl(db *DB) *PaymentControl

NewPaymentControl creates a new instance of the PaymentControl.

func (*PaymentControl) Fail

func (p *PaymentControl) Fail(paymentHash lntypes.Hash,
	reason FailureReason) (*MPPayment, error)

Fail transitions a payment into the Failed state, and records the reason the payment failed. After invoking this method, InitPayment should return nil on its next call for this payment hash, allowing the switch to make a subsequent payment.

func (*PaymentControl) FailAttempt

func (p *PaymentControl) FailAttempt(hash lntypes.Hash,
	attemptID uint64, failInfo *HTLCFailInfo) (*MPPayment, error)

FailAttempt marks the given payment attempt failed.

func (*PaymentControl) FetchInFlightPayments

func (p *PaymentControl) FetchInFlightPayments() ([]*InFlightPayment, error)

FetchInFlightPayments returns all payments with status InFlight.

func (*PaymentControl) FetchPayment

func (p *PaymentControl) FetchPayment(paymentHash lntypes.Hash) (
	*MPPayment, error)

FetchPayment returns information about a payment from the database.

func (*PaymentControl) InitPayment

func (p *PaymentControl) InitPayment(paymentHash lntypes.Hash,
	info *PaymentCreationInfo) error

InitPayment checks or records the given PaymentCreationInfo with the DB, making sure it does not already exist as an in-flight payment. When this method returns successfully, the payment is guranteeed to be in the InFlight state.

func (*PaymentControl) RegisterAttempt

func (p *PaymentControl) RegisterAttempt(paymentHash lntypes.Hash,
	attempt *HTLCAttemptInfo) (*MPPayment, error)

RegisterAttempt atomically records the provided HTLCAttemptInfo to the DB.

func (*PaymentControl) SettleAttempt

func (p *PaymentControl) SettleAttempt(hash lntypes.Hash,
	attemptID uint64, settleInfo *HTLCSettleInfo) (*MPPayment, error)

SettleAttempt marks the given attempt settled with the preimage. If this is a multi shard payment, this might implicitly mean that the full payment succeeded.

After invoking this method, InitPayment should always return an error to prevent us from making duplicate payments to the same payment hash. The provided preimage is atomically saved to the DB for record keeping.

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

	// CreationTime is the time when this payment was initiated.
	CreationTime 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) String

func (ps PaymentStatus) String() string

String returns readable representation of payment status.

type PaymentsQuery

type PaymentsQuery struct {
	// IndexOffset determines the starting point of the payments query and
	// is always exclusive. In normal order, the query starts at the next
	// higher (available) index compared to IndexOffset. In reversed order,
	// the query ends at the next lower (available) index compared to the
	// IndexOffset. In the case of a zero index_offset, the query will start
	// with the oldest payment when paginating forwards, or will end with
	// the most recent payment when paginating backwards.
	IndexOffset uint64

	// MaxPayments is the maximal number of payments returned in the
	// payments query.
	MaxPayments uint64

	// Reversed gives a meaning to the IndexOffset. If reversed is set to
	// true, the query will fetch payments with indices lower than the
	// IndexOffset, otherwise, it will return payments with indices greater
	// than the IndexOffset.
	Reversed bool

	// If IncludeIncomplete is true, then return payments that have not yet
	// fully completed. This means that pending payments, as well as failed
	// payments will show up if this field is set to true.
	IncludeIncomplete bool
}

PaymentsQuery represents a query to the payments database starting or ending at a certain offset index. The number of retrieved records can be limited.

type PaymentsResponse

type PaymentsResponse struct {
	// Payments is the set of payments returned from the database for the
	// PaymentsQuery.
	Payments []*MPPayment

	// FirstIndexOffset is the index of the first element in the set of
	// returned MPPayments. Callers can use this to resume their query
	// in the event that the slice has too many events to fit into a single
	// response. The offset can be used to continue reverse pagination.
	FirstIndexOffset uint64

	// LastIndexOffset is the index of the last element in the set of
	// returned MPPayments. Callers can use this to resume their query
	// in the event that the slice has too many events to fit into a single
	// response. The offset can be used to continue forward pagination.
	LastIndexOffset uint64
}

PaymentsResponse contains the result of a query to the payments database. It includes the set of payments that match the query and integers which represent the index of the first and last item returned in the series of payments. These integers allow callers to resume their query in the event that the query's response exceeds the max number of returnable events.

type PkgFilter

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

PkgFilter is used to compactly represent a particular subset of the Adds in a forwarding package. Each filter is represented as a simple, statically-sized bitvector, where the elements are intended to be the indices of the Adds as they are written in the FwdPkg.

func NewPkgFilter

func NewPkgFilter(count uint16) *PkgFilter

NewPkgFilter initializes an empty PkgFilter supporting `count` elements.

func (*PkgFilter) Contains

func (f *PkgFilter) Contains(i uint16) bool

Contains queries the filter for membership of index `i`. NOTE: It is assumed that i is always less than count.

func (*PkgFilter) Count

func (f *PkgFilter) Count() uint16

Count returns the number of elements represented by this PkgFilter.

func (*PkgFilter) Decode

func (f *PkgFilter) Decode(r io.Reader) error

Decode reads the filter from the provided io.Reader.

func (*PkgFilter) Encode

func (f *PkgFilter) Encode(w io.Writer) error

Encode writes the filter to the provided io.Writer.

func (*PkgFilter) Equal

func (f *PkgFilter) Equal(f2 *PkgFilter) bool

Equal checks two PkgFilters for equality.

func (*PkgFilter) IsFull

func (f *PkgFilter) IsFull() bool

IsFull returns true if every element in the filter has been Set, and false otherwise.

func (*PkgFilter) Set

func (f *PkgFilter) Set(i uint16)

Set marks the `i`-th element as included by this filter. NOTE: It is assumed that i is always less than count.

func (*PkgFilter) Size

func (f *PkgFilter) Size() uint16

Size returns number of bytes produced when the PkgFilter is serialized.

type SettleFailAcker

type SettleFailAcker interface {
	// AckSettleFails atomically updates the settle-fail filters in *other*
	// channels' forwarding packages.
	AckSettleFails(tx kvdb.RwTx, settleFailRefs ...SettleFailRef) error
}

SettleFailAcker is a generic interface providing the ability to acknowledge settle/fail HTLCs stored in forwarding packages.

type SettleFailRef

type SettleFailRef struct {
	// Source identifies the outgoing link that locked in the settle or
	// fail. This is then used by the *incoming* link to find the settle
	// fail in another link's forwarding packages.
	Source lnwire.ShortChannelID

	// Height is the remote commitment height that locked in this
	// Settle/Fail.
	Height uint64

	// Index is the index of the Add with the fwd pkg's SettleFails.
	//
	// NOTE: This index is static over the lifetime of a forwarding package.
	Index uint16
}

SettleFailRef is used to locate a Settle/Fail in another channel's FwdPkg. A channel does not remove its own Settle/Fail htlcs, so the source is provided to locate a db bucket belonging to another channel.

type SwitchPackager

type SwitchPackager struct{}

SwitchPackager is a concrete implementation of the FwdOperator interface. A SwitchPackager offers the ability to read any forwarding package, and ack arbitrary settle and fail HTLCs.

func NewSwitchPackager

func NewSwitchPackager() *SwitchPackager

NewSwitchPackager instantiates a new SwitchPackager.

func (*SwitchPackager) AckSettleFails

func (*SwitchPackager) AckSettleFails(tx kvdb.RwTx,
	settleFailRefs ...SettleFailRef) error

AckSettleFails atomically updates the settle-fail filters in *other* channels' forwarding packages, to mark that the switch has received a settle or fail residing in the forwarding package of a link.

func (*SwitchPackager) LoadChannelFwdPkgs

func (*SwitchPackager) LoadChannelFwdPkgs(tx kvdb.RwTx,
	source lnwire.ShortChannelID) ([]*FwdPkg, error)

LoadChannelFwdPkgs loads all forwarding packages for a particular channel.

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 NewUnknownElementType

func NewUnknownElementType(method string, el interface{}) UnknownElementType

NewUnknownElementType creates a new UnknownElementType error from the passed method name and element.

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 WaitingProof

type WaitingProof struct {
	*lnwire.AnnounceSignatures
	// contains filtered or unexported fields
}

WaitingProof is the storable object, which encapsulate the half proof and the information about from which side this proof came. This structure is needed to make channel proof exchange persistent, so that after client restart we may receive remote/local half proof and process it.

func NewWaitingProof

func NewWaitingProof(isRemote bool, proof *lnwire.AnnounceSignatures) *WaitingProof

NewWaitingProof constructs a new waiting prof instance.

func (*WaitingProof) Decode

func (p *WaitingProof) Decode(r io.Reader) error

Decode reads the data from the byte stream and initializes the waiting proof object with it.

func (*WaitingProof) Encode

func (p *WaitingProof) Encode(w io.Writer) error

Encode writes the internal representation of waiting proof in byte stream.

func (*WaitingProof) Key

func (p *WaitingProof) Key() WaitingProofKey

Key returns the key which uniquely identifies waiting proof.

func (*WaitingProof) OppositeKey

func (p *WaitingProof) OppositeKey() WaitingProofKey

OppositeKey returns the key which uniquely identifies opposite waiting proof.

type WaitingProofKey

type WaitingProofKey [9]byte

WaitingProofKey is the proof key which uniquely identifies the waiting proof object. The goal of this key is distinguish the local and remote proof for the same channel id.

type WaitingProofStore

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

WaitingProofStore is the bold db map-like storage for half announcement signatures. The one responsibility of this storage is to be able to retrieve waiting proofs after client restart.

func NewWaitingProofStore

func NewWaitingProofStore(db *DB) (*WaitingProofStore, error)

NewWaitingProofStore creates new instance of proofs storage.

func (*WaitingProofStore) Add

func (s *WaitingProofStore) Add(proof *WaitingProof) error

Add adds new waiting proof in the storage.

func (*WaitingProofStore) ForAll

func (s *WaitingProofStore) ForAll(cb func(*WaitingProof) error) error

ForAll iterates thought all waiting proofs and passing the waiting proof in the given callback.

func (*WaitingProofStore) Get

Get returns the object which corresponds to the given index.

func (*WaitingProofStore) Remove

func (s *WaitingProofStore) Remove(key WaitingProofKey) error

Remove removes the proof from storage by its key.

type WitnessCache

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

WitnessCache is a persistent cache of all witnesses we've encountered on the network. In the case of multi-hop, multi-step contracts, a cache of all witnesses can be useful in the case of partial contract resolution. If negotiations break down, we may be forced to locate the witness for a portion of the contract on-chain. In this case, we'll then add that witness to the cache so the incoming contract can fully resolve witness. Additionally, as one MUST always use a unique witness on the network, we may use this cache to detect duplicate witnesses.

TODO(roasbeef): need expiry policy?

  • encrypt?

func (*WitnessCache) AddSha256Witnesses

func (w *WitnessCache) AddSha256Witnesses(preimages ...lntypes.Preimage) error

AddSha256Witnesses adds a batch of new sha256 preimages into the witness cache. This is an alias for AddWitnesses that uses Sha256HashWitness as the preimages' witness type.

func (*WitnessCache) DeleteSha256Witness

func (w *WitnessCache) DeleteSha256Witness(hash lntypes.Hash) error

DeleteSha256Witness attempts to delete a sha256 preimage identified by hash.

func (*WitnessCache) DeleteWitnessClass

func (w *WitnessCache) DeleteWitnessClass(wType WitnessType) error

DeleteWitnessClass attempts to delete an *entire* class of witnesses. After this function return with a non-nil error,

func (*WitnessCache) LookupSha256Witness

func (w *WitnessCache) LookupSha256Witness(hash lntypes.Hash) (lntypes.Preimage, error)

LookupSha256Witness attempts to lookup the preimage for a sha256 hash. If the witness isn't found, ErrNoWitnesses will be returned.

type WitnessType

type WitnessType uint8

WitnessType is enum that denotes what "type" of witness is being stored/retrieved. As the WitnessCache itself is agnostic and doesn't enforce any structure on added witnesses, we use this type to partition the witnesses on disk, and also to know how to map a witness to its look up key.

var (
	// Sha256HashWitness is a witness that is simply the pre image to a
	// hash image. In order to map to its key, we'll use sha256.
	Sha256HashWitness WitnessType = 1
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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