Documentation
¶
Index ¶
- Constants
- Variables
- func AddMarker(tx kvdb.RwTx, markerKey, markerValue []byte) error
- func CheckMarkerPresent(tx kvdb.RTx, markerKey []byte) ([]byte, error)
- func DKeyLocator(r io.Reader, val interface{}, buf *[8]byte, l uint64) error
- func DeriveMusig2Shachain(revRoot shachain.Producer) (shachain.Producer, error)
- func DisableLog()
- func EKeyLocator(w io.Writer, val interface{}, buf *[8]byte) error
- func EnsureNoTombstone(tx kvdb.RTx) error
- func FetchMeta(meta *Meta, tx kvdb.RTx) error
- func LatestDBVersion() uint32
- func MakeTestInvoiceDB(t *testing.T, modifiers ...OptionModifier) (invoices.InvoiceDB, error)
- func NewMusigVerificationNonce(pubKey *btcec.PublicKey, targetHeight uint64, shaGen shachain.Producer) (*musig2.Nonces, error)
- func NewPaginator(c kvdb.RCursor, reversed bool, indexOffset, totalItems uint64) paginator
- func ReadElement(r io.Reader, element interface{}) error
- func ReadElements(r io.Reader, elements ...interface{}) error
- func SerializeHtlcs(b io.Writer, htlcs ...HTLC) error
- func UseLogger(logger btclog.Logger)
- func WriteElement(w io.Writer, element interface{}) error
- func WriteElements(w io.Writer, elements ...interface{}) error
- type AddRef
- type AddrSource
- type BigSizeAmount
- type BigSizeMilliSatoshi
- type CacheConfig
- type ChanCount
- type ChannelCloseSummary
- type ChannelCommitment
- type ChannelConfig
- type ChannelPackager
- func (p *ChannelPackager) AckAddHtlcs(tx kvdb.RwTx, addRefs ...AddRef) error
- func (p *ChannelPackager) AckSettleFails(tx kvdb.RwTx, settleFailRefs ...SettleFailRef) error
- func (*ChannelPackager) AddFwdPkg(tx kvdb.RwTx, fwdPkg *FwdPkg) error
- func (p *ChannelPackager) LoadFwdPkgs(tx kvdb.RTx) ([]*FwdPkg, error)
- func (p *ChannelPackager) RemovePkg(tx kvdb.RwTx, height uint64) error
- func (p *ChannelPackager) SetFwdFilter(tx kvdb.RwTx, height uint64, fwdFilter *PkgFilter) error
- func (p *ChannelPackager) Wipe(tx kvdb.RwTx) error
- type ChannelShell
- type ChannelSnapshot
- type ChannelStateBounds
- type ChannelStateDB
- func (c *ChannelStateDB) AbandonChannel(chanPoint *wire.OutPoint, bestHeight uint32) error
- func (c *ChannelStateDB) DeleteChannelOpeningState(outPoint []byte) error
- func (c *ChannelStateDB) DeleteInitialForwardingPolicy(chanID lnwire.ChannelID) error
- func (c *ChannelStateDB) FetchAllChannels() ([]*OpenChannel, error)
- func (c *ChannelStateDB) FetchAllOpenChannels() ([]*OpenChannel, error)
- func (c *ChannelStateDB) FetchChannel(chanPoint wire.OutPoint) (*OpenChannel, error)
- func (c *ChannelStateDB) FetchChannelByID(tx kvdb.RTx, id lnwire.ChannelID) (*OpenChannel, error)
- func (c *ChannelStateDB) FetchClosedChannel(chanID *wire.OutPoint) (*ChannelCloseSummary, error)
- func (c *ChannelStateDB) FetchClosedChannelForID(cid lnwire.ChannelID) (*ChannelCloseSummary, error)
- func (c *ChannelStateDB) FetchClosedChannels(pendingOnly bool) ([]*ChannelCloseSummary, error)
- func (c *ChannelStateDB) FetchHistoricalChannel(outPoint *wire.OutPoint) (*OpenChannel, error)
- func (c *ChannelStateDB) FetchOpenChannels(nodeID *btcec.PublicKey) ([]*OpenChannel, error)
- func (c *ChannelStateDB) FetchPendingChannels() ([]*OpenChannel, error)
- func (c *ChannelStateDB) FetchPermAndTempPeers(chainHash []byte) (map[string]ChanCount, error)
- func (c *ChannelStateDB) FetchWaitingCloseChannels() ([]*OpenChannel, error)
- func (c *ChannelStateDB) GetChannelOpeningState(outPoint []byte) ([]byte, error)
- func (c *ChannelStateDB) GetInitialForwardingPolicy(chanID lnwire.ChannelID) (*models.ForwardingPolicy, error)
- func (c *ChannelStateDB) GetParentDB() *DB
- func (c *ChannelStateDB) LinkNodeDB() *LinkNodeDB
- func (c *ChannelStateDB) LookupFinalHtlc(chanID lnwire.ShortChannelID, htlcIndex uint64) (*FinalHtlcInfo, error)
- func (c *ChannelStateDB) MarkChanFullyClosed(chanPoint *wire.OutPoint) error
- func (c *ChannelStateDB) PruneLinkNodes() error
- func (c *ChannelStateDB) PutOnchainFinalHtlcOutcome(chanID lnwire.ShortChannelID, htlcID uint64, settled bool) error
- func (c *ChannelStateDB) RepairLinkNodes(network wire.BitcoinNet) error
- func (c *ChannelStateDB) RestoreChannelShells(channelShells ...*ChannelShell) error
- func (c *ChannelStateDB) SaveChannelOpeningState(outPoint, serializedState []byte) error
- func (c *ChannelStateDB) SaveInitialForwardingPolicy(chanID lnwire.ChannelID, forwardingPolicy *models.ForwardingPolicy) error
- type ChannelStatus
- type ChannelType
- func (c ChannelType) HasAnchors() bool
- func (c ChannelType) HasFundingTx() bool
- func (c ChannelType) HasLeaseExpiration() bool
- func (c ChannelType) HasScidAliasChan() bool
- func (c ChannelType) HasScidAliasFeature() bool
- func (c ChannelType) HasTapscriptRoot() bool
- func (c ChannelType) HasZeroConf() bool
- func (c ChannelType) IsDualFunder() bool
- func (c ChannelType) IsFrozen() bool
- func (c ChannelType) IsSingleFunder() bool
- func (c ChannelType) IsTaproot() bool
- func (c ChannelType) IsTweakless() bool
- func (c ChannelType) ZeroHtlcTxFee() bool
- type ClosureType
- type CommitDiff
- type CommitmentParams
- type DB
- func (d *DB) AddInvoice(_ context.Context, newInvoice *invpkg.Invoice, paymentHash lntypes.Hash) (uint64, error)
- func (d *DB) AddrsForNode(_ context.Context, nodePub *btcec.PublicKey) (bool, []net.Addr, error)
- func (d *DB) ChannelStateDB() *ChannelStateDB
- func (d *DB) DeleteCanceledInvoices(_ context.Context) error
- func (d *DB) DeleteInvoice(_ context.Context, invoicesToDelete []invpkg.InvoiceDeleteRef) error
- func (d DB) FetchChannelReports(chainHash chainhash.Hash, outPoint *wire.OutPoint) ([]*ResolverReport, error)
- func (d *DB) FetchMeta() (*Meta, error)
- func (d *DB) FetchPendingInvoices(_ context.Context) (map[lntypes.Hash]invpkg.Invoice, error)
- func (d *DB) ForwardingLog() *ForwardingLog
- func (d *DB) GetInvoiceBucketTombstone() (bool, error)
- func (d *DB) InvoicesAddedSince(_ context.Context, sinceAddIndex uint64) ([]invpkg.Invoice, error)
- func (d *DB) InvoicesSettledSince(_ context.Context, sinceSettleIndex uint64) ([]invpkg.Invoice, error)
- func (d *DB) LookupInvoice(_ context.Context, ref invpkg.InvoiceRef) (invpkg.Invoice, error)
- func (d *DB) NewWitnessCache() *WitnessCache
- func (d *DB) Path() string
- func (d *DB) PutMeta(meta *Meta) error
- func (d *DB) PutResolverReport(tx kvdb.RwTx, chainHash chainhash.Hash, channelOutpoint *wire.OutPoint, ...) error
- func (d *DB) QueryInvoices(_ context.Context, q invpkg.InvoiceQuery) (invpkg.InvoiceSlice, error)
- func (d *DB) ReadFlapCount(pubkey route.Vertex) (*FlapCount, error)
- func (d *DB) SetInvoiceBucketTombstone() error
- func (d *DB) UpdateInvoice(_ context.Context, ref invpkg.InvoiceRef, setIDHint *invpkg.SetID, ...) (*invpkg.Invoice, error)
- func (d *DB) Wipe() error
- func (d *DB) WriteFlapCounts(flapCounts map[route.Vertex]*FlapCount) error
- type FinalHtlcByte
- type FinalHtlcInfo
- type FlapCount
- type ForwardingEvent
- type ForwardingEventQuery
- type ForwardingLog
- type ForwardingLogTimeSlice
- type FwdOperator
- type FwdPackager
- type FwdPkg
- type FwdState
- type GlobalFwdPkgReader
- type HTLC
- type HTLCEntry
- type HeightHintCache
- func (c *HeightHintCache) CommitConfirmHint(height uint32, confRequests ...chainntnfs.ConfRequest) error
- func (c *HeightHintCache) CommitSpendHint(height uint32, spendRequests ...chainntnfs.SpendRequest) error
- func (c *HeightHintCache) PurgeConfirmHint(confRequests ...chainntnfs.ConfRequest) error
- func (c *HeightHintCache) PurgeSpendHint(spendRequests ...chainntnfs.SpendRequest) error
- func (c *HeightHintCache) QueryConfirmHint(confRequest chainntnfs.ConfRequest) (uint32, error)
- func (c *HeightHintCache) QuerySpendHint(spendRequest chainntnfs.SpendRequest) (uint32, error)
- type LinkNode
- type LinkNodeDB
- func (l *LinkNodeDB) CreateLinkNodes(tx kvdb.RwTx, linkNodes []*LinkNode) error
- func (l *LinkNodeDB) DeleteLinkNode(identity *btcec.PublicKey) error
- func (l *LinkNodeDB) FetchAllLinkNodes() ([]*LinkNode, error)
- func (l *LinkNodeDB) FetchLinkNode(identity *btcec.PublicKey) (*LinkNode, error)
- func (l *LinkNodeDB) FindMissingLinkNodes(tx kvdb.RTx, pubKeys []*btcec.PublicKey) ([]*btcec.PublicKey, error)
- type LogUpdate
- type Meta
- type MigrationConfig
- type MigrationConfigImpl
- type OpenChannel
- func (c *OpenChannel) AbsoluteThawHeight() (uint32, error)
- func (c *OpenChannel) AckAddHtlcs(addRefs ...AddRef) error
- func (c *OpenChannel) AckSettleFails(settleFailRefs ...SettleFailRef) error
- func (c *OpenChannel) ActiveHtlcs() []HTLC
- func (c *OpenChannel) AdvanceCommitChainTail(fwdPkg *FwdPkg, updates []LogUpdate, ourOutputIndex, theirOutputIndex uint32) error
- func (c *OpenChannel) AppendRemoteCommitChain(diff *CommitDiff) error
- func (c *OpenChannel) ApplyChanStatus(status ChannelStatus) error
- func (c *OpenChannel) BroadcastHeight() uint32
- func (c *OpenChannel) BroadcastedCommitment() (*wire.MsgTx, error)
- func (c *OpenChannel) BroadcastedCooperative() (*wire.MsgTx, error)
- func (c *OpenChannel) ChanStatus() ChannelStatus
- func (c *OpenChannel) ChanSyncMsg() (*lnwire.ChannelReestablish, error)
- func (c *OpenChannel) ClearChanStatus(status ChannelStatus) error
- func (c *OpenChannel) CloseChannel(summary *ChannelCloseSummary, statuses ...ChannelStatus) error
- func (c *OpenChannel) CommitmentHeight() (uint64, error)
- func (c *OpenChannel) DataLossCommitPoint() (*btcec.PublicKey, error)
- func (c *OpenChannel) DeriveHeightHint() uint32
- func (c *OpenChannel) FindPreviousState(updateNum uint64) (*RevocationLog, *ChannelCommitment, error)
- func (c *OpenChannel) HasChanStatus(status ChannelStatus) bool
- func (c *OpenChannel) Initiator() lntypes.ChannelParty
- func (c *OpenChannel) InsertNextRevocation(revKey *btcec.PublicKey) error
- func (c *OpenChannel) IsOptionScidAlias() bool
- func (c *OpenChannel) IsZeroConf() bool
- func (c *OpenChannel) LatestCommitments() (*ChannelCommitment, *ChannelCommitment, error)
- func (c *OpenChannel) LoadFwdPkgs() ([]*FwdPkg, error)
- func (c *OpenChannel) MarkAsOpen(openLoc lnwire.ShortChannelID) error
- func (c *OpenChannel) MarkBorked() error
- func (c *OpenChannel) MarkCommitmentBroadcasted(closeTx *wire.MsgTx, closer lntypes.ChannelParty) error
- func (c *OpenChannel) MarkConfirmationHeight(height uint32) error
- func (c *OpenChannel) MarkCoopBroadcasted(closeTx *wire.MsgTx, closer lntypes.ChannelParty) error
- func (c *OpenChannel) MarkDataLoss(commitPoint *btcec.PublicKey) error
- func (c *OpenChannel) MarkRealScid(realScid lnwire.ShortChannelID) error
- func (c *OpenChannel) MarkScidAliasNegotiated() error
- func (c *OpenChannel) MarkShutdownSent(info *ShutdownInfo) error
- func (c *OpenChannel) NegotiatedAliasFeature() bool
- func (c *OpenChannel) NextLocalHtlcIndex() (uint64, error)
- func (c *OpenChannel) Refresh() error
- func (c *OpenChannel) RemoteCommitChainTip() (*CommitDiff, error)
- func (c *OpenChannel) RemoteRevocationStore() (shachain.Store, error)
- func (c *OpenChannel) RemoteUnsignedLocalUpdates() ([]LogUpdate, error)
- func (c *OpenChannel) RemoveFwdPkgs(heights ...uint64) error
- func (c *OpenChannel) SecondCommitmentPoint() (*btcec.PublicKey, error)
- func (c *OpenChannel) SetBroadcastHeight(height uint32)
- func (c *OpenChannel) SetFwdFilter(height uint64, fwdFilter *PkgFilter) error
- func (c *OpenChannel) ShortChanID() lnwire.ShortChannelID
- func (c *OpenChannel) ShutdownInfo() (fn.Option[ShutdownInfo], error)
- func (c *OpenChannel) Snapshot() *ChannelSnapshot
- func (c *OpenChannel) String() string
- func (c *OpenChannel) SyncPending(addr net.Addr, pendingHeight uint32) error
- func (c *OpenChannel) UnsignedAckedUpdates() ([]LogUpdate, error)
- func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment, unsignedAckedUpdates []LogUpdate) (map[uint64]bool, error)
- func (c *OpenChannel) ZeroConfConfirmed() bool
- func (c *OpenChannel) ZeroConfRealScid() lnwire.ShortChannelID
- type OptionModifier
- func OptionClock(clock clock.Clock) OptionModifier
- func OptionDryRunMigration(dryRun bool) OptionModifier
- func OptionGcDecayedLog(noGc bool) OptionModifier
- func OptionNoMigration(b bool) OptionModifier
- func OptionNoRevLogAmtData(noAmtData bool) OptionModifier
- func OptionPruneRevocationLog(prune bool) OptionModifier
- func OptionStoreFinalHtlcResolutions(storeFinalHtlcResolutions bool) OptionModifier
- func OptionWithDecayedLogDB(decayedLog kvdb.Backend) OptionModifier
- type OptionalMeta
- type OptionalMiragtionConfig
- type Options
- type PkgFilter
- func (f *PkgFilter) Contains(i uint16) bool
- func (f *PkgFilter) Count() uint16
- func (f *PkgFilter) Decode(r io.Reader) error
- func (f *PkgFilter) Encode(w io.Writer) error
- func (f *PkgFilter) Equal(f2 *PkgFilter) bool
- func (f *PkgFilter) IsFull() bool
- func (f *PkgFilter) Set(i uint16)
- func (f *PkgFilter) Size() uint16
- func (f *PkgFilter) String() string
- type ResolverOutcome
- type ResolverReport
- type ResolverType
- type RevocationLog
- type SettleFailAcker
- type SettleFailRef
- type ShutdownInfo
- type SparsePayHash
- type SwitchPackager
- type UnknownElementType
- type WaitingProof
- type WaitingProofKey
- type WaitingProofStore
- type WitnessCache
- func (w *WitnessCache) AddSha256Witnesses(preimages ...lntypes.Preimage) error
- func (w *WitnessCache) DeleteSha256Witness(hash lntypes.Hash) error
- func (w *WitnessCache) DeleteWitnessClass(wType WitnessType) error
- func (w *WitnessCache) LookupSha256Witness(hash lntypes.Hash) (lntypes.Preimage, error)
- type WitnessType
Constants ¶
const ( // AbsoluteThawHeightThreshold is the threshold at which a thaw height // begins to be interpreted as an absolute block height, rather than a // relative one. AbsoluteThawHeightThreshold uint32 = 500000 // HTLCBlindingPointTLV is the tlv type used for storing blinding // points with HTLCs. HTLCBlindingPointTLV tlv.Type = 0 )
const ( // DefaultRejectCacheSize is the default number of rejectCacheEntries to // cache for use in the rejection cache of incoming gossip traffic. This // produces a cache size of around 1MB. DefaultRejectCacheSize = 50000 // DefaultChannelCacheSize is the default number of ChannelEdges cached // in order to reply to gossip queries. This produces a cache size of // around 40MB. DefaultChannelCacheSize = 20000 // DefaultPreAllocCacheNumNodes is the default number of channels we // assume for mainnet for pre-allocating the graph cache. As of // September 2021, there currently are 14k nodes in a strictly pruned // graph, so we choose a number that is slightly higher. DefaultPreAllocCacheNumNodes = 15000 )
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 )
const ( // OutputIndexEmpty is used when the output index doesn't exist. OutputIndexEmpty = math.MaxUint16 )
Variables ¶
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") // 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") // ErrNoShutdownInfo is returned when no shutdown info has been // persisted for a channel. ErrNoShutdownInfo = errors.New("no shutdown info") // 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") // ErrMissingIndexEntry is returned when a caller attempts to close a // channel and the outpoint is missing from the index. ErrMissingIndexEntry = fmt.Errorf("missing outpoint from index") // ErrOnionBlobLength is returned is an onion blob with incorrect // length is read from disk. ErrOnionBlobLength = errors.New("onion blob < 1366 bytes") )
var ( // ErrDryRunMigrationOK signals that a migration executed successful, // but we intentionally did not commit the result. ErrDryRunMigrationOK = errors.New("dry run migration successful") // ErrFinalHtlcsBucketNotFound signals that the top-level final htlcs // bucket does not exist. ErrFinalHtlcsBucketNotFound = errors.New("final htlcs bucket not " + "found") // ErrFinalChannelBucketNotFound signals that the channel bucket for // final htlc outcomes does not exist. ErrFinalChannelBucketNotFound = errors.New("final htlcs channel " + "bucket not found") )
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") // 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") // 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") // 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") )
var ( // TombstoneKey is the key under which we add a tag in the source DB // after we've successfully and completely migrated it to the target/ // destination DB. TombstoneKey = []byte("data-migration-tombstone") // ErrMarkerNotPresent is the error that is returned if the queried // marker is not present in the given database. ErrMarkerNotPresent = errors.New("marker not present") // ErrInvalidOptionalVersion is the error that is returned if the // optional version persisted in the database is invalid. ErrInvalidOptionalVersion = errors.New("invalid optional version") )
var ( // ErrNoChainHashBucket is returned when we have not created a bucket // for the current chain hash. ErrNoChainHashBucket = errors.New("no chain hash bucket") // ErrNoChannelSummaries is returned when a channel is not found in the // chain hash bucket. ErrNoChannelSummaries = errors.New("channel bucket not found") )
var ( // ErrLogEntryNotFound is returned when we cannot find a log entry at // the height requested in the revocation log. ErrLogEntryNotFound = errors.New("log entry not found") // ErrOutputIndexTooBig is returned when the output index is greater // than uint16. ErrOutputIndexTooBig = errors.New("output index is over uint16") )
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") )
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") )
var ErrClosedChannelNotFound = errors.New("unable to find closed channel summary")
ErrClosedChannelNotFound signals that a closed channel could not be found in the channeldb.
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.
var ErrHtlcUnknown = errors.New("htlc unknown")
var ( // ErrNoPeerBucket is returned when we try to read entries for a peer // that is not tracked. ErrNoPeerBucket = errors.New("peer bucket not found") )
Functions ¶
func AddMarker ¶
AddMarker adds the marker with the given key into a top level bucket with the same name. So the structure will look like:
marker-key (top level bucket)
|-> marker-key:marker-value (key/value pair)
func CheckMarkerPresent ¶
CheckMarkerPresent returns the marker under the requested key or ErrMarkerNotFound if either the root bucket or the marker key within that bucket does not exist.
func DKeyLocator ¶
DKeyLocator is a decoder for keychain.KeyLocator.
func DeriveMusig2Shachain ¶
DeriveMusig2Shachain derives a shachain producer for the taproot channel from normal shachain revocation root.
func DisableLog ¶
func DisableLog()
DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.
func EKeyLocator ¶
EKeyLocator is an encoder for keychain.KeyLocator.
func EnsureNoTombstone ¶
EnsureNoTombstone returns an error if there is a tombstone marker in the DB of the given transaction.
func FetchMeta ¶
FetchMeta is a helper function used in order to allow callers to re-use a database transaction.
func LatestDBVersion ¶
func LatestDBVersion() uint32
LatestDBVersion returns the number of the latest database version currently known to the channel DB.
func MakeTestInvoiceDB ¶
MakeTestInvoiceDB is used to create a test invoice database for testing purposes. It simply calls into MakeTestDB so the same modifiers can be used.
func NewMusigVerificationNonce ¶
func NewMusigVerificationNonce(pubKey *btcec.PublicKey, targetHeight uint64, shaGen shachain.Producer) (*musig2.Nonces, error)
NewMusigVerificationNonce generates the local or verification nonce for another musig2 session. In order to permit our implementation to not have to write any secret nonce state to disk, we'll use the _next_ shachain pre-image as our primary randomness source. When used to generate the nonce again to broadcast our commitment hte current height will be used.
func NewPaginator ¶
NewPaginator returns a struct which can be used to query an indexed bucket in pages.
func ReadElement ¶
ReadElement is a one-stop utility function to deserialize any datastructure encoded using the serialization format of the database.
func ReadElements ¶
ReadElements deserializes a variable number of elements into the passed io.Reader, with each element being deserialized according to the ReadElement function.
func SerializeHtlcs ¶
SerializeHtlcs writes out the passed set of HTLC's into the passed writer using the current default on-disk serialization format.
This inline serialization has been extended to allow storage of extra data associated with a HTLC in the following way:
- The known-length onion blob (1366 bytes) is serialized as var bytes in WriteElements (ie, the length 1366 was written, followed by the 1366 onion bytes).
- To include extra data, we append any extra data present to this one variable length of data. Since we know that the onion is strictly 1366 bytes, any length after that should be considered to be extra data.
NOTE: This API is NOT stable, the on-disk format will likely change in the future.
func UseLogger ¶
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 ¶
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 ¶
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.
type AddrSource ¶
type AddrSource interface {
// AddrsForNode returns all known addresses for the target node public
// key. The returned boolean must indicate if the given node is unknown
// to the backing source.
AddrsForNode(ctx context.Context,
nodePub *btcec.PublicKey) (bool, []net.Addr, error)
}
AddrSource is an interface that allow us to get the addresses for a target node. It may combine the results of multiple address sources.
func NewMultiAddrSource ¶
func NewMultiAddrSource(sources ...AddrSource) AddrSource
NewMultiAddrSource constructs a new AddrSource which will query all the provided sources for a node's addresses and will then de-duplicate the results.
type BigSizeAmount ¶
BigSizeAmount is a type alias for a TLV record of a btcutil.Amount.
type BigSizeMilliSatoshi ¶
type BigSizeMilliSatoshi = tlv.BigSizeT[lnwire.MilliSatoshi]
BigSizeMilliSatoshi is a type alias for a TLV record of a lnwire.MilliSatoshi.
type CacheConfig ¶
type CacheConfig struct {
// QueryDisable prevents reliance on the Height Hint Cache. This is
// necessary to recover from an edge case when the height recorded in
// the cache is higher than the actual height of a spend, causing a
// channel to become "stuck" in a pending close state.
QueryDisable bool
}
CacheConfig contains the HeightHintCache configuration.
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
// LocalChanConfig 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
// CustomBlob is an optional blob that can be used to store information
// specific to a custom channel type. This may track some custom
// specific state for this given commitment.
CustomBlob fn.Option[tlv.Blob]
// 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 {
// ChannelStateBounds 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.
ChannelStateBounds
// CommitmentParams is an embedding of the parameters
// required to render an abstract channel state into a concrete
// commitment transaction.
CommitmentParams
// 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 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.RTx) ([]*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 ¶
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 ChannelStateBounds ¶
type ChannelStateBounds struct {
// 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
}
ChannelStateBounds are the parameters from OpenChannel and AcceptChannel that are responsible for providing bounds on the state space of the abstract channel state. These values must be remembered for normal channel operation but they do not impact how we compute the commitment transactions themselves.
type ChannelStateDB ¶
type ChannelStateDB struct {
// contains filtered or unexported fields
}
ChannelStateDB is a database that keeps track of all channel state.
func (*ChannelStateDB) AbandonChannel ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) DeleteChannelOpeningState ¶
func (c *ChannelStateDB) DeleteChannelOpeningState(outPoint []byte) error
DeleteChannelOpeningState removes any state for outPoint from the database.
func (*ChannelStateDB) DeleteInitialForwardingPolicy ¶
func (c *ChannelStateDB) DeleteInitialForwardingPolicy( chanID lnwire.ChannelID) error
DeleteInitialForwardingPolicy removes the forwarding policy for a given channel from the database.
func (*ChannelStateDB) FetchAllChannels ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) FetchAllOpenChannels ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) FetchChannel ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) FetchChannelByID ¶
func (c *ChannelStateDB) FetchChannelByID(tx kvdb.RTx, id lnwire.ChannelID) ( *OpenChannel, error)
FetchChannelByID attempts to locate a channel specified by the passed channel ID. If the channel cannot be found, then an error will be returned. Optionally an existing db tx can be supplied.
func (*ChannelStateDB) FetchClosedChannel ¶
func (c *ChannelStateDB) FetchClosedChannel(chanID *wire.OutPoint) ( *ChannelCloseSummary, error)
FetchClosedChannel queries for a channel close summary using the channel point of the channel in question.
func (*ChannelStateDB) FetchClosedChannelForID ¶
func (c *ChannelStateDB) FetchClosedChannelForID(cid lnwire.ChannelID) ( *ChannelCloseSummary, error)
FetchClosedChannelForID queries for a channel close summary using the channel ID of the channel in question.
func (*ChannelStateDB) FetchClosedChannels ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) FetchHistoricalChannel ¶
func (c *ChannelStateDB) FetchHistoricalChannel(outPoint *wire.OutPoint) ( *OpenChannel, error)
FetchHistoricalChannel fetches open channel data from the historical channel bucket.
func (*ChannelStateDB) FetchOpenChannels ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) FetchPendingChannels ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) FetchPermAndTempPeers ¶
func (c *ChannelStateDB) FetchPermAndTempPeers( chainHash []byte) (map[string]ChanCount, error)
FetchPermAndTempPeers returns a map where the key is the remote node's public key and the value is a struct that has a tally of the pending-open channels and whether the peer has an open or closed channel with us.
func (*ChannelStateDB) FetchWaitingCloseChannels ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) GetChannelOpeningState ¶
func (c *ChannelStateDB) GetChannelOpeningState(outPoint []byte) ([]byte, error)
GetChannelOpeningState fetches the serialized channel state for the provided outPoint from the database, or returns ErrChannelNotFound if the channel is not found.
func (*ChannelStateDB) GetInitialForwardingPolicy ¶
func (c *ChannelStateDB) GetInitialForwardingPolicy( chanID lnwire.ChannelID) (*models.ForwardingPolicy, error)
GetInitialForwardingPolicy fetches the serialized forwarding policy for the provided channel id from the database, or returns ErrChannelNotFound if a forwarding policy for this channel id is not found.
func (*ChannelStateDB) GetParentDB ¶
func (c *ChannelStateDB) GetParentDB() *DB
GetParentDB returns the "main" channeldb.DB object that is the owner of this ChannelStateDB instance. Use this function only in tests where passing around pointers makes testing less readable. Never to be used in production code!
func (*ChannelStateDB) LinkNodeDB ¶
func (c *ChannelStateDB) LinkNodeDB() *LinkNodeDB
LinkNodeDB returns the current instance of the link node database.
func (*ChannelStateDB) LookupFinalHtlc ¶
func (c *ChannelStateDB) LookupFinalHtlc(chanID lnwire.ShortChannelID, htlcIndex uint64) (*FinalHtlcInfo, error)
LookupFinalHtlc retrieves a final htlc resolution from the database. If the htlc has no final resolution yet, ErrHtlcUnknown is returned.
func (*ChannelStateDB) MarkChanFullyClosed ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) PruneLinkNodes ¶
func (c *ChannelStateDB) PruneLinkNodes() error
PruneLinkNodes attempts to prune all link nodes found within the database with whom we no longer have any open channels with.
func (*ChannelStateDB) PutOnchainFinalHtlcOutcome ¶
func (c *ChannelStateDB) PutOnchainFinalHtlcOutcome( chanID lnwire.ShortChannelID, htlcID uint64, settled bool) error
PutOnchainFinalHtlcOutcome stores the final on-chain outcome of an htlc in the database.
func (*ChannelStateDB) RepairLinkNodes ¶
func (c *ChannelStateDB) RepairLinkNodes(network wire.BitcoinNet) error
RepairLinkNodes scans all channels in the database and ensures that a link node exists for each remote peer. This should be called on startup to ensure that our database is consistent.
NOTE: This function is designed to repair database inconsistencies that may have occurred due to the race condition in link node pruning (where link nodes could be incorrectly deleted while channels still existed). This can be removed once we move to native sql.
func (*ChannelStateDB) RestoreChannelShells ¶
func (c *ChannelStateDB) 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 (*ChannelStateDB) SaveChannelOpeningState ¶
func (c *ChannelStateDB) SaveChannelOpeningState(outPoint, serializedState []byte) error
SaveChannelOpeningState saves the serialized channel state for the provided chanPoint to the channelOpeningStateBucket.
func (*ChannelStateDB) SaveInitialForwardingPolicy ¶
func (c *ChannelStateDB) SaveInitialForwardingPolicy(chanID lnwire.ChannelID, forwardingPolicy *models.ForwardingPolicy) error
SaveInitialForwardingPolicy saves the serialized forwarding policy for the provided permanent channel id to the initialChannelForwardingPolicyBucket.
type ChannelStatus ¶
type ChannelStatus uint64
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 uint64
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 // SingleFunderTweaklessBit 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. 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 // ZeroHtlcTxFeeBit indicates that the channel should use zero-fee // second-level HTLC transactions. ZeroHtlcTxFeeBit ChannelType = 1 << 5 // LeaseExpirationBit indicates that the channel has been leased for a // period of time, constraining every output that pays to the channel // initiator with an additional CLTV of the lease maturity. LeaseExpirationBit ChannelType = 1 << 6 // ZeroConfBit indicates that the channel is a zero-conf channel. ZeroConfBit ChannelType = 1 << 7 // ScidAliasChanBit indicates that the channel has negotiated the // scid-alias channel type. ScidAliasChanBit ChannelType = 1 << 8 // ScidAliasFeatureBit indicates that the scid-alias feature bit was // negotiated during the lifetime of this channel. ScidAliasFeatureBit ChannelType = 1 << 9 // SimpleTaprootFeatureBit indicates that the simple-taproot-chans // feature bit was negotiated during the lifetime of the channel. SimpleTaprootFeatureBit ChannelType = 1 << 10 // TapscriptRootBit indicates that this is a MuSig2 channel with a top // level tapscript commitment. This MUST be set along with the // SimpleTaprootFeatureBit. TapscriptRootBit ChannelType = 1 << 11 )
func (ChannelType) HasAnchors ¶
func (c ChannelType) HasAnchors() bool
HasAnchors returns true if this channel type has anchor outputs 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) HasLeaseExpiration ¶
func (c ChannelType) HasLeaseExpiration() bool
HasLeaseExpiration returns true if the channel originated from a lease.
func (ChannelType) HasScidAliasChan ¶
func (c ChannelType) HasScidAliasChan() bool
HasScidAliasChan returns true if the scid-alias channel type was negotiated.
func (ChannelType) HasScidAliasFeature ¶
func (c ChannelType) HasScidAliasFeature() bool
HasScidAliasFeature returns true if the scid-alias feature bit was negotiated during the lifetime of this channel.
func (ChannelType) HasTapscriptRoot ¶
func (c ChannelType) HasTapscriptRoot() bool
HasTapscriptRoot returns true if the channel is using a top level tapscript root commitment.
func (ChannelType) HasZeroConf ¶
func (c ChannelType) HasZeroConf() bool
HasZeroConf returns true if the channel is a zero-conf channel.
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) IsTaproot ¶
func (c ChannelType) IsTaproot() bool
IsTaproot returns true if the channel is using taproot features.
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.
func (ChannelType) ZeroHtlcTxFee ¶
func (c ChannelType) ZeroHtlcTxFee() bool
ZeroHtlcTxFee returns true if this channel type uses second-level HTLC transactions signed with zero-fee.
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 []models.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 []models.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 CommitmentParams ¶
type CommitmentParams 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
// 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
}
CommitmentParams are the parameters from OpenChannel and AcceptChannel that are required to render an abstract channel state to a concrete commitment transaction. These values are necessary to (re)compute the commitment transaction. We treat these differently than the state space bounds because their history needs to be stored in order to properly handle chain resolution.
type DB ¶
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 CreateWithBackend ¶
func CreateWithBackend(backend kvdb.Backend, modifiers ...OptionModifier) (*DB, error)
CreateWithBackend creates channeldb instance using the passed kvdb.Backend. Any necessary schemas migrations due to updates will take place as necessary.
func MakeTestDB ¶
func MakeTestDB(t *testing.T, modifiers ...OptionModifier) (*DB, error)
MakeTestDB creates a new instance of the ChannelDB for testing purposes. A callback which cleans up the created temporary directories is also returned and intended to be executed after the test completes.
func OpenForTesting ¶
func OpenForTesting(t testing.TB, dbPath string, modifiers ...OptionModifier) *DB
OpenForTesting opens or creates a channeldb to be used for tests. Any necessary schemas migrations due to updates will take place as necessary.
func (*DB) AddInvoice ¶
func (d *DB) AddInvoice(_ context.Context, newInvoice *invpkg.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 ¶
AddrsForNode consults the channel database for all addresses known to the passed node public key. The returned boolean indicates if the given node is unknown to the channel DB or not.
NOTE: this is part of the AddrSource interface.
func (*DB) ChannelStateDB ¶
func (d *DB) ChannelStateDB() *ChannelStateDB
ChannelStateDB returns the sub database that is concerned with the channel state.
func (*DB) DeleteCanceledInvoices ¶
DeleteCanceledInvoices deletes all canceled invoices from the database.
func (*DB) DeleteInvoice ¶
DeleteInvoice attempts to delete the passed invoices from the database in one transaction. The passed delete references hold all keys required to delete the invoices without also needing to deserialize them.
func (DB) FetchChannelReports ¶
func (d DB) FetchChannelReports(chainHash chainhash.Hash, outPoint *wire.OutPoint) ([]*ResolverReport, error)
FetchChannelReports fetches the set of reports for a channel.
func (*DB) FetchMeta ¶
FetchMeta fetches the metadata from boltdb and returns filled meta structure.
func (*DB) FetchPendingInvoices ¶
FetchPendingInvoices returns all invoices that have not yet been settled or canceled. The returned map is keyed by the payment hash of each respective invoice.
func (*DB) ForwardingLog ¶
func (d *DB) ForwardingLog() *ForwardingLog
ForwardingLog returns an instance of the ForwardingLog object backed by the target database instance.
func (*DB) GetInvoiceBucketTombstone ¶
GetInvoiceBucketTombstone checks if the tombstone key exists in the invoice bucket. It returns true if the tombstone is present and false otherwise.
func (*DB) InvoicesAddedSince ¶
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(_ context.Context, sinceSettleIndex uint64) ( []invpkg.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 ¶
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) NewWitnessCache ¶
func (d *DB) NewWitnessCache() *WitnessCache
NewWitnessCache returns a new instance of the witness cache.
func (*DB) PutResolverReport ¶
func (d *DB) PutResolverReport(tx kvdb.RwTx, chainHash chainhash.Hash, channelOutpoint *wire.OutPoint, report *ResolverReport) error
PutResolverReport creates and commits a transaction that is used to write a resolver report to disk.
func (*DB) QueryInvoices ¶
func (d *DB) QueryInvoices(_ context.Context, q invpkg.InvoiceQuery) ( invpkg.InvoiceSlice, error)
QueryInvoices allows a caller to query the invoice database for invoices within the specified add index range.
func (*DB) ReadFlapCount ¶
ReadFlapCount attempts to read the flap count for a peer, failing if the peer is not found or we do not have flap count stored.
func (*DB) SetInvoiceBucketTombstone ¶
SetInvoiceBucketTombstone sets the tombstone key in the invoice bucket to mark the bucket as permanently closed. This prevents it from being reopened in the future.
func (*DB) UpdateInvoice ¶
func (d *DB) UpdateInvoice(_ context.Context, ref invpkg.InvoiceRef, setIDHint *invpkg.SetID, callback invpkg.InvoiceUpdateCallback) ( *invpkg.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. When updating an invoice, the update itself happens in-memory on a copy of the invoice. Once it is written successfully to the database, the in-memory copy is returned to the caller.
type FinalHtlcByte ¶
type FinalHtlcByte byte
FinalHtlcByte defines a byte type that encodes information about the final htlc resolution.
const ( // FinalHtlcSettledBit is the bit that encodes whether the htlc was // settled or failed. FinalHtlcSettledBit FinalHtlcByte = 1 << 0 // FinalHtlcOffchainBit is the bit that encodes whether the htlc was // resolved offchain or onchain. FinalHtlcOffchainBit FinalHtlcByte = 1 << 1 )
type FinalHtlcInfo ¶
type FinalHtlcInfo struct {
// Settled is true is the htlc was settled. If false, the htlc was
// failed.
Settled bool
// Offchain indicates whether the htlc was resolved off-chain or
// on-chain.
Offchain bool
}
FinalHtlcInfo contains information about the final outcome of an htlc.
type FlapCount ¶
type FlapCount struct {
// Count provides the total flap count for a peer.
Count uint32
// LastFlap is the timestamp of the last flap recorded for a peer.
LastFlap time.Time
}
FlapCount contains information about a peer's flap count.
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
// IncomingHtlcID is the ID of the incoming HTLC in the payment circuit.
// If this is not set, the value will be nil. This field is added in
// v0.20 and is made optional to make it backward compatible with
// existing forwarding events created before it's introduction.
IncomingHtlcID fn.Option[uint64]
// OutgoingHtlcID is the ID of the outgoing HTLC in the payment circuit.
// If this is not set, the value will be nil. This field is added in
// v0.20 and is made optional to make it backward compatible with
// existing forwarding events created before it's introduction.
OutgoingHtlcID fn.Option[uint64]
}
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
// IncomingChanIds is the list of channels to filter HTLCs being
// received from a particular channel.
// If the list is empty, then it is ignored.
IncomingChanIDs fn.Set[uint64]
// OutgoingChanIds is the list of channels to filter HTLCs being
// forwarded to a particular channel.
// If the list is empty, then it is ignored.
OutgoingChanIDs fn.Set[uint64]
}
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 fulfillment 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 ¶
func (f *ForwardingLog) Query(q ForwardingEventQuery) (ForwardingLogTimeSlice, error)
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 returned 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.RTx) ([]*FwdPkg, error)
// RemovePkg deletes a forwarding package owned by this channel at
// the provided remote `height`.
RemovePkg(tx kvdb.RwTx, height uint64) error
// Wipe deletes all the forwarding packages owned by this channel.
Wipe(tx kvdb.RwTx) 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.
//
// NOTE: This value signals when persisted to disk that the fwd package
// has been processed and garbage collection can happen. So it also
// has to be set for packages with no adds (empty packages or only
// settle/fail packages) so that they can be garbage collected as well.
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) DestRef ¶
func (f *FwdPkg) DestRef(i uint16) SettleFailRef
DestRef is a convenience method that returns a SettleFailRef to this forwarding package for the index in the argument. It is the caller's responsibility to ensure that the index is in bounds.
func (*FwdPkg) ID ¶
ID returns an unique identifier for this package, used to ensure that sphinx replay processing of this batch is idempotent.
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.RTx,
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 [lnwire.OnionPacketSize]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
// ExtraData contains any additional information that was transmitted
// with the HTLC via TLVs. This data *must* already be encoded as a
// TLV stream, and may be empty. The length of this data is naturally
// limited by the space available to TLVs in update_add_htlc:
// = 65535 bytes (bolt 8 maximum message size):
// - 2 bytes (bolt 1 message_type)
// - 32 bytes (channel_id)
// - 8 bytes (id)
// - 8 bytes (amount_msat)
// - 32 bytes (payment_hash)
// - 4 bytes (cltv_expiry)
// - 1366 bytes (onion_routing_packet)
// = 64083 bytes maximum possible TLV stream
//
// Note that this extra data is stored inline with the OnionBlob for
// legacy reasons, see serialization/deserialization functions for
// detail.
ExtraData lnwire.ExtraOpaqueData
// BlindingPoint is an optional blinding point included with the HTLC.
//
// Note: this field is not a part of on-disk representation of the
// HTLC. It is stored in the ExtraData field, which is used to store
// a TLV stream of additional information associated with the HTLC.
BlindingPoint lnwire.BlindingPointRecord
// CustomRecords is a set of custom TLV records that are associated with
// this HTLC. These records are used to store additional information
// about the HTLC that is not part of the standard HTLC fields. This
// field is encoded within the ExtraData field.
CustomRecords lnwire.CustomRecords
}
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 ¶
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.
This inline deserialization has been extended to allow storage of extra data associated with a HTLC in the following way:
- The known-length onion blob (1366 bytes) and any additional data present are read out as a single blob of variable byte data.
- They are stored like this to take advantage of the variable space available for extension without migration (see SerializeHtlcs).
- The first 1366 bytes are interpreted as the onion blob, and any remaining bytes as extra HTLC data.
- This extra HTLC data is expected to be serialized as a TLV stream, and its parsing is left to higher layers.
NOTE: This API is NOT stable, the on-disk format will likely change in the future.
type HTLCEntry ¶
type HTLCEntry struct {
// RHash is the payment hash of the HTLC.
RHash tlv.RecordT[tlv.TlvType0, SparsePayHash]
// RefundTimeout is the absolute timeout on the HTLC that the sender
// must wait before reclaiming the funds in limbo.
RefundTimeout tlv.RecordT[tlv.TlvType1, uint32]
// OutputIndex is the output index for this particular HTLC output
// within the commitment transaction.
//
// NOTE: we use uint16 instead of int32 here to save us 2 bytes, which
// gives us a max number of HTLCs of 65K.
OutputIndex tlv.RecordT[tlv.TlvType2, uint16]
// Incoming denotes whether we're the receiver or the sender of this
// HTLC.
Incoming tlv.RecordT[tlv.TlvType3, bool]
// Amt is the amount of satoshis this HTLC escrows.
Amt tlv.RecordT[tlv.TlvType4, tlv.BigSizeT[btcutil.Amount]]
// CustomBlob is an optional blob that can be used to store information
// specific to revocation handling for a custom channel type.
CustomBlob tlv.OptionalRecordT[tlv.TlvType5, tlv.Blob]
// HtlcIndex is the index of the HTLC in the channel.
HtlcIndex tlv.OptionalRecordT[tlv.TlvType6, tlv.BigSizeT[uint64]]
}
HTLCEntry specifies the minimal info needed to be stored on disk for ALL the historical HTLCs, which is useful for constructing RevocationLog when a breach is detected. The actual size of each HTLCEntry varies based on its RHash and Amt(sat), summarized as follows,
| RHash empty | Amt<=252 | Amt<=65,535 | Amt<=4,294,967,295 | otherwise | |:-----------:|:--------:|:-----------:|:------------------:|:---------:| | true | 19 | 21 | 23 | 26 | | false | 51 | 53 | 55 | 58 |
So the size varies from 19 bytes to 58 bytes, where most likely to be 23 or 55 bytes.
NOTE: all the fields saved to disk use the primitive go types so they can be made into tlv records without further conversion.
func NewHTLCEntryFromHTLC ¶
NewHTLCEntryFromHTLC creates a new HTLCEntry from an HTLC.
type HeightHintCache ¶
type HeightHintCache struct {
// contains filtered or unexported fields
}
HeightHintCache is an implementation of the SpendHintCache and ConfirmHintCache interfaces backed by a channeldb DB instance where the hints will be stored.
func NewHeightHintCache ¶
func NewHeightHintCache(cfg CacheConfig, db kvdb.Backend) (*HeightHintCache, error)
NewHeightHintCache returns a new height hint cache backed by a database.
func (*HeightHintCache) CommitConfirmHint ¶
func (c *HeightHintCache) CommitConfirmHint(height uint32, confRequests ...chainntnfs.ConfRequest) error
CommitConfirmHint commits a confirm hint for the transactions to the cache.
func (*HeightHintCache) CommitSpendHint ¶
func (c *HeightHintCache) CommitSpendHint(height uint32, spendRequests ...chainntnfs.SpendRequest) error
CommitSpendHint commits a spend hint for the outpoints to the cache.
func (*HeightHintCache) PurgeConfirmHint ¶
func (c *HeightHintCache) PurgeConfirmHint( confRequests ...chainntnfs.ConfRequest) error
PurgeConfirmHint removes the confirm hint for the transactions from the cache.
func (*HeightHintCache) PurgeSpendHint ¶
func (c *HeightHintCache) PurgeSpendHint( spendRequests ...chainntnfs.SpendRequest) error
PurgeSpendHint removes the spend hint for the outpoints from the cache.
func (*HeightHintCache) QueryConfirmHint ¶
func (c *HeightHintCache) QueryConfirmHint( confRequest chainntnfs.ConfRequest) (uint32, error)
QueryConfirmHint returns the latest confirm hint for a transaction hash. ErrConfirmHintNotFound is returned if a confirm hint does not exist within the cache for the transaction hash.
func (*HeightHintCache) QuerySpendHint ¶
func (c *HeightHintCache) QuerySpendHint( spendRequest chainntnfs.SpendRequest) (uint32, error)
QuerySpendHint returns the latest spend hint for an outpoint. ErrSpendHintNotFound is returned if a spend hint does not exist within the cache for the outpoint.
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 NewLinkNode ¶
func NewLinkNode(db *LinkNodeDB, 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 a link node DB.
func (*LinkNode) AddAddress ¶
AddAddress appends the specified TCP address to the list of known addresses this node is/was known to be reachable at.
type LinkNodeDB ¶
type LinkNodeDB struct {
// contains filtered or unexported fields
}
LinkNodeDB is a database that keeps track of all link nodes.
func (*LinkNodeDB) CreateLinkNodes ¶
func (l *LinkNodeDB) CreateLinkNodes(tx kvdb.RwTx, linkNodes []*LinkNode) error
CreateLinkNodes creates multiple link nodes. If tx is nil, a new write transaction will be created. Otherwise, the provided transaction is used, allowing this to be part of a larger batch operation.
func (*LinkNodeDB) DeleteLinkNode ¶
func (l *LinkNodeDB) DeleteLinkNode(identity *btcec.PublicKey) error
DeleteLinkNode removes the link node with the given identity from the database.
func (*LinkNodeDB) FetchAllLinkNodes ¶
func (l *LinkNodeDB) FetchAllLinkNodes() ([]*LinkNode, error)
FetchAllLinkNodes starts a new database transaction to fetch all nodes with whom we have active channels with.
func (*LinkNodeDB) FetchLinkNode ¶
func (l *LinkNodeDB) 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 (*LinkNodeDB) FindMissingLinkNodes ¶
func (l *LinkNodeDB) FindMissingLinkNodes(tx kvdb.RTx, pubKeys []*btcec.PublicKey) ([]*btcec.PublicKey, error)
FindMissingLinkNodes checks which of the provided public keys do not have corresponding link nodes in the database. If tx is nil, a new read transaction will be created. Otherwise, the provided transaction is used, allowing this to be part of a larger batch operation.
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 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.
type Meta ¶
type Meta struct {
// DbVersionNumber is the current schema version of the database.
DbVersionNumber uint32
}
Meta structure holds the database meta information.
type MigrationConfig ¶
type MigrationConfig interface {
migration30.MigrateRevLogConfig
migration34.MigrationConfig
}
MigrationConfig is an interface combines the config interfaces of all optional migrations.
type MigrationConfigImpl ¶
type MigrationConfigImpl struct {
migration30.MigrateRevLogConfigImpl
migration34.MigrationConfigImpl
}
MigrationConfigImpl is a super set of all the various migration configs and an implementation of MigrationConfig.
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.
//
// If IsZeroConf(), then this will the "base" (very first) ALIAS scid
// and the confirmed SCID will be stored in ConfirmedScid.
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
// ConfirmationHeight records the block height at which the funding
// transaction was first confirmed.
ConfirmationHeight 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
// InitialLocalBalance is the balance we have during the channel
// opening. When we are not the initiator, this value represents the
// push amount.
InitialLocalBalance lnwire.MilliSatoshi
// InitialRemoteBalance is the balance they have during the channel
// opening.
InitialRemoteBalance 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. If the value is lower than 500,000, then it's
// interpreted as a relative height, or an absolute height otherwise.
ThawHeight uint32
// LastWasRevoke is a boolean that determines if the last update we sent
// was a revocation (true) or a commitment signature (false).
LastWasRevoke bool
// RevocationKeyLocator stores the KeyLocator information that we will
// need to derive the shachain root for this channel. This allows us to
// have private key isolation from lnd.
RevocationKeyLocator keychain.KeyLocator
// Memo is any arbitrary information we wish to store locally about the
// channel that will be useful to our future selves.
Memo []byte
// TapscriptRoot is an optional tapscript root used to derive the MuSig2
// funding output.
TapscriptRoot fn.Option[chainhash.Hash]
// CustomBlob is an optional blob that can be used to store information
// specific to a custom channel type. This information is only created
// at channel funding time, and after wards is to be considered
// immutable.
CustomBlob fn.Option[tlv.Blob]
// TODO(roasbeef): eww
Db *ChannelStateDB
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) AbsoluteThawHeight ¶
func (c *OpenChannel) AbsoluteThawHeight() (uint32, error)
AbsoluteThawHeight determines a frozen channel's absolute thaw height. If the channel is not frozen, then 0 is returned.
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, updates []LogUpdate, ourOutputIndex, theirOutputIndex uint32) 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. The updates parameter is the set of local updates that the peer still needs to send us a signature for. We store this set of updates in case we go down.
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) BroadcastHeight ¶
func (c *OpenChannel) BroadcastHeight() uint32
BroadcastHeight returns the height at which the funding tx was broadcast.
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 receives this message one of three things may happen:
- We're fully synced and no messages need to be sent.
- We didn't get the last CommitSig message they sent, so they'll re-send it.
- 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) DeriveHeightHint ¶
func (c *OpenChannel) DeriveHeightHint() uint32
DeriveHeightHint derives the block height for the channel opening.
func (*OpenChannel) FindPreviousState ¶
func (c *OpenChannel) FindPreviousState( updateNum uint64) (*RevocationLog, *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) Initiator ¶
func (c *OpenChannel) Initiator() lntypes.ChannelParty
Initiator returns the ChannelParty that originally opened this channel.
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) IsOptionScidAlias ¶
func (c *OpenChannel) IsOptionScidAlias() bool
IsOptionScidAlias returns whether the option_scid_alias channel type was negotiated.
func (*OpenChannel) IsZeroConf ¶
func (c *OpenChannel) IsZeroConf() bool
IsZeroConf returns whether the option_zeroconf channel type was negotiated.
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, closer lntypes.ChannelParty) 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) MarkConfirmationHeight ¶
func (c *OpenChannel) MarkConfirmationHeight(height uint32) error
MarkConfirmationHeight updates the channel's confirmation height once the channel opening transaction receives one confirmation.
func (*OpenChannel) MarkCoopBroadcasted ¶
func (c *OpenChannel) MarkCoopBroadcasted(closeTx *wire.MsgTx, closer lntypes.ChannelParty) 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) MarkRealScid ¶
func (c *OpenChannel) MarkRealScid(realScid lnwire.ShortChannelID) error
MarkRealScid marks the zero-conf channel's confirmed ShortChannelID. This should only be done if IsZeroConf returns true.
func (*OpenChannel) MarkScidAliasNegotiated ¶
func (c *OpenChannel) MarkScidAliasNegotiated() error
MarkScidAliasNegotiated adds ScidAliasFeatureBit to ChanType in-memory and in the database.
func (*OpenChannel) MarkShutdownSent ¶
func (c *OpenChannel) MarkShutdownSent(info *ShutdownInfo) error
MarkShutdownSent serialises and persist the given ShutdownInfo for this channel. Persisting this info represents the fact that we have sent the Shutdown message to the remote side and hence that we should re-transmit the same Shutdown message on re-establish.
func (*OpenChannel) NegotiatedAliasFeature ¶
func (c *OpenChannel) NegotiatedAliasFeature() bool
NegotiatedAliasFeature returns whether the option-scid-alias feature bit was negotiated.
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) Refresh ¶
func (c *OpenChannel) Refresh() error
Refresh updates the in-memory channel state using the latest state observed on disk.
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) RemoteUnsignedLocalUpdates ¶
func (c *OpenChannel) RemoteUnsignedLocalUpdates() ([]LogUpdate, error)
RemoteUnsignedLocalUpdates retrieves the persisted, unsigned local log updates that the remote still needs to sign for.
func (*OpenChannel) RemoveFwdPkgs ¶
func (c *OpenChannel) RemoveFwdPkgs(heights ...uint64) error
RemoveFwdPkgs atomically removes forwarding packages specified by the remote commitment heights. If one of the intermediate RemovePkg calls fails, then the later packages won't be removed.
NOTE: This method should only be called on packages marked FwdStateCompleted.
func (*OpenChannel) SecondCommitmentPoint ¶
func (c *OpenChannel) SecondCommitmentPoint() (*btcec.PublicKey, error)
SecondCommitmentPoint returns the second per-commitment-point for use in the channel_ready message.
func (*OpenChannel) SetBroadcastHeight ¶
func (c *OpenChannel) SetBroadcastHeight(height uint32)
SetBroadcastHeight sets the FundingBroadcastHeight.
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) ShutdownInfo ¶
func (c *OpenChannel) ShutdownInfo() (fn.Option[ShutdownInfo], error)
ShutdownInfo decodes the shutdown info stored for this channel and returns the result. If no shutdown info has been persisted for this channel then the ErrNoShutdownInfo error is returned.
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) String ¶
func (c *OpenChannel) String() string
String returns a string representation of the channel.
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) (map[uint64]bool, 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.
A map is returned of all the htlc resolutions that were locked in this commitment. Keys correspond to htlc indices and values indicate whether the htlc was settled or failed.
func (*OpenChannel) ZeroConfConfirmed ¶
func (c *OpenChannel) ZeroConfConfirmed() bool
ZeroConfConfirmed returns whether the zero-conf channel has confirmed. This should only be called if IsZeroConf returns true.
func (*OpenChannel) ZeroConfRealScid ¶
func (c *OpenChannel) ZeroConfRealScid() lnwire.ShortChannelID
ZeroConfRealScid returns the zero-conf channel's confirmed scid. This should only be called if IsZeroConf returns true.
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 intentionally fail to commit a successful migration that occurs when opening the database.
func OptionGcDecayedLog ¶
func OptionGcDecayedLog(noGc bool) OptionModifier
OptionGcDecayedLog specifies whether the decayed log migration has to take place.
func OptionNoMigration ¶
func OptionNoMigration(b bool) OptionModifier
OptionNoMigration allows the database to be opened in read only mode by disabling migrations.
func OptionNoRevLogAmtData ¶
func OptionNoRevLogAmtData(noAmtData bool) OptionModifier
OptionNoRevLogAmtData sets the NoRevLogAmtData option to the given value. If it is set to true then amount data will not be stored in the revocation log.
func OptionPruneRevocationLog ¶
func OptionPruneRevocationLog(prune bool) OptionModifier
OptionPruneRevocationLog specifies whether the migration for pruning revocation logs needs to be applied or not.
func OptionStoreFinalHtlcResolutions ¶
func OptionStoreFinalHtlcResolutions( storeFinalHtlcResolutions bool) OptionModifier
OptionStoreFinalHtlcResolutions controls whether to persistently store the final resolution of incoming htlcs.
func OptionWithDecayedLogDB ¶
func OptionWithDecayedLogDB(decayedLog kvdb.Backend) OptionModifier
OptionWithDecayedLogDB sets the decayed log database reference which might be used for some migrations because generally we only touch the channeldb databases in the migrations, this is a way to allow also access to the decayed log database.
type OptionalMeta ¶
type OptionalMeta struct {
// Versions is a set that contains the versions that have been applied.
// When saved to disk, only the indexes are stored.
Versions map[uint64]string
}
OptionalMeta structure holds the database optional migration information.
func (*OptionalMeta) String ¶
func (om *OptionalMeta) String() string
String returns a string representation of the optional meta.
type OptionalMiragtionConfig ¶
type OptionalMiragtionConfig struct {
// MigrationFlags is an array of booleans indicating which optional
// migrations should be run. The index in the array corresponds to the
// migration number in optionalVersions.
MigrationFlags []bool
// DecayedLog is a reference to the decayed log database. The channeldb
// is inherently part of the optional migration flow so there is no need
// to specify it here. The DecayedLog is a separate database in case the
// kvdb backend is set to `bbolt`. And also for the kvdb SQL backend
// case it is a separate table therefore we need to reference it here
// as well to use the right query to access the decayed log.
DecayedLog kvdb.Backend
}
OptionalMiragtionConfig defines the flags used to signal whether a particular migration needs to be applied.
func NewOptionalMiragtionConfig ¶
func NewOptionalMiragtionConfig() OptionalMiragtionConfig
NewOptionalMiragtionConfig creates a new OptionalMiragtionConfig with the default migration flags.
type Options ¶
type Options struct {
OptionalMiragtionConfig
// NoMigration specifies that underlying backend was opened in read-only
// mode and migrations shouldn't be performed. This can be useful for
// applications that use the channeldb package as a library.
NoMigration bool
// NoRevLogAmtData when set to true, indicates that amount data should
// not be stored in the revocation log.
NoRevLogAmtData 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 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 ¶
NewPkgFilter initializes an empty PkgFilter supporting `count` elements.
func (*PkgFilter) Contains ¶
Contains queries the filter for membership of index `i`. NOTE: It is assumed that i is always less than count.
func (*PkgFilter) IsFull ¶
IsFull returns true if every element in the filter has been Set, and false otherwise.
func (*PkgFilter) Set ¶
Set marks the `i`-th element as included by this filter. NOTE: It is assumed that i is always less than count.
type ResolverOutcome ¶
type ResolverOutcome uint8
ResolverOutcome indicates the outcome for the resolver that that the contract court reached. This state is not necessarily final, since htlcs on our own commitment are resolved across two resolvers.
const ( // ResolverOutcomeClaimed indicates that funds were claimed on chain. ResolverOutcomeClaimed ResolverOutcome = 0 // ResolverOutcomeUnclaimed indicates that we did not claim our funds on // chain. This may be the case for anchors that we did not sweep, or // outputs that were not economical to sweep. ResolverOutcomeUnclaimed ResolverOutcome = 1 // ResolverOutcomeAbandoned indicates that we did not attempt to claim // an output on chain. This is the case for htlcs that we could not // decode to claim, or invoice which we fail when an attempt is made // to settle them on chain. ResolverOutcomeAbandoned ResolverOutcome = 2 // ResolverOutcomeTimeout indicates that a contract was timed out on // chain. ResolverOutcomeTimeout ResolverOutcome = 3 // ResolverOutcomeFirstStage indicates that a htlc had to be claimed // over two stages, with this outcome representing the confirmation // of our success/timeout tx. ResolverOutcomeFirstStage ResolverOutcome = 4 )
type ResolverReport ¶
type ResolverReport struct {
// OutPoint is the on chain outpoint that was spent as a result of this
// resolution. When an output is directly resolved (eg, commitment
// sweeps and single stage htlcs on the remote party's output) this
// is an output on the commitment tx that was broadcast. When we resolve
// across two stages (eg, htlcs on our own force close commit), the
// first stage outpoint is the output on our commitment and the second
// stage output is the spend from our htlc success/timeout tx.
OutPoint wire.OutPoint
// Amount is the value of the output referenced above.
Amount btcutil.Amount
// ResolverType indicates the type of resolution that occurred.
ResolverType
// ResolverOutcome indicates the outcome of the resolver.
ResolverOutcome
// SpendTxID is the transaction ID of the spending transaction that
// claimed the outpoint. This may be a sweep transaction, or a first
// stage success/timeout transaction.
SpendTxID *chainhash.Hash
}
ResolverReport provides an account of the outcome of a resolver. This differs from a ContractReport because it does not necessarily fully resolve the contract; each step of two stage htlc resolution is included.
type ResolverType ¶
type ResolverType uint8
ResolverType indicates the type of resolver that was resolved on chain.
const ( // ResolverTypeAnchor represents a resolver for an anchor output. ResolverTypeAnchor ResolverType = 0 // ResolverTypeIncomingHtlc represents resolution of an incoming htlc. ResolverTypeIncomingHtlc ResolverType = 1 // ResolverTypeOutgoingHtlc represents resolution of an outgoing htlc. ResolverTypeOutgoingHtlc ResolverType = 2 // ResolverTypeCommit represents resolution of our time locked commit // when we force close. ResolverTypeCommit ResolverType = 3 )
type RevocationLog ¶
type RevocationLog struct {
// OurOutputIndex specifies our output index in this commitment. In a
// remote commitment transaction, this is the to remote output index.
OurOutputIndex tlv.RecordT[tlv.TlvType0, uint16]
// TheirOutputIndex specifies their output index in this commitment. In
// a remote commitment transaction, this is the to local output index.
TheirOutputIndex tlv.RecordT[tlv.TlvType1, uint16]
// CommitTxHash is the hash of the latest version of the commitment
// state, broadcast able by us.
CommitTxHash tlv.RecordT[tlv.TlvType2, [32]byte]
// HTLCEntries is the set of HTLCEntry's that are pending at this
// particular commitment height.
HTLCEntries []*HTLCEntry
// OurBalance is the current available balance within the channel
// directly spendable by us. In other words, it is the value of the
// to_remote output on the remote parties' commitment transaction.
//
// NOTE: this is an option so that it is clear if the value is zero or
// nil. Since migration 30 of the channeldb initially did not include
// this field, it could be the case that the field is not present for
// all revocation logs.
OurBalance tlv.OptionalRecordT[tlv.TlvType3, BigSizeMilliSatoshi]
// TheirBalance is the current available balance within the channel
// directly spendable by the remote node. In other words, it is the
// value of the to_local output on the remote parties' commitment.
//
// NOTE: this is an option so that it is clear if the value is zero or
// nil. Since migration 30 of the channeldb initially did not include
// this field, it could be the case that the field is not present for
// all revocation logs.
TheirBalance tlv.OptionalRecordT[tlv.TlvType4, BigSizeMilliSatoshi]
// CustomBlob is an optional blob that can be used to store information
// specific to a custom channel type. This information is only created
// at channel funding time, and after wards is to be considered
// immutable.
CustomBlob tlv.OptionalRecordT[tlv.TlvType5, tlv.Blob]
}
RevocationLog stores the info needed to construct a breach retribution. Its fields can be viewed as a subset of a ChannelCommitment's. In the database, all historical versions of the RevocationLog are saved using the CommitHeight as the key.
func NewRevocationLog ¶
func NewRevocationLog(ourOutputIndex uint16, theirOutputIndex uint16, commitHash [32]byte, ourBalance, theirBalance fn.Option[lnwire.MilliSatoshi], htlcs []*HTLCEntry, customBlob fn.Option[tlv.Blob]) RevocationLog
NewRevocationLog creates a new RevocationLog from the given parameters.
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 ShutdownInfo ¶
type ShutdownInfo struct {
// DeliveryScript is the address that we have included in any previous
// Shutdown message for a particular channel and so should include in
// any future re-sends of the Shutdown message.
DeliveryScript tlv.RecordT[tlv.TlvType0, lnwire.DeliveryAddress]
// LocalInitiator is true if we sent a Shutdown message before ever
// receiving a Shutdown message from the remote peer.
LocalInitiator tlv.RecordT[tlv.TlvType1, bool]
}
ShutdownInfo contains various info about the shutdown initiation of a channel.
func NewShutdownInfo ¶
func NewShutdownInfo(deliveryScript lnwire.DeliveryAddress, locallyInitiated bool) *ShutdownInfo
NewShutdownInfo constructs a new ShutdownInfo object.
func (ShutdownInfo) Closer ¶
func (s ShutdownInfo) Closer() lntypes.ChannelParty
Closer identifies the ChannelParty that initiated the coop-closure process.
type SparsePayHash ¶
type SparsePayHash [32]byte
SparsePayHash is a type alias for a 32 byte array, which when serialized is able to save some space by not including an empty payment hash on disk.
func NewSparsePayHash ¶
func NewSparsePayHash(rHash [32]byte) SparsePayHash
NewSparsePayHash creates a new SparsePayHash from a 32 byte array.
func (*SparsePayHash) Record ¶
func (s *SparsePayHash) Record() tlv.Record
Record returns a tlv record for the SparsePayHash.
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.RTx, 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.AnnounceSignatures1
// 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.AnnounceSignatures1) *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 kvdb.Backend) (*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, reset func()) error
ForAll iterates thought all waiting proofs and passing the waiting proof in the given callback.
func (*WaitingProofStore) Get ¶
func (s *WaitingProofStore) Get(key WaitingProofKey) (*WaitingProof, error)
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 ¶
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 )