lnwallet

package
v0.18.0-beta Latest Latest
Warning

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

Go to latest
Published: May 29, 2024 License: MIT Imports: 51 Imported by: 257

README

lnwallet

Build Status MIT licensed GoDoc

The lnwallet package implements an abstracted wallet controller that is able to drive channel funding workflows, a number of script utilities, witness generation functions for the various Lightning scripts, revocation key derivation, and the commitment update state machine.

The package is used within lnd as the core wallet of the daemon. The wallet itself is composed of several distinct interfaces that decouple the implementation of things like signing and blockchain access. This separation allows new WalletController implementations to be easily dropped into lnd without disrupting the code base. A series of integration tests at the interface level are also in place to ensure conformance of the implementation with the interface.

Installation and Updating

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

Documentation

Index

Constants

View Source
const (
	// Add is an update type that adds a new HTLC entry into the log.
	// Either side can add a new pending HTLC by adding a new Add entry
	// into their update log.
	Add updateType = iota

	// Fail is an update type which removes a prior HTLC entry from the
	// log. Adding a Fail entry to one's log will modify the _remote_
	// party's update log once a new commitment view has been evaluated
	// which contains the Fail entry.
	Fail

	// MalformedFail is an update type which removes a prior HTLC entry
	// from the log. Adding a MalformedFail entry to one's log will modify
	// the _remote_ party's update log once a new commitment view has been
	// evaluated which contains the MalformedFail entry. The difference
	// from Fail type lie in the different data we have to store.
	MalformedFail

	// Settle is an update type which settles a prior HTLC crediting the
	// balance of the receiving node. Adding a Settle entry to a log will
	// result in the settle entry being removed on the log as well as the
	// original add entry from the remote party's log after the next state
	// transition.
	Settle

	// FeeUpdate is an update type sent by the channel initiator that
	// updates the fee rate used when signing the commitment transaction.
	FeeUpdate
)
View Source
const (
	// CommitmentTypeLegacy is the legacy commitment format with a tweaked
	// to_remote key.
	CommitmentTypeLegacy = iota

	// CommitmentTypeTweakless is a newer commitment format where the
	// to_remote key is static.
	CommitmentTypeTweakless

	// CommitmentTypeAnchorsZeroFeeHtlcTx is a commitment type that is an
	// extension of the outdated CommitmentTypeAnchors, which in addition
	// requires second-level HTLC transactions to be signed using a
	// zero-fee.
	CommitmentTypeAnchorsZeroFeeHtlcTx

	// CommitmentTypeScriptEnforcedLease is a commitment type that builds
	// upon CommitmentTypeTweakless and CommitmentTypeAnchorsZeroFeeHtlcTx,
	// which in addition requires a CLTV clause to spend outputs paying to
	// the channel initiator. This is intended for use on leased channels to
	// guarantee that the channel initiator has no incentives to close a
	// leased channel before its maturity date.
	CommitmentTypeScriptEnforcedLease

	// CommitmentTypeSimpleTaproot is the base commitment type for the
	// channels that use a musig2 funding output and the tapscript tree
	// where relevant for the commitment transaction pk scripts.
	CommitmentTypeSimpleTaproot
)
View Source
const (

	// AnchorChanReservedValue is the amount we'll keep around in the
	// wallet in case we have to fee bump anchor channels on force close.
	// TODO(halseth): update constant to target a specific commit size at
	// set fee rate.
	AnchorChanReservedValue = btcutil.Amount(10_000)

	// MaxAnchorChanReservedValue is the maximum value we'll reserve for
	// anchor channel fee bumping. We cap it at 10 times the per-channel
	// amount such that nodes with a high number of channels don't have to
	// keep around a very large amount for the unlikely scenario that they
	// all close at the same time.
	MaxAnchorChanReservedValue = 10 * AnchorChanReservedValue
)
View Source
const (
	// DefaultAccountName is the name for the default account used to manage
	// on-chain funds within the wallet.
	DefaultAccountName = "default"
)
View Source
const DefaultAnchorsCommitMaxFeeRateSatPerVByte = 10

DefaultAnchorsCommitMaxFeeRateSatPerVByte is the default max fee rate in sat/vbyte the initiator will use for anchor channels. This should be enough to ensure propagation before anchoring down the commitment transaction.

View Source
const (

	// DefaultRoutingFeePercentage is the default off-chain routing fee we
	// allow to be charged for a payment over the RoutingFee100PercentUpTo
	// size.
	DefaultRoutingFeePercentage lnwire.MilliSatoshi = 5
)
View Source
const (
	// StateHintSize is the total number of bytes used between the sequence
	// number and locktime of the commitment transaction use to encode a hint
	// to the state number of a particular commitment transaction.
	StateHintSize = 6
)

Variables

View Source
var (
	// ErrChanClosing is returned when a caller attempts to close a channel
	// that has already been closed or is in the process of being closed.
	ErrChanClosing = fmt.Errorf("channel is being closed, operation disallowed")

	// ErrNoWindow is returned when revocation window is exhausted.
	ErrNoWindow = fmt.Errorf("unable to sign new commitment, the current" +
		" revocation window is exhausted")

	// ErrMaxWeightCost is returned when the cost/weight (see segwit)
	// exceeds the widely used maximum allowed policy weight limit. In this
	// case the commitment transaction can't be propagated through the
	// network.
	ErrMaxWeightCost = fmt.Errorf("commitment transaction exceed max " +
		"available cost")

	// ErrMaxHTLCNumber is returned when a proposed HTLC would exceed the
	// maximum number of allowed HTLC's if committed in a state transition
	ErrMaxHTLCNumber = fmt.Errorf("commitment transaction exceed max " +
		"htlc number")

	// ErrMaxPendingAmount is returned when a proposed HTLC would exceed
	// the overall maximum pending value of all HTLCs if committed in a
	// state transition.
	ErrMaxPendingAmount = fmt.Errorf("commitment transaction exceed max" +
		"overall pending htlc value")

	// ErrBelowChanReserve is returned when a proposed HTLC would cause
	// one of the peer's funds to dip below the channel reserve limit.
	ErrBelowChanReserve = fmt.Errorf("commitment transaction dips peer " +
		"below chan reserve")

	// ErrBelowMinHTLC is returned when a proposed HTLC has a value that
	// is below the minimum HTLC value constraint for either us or our
	// peer depending on which flags are set.
	ErrBelowMinHTLC = fmt.Errorf("proposed HTLC value is below minimum " +
		"allowed HTLC value")

	// ErrFeeBufferNotInitiator is returned when the FeeBuffer is enforced
	// although the channel was not initiated (opened) locally.
	ErrFeeBufferNotInitiator = fmt.Errorf("unable to enforce FeeBuffer, " +
		"not initiator of the channel")

	// ErrInvalidHTLCAmt signals that a proposed HTLC has a value that is
	// not positive.
	ErrInvalidHTLCAmt = fmt.Errorf("proposed HTLC value must be positive")

	// ErrCannotSyncCommitChains is returned if, upon receiving a ChanSync
	// message, the state machine deems that is unable to properly
	// synchronize states with the remote peer. In this case we should fail
	// the channel, but we won't automatically force close.
	ErrCannotSyncCommitChains = fmt.Errorf("unable to sync commit chains")

	// ErrInvalidLastCommitSecret is returned in the case that the
	// commitment secret sent by the remote party in their
	// ChannelReestablish message doesn't match the last secret we sent.
	ErrInvalidLastCommitSecret = fmt.Errorf("commit secret is incorrect")

	// ErrInvalidLocalUnrevokedCommitPoint is returned in the case that the
	// commitment point sent by the remote party in their
	// ChannelReestablish message doesn't match the last unrevoked commit
	// point they sent us.
	ErrInvalidLocalUnrevokedCommitPoint = fmt.Errorf("unrevoked commit " +
		"point is invalid")

	// ErrCommitSyncRemoteDataLoss is returned in the case that we receive
	// a ChannelReestablish message from the remote that advertises a
	// NextLocalCommitHeight that is lower than what they have already
	// ACKed, or a RemoteCommitTailHeight that is lower than our revoked
	// height. In this case we should force close the channel such that
	// both parties can retrieve their funds.
	ErrCommitSyncRemoteDataLoss = fmt.Errorf("possible remote commitment " +
		"state data loss")

	// ErrNoRevocationLogFound is returned when both the returned logs are
	// nil from querying the revocation log bucket. In theory this should
	// never happen as the query will return `ErrLogEntryNotFound`, yet
	// we'd still perform a sanity check to make sure at least one of the
	// logs is non-nil.
	ErrNoRevocationLogFound = errors.New("no revocation log found")

	// ErrOutputIndexOutOfRange is returned when an output index is greater
	// than or equal to the length of a given transaction's outputs.
	ErrOutputIndexOutOfRange = errors.New("output index is out of range")

	// ErrRevLogDataMissing is returned when a certain wanted optional field
	// in a revocation log entry is missing.
	ErrRevLogDataMissing = errors.New("revocation log data missing")

	// ErrForceCloseLocalDataLoss is returned in the case a user (or
	// another sub-system) attempts to force close when we've detected that
	// we've likely lost data ourselves.
	ErrForceCloseLocalDataLoss = errors.New("cannot force close " +
		"channel with local data loss")
)
View Source
var (
	// DefaultPublicPassphrase is the default public passphrase used for the
	// wallet.
	DefaultPublicPassphrase = []byte("public")

	// DefaultPrivatePassphrase is the default private passphrase used for
	// the wallet.
	DefaultPrivatePassphrase = []byte("hello")

	// ErrDoubleSpend is returned from PublishTransaction in case the
	// tx being published is spending an output spent by a conflicting
	// transaction.
	ErrDoubleSpend = errors.New("transaction rejected: output already spent")

	// ErrNotMine is an error denoting that a WalletController instance is
	// unable to spend a specified output.
	ErrNotMine = errors.New("the passed output doesn't belong to the wallet")

	// ErrMempoolFee is returned from PublishTransaction in case the tx
	// being published is not accepted into mempool because the fee
	// requirements of the mempool backend are not met.
	ErrMempoolFee = errors.New("transaction rejected by the mempool " +
		"because of low fees")
)
View Source
var (
	// ErrPsbtFundingRequired is the error that is returned during the
	// contribution handling process if the process should be paused for
	// the construction of a PSBT outside of lnd's wallet.
	ErrPsbtFundingRequired = errors.New("PSBT funding required")

	// ErrReservedValueInvalidated is returned if we try to publish a
	// transaction that would take the walletbalance below what we require
	// to keep around to fee bump our open anchor channels.
	ErrReservedValueInvalidated = errors.New("reserved wallet balance " +
		"invalidated: transaction would leave insufficient funds for " +
		"fee bumping anchor channel closings (see debug log for details)")

	// ErrEmptyPendingChanID is returned when an empty value is used for
	// the pending channel ID.
	ErrEmptyPendingChanID = errors.New("pending channel ID is empty")

	// ErrDuplicatePendingChanID is returned when an existing pending
	// channel ID is registered again.
	ErrDuplicatePendingChanID = errors.New("duplicate pending channel ID")
)
View Source
var (
	CoinPkScript, _ = hex.DecodeString(
		"001431df1bde03c074d0cf21ea2529427e1499b8f1de",
	)
)
View Source
var ErrInvalidMinconf = errors.New("minimum number of confirmations must " +
	"be a non-negative number")

ErrInvalidMinconf is returned if we try to create a transaction with invalid minConfs value.

View Source
var ErrNoOutputs = errors.New("no outputs")

ErrNoOutputs is returned if we try to create a transaction with no outputs or send coins to a set of outputs that is empty.

View Source
var (
	// ErrSessionNotFinalized is returned when the SignCommit method is
	// called for a local commitment, without the session being finalized
	// (missing nonce).
	ErrSessionNotFinalized = fmt.Errorf("musig2 session not finalized")
)
View Source
var (
	// RoutingFee100PercentUpTo is the cut-off amount we allow 100% fees to
	// be charged up to.
	RoutingFee100PercentUpTo = lnwire.NewMSatFromSatoshis(1_000)
)
View Source
var (
	// TimelockShift is used to make sure the commitment transaction is
	// spendable by setting the locktime with it so that it is larger than
	// 500,000,000, thus interpreting it as Unix epoch timestamp and not
	// a block height. It is also smaller than the current timestamp which
	// has bit (1 << 30) set, so there is no risk of having the commitment
	// transaction be rejected. This way we can safely use the lower 24 bits
	// of the locktime field for part of the obscured commitment transaction
	// number.
	TimelockShift = uint32(1 << 29)
)

Functions

func CalcFeeBuffer

func CalcFeeBuffer(feePerKw chainfee.SatPerKWeight,
	commitWeight lntypes.WeightUnit) lnwire.MilliSatoshi

CalcFeeBuffer calculates a FeeBuffer in accordance with the recommended amount specified in BOLT 02. It accounts for two times the current fee rate plus an additional htlc at this higher fee rate which allows our peer to add an htlc even if our channel is drained locally. See: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md

func CommitScriptAnchors

func CommitScriptAnchors(chanType channeldb.ChannelType,
	localChanCfg, remoteChanCfg *channeldb.ChannelConfig,
	keyRing *CommitmentKeyRing) (
	input.ScriptDescriptor, input.ScriptDescriptor, error)

CommitScriptAnchors return the scripts to use for the local and remote anchor.

func CommitScriptToRemote

func CommitScriptToRemote(chanType channeldb.ChannelType, initiator bool,
	remoteKey *btcec.PublicKey,
	leaseExpiry uint32) (input.ScriptDescriptor, uint32, error)

CommitScriptToRemote derives the appropriate to_remote script based on the channel's commitment type. The `initiator` argument should correspond to the owner of the commitment transaction which we are generating the to_remote script for. The second return value is the CSV delay of the output script, what must be satisfied in order to spend the output.

func CommitScriptToSelf

func CommitScriptToSelf(chanType channeldb.ChannelType, initiator bool,
	selfKey, revokeKey *btcec.PublicKey, csvDelay, leaseExpiry uint32,
) (
	input.ScriptDescriptor, error)

CommitScriptToSelf constructs the public key script for the output on the commitment transaction paying to the "owner" of said commitment transaction. The `initiator` argument should correspond to the owner of the commitment transaction which we are generating the to_local script for. If the other party learns of the preimage to the revocation hash, then they can claim all the settled funds in the channel, plus the unsettled funds.

func CommitWeight

func CommitWeight(chanType channeldb.ChannelType) lntypes.WeightUnit

CommitWeight returns the base commitment weight before adding HTLCs.

func CoopCloseBalance

func CoopCloseBalance(chanType channeldb.ChannelType, isInitiator bool,
	coopCloseFee btcutil.Amount, localCommit channeldb.ChannelCommitment) (
	btcutil.Amount, btcutil.Amount, error)

CoopCloseBalance returns the final balances that should be used to create the cooperative close tx, given the channel type and transaction fee.

func CreateCommitTx

func CreateCommitTx(chanType channeldb.ChannelType,
	fundingOutput wire.TxIn, keyRing *CommitmentKeyRing,
	localChanCfg, remoteChanCfg *channeldb.ChannelConfig,
	amountToLocal, amountToRemote btcutil.Amount,
	numHTLCs int64, initiator bool, leaseExpiry uint32) (*wire.MsgTx, error)

CreateCommitTx creates a commitment transaction, spending from specified funding output. The commitment transaction contains two outputs: one local output paying to the "owner" of the commitment transaction which can be spent after a relative block delay or revocation event, and a remote output paying the counterparty within the channel, which can be spent immediately or after a delay depending on the commitment type. The `initiator` argument should correspond to the owner of the commitment transaction we are creating.

func CreateCommitmentTxns

func CreateCommitmentTxns(localBalance, remoteBalance btcutil.Amount,
	ourChanCfg, theirChanCfg *channeldb.ChannelConfig,
	localCommitPoint, remoteCommitPoint *btcec.PublicKey,
	fundingTxIn wire.TxIn, chanType channeldb.ChannelType, initiator bool,
	leaseExpiry uint32) (*wire.MsgTx, *wire.MsgTx, error)

CreateCommitmentTxns is a helper function that creates the initial commitment transaction for both parties. This function is used during the initial funding workflow as both sides must generate a signature for the remote party's commitment transaction, and verify the signature for their version of the commitment transaction.

func CreateCooperativeCloseTx

func CreateCooperativeCloseTx(fundingTxIn wire.TxIn,
	localDust, remoteDust, ourBalance, theirBalance btcutil.Amount,
	ourDeliveryScript, theirDeliveryScript []byte,
	closeOpts ...CloseTxOpt) *wire.MsgTx

CreateCooperativeCloseTx creates a transaction which if signed by both parties, then broadcast cooperatively closes an active channel. The creation of the closure transaction is modified by a boolean indicating if the party constructing the channel is the initiator of the closure. Currently it is expected that the initiator pays the transaction fees for the closing transaction in full.

func CreateHtlcSuccessTx

func CreateHtlcSuccessTx(chanType channeldb.ChannelType, initiator bool,
	htlcOutput wire.OutPoint, htlcAmt btcutil.Amount, csvDelay,
	leaseExpiry uint32, revocationKey, delayKey *btcec.PublicKey) (
	*wire.MsgTx, error)

CreateHtlcSuccessTx creates a transaction that spends the output on the commitment transaction of the peer that receives an HTLC. This transaction essentially acts as an off-chain covenant as it's only permitted to spend the designated HTLC output, and also that spend can _only_ be used as a state transition to create another output which actually allows redemption or revocation of an HTLC.

In order to spend the segwit v0 HTLC output, the witness for the passed transaction should be:

  • <0> <sender sig> <recvr sig> <preimage>

In order to spend the segwit v1 (taproot) HTLC output, the witness for the passed transaction should be:

  • <sender sig> <receiver sig> <preimage> <success_script> <control_block>

func CreateHtlcTimeoutTx

func CreateHtlcTimeoutTx(chanType channeldb.ChannelType, initiator bool,
	htlcOutput wire.OutPoint, htlcAmt btcutil.Amount,
	cltvExpiry, csvDelay, leaseExpiry uint32,
	revocationKey, delayKey *btcec.PublicKey) (*wire.MsgTx, error)

CreateHtlcTimeoutTx creates a transaction that spends the HTLC output on the commitment transaction of the peer that created an HTLC (the sender). This transaction essentially acts as an off-chain covenant as it spends a 2-of-2 multi-sig output. This output requires a signature from both the sender and receiver of the HTLC. By using a distinct transaction, we're able to uncouple the timeout and delay clauses of the HTLC contract. This transaction is locked with an absolute lock-time so the sender can only attempt to claim the output using it after the lock time has passed.

In order to spend the HTLC output for segwit v0, the witness for the passed transaction should be:

  • <0> <sender sig> <receiver sig> <0>

In order to spend the HTLC output for segwit v1, then witness for the passed transaction should be:

  • <sender sig> <receiver sig> <timeout_script> <control_block>

NOTE: The passed amount for the HTLC should take into account the required fee rate at the time the HTLC was created. The fee should be able to entirely pay for this (tiny: 1-in 1-out) transaction.

func CreateTestChannels

func CreateTestChannels(t *testing.T, chanType channeldb.ChannelType,
	dbModifiers ...channeldb.OptionModifier) (*LightningChannel,
	*LightningChannel, error)

CreateTestChannels creates to fully populated channels to be used within testing fixtures. The channels will be returned as if the funding process has just completed. The channel itself is funded with 10 BTC, with 5 BTC allocated to each side. Within the channel, Alice is the initiator. If tweaklessCommits is true, then the commits within the channels will use the new format, otherwise the legacy format.

func DefaultRoutingFeeLimitForAmount

func DefaultRoutingFeeLimitForAmount(a lnwire.MilliSatoshi) lnwire.MilliSatoshi

DefaultRoutingFeeLimitForAmount returns the default off-chain routing fee limit lnd uses if the user does not specify a limit manually. The fee is amount dependent because of the base routing fee that is set on many channels. For example the default base fee is 1 satoshi. So sending a payment of one satoshi will cost 1 satoshi in fees over most channels, which comes to a fee of 100%. That's why for very small amounts we allow 100% fee.

func DeriveStateHintObfuscator

func DeriveStateHintObfuscator(key1, key2 *btcec.PublicKey) [StateHintSize]byte

DeriveStateHintObfuscator derives the bytes to be used for obfuscating the state hints from the root to be used for a new channel. The obfuscator is generated via the following computation:

  • sha256(initiatorKey || responderKey)[26:] -- where both keys are the multi-sig keys of the respective parties

The first 6 bytes of the resulting hash are used as the state hint.

func DisableLog

func DisableLog()

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

func DustLimitForSize

func DustLimitForSize(scriptSize int) btcutil.Amount

DustLimitForSize retrieves the dust limit for a given pkscript size. Given the size, it automatically determines whether the script is a witness script or not. It calls btcd's GetDustThreshold method under the hood. It must be called with a proper size parameter or else a panic occurs.

func DustLimitUnknownWitness

func DustLimitUnknownWitness() btcutil.Amount

DustLimitUnknownWitness returns the dust limit for an UnknownWitnessSize.

func ErrNumConfsTooLarge

func ErrNumConfsTooLarge(numConfs, maxNumConfs uint32) error

ErrNumConfsTooLarge returns an error indicating that the number of confirmations required for a channel is too large.

func ForceStateTransition

func ForceStateTransition(chanA, chanB *LightningChannel) error

ForceStateTransition executes the necessary interaction between the two commitment state machines to transition to a new state locking in any pending updates. This method is useful when testing interactions between two live state machines.

func GetStateNumHint

func GetStateNumHint(commitTx *wire.MsgTx, obfuscator [StateHintSize]byte) uint64

GetStateNumHint recovers the current state number given a commitment transaction which has previously had the state number encoded within it via setStateNumHint and a shared obfuscator.

See setStateNumHint for further details w.r.t exactly how the state-hints are encoded.

func HtlcIsDust

func HtlcIsDust(chanType channeldb.ChannelType,
	incoming, ourCommit bool, feePerKw chainfee.SatPerKWeight,
	htlcAmt, dustLimit btcutil.Amount) bool

HtlcIsDust determines if an HTLC output is dust or not depending on two bits: if the HTLC is incoming and if the HTLC will be placed on our commitment transaction, or theirs. These two pieces of information are required as we currently used second-level HTLC transactions as off-chain covenants. Depending on the two bits, we'll either be using a timeout or success transaction which have different weights.

func HtlcSecondLevelInputSequence

func HtlcSecondLevelInputSequence(chanType channeldb.ChannelType) uint32

HtlcSecondLevelInputSequence dictates the sequence number we must use on the input to a second level HTLC transaction.

func HtlcSigHashType

func HtlcSigHashType(chanType channeldb.ChannelType) txscript.SigHashType

HtlcSigHashType returns the sighash type to use for HTLC success and timeout transactions given the channel type.

func HtlcSignDetails

func HtlcSignDetails(chanType channeldb.ChannelType, signDesc input.SignDescriptor,
	sigHash txscript.SigHashType, peerSig input.Signature) *input.SignDetails

HtlcSignDetails converts the passed parameters to a SignDetails valid for this channel type. For non-anchor channels this will return nil.

func HtlcSuccessFee

func HtlcSuccessFee(chanType channeldb.ChannelType,
	feePerKw chainfee.SatPerKWeight) btcutil.Amount

HtlcSuccessFee returns the fee in satoshis required for an HTLC success transaction based on the current fee rate.

func HtlcTimeoutFee

func HtlcTimeoutFee(chanType channeldb.ChannelType,
	feePerKw chainfee.SatPerKWeight) btcutil.Amount

HtlcTimeoutFee returns the fee in satoshis required for an HTLC timeout transaction based on the current fee rate.

func InPlaceCommitSort

func InPlaceCommitSort(tx *wire.MsgTx, cltvs []uint32)

InPlaceCommitSort performs an in-place sort of a commitment transaction, given an unsorted transaction and a list of CLTV values for the HTLCs.

The sort applied is a modified BIP69 sort, that uses the CLTV values of HTLCs as a tie breaker in case two HTLC outputs have an identical amount and pkscript. The pkscripts can be the same if they share the same payment hash, but since the CLTV is enforced via the nLockTime of the second-layer transactions, the script does not directly commit to them. Instead, the CLTVs must be supplied separately to act as a tie-breaker, otherwise we may produce invalid HTLC signatures if the receiver produces an alternative ordering during verification.

NOTE: Commitment outputs should have a 0 CLTV corresponding to their index on the unsorted commitment transaction.

func RegisterWallet

func RegisterWallet(driver *WalletDriver) error

RegisterWallet registers a WalletDriver which is capable of driving a concrete WalletController interface. In the case that this driver has already been registered, an error is returned.

NOTE: This function is safe for concurrent access.

func SecondLevelHtlcScript

func SecondLevelHtlcScript(chanType channeldb.ChannelType, initiator bool,
	revocationKey, delayKey *btcec.PublicKey,
	csvDelay, leaseExpiry uint32) (input.ScriptDescriptor, error)

SecondLevelHtlcScript derives the appropriate second level HTLC script based on the channel's commitment type. It is the uniform script that's used as the output for the second-level HTLC transactions. The second level transaction act as a sort of covenant, ensuring that a 2-of-2 multi-sig output can only be spent in a particular way, and to a particular output. The `initiator` argument should correspond to the owner of the commitment transaction which we are generating the to_local script for.

func SetStateNumHint

func SetStateNumHint(commitTx *wire.MsgTx, stateNum uint64,
	obfuscator [StateHintSize]byte) error

SetStateNumHint encodes the current state number within the passed commitment transaction by re-purposing the locktime and sequence fields in the commitment transaction to encode the obfuscated state number. The state number is encoded using 48 bits. The lower 24 bits of the lock time are the lower 24 bits of the obfuscated state number and the lower 24 bits of the sequence field are the higher 24 bits. Finally before encoding, the obfuscator is XOR'd against the state number in order to hide the exact state number from the PoV of outside parties.

func SupportedWallets

func SupportedWallets() []string

SupportedWallets returns a slice of strings that represents the wallet drivers that have been registered and are therefore supported.

NOTE: This function is safe for concurrent access.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

func ValidateUpfrontShutdown

func ValidateUpfrontShutdown(shutdown lnwire.DeliveryAddress,
	params *chaincfg.Params) bool

ValidateUpfrontShutdown checks whether the provided upfront_shutdown_script is of a valid type that we accept.

func VerifyConstraints

func VerifyConstraints(c *channeldb.ChannelConstraints,
	maxLocalCSVDelay uint16, channelCapacity btcutil.Amount) error

VerifyConstraints is a helper function that can be used to check the sanity of various channel constraints.

Types

type AccountAddressMap

type AccountAddressMap map[*waddrmgr.AccountProperties][]AddressProperty

AccountAddressMap maps the account properties to an array of address properties.

type AccountIdentifier

type AccountIdentifier struct {
	// Name is the name of the account.
	Name string

	// AddressType is the type of addresses supported by the account.
	AddressType AddressType

	// DerivationPath is the derivation path corresponding to the account
	// public key.
	DerivationPath string
}

AccountIdentifier contains information to uniquely identify an account.

type AddressProperty

type AddressProperty struct {
	// Address is the address of an account.
	Address string

	// Internal denotes if the address is a change address.
	Internal bool

	// Balance returns the total balance of an address.
	Balance btcutil.Amount

	// DerivationPath is the derivation path of the address.
	DerivationPath string

	// PublicKey is the public key of the address.
	PublicKey *btcec.PublicKey
}

AddressProperty contains wallet related information of an address.

type AddressType

type AddressType uint8

AddressType is an enum-like type which denotes the possible address types WalletController supports.

const (
	// UnknownAddressType represents an output with an unknown or non-standard
	// script.
	UnknownAddressType AddressType = iota

	// WitnessPubKey represents a p2wkh address.
	WitnessPubKey

	// NestedWitnessPubKey represents a p2sh output which is itself a
	// nested p2wkh output.
	NestedWitnessPubKey

	// TaprootPubkey represents a p2tr key path spending address.
	TaprootPubkey
)

type AnchorResolution

type AnchorResolution struct {
	// AnchorSignDescriptor is the sign descriptor for our anchor.
	AnchorSignDescriptor input.SignDescriptor

	// CommitAnchor is the anchor outpoint on the commit tx.
	CommitAnchor wire.OutPoint

	// CommitFee is the fee of the commit tx.
	CommitFee btcutil.Amount

	// CommitWeight is the weight of the commit tx.
	CommitWeight lntypes.WeightUnit
}

AnchorResolution holds the information necessary to spend our commitment tx anchor.

func NewAnchorResolution

func NewAnchorResolution(chanState *channeldb.OpenChannel,
	commitTx *wire.MsgTx, keyRing *CommitmentKeyRing,
	isLocalCommit bool) (*AnchorResolution, error)

NewAnchorResolution returns the information that is required to sweep the local anchor.

type AnchorResolutions

type AnchorResolutions struct {
	// Local is the anchor resolution for the local commitment tx.
	Local *AnchorResolution

	// Remote is the anchor resolution for the remote commitment tx.
	Remote *AnchorResolution

	// RemotePending is the anchor resolution for the remote pending
	// commitment tx. The value will be non-nil iff we've created a new
	// commitment tx for the remote party which they haven't ACKed yet.
	RemotePending *AnchorResolution
}

AnchorResolutions is a set of anchor resolutions that's being used when sweeping anchors during local channel force close.

type BlockChainIO

type BlockChainIO interface {
	// GetBestBlock returns the current height and block hash of the valid
	// most-work chain the implementation is aware of.
	GetBestBlock() (*chainhash.Hash, int32, error)

	// GetUtxo attempts to return the passed outpoint if it's still a
	// member of the utxo set. The passed height hint should be the "birth
	// height" of the passed outpoint. The script passed should be the
	// script that the outpoint creates. In the case that the output is in
	// the UTXO set, then the output corresponding to that output is
	// returned.  Otherwise, a non-nil error will be returned.
	// As for some backends this call can initiate a rescan, the passed
	// cancel channel can be closed to abort the call.
	GetUtxo(op *wire.OutPoint, pkScript []byte, heightHint uint32,
		cancel <-chan struct{}) (*wire.TxOut, error)

	// GetBlockHash returns the hash of the block in the best blockchain
	// at the given height.
	GetBlockHash(blockHeight int64) (*chainhash.Hash, error)

	// GetBlock returns the block in the main chain identified by the given
	// hash.
	GetBlock(blockHash *chainhash.Hash) (*wire.MsgBlock, error)

	// GetBlockHeader returns the block header for the given block hash.
	GetBlockHeader(blockHash *chainhash.Hash) (*wire.BlockHeader, error)
}

BlockChainIO is a dedicated source which will be used to obtain queries related to the current state of the blockchain. The data returned by each of the defined methods within this interface should always return the most up to date data possible.

TODO(roasbeef): move to diff package perhaps? TODO(roasbeef): move publish txn here?

type BreachRetribution

type BreachRetribution struct {
	// BreachTxHash is the transaction hash which breached the channel
	// contract by spending from the funding multi-sig with a revoked
	// commitment transaction.
	BreachTxHash chainhash.Hash

	// BreachHeight records the block height confirming the breach
	// transaction, used as a height hint when registering for
	// confirmations.
	BreachHeight uint32

	// ChainHash is the chain that the contract beach was identified
	// within. This is also the resident chain of the contract (the chain
	// the contract was created on).
	ChainHash chainhash.Hash

	// RevokedStateNum is the revoked state number which was broadcast.
	RevokedStateNum uint64

	// LocalOutputSignDesc is a SignDescriptor which is capable of
	// generating the signature necessary to sweep the output within the
	// breach transaction that pays directly us.
	//
	// NOTE: A nil value indicates that the local output is considered dust
	// according to the remote party's dust limit.
	LocalOutputSignDesc *input.SignDescriptor

	// LocalOutpoint is the outpoint of the output paying to us (the local
	// party) within the breach transaction.
	LocalOutpoint wire.OutPoint

	// LocalDelay is the CSV delay for the to_remote script on the breached
	// commitment.
	LocalDelay uint32

	// RemoteOutputSignDesc is a SignDescriptor which is capable of
	// generating the signature required to claim the funds as described
	// within the revocation clause of the remote party's commitment
	// output.
	//
	// NOTE: A nil value indicates that the local output is considered dust
	// according to the remote party's dust limit.
	RemoteOutputSignDesc *input.SignDescriptor

	// RemoteOutpoint is the outpoint of the output paying to the remote
	// party within the breach transaction.
	RemoteOutpoint wire.OutPoint

	// RemoteDelay specifies the CSV delay applied to to-local scripts on
	// the breaching commitment transaction.
	RemoteDelay uint32

	// HtlcRetributions is a slice of HTLC retributions for each output
	// active HTLC output within the breached commitment transaction.
	HtlcRetributions []HtlcRetribution

	// KeyRing contains the derived public keys used to construct the
	// breaching commitment transaction. This allows downstream clients to
	// have access to the public keys used in the scripts.
	KeyRing *CommitmentKeyRing
}

BreachRetribution contains all the data necessary to bring a channel counterparty to justice claiming ALL lingering funds within the channel in the scenario that they broadcast a revoked commitment transaction. A BreachRetribution is created by the closeObserver if it detects an uncooperative close of the channel which uses a revoked commitment transaction. The BreachRetribution is then sent over the ContractBreach channel in order to allow the subscriber of the channel to dispatch justice.

func NewBreachRetribution

func NewBreachRetribution(chanState *channeldb.OpenChannel, stateNum uint64,
	breachHeight uint32, spendTx *wire.MsgTx) (*BreachRetribution, error)

NewBreachRetribution creates a new fully populated BreachRetribution for the passed channel, at a particular revoked state number. If the spend transaction that the breach retribution should target is known, then it can be provided via the spendTx parameter. Otherwise, if the spendTx parameter is nil, then the revocation log will be checked to see if it contains the info required to construct the BreachRetribution. If the revocation log is missing the required fields then ErrRevLogDataMissing will be returned.

type BufferType

type BufferType uint8

BufferType is used to determine what kind of additional buffer should be left when evaluating the usable balance of a channel.

const (
	// NoBuffer means no additional buffer is accounted for. This is
	// important when verifying an already locked-in commitment state.
	NoBuffer BufferType = iota

	// FeeBuffer accounts for several edge cases. One of them is where
	// a locally drained channel might become unusable due to the non-opener
	// of the channel not being able to add a non-dust htlc to the channel
	// state because we as a channel opener cannot pay the additional fees
	// an htlc would require on the commitment tx.
	// See: https://github.com/lightningnetwork/lightning-rfc/issues/728
	//
	// Moreover it mitigates the situation where htlcs are added
	// simultaneously to the commitment transaction. This cannot be avoided
	// until the feature __option_simplified_update__ is available in the
	// protocol and deployed widely in the network.
	// More information about the issue and the simplified commitment flow
	// can be found here:
	// https://github.com/lightningnetwork/lnd/issues/7657
	// https://github.com/lightning/bolts/pull/867
	//
	// The last advantage is that we can react to fee spikes (up or down)
	// by accounting for at least twice the size of the current fee rate
	// (BOLT02). It also accounts for decreases in the fee rate because
	// former dust htlcs might now become normal outputs so the overall
	// fee might increase although the fee rate decreases (this is only true
	// for non-anchor channels because htlcs have to account for their
	// fee of the second-level covenant transactions).
	FeeBuffer

	// AdditionalHtlc just accounts for an additional htlc which is helpful
	// when deciding about a fee update of the commitment transaction.
	// Leaving always room for an additional htlc makes sure that even
	// though we are the opener of a channel a new fee update will always
	// allow an htlc from our peer to be added to the commitment tx.
	AdditionalHtlc
)

func (BufferType) String

func (b BufferType) String() string

String returns a human readable name for the buffer type.

type ChanCloseOpt

type ChanCloseOpt func(*chanCloseOpt)

ChanCloseOpt is a closure type that cen be used to modify the set of default options.

func WithCoopCloseMusigSession

func WithCoopCloseMusigSession(session *MusigSession) ChanCloseOpt

WithCoopCloseMusigSession can be used to apply an existing musig2 session to the cooperative close process. If specified, then a musig2 co-op close (single sig keyspend) will be used.

type ChannelContribution

type ChannelContribution struct {
	// FundingOutpoint is the amount of funds contributed to the funding
	// transaction.
	FundingAmount btcutil.Amount

	// Inputs to the funding transaction.
	Inputs []*wire.TxIn

	// ChangeOutputs are the Outputs to be used in the case that the total
	// value of the funding inputs is greater than the total potential
	// channel capacity.
	ChangeOutputs []*wire.TxOut

	// FirstCommitmentPoint is the first commitment point that will be used
	// to create the revocation key in the first commitment transaction we
	// send to the remote party.
	FirstCommitmentPoint *btcec.PublicKey

	// ChannelConfig is the concrete contribution that this node is
	// offering to the channel. This includes all the various constraints
	// such as the min HTLC, and also all the keys which will be used for
	// the duration of the channel.
	*channeldb.ChannelConfig

	// UpfrontShutdown is an optional address to which the channel should be
	// paid out to on cooperative close.
	UpfrontShutdown lnwire.DeliveryAddress

	// LocalNonce is populated if the channel type is a simple taproot
	// channel. This stores the public (and secret) nonce that will be used
	// to generate commitments for the local party.
	LocalNonce *musig2.Nonces
}

ChannelContribution is the primary constituent of the funding workflow within lnwallet. Each side first exchanges their respective contributions along with channel specific parameters like the min fee/KB. Once contributions have been exchanged, each side will then produce signatures for all their inputs to the funding transactions, and finally a signature for the other party's version of the commitment transaction.

type ChannelOpt

type ChannelOpt func(*channelOpts)

ChannelOpt is a functional option that lets callers modify how a new channel is created.

func WithLocalMusigNonces

func WithLocalMusigNonces(nonce *musig2.Nonces) ChannelOpt

WithLocalMusigNonces is used to bind an existing verification/local nonce to a new channel.

func WithRemoteMusigNonces

func WithRemoteMusigNonces(nonces *musig2.Nonces) ChannelOpt

WithRemoteMusigNonces is used to bind the remote party's local/verification nonce to a new channel.

func WithSkipNonceInit

func WithSkipNonceInit() ChannelOpt

WithSkipNonceInit is used to modify the way nonces are handled during channel initialization for taproot channels. If this option is specified, then when we receive the chan reest message from the remote party, we won't modify our nonce state. This is needed if we create a channel, get a channel ready message, then also get the chan reest message after that.

type ChannelReservation

type ChannelReservation struct {
	// This mutex MUST be held when either reading or modifying any of the
	// fields below.
	sync.RWMutex
	// contains filtered or unexported fields
}

ChannelReservation represents an intent to open a lightning payment channel with a counterparty. The funding processes from reservation to channel opening is a 3-step process. In order to allow for full concurrency during the reservation workflow, resources consumed by a contribution are "locked" themselves. This prevents a number of race conditions such as two funding transactions double-spending the same input. A reservation can also be canceled, which removes the resources from limbo, allowing another reservation to claim them.

The reservation workflow consists of the following three steps:

  1. lnwallet.InitChannelReservation * One requests the wallet to allocate the necessary resources for a channel reservation. These resources are put in limbo for the lifetime of a reservation. * Once completed the reservation will have the wallet's contribution accessible via the .OurContribution() method. This contribution contains the necessary items to allow the remote party to build both the funding, and commitment transactions.
  2. ChannelReservation.ProcessContribution/ChannelReservation.ProcessSingleContribution * The counterparty presents their contribution to the payment channel. This allows us to build the funding, and commitment transactions ourselves. * We're now able to sign our inputs to the funding transactions, and the counterparty's version of the commitment transaction. * All signatures crafted by us, are now available via .OurSignatures().
  3. ChannelReservation.CompleteReservation/ChannelReservation.CompleteReservationSingle * The final step in the workflow. The counterparty presents the signatures for all their inputs to the funding transaction, as well as a signature to our version of the commitment transaction. * We then verify the validity of all signatures before considering the channel "open".

func NewChannelReservation

func NewChannelReservation(capacity, localFundingAmt btcutil.Amount,
	wallet *LightningWallet, id uint64, chainHash *chainhash.Hash,
	thawHeight uint32, req *InitFundingReserveMsg) (*ChannelReservation,
	error)

NewChannelReservation creates a new channel reservation. This function is used only internally by lnwallet. In order to concurrent safety, the creation of all channel reservations should be carried out via the lnwallet.InitChannelReservation interface.

func (*ChannelReservation) AddAlias

func (r *ChannelReservation) AddAlias(scid lnwire.ShortChannelID)

AddAlias stores the first alias for zero-conf channels.

func (*ChannelReservation) Cancel

func (r *ChannelReservation) Cancel() error

Cancel abandons this channel reservation. This method should be called in the scenario that communications with the counterparty break down. Upon cancellation, all resources previously reserved for this pending payment channel are returned to the free pool, allowing subsequent reservations to utilize the now freed resources.

func (*ChannelReservation) Capacity

func (r *ChannelReservation) Capacity() btcutil.Amount

Capacity returns the channel capacity for this reservation.

func (*ChannelReservation) CommitConstraints

func (r *ChannelReservation) CommitConstraints(c *channeldb.ChannelConstraints,
	maxLocalCSVDelay uint16, responder bool) error

CommitConstraints takes the constraints that the remote party specifies for the type of commitments that we can generate for them. These constraints include several parameters that serve as flow control restricting the amount of satoshis that can be transferred in a single commitment. This function will also attempt to verify the constraints for sanity, returning an error if the parameters are seemed unsound.

func (*ChannelReservation) CompleteReservation

func (r *ChannelReservation) CompleteReservation(fundingInputScripts []*input.Script,
	commitmentSig input.Signature) (*channeldb.OpenChannel, error)

CompleteReservation finalizes the pending channel reservation, transitioning from a pending payment channel, to an open payment channel. All passed signatures to the counterparty's inputs to the funding transaction will be fully verified. Signatures are expected to be passed in sorted order according to BIP-69: https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki. Additionally, verification is performed in order to ensure that the counterparty supplied a valid signature to our version of the commitment transaction. Once this method returns, callers should broadcast the created funding transaction, then call .WaitForChannelOpen() which will block until the funding transaction obtains the configured number of confirmations. Once the method unblocks, a LightningChannel instance is returned, marking the channel available for updates.

func (*ChannelReservation) CompleteReservationSingle

func (r *ChannelReservation) CompleteReservationSingle(fundingPoint *wire.OutPoint,
	commitSig input.Signature) (*channeldb.OpenChannel, error)

CompleteReservationSingle finalizes the pending single funder channel reservation. Using the funding outpoint of the constructed funding transaction, and the initiator's signature for our version of the commitment transaction, we are able to verify the correctness of our commitment transaction as crafted by the initiator. Once this method returns, our signature for the initiator's version of the commitment transaction is available via the .OurSignatures() method. As this method should only be called as a response to a single funder channel, only a commitment signature will be populated.

func (*ChannelReservation) FinalFundingTx

func (r *ChannelReservation) FinalFundingTx() *wire.MsgTx

FinalFundingTx returns the finalized, fully signed funding transaction for this reservation.

NOTE: If this reservation was created as the non-initiator to a single funding workflow, then the full funding transaction will not be available. Instead we will only have the final outpoint of the funding transaction.

func (*ChannelReservation) FundingOutpoint

func (r *ChannelReservation) FundingOutpoint() *wire.OutPoint

FundingOutpoint returns the outpoint of the funding transaction.

NOTE: The pointer returned will only be set once the .ProcessContribution() method is called in the case of the initiator of a single funder workflow, and after the .CompleteReservationSingle() method is called in the case of a responder to a single funder workflow.

func (*ChannelReservation) IsCannedShim

func (r *ChannelReservation) IsCannedShim() bool

IsCannedShim returns true if there is a canned shim funding intent mapped to this reservation.

func (*ChannelReservation) IsPsbt

func (r *ChannelReservation) IsPsbt() bool

IsPsbt returns true if there is a PSBT funding intent mapped to this reservation.

func (*ChannelReservation) IsTaproot

func (r *ChannelReservation) IsTaproot() bool

IsTaproot returns if the reservation's underlying partial channel state is a taproot channel.

func (*ChannelReservation) IsZeroConf

func (r *ChannelReservation) IsZeroConf() bool

IsZeroConf returns if the reservation's underlying partial channel state is a zero-conf channel.

func (*ChannelReservation) LeaseExpiry

func (r *ChannelReservation) LeaseExpiry() uint32

LeaseExpiry returns the absolute expiration height for a leased channel using the script enforced commitment type. A zero value is returned when the channel is not using a script enforced lease commitment type.

func (*ChannelReservation) OurContribution

func (r *ChannelReservation) OurContribution() *ChannelContribution

OurContribution returns the wallet's fully populated contribution to the pending payment channel. See 'ChannelContribution' for further details regarding the contents of a contribution.

NOTE: This SHOULD NOT be modified. TODO(roasbeef): make copy?

func (*ChannelReservation) OurSignatures

func (r *ChannelReservation) OurSignatures() ([]*input.Script,
	input.Signature)

OurSignatures retrieves the wallet's signatures to all inputs to the funding transaction belonging to itself, and also a signature for the counterparty's version of the commitment transaction. The signatures for the wallet's inputs to the funding transaction are returned in sorted order according to BIP-69: https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki.

NOTE: These signatures will only be populated after a call to .ProcessContribution()

func (*ChannelReservation) ProcessContribution

func (r *ChannelReservation) ProcessContribution(theirContribution *ChannelContribution) error

ProcessContribution verifies the counterparty's contribution to the pending payment channel. As a result of this incoming message, lnwallet is able to build the funding transaction, and both commitment transactions. Once this message has been processed, all signatures to inputs to the funding transaction belonging to the wallet are available. Additionally, the wallet will generate a signature to the counterparty's version of the commitment transaction.

func (*ChannelReservation) ProcessPsbt

func (r *ChannelReservation) ProcessPsbt() error

ProcessPsbt continues a previously paused funding flow that involves PSBT to construct the funding transaction. This method can be called once the PSBT is finalized and the signed transaction is available.

func (*ChannelReservation) ProcessSingleContribution

func (r *ChannelReservation) ProcessSingleContribution(theirContribution *ChannelContribution) error

ProcessSingleContribution verifies, and records the initiator's contribution to this pending single funder channel. Internally, no further action is taken other than recording the initiator's contribution to the single funder channel.

func (*ChannelReservation) RemoteCanceled

func (r *ChannelReservation) RemoteCanceled()

RemoteCanceled informs the PSBT funding state machine that the remote peer has canceled the pending reservation, likely due to a timeout.

func (*ChannelReservation) SetNumConfsRequired

func (r *ChannelReservation) SetNumConfsRequired(numConfs uint16)

SetNumConfsRequired sets the number of confirmations that are required for the ultimate funding transaction before the channel can be considered open. This is distinct from the main reservation workflow as it allows implementations a bit more flexibility w.r.t to if the responder of the initiator sets decides the number of confirmations needed.

func (*ChannelReservation) SetOurUpfrontShutdown

func (r *ChannelReservation) SetOurUpfrontShutdown(shutdown lnwire.DeliveryAddress)

SetOurUpfrontShutdown sets the upfront shutdown address on our contribution.

func (*ChannelReservation) TheirContribution

func (r *ChannelReservation) TheirContribution() *ChannelContribution

TheirContribution returns the counterparty's pending contribution to the payment channel. See 'ChannelContribution' for further details regarding the contents of a contribution. This attribute will ONLY be available after a call to .ProcessContribution().

NOTE: This SHOULD NOT be modified.

func (*ChannelReservation) TheirSignatures

func (r *ChannelReservation) TheirSignatures() ([]*input.Script,
	input.Signature)

TheirSignatures returns the counterparty's signatures to all inputs to the funding transaction belonging to them, as well as their signature for the wallet's version of the commitment transaction. This methods is provided for additional verification, such as needed by tests.

NOTE: These attributes will be unpopulated before a call to .CompleteReservation().

type CheckReservedValueTxReq

type CheckReservedValueTxReq struct {
	// Tx is the transaction to check the outputs for.
	Tx *wire.MsgTx

	// ChangeIndex denotes an optional output index that can be explicitly
	// set for a change that is not being watched by the wallet and would
	// otherwise not be recognized as a change output.
	ChangeIndex *int
}

CheckReservedValueTxReq is the request struct used to call CheckReservedValueTx with. It contains the transaction to check as well as an optional explicitly defined index to denote a change output that is not watched by the wallet.

type CloseTxOpt

type CloseTxOpt func(*closeTxOpts)

CloseTxOpt is a functional option that allows us to modify how the closing transaction is created.

func WithRBFCloseTx

func WithRBFCloseTx() CloseTxOpt

WithRBFCloseTx signals that the cooperative close tx should signal RBF.

type CoinSource

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

CoinSource is a wrapper around the wallet that implements the chanfunding.CoinSource interface.

func NewCoinSource

func NewCoinSource(w *LightningWallet, allowUtxo func(Utxo) bool) *CoinSource

NewCoinSource creates a new instance of the CoinSource wrapper struct.

func (*CoinSource) CoinFromOutPoint

func (c *CoinSource) CoinFromOutPoint(op wire.OutPoint) (*wallet.Coin, error)

CoinFromOutPoint attempts to locate details pertaining to a coin based on its outpoint. If the coin isn't under the control of the backing CoinSource, then an error should be returned.

func (*CoinSource) ListCoins

func (c *CoinSource) ListCoins(minConfs int32,
	maxConfs int32) ([]wallet.Coin, error)

ListCoins returns all UTXOs from the source that have between minConfs and maxConfs number of confirmations.

type CommitOutputResolution

type CommitOutputResolution struct {
	// SelfOutPoint is the full outpoint that points to out pay-to-self
	// output within the closing commitment transaction.
	SelfOutPoint wire.OutPoint

	// SelfOutputSignDesc is a fully populated sign descriptor capable of
	// generating a valid signature to sweep the output paying to us.
	SelfOutputSignDesc input.SignDescriptor

	// MaturityDelay is the relative time-lock, in blocks for all outputs
	// that pay to the local party within the broadcast commitment
	// transaction.
	MaturityDelay uint32
}

CommitOutputResolution carries the necessary information required to allow us to sweep our commitment output in the case that either party goes to chain.

type CommitSigs

type CommitSigs struct {
	// CommitSig is the normal commitment signature. This will only be a
	// non-zero commitment signature for non-taproot channels.
	CommitSig lnwire.Sig

	// HtlcSigs is the set of signatures for all HTLCs in the commitment
	// transaction. Depending on the channel type, these will either be
	// ECDSA or Schnorr signatures.
	HtlcSigs []lnwire.Sig

	// PartialSig is the musig2 partial signature for taproot commitment
	// transactions.
	PartialSig lnwire.OptPartialSigWithNonceTLV
}

CommitSigs holds the set of related signatures for a new commitment transaction state.

type CommitmentBuilder

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

CommitmentBuilder is a type that wraps the type of channel we are dealing with, and abstracts the various ways of constructing commitment transactions.

func NewCommitmentBuilder

func NewCommitmentBuilder(chanState *channeldb.OpenChannel) *CommitmentBuilder

NewCommitmentBuilder creates a new CommitmentBuilder from chanState.

type CommitmentKeyRing

type CommitmentKeyRing struct {
	// CommitPoint is the "per commitment point" used to derive the tweak
	// for each base point.
	CommitPoint *btcec.PublicKey

	// LocalCommitKeyTweak is the tweak used to derive the local public key
	// from the local payment base point or the local private key from the
	// base point secret. This may be included in a SignDescriptor to
	// generate signatures for the local payment key.
	//
	// NOTE: This will always refer to "our" local key, regardless of
	// whether this is our commit or not.
	LocalCommitKeyTweak []byte

	// LocalHtlcKeyTweak is the tweak used to derive the local HTLC key
	// from the local HTLC base point. This value is needed in order to
	// derive the final key used within the HTLC scripts in the commitment
	// transaction.
	//
	// NOTE: This will always refer to "our" local HTLC key, regardless of
	// whether this is our commit or not.
	LocalHtlcKeyTweak []byte

	// LocalHtlcKey is the key that will be used in any clause paying to
	// our node of any HTLC scripts within the commitment transaction for
	// this key ring set.
	//
	// NOTE: This will always refer to "our" local HTLC key, regardless of
	// whether this is our commit or not.
	LocalHtlcKey *btcec.PublicKey

	// RemoteHtlcKey is the key that will be used in clauses within the
	// HTLC script that send money to the remote party.
	//
	// NOTE: This will always refer to "their" remote HTLC key, regardless
	// of whether this is our commit or not.
	RemoteHtlcKey *btcec.PublicKey

	// ToLocalKey is the commitment transaction owner's key which is
	// included in HTLC success and timeout transaction scripts. This is
	// the public key used for the to_local output of the commitment
	// transaction.
	//
	// NOTE: Who's key this is depends on the current perspective. If this
	// is our commitment this will be our key.
	ToLocalKey *btcec.PublicKey

	// ToRemoteKey is the non-owner's payment key in the commitment tx.
	// This is the key used to generate the to_remote output within the
	// commitment transaction.
	//
	// NOTE: Who's key this is depends on the current perspective. If this
	// is our commitment this will be their key.
	ToRemoteKey *btcec.PublicKey

	// RevocationKey is the key that can be used by the other party to
	// redeem outputs from a revoked commitment transaction if it were to
	// be published.
	//
	// NOTE: Who can sign for this key depends on the current perspective.
	// If this is our commitment, it means the remote node can sign for
	// this key in case of a breach.
	RevocationKey *btcec.PublicKey
}

CommitmentKeyRing holds all derived keys needed to construct commitment and HTLC transactions. The keys are derived differently depending whether the commitment transaction is ours or the remote peer's. Private keys associated with each key may belong to the commitment owner or the "other party" which is referred to in the field comments, regardless of which is local and which is remote.

func DeriveCommitmentKeys

func DeriveCommitmentKeys(commitPoint *btcec.PublicKey,
	isOurCommit bool, chanType channeldb.ChannelType,
	localChanCfg, remoteChanCfg *channeldb.ChannelConfig) *CommitmentKeyRing

DeriveCommitmentKeys generates a new commitment key set using the base points and commitment point. The keys are derived differently depending on the type of channel, and whether the commitment transaction is ours or the remote peer's.

type CommitmentType

type CommitmentType int

CommitmentType is an enum indicating the commitment type we should use for the channel we are opening.

func (CommitmentType) HasAnchors

func (c CommitmentType) HasAnchors() bool

HasAnchors returns whether the commitment type supports anchor outputs.

func (CommitmentType) HasStaticRemoteKey

func (c CommitmentType) HasStaticRemoteKey() bool

HasStaticRemoteKey returns whether the commitment type supports remote outputs backed by static keys.

func (CommitmentType) IsTaproot

func (c CommitmentType) IsTaproot() bool

IsTaproot returns true if the channel type is a taproot channel.

func (CommitmentType) String

func (c CommitmentType) String() string

String returns the name of the CommitmentType.

type Config

type Config struct {
	// Database is a wrapper around a namespace within boltdb reserved for
	// ln-based wallet metadata. See the 'channeldb' package for further
	// information.
	Database *channeldb.ChannelStateDB

	// Notifier is used by in order to obtain notifications about funding
	// transaction reaching a specified confirmation depth, and to catch
	// counterparty's broadcasting revoked commitment states.
	Notifier chainntnfs.ChainNotifier

	// SecretKeyRing is used by the wallet during the funding workflow
	// process to obtain keys to be used directly within contracts. Usage
	// of this interface ensures that all key derivation is itself fully
	// deterministic.
	SecretKeyRing keychain.SecretKeyRing

	// WalletController is the core wallet, all non Lightning Network
	// specific interaction is proxied to the internal wallet.
	WalletController WalletController

	// Signer is the wallet's current Signer implementation. This Signer is
	// used to generate signature for all inputs to potential funding
	// transactions, as well as for spends from the funding transaction to
	// update the commitment state.
	Signer input.Signer

	// FeeEstimator is the implementation that the wallet will use for the
	// calculation of on-chain transaction fees.
	FeeEstimator chainfee.Estimator

	// ChainIO is an instance of the BlockChainIO interface. ChainIO is
	// used to lookup the existence of outputs within the UTXO set.
	ChainIO BlockChainIO

	// NetParams is the set of parameters that tells the wallet which chain
	// it will be operating on.
	NetParams chaincfg.Params

	// Rebroadcaster is an optional config param that can be used to
	// passively rebroadcast transactions in the background until they're
	// detected as being confirmed.
	Rebroadcaster Rebroadcaster

	// CoinSelectionStrategy is the strategy that is used for selecting
	// coins when funding a transaction.
	CoinSelectionStrategy wallet.CoinSelectionStrategy
}

Config is a struct which houses configuration parameters which modify the behaviour of LightningWallet.

NOTE: The passed channeldb, and ChainNotifier should already be fully initialized/started before being passed as a function argument.

type ErrCommitSyncLocalDataLoss

type ErrCommitSyncLocalDataLoss struct {
	// ChannelPoint is the identifier for the channel that experienced data
	// loss.
	ChannelPoint wire.OutPoint

	// CommitPoint is the last unrevoked commit point, sent to us by the
	// remote when we determined we had lost state.
	CommitPoint *btcec.PublicKey
}

ErrCommitSyncLocalDataLoss is returned in the case that we receive a valid commit secret within the ChannelReestablish message from the remote node AND they advertise a RemoteCommitTailHeight higher than our current known height. This means we have lost some critical data, and must fail the channel and MUST NOT force close it. Instead we should wait for the remote to force close it, such that we can attempt to sweep our funds. The commitment point needed to sweep the remote's force close is encapsulated.

func (*ErrCommitSyncLocalDataLoss) Error

Error returns a string representation of the local data loss error.

type ErrHtlcIndexAlreadyFailed

type ErrHtlcIndexAlreadyFailed uint64

ErrHtlcIndexAlreadyFailed is returned when the HTLC index has already been failed, but has not been committed by our commitment state.

func (ErrHtlcIndexAlreadyFailed) Error

Error returns a message indicating the index that had already been failed.

type ErrHtlcIndexAlreadySettled

type ErrHtlcIndexAlreadySettled uint64

ErrHtlcIndexAlreadySettled is returned when the HTLC index has already been settled, but has not been committed by our commitment state.

func (ErrHtlcIndexAlreadySettled) Error

Error returns a message indicating the index that had already been settled.

type ErrInvalidSettlePreimage

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

ErrInvalidSettlePreimage is returned when trying to settle an HTLC, but the preimage does not correspond to the payment hash.

func (ErrInvalidSettlePreimage) Error

func (e ErrInvalidSettlePreimage) Error() string

Error returns an error message with the offending preimage and intended payment hash.

type ErrUnknownHtlcIndex

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

ErrUnknownHtlcIndex is returned when locally settling or failing an HTLC, but the HTLC index is not known to the channel. This typically indicates that the HTLC was already settled in a prior commitment.

func (ErrUnknownHtlcIndex) Error

func (e ErrUnknownHtlcIndex) Error() string

Error returns an error logging the channel and HTLC index that was unknown.

type HtlcIndexErr

type HtlcIndexErr struct {
	*VerifyJob
	// contains filtered or unexported fields
}

HtlcIndexErr is a special type of error that also includes a pointer to the original validation job. This error message allows us to craft more detailed errors at upper layers.

type HtlcResolutions

type HtlcResolutions struct {
	// IncomingHTLCs contains a set of structs that can be used to sweep
	// all the incoming HTL'C that we know the preimage to.
	IncomingHTLCs []IncomingHtlcResolution

	// OutgoingHTLCs contains a set of structs that contains all the info
	// needed to sweep an outgoing HTLC we've sent to the remote party
	// after an absolute delay has expired.
	OutgoingHTLCs []OutgoingHtlcResolution
}

HtlcResolutions contains the items necessary to sweep HTLC's on chain directly from a commitment transaction. We'll use this in case either party goes broadcasts a commitment transaction with live HTLC's.

type HtlcRetribution

type HtlcRetribution struct {
	// SignDesc is a design descriptor capable of generating the necessary
	// signatures to satisfy the revocation clause of the HTLC's public key
	// script.
	SignDesc input.SignDescriptor

	// OutPoint is the target outpoint of this HTLC pointing to the
	// breached commitment transaction.
	OutPoint wire.OutPoint

	// SecondLevelWitnessScript is the witness script that will be created
	// if the second level HTLC transaction for this output is
	// broadcast/confirmed. We provide this as if the remote party attempts
	// to go to the second level to claim the HTLC then we'll need to
	// update the SignDesc above accordingly to sweep properly.
	SecondLevelWitnessScript []byte

	// SecondLevelTapTweak is the tap tweak value needed to spend the
	// second level output in case the breaching party attempts to publish
	// it.
	SecondLevelTapTweak [32]byte

	// IsIncoming is a boolean flag that indicates whether or not this
	// HTLC was accepted from the counterparty. A false value indicates that
	// this HTLC was offered by us. This flag is used determine the exact
	// witness type should be used to sweep the output.
	IsIncoming bool
}

HtlcRetribution contains all the items necessary to seep a revoked HTLC transaction from a revoked commitment transaction broadcast by the remote party.

type IncomingHtlcResolution

type IncomingHtlcResolution struct {
	// Preimage is the preimage that will be used to satisfy the contract of
	// the HTLC.
	//
	// NOTE: This field will only be populated in the incoming contest
	// resolver.
	Preimage [32]byte

	// SignedSuccessTx is the fully signed HTLC success transaction. This
	// transaction (if non-nil) can be broadcast immediately. After a csv
	// delay (included below), then the output created by this transactions
	// can be swept on-chain.
	//
	// NOTE: If this field is nil, then this indicates that we don't need
	// to go to the second level to claim this HTLC. Instead, it can be
	// claimed directly from the outpoint listed below.
	SignedSuccessTx *wire.MsgTx

	// SignDetails is non-nil if SignedSuccessTx is non-nil, and the
	// channel is of the anchor type. As the above HTLC transaction will be
	// signed by the channel peer using SINGLE|ANYONECANPAY for such
	// channels, we can use the sign details to add the input-output pair
	// of the HTLC transaction to another transaction, thereby aggregating
	// multiple HTLC transactions together, and adding fees as needed.
	SignDetails *input.SignDetails

	// CsvDelay is the relative time lock (expressed in blocks) that must
	// pass after the SignedSuccessTx is confirmed in the chain before the
	// output can be swept.
	//
	// NOTE: If SignedTimeoutTx is nil, then this field denotes the CSV
	// delay needed to spend from the commitment transaction.
	CsvDelay uint32

	// ClaimOutpoint is the final outpoint that needs to be spent in order
	// to fully sweep the HTLC. The SignDescriptor below should be used to
	// spend this outpoint. In the case of a second-level HTLC (non-nil
	// SignedTimeoutTx), then we'll be spending a new transaction.
	// Otherwise, it'll be an output in the commitment transaction.
	ClaimOutpoint wire.OutPoint

	// SweepSignDesc is a sign descriptor that has been populated with the
	// necessary items required to spend the sole output of the above
	// transaction.
	SweepSignDesc input.SignDescriptor
}

IncomingHtlcResolution houses the information required to sweep any incoming HTLC's that we know the preimage to. We'll need to sweep an HTLC manually using this struct if we need to go on-chain for any reason, or if we detect that the remote party broadcasts their commitment transaction.

func (*IncomingHtlcResolution) HtlcPoint

func (r *IncomingHtlcResolution) HtlcPoint() wire.OutPoint

HtlcPoint returns the htlc's outpoint on the commitment tx.

type InitFundingReserveMsg

type InitFundingReserveMsg struct {
	// ChainHash denotes that chain to be used to ultimately open the
	// target channel.
	ChainHash *chainhash.Hash

	// PendingChanID is the pending channel ID for this funding flow as
	// used in the wire protocol.
	PendingChanID [32]byte

	// NodeID is the ID of the remote node we would like to open a channel
	// with.
	NodeID *btcec.PublicKey

	// NodeAddr is the address port that we used to either establish or
	// accept the connection which led to the negotiation of this funding
	// workflow.
	NodeAddr net.Addr

	// SubtractFees should be set if we intend to spend exactly
	// LocalFundingAmt when opening the channel, subtracting the fees from
	// the funding output. This can be used for instance to use all our
	// remaining funds to open the channel, since it will take fees into
	// account.
	SubtractFees bool

	// LocalFundingAmt is the amount of funds requested from us for this
	// channel.
	LocalFundingAmt btcutil.Amount

	// RemoteFundingAmnt is the amount of funds the remote will contribute
	// to this channel.
	RemoteFundingAmt btcutil.Amount

	// FundUpToMaxAmt defines if channel funding should try to add as many
	// funds to the channel opening as possible up to this amount. If used,
	// then MinFundAmt is treated as the minimum amount of funds that must
	// be available to open the channel. If set to zero it is ignored.
	FundUpToMaxAmt btcutil.Amount

	// MinFundAmt denotes the minimum channel capacity that has to be
	// allocated iff the FundUpToMaxAmt is set.
	MinFundAmt btcutil.Amount

	// Outpoints is a list of client-selected outpoints that should be used
	// for funding a channel. If LocalFundingAmt is specified then this
	// amount is allocated from the sum of outpoints towards funding. If the
	// FundUpToMaxAmt is specified the entirety of selected funds is
	// allocated towards channel funding.
	Outpoints []wire.OutPoint

	// RemoteChanReserve is the channel reserve we required for the remote
	// peer.
	RemoteChanReserve btcutil.Amount

	// CommitFeePerKw is the starting accepted satoshis/Kw fee for the set
	// of initial commitment transactions. In order to ensure timely
	// confirmation, it is recommended that this fee should be generous,
	// paying some multiple of the accepted base fee rate of the network.
	CommitFeePerKw chainfee.SatPerKWeight

	// FundingFeePerKw is the fee rate in sat/kw to use for the initial
	// funding transaction.
	FundingFeePerKw chainfee.SatPerKWeight

	// PushMSat is the number of milli-satoshis that should be pushed over
	// the responder as part of the initial channel creation.
	PushMSat lnwire.MilliSatoshi

	// Flags are the channel flags specified by the initiator in the
	// open_channel message.
	Flags lnwire.FundingFlag

	// MinConfs indicates the minimum number of confirmations that each
	// output selected to fund the channel should satisfy.
	MinConfs int32

	// CommitType indicates what type of commitment type the channel should
	// be using, like tweakless or anchors.
	CommitType CommitmentType

	// ChanFunder is an optional channel funder that allows the caller to
	// control exactly how the channel funding is carried out. If not
	// specified, then the default chanfunding.WalletAssembler will be
	// used.
	ChanFunder chanfunding.Assembler

	// AllowUtxoForFunding enables the channel funding workflow to restrict
	// the selection of utxos when selecting the inputs for the channel
	// opening. This does ONLY apply for the internal wallet backed channel
	// opening case.
	//
	// NOTE: This is very useful when opening channels with unconfirmed
	// inputs to make sure stable non-replaceable inputs are used.
	AllowUtxoForFunding func(Utxo) bool

	// ZeroConf is a boolean that is true if a zero-conf channel was
	// negotiated.
	ZeroConf bool

	// OptionScidAlias is a boolean that is true if an option-scid-alias
	// channel type was explicitly negotiated.
	OptionScidAlias bool

	// ScidAliasFeature is true if the option-scid-alias feature bit was
	// negotiated.
	ScidAliasFeature bool

	// Memo is any arbitrary information we wish to store locally about the
	// channel that will be useful to our future selves.
	Memo []byte
	// contains filtered or unexported fields
}

InitFundingReserveMsg is the first message sent to initiate the workflow required to open a payment channel with a remote peer. The initial required parameters are configurable across channels. These parameters are to be chosen depending on the fee climate within the network, and time value of funds to be locked up within the channel. Upon success a ChannelReservation will be created in order to track the lifetime of this pending channel. Outputs selected will be 'locked', making them unavailable, for any other pending reservations. Therefore, all channels in reservation limbo will be periodically timed out after an idle period in order to avoid "exhaustion" attacks.

type InvalidCommitSigError

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

InvalidCommitSigError is a struct that implements the error interface to report a failure to validate a commitment signature for a remote peer. We'll use the items in this struct to generate a rich error message for the remote peer when we receive an invalid signature from it. Doing so can greatly aide in debugging cross implementation issues.

func (*InvalidCommitSigError) Error

func (i *InvalidCommitSigError) Error() string

Error returns a detailed error string including the exact transaction that caused an invalid commitment signature.

type InvalidHtlcSigError

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

InvalidHtlcSigError is a struct that implements the error interface to report a failure to validate an htlc signature from a remote peer. We'll use the items in this struct to generate a rich error message for the remote peer when we receive an invalid signature from it. Doing so can greatly aide in debugging across implementation issues.

func (*InvalidHtlcSigError) Error

func (i *InvalidHtlcSigError) Error() string

Error returns a detailed error string including the exact transaction that caused an invalid htlc signature.

type InvalidPartialCommitSigError

type InvalidPartialCommitSigError struct {
	InvalidCommitSigError
	// contains filtered or unexported fields
}

InvalidPartialCommitSigError is used when we encounter an invalid musig2 partial signature.

func (*InvalidPartialCommitSigError) Error

Error returns a detailed error string including the exact transaction that caused an invalid partial commit sig signature.

type LightningChannel

type LightningChannel struct {
	// Signer is the main signer instances that will be responsible for
	// signing any HTLC and commitment transaction generated by the state
	// machine.
	Signer input.Signer

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

	sync.RWMutex
	// contains filtered or unexported fields
}

LightningChannel implements the state machine which corresponds to the current commitment protocol wire spec. The state machine implemented allows for asynchronous fully desynchronized, batched+pipelined updates to commitment transactions allowing for a high degree of non-blocking bi-directional payment throughput.

In order to allow updates to be fully non-blocking, either side is able to create multiple new commitment states up to a pre-determined window size. This window size is encoded within InitialRevocationWindow. Before the start of a session, both side should send out revocation messages with nil preimages in order to populate their revocation window for the remote party.

The state machine has for main methods:

  • .SignNextCommitment()
  • Called once when one wishes to sign the next commitment, either initiating a new state update, or responding to a received commitment.
  • .ReceiveNewCommitment()
  • Called upon receipt of a new commitment from the remote party. If the new commitment is valid, then a revocation should immediately be generated and sent.
  • .RevokeCurrentCommitment()
  • Revokes the current commitment. Should be called directly after receiving a new commitment.
  • .ReceiveRevocation()
  • Processes a revocation from the remote party. If successful creates a new defacto broadcastable state.

See the individual comments within the above methods for further details.

func NewLightningChannel

func NewLightningChannel(signer input.Signer,
	state *channeldb.OpenChannel,
	sigPool *SigPool, chanOpts ...ChannelOpt) (*LightningChannel, error)

NewLightningChannel creates a new, active payment channel given an implementation of the chain notifier, channel database, and the current settled channel state. Throughout state transitions, then channel will automatically persist pertinent state to the database in an efficient manner.

func (*LightningChannel) AbsoluteThawHeight

func (lc *LightningChannel) AbsoluteThawHeight() (uint32, error)

AbsoluteThawHeight determines a frozen channel's absolute thaw height. If the channel is not frozen, then 0 is returned.

An error is returned if the channel is pending, or is an unconfirmed zero conf channel.

func (*LightningChannel) AckAddHtlcs

func (lc *LightningChannel) AckAddHtlcs(addRef channeldb.AddRef) error

AckAddHtlcs sets a bit in the FwdFilter of a forwarding package belonging to this channel, that corresponds to the given AddRef. This method also succeeds if no forwarding package is found.

func (*LightningChannel) AckSettleFails

func (lc *LightningChannel) AckSettleFails(
	settleFailRefs ...channeldb.SettleFailRef) error

AckSettleFails sets a bit in the SettleFailFilter of a forwarding package belonging to this channel, that corresponds to the given SettleFailRef. This method also succeeds if no forwarding package is found.

func (*LightningChannel) ActiveHtlcs

func (lc *LightningChannel) ActiveHtlcs() []channeldb.HTLC

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

func (*LightningChannel) AddHTLC

func (lc *LightningChannel) AddHTLC(htlc *lnwire.UpdateAddHTLC,
	openKey *models.CircuitKey) (uint64, error)

AddHTLC is a wrapper of the `addHTLC` function which always enforces the FeeBuffer on the local balance if being the initiator of the channel. This method should be called when preparing to send an outgoing HTLC.

The additional openKey argument corresponds to the incoming CircuitKey of the committed circuit for this HTLC. This value should never be nil.

NOTE: It is okay for sourceRef to be nil when unit testing the wallet.

func (*LightningChannel) AvailableBalance

func (lc *LightningChannel) AvailableBalance() lnwire.MilliSatoshi

AvailableBalance returns the current balance available for sending within the channel. By available balance, we mean that if at this very instance a new commitment were to be created which evals all the log entries, what would our available balance for adding an additional HTLC be. It takes into account the fee that must be paid for adding this HTLC, that we cannot spend from the channel reserve and moreover the FeeBuffer when we are the initiator of the channel. This method is useful when deciding if a given channel can accept an HTLC in the multi-hop forwarding scenario.

func (*LightningChannel) CalcFee

func (lc *LightningChannel) CalcFee(feeRate chainfee.SatPerKWeight) btcutil.Amount

CalcFee returns the commitment fee to use for the given fee rate (fee-per-kw).

func (*LightningChannel) ChanType

func (lc *LightningChannel) ChanType() channeldb.ChannelType

ChanType returns the channel type.

func (*LightningChannel) ChannelPoint

func (lc *LightningChannel) ChannelPoint() wire.OutPoint

ChannelPoint returns the outpoint of the original funding transaction which created this active channel. This outpoint is used throughout various subsystems to uniquely identify an open channel.

func (*LightningChannel) CommitFeeRate

func (lc *LightningChannel) CommitFeeRate() chainfee.SatPerKWeight

CommitFeeRate returns the current fee rate of the commitment transaction in units of sat-per-kw.

func (*LightningChannel) CompleteCooperativeClose

func (lc *LightningChannel) CompleteCooperativeClose(
	localSig, remoteSig input.Signature,
	localDeliveryScript, remoteDeliveryScript []byte,
	proposedFee btcutil.Amount,
	closeOpts ...ChanCloseOpt) (*wire.MsgTx, btcutil.Amount, error)

CompleteCooperativeClose completes the cooperative closure of the target active lightning channel. A fully signed closure transaction as well as the signature itself are returned. Additionally, we also return our final settled balance, which reflects any fees we may have paid.

NOTE: The passed local and remote sigs are expected to be fully complete signatures including the proper sighash byte.

func (*LightningChannel) CreateCloseProposal

func (lc *LightningChannel) CreateCloseProposal(proposedFee btcutil.Amount,
	localDeliveryScript []byte, remoteDeliveryScript []byte,
	closeOpts ...ChanCloseOpt) (input.Signature, *chainhash.Hash,
	btcutil.Amount, error)

CreateCloseProposal is used by both parties in a cooperative channel close workflow to generate proposed close transactions and signatures. This method should only be executed once all pending HTLCs (if any) on the channel have been cleared/removed. Upon completion, the source channel will shift into the "closing" state, which indicates that all incoming/outgoing HTLC requests should be rejected. A signature for the closing transaction is returned.

TODO(roasbeef): caller should initiate signal to reject all incoming HTLCs, settle any in flight.

func (*LightningChannel) FailHTLC

func (lc *LightningChannel) FailHTLC(htlcIndex uint64, reason []byte,
	sourceRef *channeldb.AddRef, destRef *channeldb.SettleFailRef,
	closeKey *models.CircuitKey) error

FailHTLC attempts to fail a targeted HTLC by its payment hash, inserting an entry which will remove the target log entry within the next commitment update. This method is intended to be called in order to cancel in _incoming_ HTLC.

The additional arguments correspond to:

  • sourceRef: specifies the location of the Add HTLC within a forwarding package that this HTLC is failing. Every Fail fails exactly one Add, so this should never be empty in practice.

  • destRef: specifies the location of the Fail HTLC within another channel's forwarding package. This value can be nil if the corresponding Add HTLC was never locked into an outgoing commitment txn, or this HTLC does not originate as a response from the peer on the outgoing link, e.g. on-chain resolutions.

  • closeKey: identifies the circuit that should be deleted after this Fail HTLC is included in a commitment txn. This value should only be nil if the HTLC was failed locally before committing a circuit to the circuit map.

NOTE: It is okay for sourceRef, destRef, and closeKey to be nil when unit testing the wallet.

func (*LightningChannel) ForceClose

func (lc *LightningChannel) ForceClose() (*LocalForceCloseSummary, error)

ForceClose executes a unilateral closure of the transaction at the current lowest commitment height of the channel. Following a force closure, all state transitions, or modifications to the state update logs will be rejected. Additionally, this function also returns a LocalForceCloseSummary which includes the necessary details required to sweep all the time-locked outputs within the commitment transaction.

TODO(roasbeef): all methods need to abort if in dispute state

func (*LightningChannel) FundingTxOut

func (lc *LightningChannel) FundingTxOut() *wire.TxOut

FundingTxOut returns the funding output of the channel.

func (*LightningChannel) FwdMinHtlc

func (lc *LightningChannel) FwdMinHtlc() lnwire.MilliSatoshi

FwdMinHtlc returns the minimum HTLC value required by the remote node, i.e. the minimum value HTLC we can forward on this channel.

func (*LightningChannel) GenMusigNonces

func (lc *LightningChannel) GenMusigNonces() (*musig2.Nonces, error)

GenMusigNonces generates the verification nonce to start off a new musig2 channel session.

func (*LightningChannel) GetDustSum

func (lc *LightningChannel) GetDustSum(remote bool) lnwire.MilliSatoshi

GetDustSum takes in a boolean that determines which commitment to evaluate the dust sum on. The return value is the sum of dust on the desired commitment tx.

NOTE: This over-estimates the dust exposure.

func (*LightningChannel) HasRemoteNonces

func (lc *LightningChannel) HasRemoteNonces() bool

HasRemoteNonces returns true if the channel has a remote nonce pair.

func (*LightningChannel) IdealCommitFeeRate

func (lc *LightningChannel) IdealCommitFeeRate(netFeeRate, minRelayFeeRate,
	maxAnchorCommitFeeRate chainfee.SatPerKWeight,
	maxFeeAlloc float64) chainfee.SatPerKWeight

IdealCommitFeeRate uses the current network fee, the minimum relay fee, maximum fee allocation and anchor channel commitment fee rate to determine the ideal fee to be used for the commitments of the channel.

func (*LightningChannel) InitNextRevocation

func (lc *LightningChannel) InitNextRevocation(revKey *btcec.PublicKey) error

InitNextRevocation inserts the passed commitment point as the _next_ revocation to be used when creating a new commitment state for the remote party. This function MUST be called before the channel can accept or propose any new states.

func (*LightningChannel) InitRemoteMusigNonces

func (lc *LightningChannel) InitRemoteMusigNonces(remoteNonce *musig2.Nonces,
) error

InitRemoteMusigNonces processes the remote musig nonces sent by the remote party. This should be called upon connection re-establishment, after we've generated our own nonces. Once this method returns a nil error, then the channel can be used to sign commitment states.

func (*LightningChannel) IsChannelClean

func (lc *LightningChannel) IsChannelClean() bool

IsChannelClean returns true if neither side has pending commitments, neither side has HTLC's, and all updates are locked in irrevocably. Internally, it utilizes the oweCommitment function by calling it for local and remote evaluation. We check if we have a pending commitment for our local state since this function may be called by sub-systems that are not the link (e.g. the rpcserver), and the ReceiveNewCommitment & RevokeCurrentCommitment calls are not atomic, even though link processing ensures no updates can happen in between.

func (*LightningChannel) IsInitiator

func (lc *LightningChannel) IsInitiator() bool

IsInitiator returns true if we were the ones that initiated the funding workflow which led to the creation of this channel. Otherwise, it returns false.

func (*LightningChannel) IsPending

func (lc *LightningChannel) IsPending() bool

IsPending returns true if the channel's funding transaction has been fully confirmed, and false otherwise.

func (*LightningChannel) LoadFwdPkgs

func (lc *LightningChannel) LoadFwdPkgs() ([]*channeldb.FwdPkg, error)

LoadFwdPkgs loads any pending log updates from disk and returns the payment descriptors to be processed by the link.

func (*LightningChannel) LocalBalanceDust

func (lc *LightningChannel) LocalBalanceDust() bool

LocalBalanceDust returns true if when creating a co-op close transaction, the balance of the local party will be dust after accounting for any anchor outputs.

func (*LightningChannel) LocalChanReserve

func (lc *LightningChannel) LocalChanReserve() btcutil.Amount

LocalChanReserve returns our local ChanReserve requirement for the remote party.

func (*LightningChannel) LocalUpfrontShutdownScript

func (lc *LightningChannel) LocalUpfrontShutdownScript() lnwire.DeliveryAddress

LocalUpfrontShutdownScript returns the local upfront shutdown script for the channel. If it was not set, an empty byte array is returned.

func (*LightningChannel) MalformedFailHTLC

func (lc *LightningChannel) MalformedFailHTLC(htlcIndex uint64,
	failCode lnwire.FailCode, shaOnionBlob [sha256.Size]byte,
	sourceRef *channeldb.AddRef) error

MalformedFailHTLC attempts to fail a targeted HTLC by its payment hash, inserting an entry which will remove the target log entry within the next commitment update. This method is intended to be called in order to cancel in _incoming_ HTLC.

The additional sourceRef specifies the location of the Add HTLC within a forwarding package that this HTLC is failing. This value should never be empty.

NOTE: It is okay for sourceRef to be nil when unit testing the wallet.

func (*LightningChannel) MarkBorked

func (lc *LightningChannel) 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 (*LightningChannel) MarkCommitmentBroadcasted

func (lc *LightningChannel) MarkCommitmentBroadcasted(tx *wire.MsgTx,
	locallyInitiated bool) error

MarkCommitmentBroadcasted marks the channel as a commitment transaction has been broadcast, either our own or the remote, and we should watch the chain for it to confirm before taking any further action. It takes a boolean which indicates whether we initiated the close.

func (*LightningChannel) MarkCoopBroadcasted

func (lc *LightningChannel) MarkCoopBroadcasted(tx *wire.MsgTx,
	localInitiated bool) error

MarkCoopBroadcasted marks the channel as a cooperative close transaction has been broadcast, and that we should watch the chain for it to confirm before taking any further action. It takes a locally initiated bool which is true if we initiated the cooperative close.

func (*LightningChannel) MarkDataLoss

func (lc *LightningChannel) 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 (*LightningChannel) MarkShutdownSent

func (lc *LightningChannel) MarkShutdownSent(
	info *channeldb.ShutdownInfo) error

MarkShutdownSent persists the given ShutdownInfo. The existence of the ShutdownInfo represents the fact that the Shutdown message has been sent by us and so should be re-sent on re-establish.

func (*LightningChannel) MaxFeeRate

func (lc *LightningChannel) MaxFeeRate(
	maxAllocation float64) (chainfee.SatPerKWeight, float64)

MaxFeeRate returns the maximum fee rate given an allocation of the channel initiator's spendable balance along with the local reserve amount. This can be useful to determine when we should stop proposing fee updates that exceed our maximum allocation. Moreover it returns the share of the total balance in the range of [0,1] which can be allocated to fees. When our desired fee allocation would lead to a maximum fee rate below the current commitment fee rate we floor the maximum at the current fee rate which leads to different fee allocations than initially requested via `maxAllocation`.

NOTE: This should only be used for channels in which the local commitment is the initiator.

func (*LightningChannel) MayAddOutgoingHtlc

func (lc *LightningChannel) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error

MayAddOutgoingHtlc validates whether we can add an outgoing htlc to this channel. We don't have a circuit for this htlc, because we just want to test that we have slots for a potential htlc so we use a "mock" htlc to validate a potential commitment state with one more outgoing htlc. If a zero htlc amount is provided, we'll attempt to add the smallest possible htlc to the channel (either the minimum htlc, or 1 sat).

func (*LightningChannel) MultiSigKeys

MultiSigKeys returns the set of multi-sig keys for an channel.

func (*LightningChannel) NeedCommitment

func (lc *LightningChannel) NeedCommitment() bool

NeedCommitment returns a boolean value reflecting whether we are waiting on a commitment signature because there are outstanding remote updates and/or updates in the remote commit tx that aren't reflected in the local commit tx yet.

func (*LightningChannel) NewAnchorResolutions

func (lc *LightningChannel) NewAnchorResolutions() (*AnchorResolutions,
	error)

NewAnchorResolutions returns a set of anchor resolutions wrapped in the struct AnchorResolutions. Because we have no view on the mempool, we can only blindly anchor all of these txes down. The caller needs to check the returned values against nil to decide whether there exists an anchor resolution for local/remote/pending remote commitment txes.

func (*LightningChannel) NextLocalHtlcIndex

func (lc *LightningChannel) 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 local commitment.

func (*LightningChannel) NextRevocationKey

func (lc *LightningChannel) NextRevocationKey() (*btcec.PublicKey, error)

NextRevocationKey returns the commitment point for the _next_ commitment height. The pubkey returned by this function is required by the remote party along with their revocation base to extend our commitment chain with a new commitment.

func (*LightningChannel) OweCommitment

func (lc *LightningChannel) OweCommitment() bool

OweCommitment returns a boolean value reflecting whether we need to send out a commitment signature because there are outstanding local updates and/or updates in the local commit tx that aren't reflected in the remote commit tx yet.

func (*LightningChannel) PendingLocalUpdateCount

func (lc *LightningChannel) PendingLocalUpdateCount() uint64

PendingLocalUpdateCount returns the number of local updates that still need to be applied to the remote commitment tx.

func (*LightningChannel) ProcessChanSyncMsg

ProcessChanSyncMsg processes a ChannelReestablish message sent by the remote connection upon re establishment of our connection with them. This method will return a single message if we are currently out of sync, otherwise a nil lnwire.Message will be returned. If it is decided that our level of de-synchronization is irreconcilable, then an error indicating the issue will be returned. In this case that an error is returned, the channel should be force closed, as we cannot continue updates.

One of two message sets will be returned:

  • CommitSig+Updates: if we have a pending remote commit which they claim to have not received
  • RevokeAndAck: if we sent a revocation message that they claim to have not received

If we detect a scenario where we need to send a CommitSig+Updates, this method also returns two sets models.CircuitKeys identifying the circuits that were opened and closed, respectively, as a result of signing the previous commitment txn. This allows the link to clear its mailbox of those circuits in case they are still in memory, and ensure the switch's circuit map has been updated by deleting the closed circuits.

func (*LightningChannel) ReceiveFailHTLC

func (lc *LightningChannel) ReceiveFailHTLC(htlcIndex uint64, reason []byte,
) error

ReceiveFailHTLC attempts to cancel a targeted HTLC by its log index, inserting an entry which will remove the target log entry within the next commitment update. This method should be called in response to the upstream party cancelling an outgoing HTLC.

func (*LightningChannel) ReceiveHTLC

func (lc *LightningChannel) ReceiveHTLC(htlc *lnwire.UpdateAddHTLC) (uint64, error)

ReceiveHTLC adds an HTLC to the state machine's remote update log. This method should be called in response to receiving a new HTLC from the remote party.

func (*LightningChannel) ReceiveHTLCSettle

func (lc *LightningChannel) ReceiveHTLCSettle(preimage [32]byte, htlcIndex uint64) error

ReceiveHTLCSettle attempts to settle an existing outgoing HTLC indexed by an index into the local log. If the specified index doesn't exist within the log, and error is returned. Similarly if the preimage is invalid w.r.t to the referenced of then a distinct error is returned.

func (*LightningChannel) ReceiveNewCommitment

func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error

ReceiveNewCommitment process a signature for a new commitment state sent by the remote party. This method should be called in response to the remote party initiating a new change, or when the remote party sends a signature fully accepting a new state we've initiated. If we are able to successfully validate the signature, then the generated commitment is added to our local commitment chain. Once we send a revocation for our prior state, then this newly added commitment becomes our current accepted channel state.

func (*LightningChannel) ReceiveRevocation

ReceiveRevocation processes a revocation sent by the remote party for the lowest unrevoked commitment within their commitment chain. We receive a revocation either during the initial session negotiation wherein revocation windows are extended, or in response to a state update that we initiate. If successful, then the remote commitment chain is advanced by a single commitment, and a log compaction is attempted.

The returned values correspond to:

  1. The forwarding package corresponding to the remote commitment height that was revoked.
  2. The PaymentDescriptor of any Add HTLCs that were locked in by this revocation.
  3. The PaymentDescriptor of any Settle/Fail HTLCs that were locked in by this revocation.
  4. The set of HTLCs present on the current valid commitment transaction for the remote party.

func (*LightningChannel) ReceiveUpdateFee

func (lc *LightningChannel) ReceiveUpdateFee(feePerKw chainfee.SatPerKWeight) error

ReceiveUpdateFee handles an updated fee sent from remote. This method will return an error if called as channel initiator.

func (*LightningChannel) RemoteBalanceDust

func (lc *LightningChannel) RemoteBalanceDust() bool

RemoteBalanceDust returns true if when creating a co-op close transaction, the balance of the remote party will be dust after accounting for any anchor outputs.

func (*LightningChannel) RemoteNextRevocation

func (lc *LightningChannel) RemoteNextRevocation() *btcec.PublicKey

RemoteNextRevocation returns the channelState's RemoteNextRevocation. For musig2 channels, until a nonce pair is processed by the remote party, a nil public key is returned.

TODO(roasbeef): revisit, maybe just make a more general method instead?

func (*LightningChannel) RemoteUpfrontShutdownScript

func (lc *LightningChannel) RemoteUpfrontShutdownScript() lnwire.DeliveryAddress

RemoteUpfrontShutdownScript returns the remote upfront shutdown script for the channel. If it was not set, an empty byte array is returned.

func (*LightningChannel) RemoveFwdPkgs

func (lc *LightningChannel) RemoveFwdPkgs(heights ...uint64) error

RemoveFwdPkgs permanently deletes the forwarding package at the given heights.

func (*LightningChannel) ResetState

func (lc *LightningChannel) ResetState()

ResetState resets the state of the channel back to the default state. This ensures that any active goroutines which need to act based on on-chain events do so properly.

func (*LightningChannel) RevokeCurrentCommitment

func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck,
	[]channeldb.HTLC, map[uint64]bool, error)

RevokeCurrentCommitment revokes the next lowest unrevoked commitment transaction in the local commitment chain. As a result the edge of our revocation window is extended by one, and the tail of our local commitment chain is advanced by a single commitment. This now lowest unrevoked commitment becomes our currently accepted state within the channel. This method also returns the set of HTLC's currently active within the commitment transaction and the htlcs the were resolved. This return value allows callers to act once an HTLC has been locked into our commitment transaction.

func (*LightningChannel) SetFwdFilter

func (lc *LightningChannel) SetFwdFilter(height uint64,
	fwdFilter *channeldb.PkgFilter) error

SetFwdFilter writes the forwarding decision for a given remote commitment height.

func (*LightningChannel) SettleHTLC

func (lc *LightningChannel) SettleHTLC(preimage [32]byte,
	htlcIndex uint64, sourceRef *channeldb.AddRef,
	destRef *channeldb.SettleFailRef, closeKey *models.CircuitKey) error

SettleHTLC attempts to settle an existing outstanding received HTLC. The remote log index of the HTLC settled is returned in order to facilitate creating the corresponding wire message. In the case the supplied preimage is invalid, an error is returned.

The additional arguments correspond to:

  • sourceRef: specifies the location of the Add HTLC within a forwarding package that this HTLC is settling. Every Settle fails exactly one Add, so this should never be empty in practice.

  • destRef: specifies the location of the Settle HTLC within another channel's forwarding package. This value can be nil if the corresponding Add HTLC was never locked into an outgoing commitment txn, or this HTLC does not originate as a response from the peer on the outgoing link, e.g. on-chain resolutions.

  • closeKey: identifies the circuit that should be deleted after this Settle HTLC is included in a commitment txn. This value should only be nil if the HTLC was settled locally before committing a circuit to the circuit map.

NOTE: It is okay for sourceRef, destRef, and closeKey to be nil when unit testing the wallet.

func (*LightningChannel) ShortChanID

func (lc *LightningChannel) ShortChanID() lnwire.ShortChannelID

ShortChanID returns the short channel ID for the channel. The short channel ID encodes the exact location in the main chain that the original funding output can be found.

func (*LightningChannel) SignNextCommitment

func (lc *LightningChannel) SignNextCommitment() (*NewCommitState, error)

SignNextCommitment signs a new commitment which includes any previous unsettled HTLCs, any new HTLCs, and any modifications to prior HTLCs committed in previous commitment updates. Signing a new commitment decrements the available revocation window by 1. After a successful method call, the remote party's commitment chain is extended by a new commitment which includes all updates to the HTLC log prior to this method invocation. The first return parameter is the signature for the commitment transaction itself, while the second parameter is a slice of all HTLC signatures (if any). The HTLC signatures are sorted according to the BIP 69 order of the HTLC's on the commitment transaction. Finally, the new set of pending HTLCs for the remote party's commitment are also returned.

func (*LightningChannel) State

func (lc *LightningChannel) State() *channeldb.OpenChannel

State provides access to the channel's internal state.

func (*LightningChannel) StateSnapshot

func (lc *LightningChannel) StateSnapshot() *channeldb.ChannelSnapshot

StateSnapshot returns a snapshot of the current fully committed state within the channel.

func (*LightningChannel) UpdateFee

func (lc *LightningChannel) UpdateFee(feePerKw chainfee.SatPerKWeight) error

UpdateFee initiates a fee update for this channel. Must only be called by the channel initiator, and must be called before sending update_fee to the remote.

type LightningWallet

type LightningWallet struct {

	// Cfg is the configuration struct that will be used by the wallet to
	// access the necessary interfaces and default it needs to carry on its
	// duties.
	Cfg Config

	// WalletController is the core wallet, all non Lightning Network
	// specific interaction is proxied to the internal wallet.
	WalletController

	// SecretKeyRing is the interface we'll use to derive any keys related
	// to our purpose within the network including: multi-sig keys, node
	// keys, revocation keys, etc.
	keychain.SecretKeyRing
	// contains filtered or unexported fields
}

LightningWallet is a domain specific, yet general Bitcoin wallet capable of executing workflow required to interact with the Lightning Network. It is domain specific in the sense that it understands all the fancy scripts used within the Lightning Network, channel lifetimes, etc. However, it embeds a general purpose Bitcoin wallet within it. Therefore, it is also able to serve as a regular Bitcoin wallet which uses HD keys. The wallet is highly concurrent internally. All communication, and requests towards the wallet are dispatched as messages over channels, ensuring thread safety across all operations. Interaction has been designed independent of any peer-to-peer communication protocol, allowing the wallet to be self-contained and embeddable within future projects interacting with the Lightning Network.

NOTE: At the moment the wallet requires a btcd full node, as it's dependent on btcd's websockets notifications as event triggers during the lifetime of a channel. However, once the chainntnfs package is complete, the wallet will be compatible with multiple RPC/notification services such as Electrum, Bitcoin Core + ZeroMQ, etc. Eventually, the wallet won't require a full-node at all, as SPV support is integrated into btcwallet.

func NewLightningWallet

func NewLightningWallet(Cfg Config) (*LightningWallet, error)

NewLightningWallet creates/opens and initializes a LightningWallet instance. If the wallet has never been created (according to the passed dataDir), first-time setup is executed.

func (*LightningWallet) ActiveReservations

func (l *LightningWallet) ActiveReservations() []*ChannelReservation

ActiveReservations returns a slice of all the currently active (non-canceled) reservations.

func (*LightningWallet) CancelFundingIntent

func (l *LightningWallet) CancelFundingIntent(pid [32]byte) error

CancelFundingIntent allows a caller to cancel a previously registered funding intent. If no intent was found, then an error will be returned.

func (*LightningWallet) CancelRebroadcast

func (l *LightningWallet) CancelRebroadcast(txid chainhash.Hash)

CancelRebroadcast cancels the rebroadcast of the given transaction.

func (*LightningWallet) CheckReservedValue

func (l *LightningWallet) CheckReservedValue(in []wire.OutPoint,
	out []*wire.TxOut, numAnchorChans int) (btcutil.Amount, error)

CheckReservedValue checks whether publishing a transaction with the given inputs and outputs would violate the value we reserve in the wallet for bumping the fee of anchor channels. The numAnchorChans argument should be set the number of open anchor channels controlled by the wallet after the transaction has been published.

If the reserved value is violated, the returned error will be ErrReservedValueInvalidated. The method will also return the current reserved value, both in case of success and in case of ErrReservedValueInvalidated.

NOTE: This method should only be run with the CoinSelectLock held.

func (*LightningWallet) CheckReservedValueTx

func (l *LightningWallet) CheckReservedValueTx(req CheckReservedValueTxReq) (
	btcutil.Amount, error)

CheckReservedValueTx calls CheckReservedValue with the inputs and outputs from the given tx, with the number of anchor channels currently open in the database.

NOTE: This method should only be run with the CoinSelectLock held.

func (*LightningWallet) ConfirmedBalance

func (l *LightningWallet) ConfirmedBalance(confs int32,
	account string) (btcutil.Amount, error)

ConfirmedBalance returns the current confirmed balance of a wallet account. This methods wraps the internal WalletController method so we're able to properly hold the coin select mutex while we compute the balance.

func (*LightningWallet) CurrentNumAnchorChans

func (l *LightningWallet) CurrentNumAnchorChans() (int, error)

CurrentNumAnchorChans returns the current number of non-private anchor channels the wallet should be ready to fee bump if needed.

func (*LightningWallet) InitChannelReservation

func (l *LightningWallet) InitChannelReservation(
	req *InitFundingReserveMsg) (*ChannelReservation, error)

InitChannelReservation kicks off the 3-step workflow required to successfully open a payment channel with a remote node. As part of the funding reservation, the inputs selected for the funding transaction are 'locked'. This ensures that multiple channel reservations aren't double spending the same inputs in the funding transaction. If reservation initialization is successful, a ChannelReservation containing our completed contribution is returned. Our contribution contains all the items necessary to allow the counterparty to build the funding transaction, and both versions of the commitment transaction. Otherwise, an error occurred and a nil pointer along with an error are returned.

Once a ChannelReservation has been obtained, two additional steps must be processed before a payment channel can be considered 'open'. The second step validates, and processes the counterparty's channel contribution. The third, and final step verifies all signatures for the inputs of the funding transaction, and that the signature we record for our version of the commitment transaction is valid.

func (*LightningWallet) ListUnspentWitnessFromDefaultAccount

func (l *LightningWallet) ListUnspentWitnessFromDefaultAccount(
	minConfs, maxConfs int32) ([]*Utxo, error)

ListUnspentWitnessFromDefaultAccount returns all unspent outputs from the default wallet account which are version 0 witness programs. The 'minConfs' and 'maxConfs' parameters indicate the minimum and maximum number of confirmations an output needs in order to be returned by this method. Passing -1 as 'minConfs' indicates that even unconfirmed outputs should be returned. Using MaxInt32 as 'maxConfs' implies returning all outputs with at least 'minConfs'.

NOTE: This method requires the global coin selection lock to be held.

func (*LightningWallet) LockedOutpoints

func (l *LightningWallet) LockedOutpoints() []*wire.OutPoint

LockedOutpoints returns a list of all currently locked outpoint.

func (*LightningWallet) PsbtFundingFinalize

func (l *LightningWallet) PsbtFundingFinalize(pid [32]byte, packet *psbt.Packet,
	rawTx *wire.MsgTx) error

PsbtFundingFinalize looks up a previously registered funding intent by its pending channel ID and tries to advance the state machine by finalizing the passed PSBT.

func (*LightningWallet) PsbtFundingVerify

func (l *LightningWallet) PsbtFundingVerify(pendingChanID [32]byte,
	packet *psbt.Packet, skipFinalize bool) error

PsbtFundingVerify looks up a previously registered funding intent by its pending channel ID and tries to advance the state machine by verifying the passed PSBT.

func (*LightningWallet) PublishTransaction

func (l *LightningWallet) PublishTransaction(tx *wire.MsgTx,
	label string) error

PublishTransaction wraps the wallet controller tx publish method with an extra rebroadcaster layer if the sub-system is configured.

func (*LightningWallet) RegisterFundingIntent

func (l *LightningWallet) RegisterFundingIntent(expectedID [32]byte,
	shimIntent chanfunding.Intent) error

RegisterFundingIntent allows a caller to signal to the wallet that if a pending channel ID of expectedID is found, then it can skip constructing a new chanfunding.Assembler, and instead use the specified chanfunding.Intent. As an example, this lets some of the parameters for funding transaction to be negotiated outside the regular funding protocol.

func (*LightningWallet) ResetReservations

func (l *LightningWallet) ResetReservations()

ResetReservations reset the volatile wallet state which tracks all currently active reservations.

func (*LightningWallet) Shutdown

func (l *LightningWallet) Shutdown() error

Shutdown gracefully stops the wallet, and all active goroutines.

func (*LightningWallet) Startup

func (l *LightningWallet) Startup() error

Startup establishes a connection to the RPC source, and spins up all goroutines required to handle incoming messages.

func (*LightningWallet) ValidateChannel

func (l *LightningWallet) ValidateChannel(channelState *channeldb.OpenChannel,
	fundingTx *wire.MsgTx) error

ValidateChannel will attempt to fully validate a newly mined channel, given its funding transaction and existing channel state. If this method returns an error, then the mined channel is invalid, and shouldn't be used.

func (*LightningWallet) WithCoinSelectLock

func (l *LightningWallet) WithCoinSelectLock(f func() error) error

WithCoinSelectLock will execute the passed function closure in a synchronized manner preventing any coin selection operations from proceeding while the closure is executing. This can be seen as the ability to execute a function closure under an exclusive coin selection lock.

type LocalForceCloseSummary

type LocalForceCloseSummary struct {
	// ChanPoint is the outpoint that created the channel which has been
	// force closed.
	ChanPoint wire.OutPoint

	// CloseTx is the transaction which can be used to close the channel
	// on-chain. When we initiate a force close, this will be our latest
	// commitment state.
	CloseTx *wire.MsgTx

	// CommitResolution contains all the data required to sweep the output
	// to ourselves. Since this is our commitment transaction, we'll need
	// to wait a time delay before we can sweep the output.
	//
	// NOTE: If our commitment delivery output is below the dust limit,
	// then this will be nil.
	CommitResolution *CommitOutputResolution

	// HtlcResolutions contains all the data required to sweep any outgoing
	// HTLC's and incoming HTLc's we know the preimage to. For each of these
	// HTLC's, we'll need to go to the second level to sweep them fully.
	HtlcResolutions *HtlcResolutions

	// ChanSnapshot is a snapshot of the final state of the channel at the
	// time the summary was created.
	ChanSnapshot channeldb.ChannelSnapshot

	// AnchorResolution contains the data required to sweep the anchor
	// output. If the channel type doesn't include anchors, the value of
	// this field will be nil.
	AnchorResolution *AnchorResolution
}

LocalForceCloseSummary describes the final commitment state before the channel is locked-down to initiate a force closure by broadcasting the latest state on-chain. If we intend to broadcast this this state, the channel should not be used after generating this close summary. The summary includes all the information required to claim all rightfully owned outputs when the commitment gets confirmed.

func NewLocalForceCloseSummary

func NewLocalForceCloseSummary(chanState *channeldb.OpenChannel,
	signer input.Signer, commitTx *wire.MsgTx, stateNum uint64) (
	*LocalForceCloseSummary, error)

NewLocalForceCloseSummary generates a LocalForceCloseSummary from the given channel state. The passed commitTx must be a fully signed commitment transaction corresponding to localCommit.

type MessageSigner

type MessageSigner interface {
	// SignMessage attempts to sign a target message with the private key
	// described in the key locator. If the target private key is unable to
	// be found, then an error will be returned. The actual digest signed is
	// the single or double SHA-256 of the passed message.
	SignMessage(keyLoc keychain.KeyLocator, msg []byte,
		doubleHash bool) (*ecdsa.Signature, error)
}

MessageSigner represents an abstract object capable of signing arbitrary messages. The capabilities of this interface are used to sign announcements to the network, or just arbitrary messages that leverage the wallet's keys to attest to some message.

type MusigCommitType

type MusigCommitType uint8

MusigCommitType is an enum that denotes if this is the local or remote commitment.

const (
	// LocalMusigCommit denotes that this a session for the local
	// commitment.
	LocalMusigCommit MusigCommitType = iota

	// RemoteMusigCommit denotes that this is a session for the remote
	// commitment.
	RemoteMusigCommit
)

type MusigNoncePair

type MusigNoncePair struct {
	// SigningNonce is the nonce used by the signer to sign the commitment.
	SigningNonce musig2.Nonces

	// VerificationNonce is the nonce used by the verifier to verify the
	// commitment.
	VerificationNonce musig2.Nonces
}

MusigNoncePair holds the two nonces needed to sign/verify a new commitment state. The signer nonce is the nonce used by the signer (remote nonce), and the verification nonce, the nonce used by the verifier (local nonce).

func (*MusigNoncePair) String

func (n *MusigNoncePair) String() string

String returns a string representation of the MusigNoncePair.

type MusigPairSession

type MusigPairSession struct {
	// LocalSession is the local party's musig2 session.
	LocalSession *MusigSession

	// RemoteSession is the remote party's musig2 session.
	RemoteSession *MusigSession
	// contains filtered or unexported fields
}

MusigPairSession houses the two musig2 sessions needed to do funding and drive forward the state machine. The local session is used to verify incoming commitment states. The remote session is used to propose new commitment states to the remote party.

func NewMusigPairSession

func NewMusigPairSession(cfg *MusigSessionCfg) *MusigPairSession

NewMusigPairSession creates a new musig2 pair session.

type MusigPartialSig

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

MusigPartialSig is a wrapper around the base musig2.PartialSignature type that also includes information about the set of nonces used, and also the signer. This allows us to implement the input.Signature interface, as that requires the ability to perform abstract verification based on a public key.

func NewMusigPartialSig

func NewMusigPartialSig(sig *musig2.PartialSignature,
	signerNonce, combinedNonce lnwire.Musig2Nonce,
	signerKeys []*btcec.PublicKey) *MusigPartialSig

NewMusigPartialSig creates a new musig partial signature.

func (*MusigPartialSig) FromSchnorrShell

func (p *MusigPartialSig) FromSchnorrShell(sig *schnorr.Signature)

FromSchnorrShell takes a schnorr signature and parses out the last 32 bytes as a normal musig2 partial signature.

func (*MusigPartialSig) FromWireSig

FromWireSig maps a wire partial sig to this internal type that we'll use to perform signature validation.

func (*MusigPartialSig) Serialize

func (p *MusigPartialSig) Serialize() []byte

Serialize serializes the musig2 partial signature. The serializing includes the signer's public nonce _and_ the partial signature. The final signature is always 98 bytes in length.

func (*MusigPartialSig) ToSchnorrShell

func (p *MusigPartialSig) ToSchnorrShell() *schnorr.Signature

ToSchnorrShell converts the musig partial signature to a regular schnorr. This schnorr signature uses a zero value for the 'r' field, so we're just only using the last 32-bytes of the signature. This is useful when we need to convert an HTLC schnorr signature into something we can send using the existing messages.

func (*MusigPartialSig) ToWireSig

func (p *MusigPartialSig) ToWireSig() *lnwire.PartialSigWithNonce

ToWireSig maps the partial signature to something that we can use to write out for the wire protocol.

func (*MusigPartialSig) Verify

func (p *MusigPartialSig) Verify(msg []byte, pub *btcec.PublicKey) bool

Verify attempts to verify the partial musig2 signature using the passed message and signer public key.

NOTE: This implements the input.Signature interface.

type MusigSession

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

MusigSession abstracts over the details of a logical musig session. A single session is used for each commitment transactions. The sessions use a JIT nonce style, wherein part of the session can be created using only the verifier nonce. Once a new state is signed, then the signer nonce is generated. Similarly, the verifier then uses the received signer nonce to complete the session and verify the incoming signature.

func NewPartialMusigSession

func NewPartialMusigSession(verificationNonce musig2.Nonces,
	localKey, remoteKey keychain.KeyDescriptor,
	signer input.MuSig2Signer, inputTxOut *wire.TxOut,
	commitType MusigCommitType) *MusigSession

NewPartialMusigSession creates a new musig2 session given only the verification nonce (local nonce), and the other information that has already been bound to the session.

func (*MusigSession) CombineSigs

func (m *MusigSession) CombineSigs(sigs ...*musig2.PartialSignature,
) (*schnorr.Signature, error)

CombineSigs combines the passed partial signatures into a valid schnorr signature.

func (*MusigSession) FinalizeSession

func (m *MusigSession) FinalizeSession(signingNonce musig2.Nonces) error

FinalizeSession finalizes the session given the signer nonce. This is called before signing or verifying a new commitment.

func (*MusigSession) Refresh

func (m *MusigSession) Refresh(verificationNonce *musig2.Nonces,
) (*MusigSession, error)

Refresh is called once we receive a new verification nonce from the remote party after sending a signature. This nonce will be coupled within the revoke-and-ack message of the remote party.

func (*MusigSession) SignCommit

func (m *MusigSession) SignCommit(tx *wire.MsgTx) (*MusigPartialSig, error)

SignCommit signs the passed commitment w/ the current signing (relative remote) nonce. Given nonces should only ever be used once, once the method returns a new nonce is returned, w/ the existing nonce blanked out.

func (*MusigSession) VerificationNonce

func (m *MusigSession) VerificationNonce() *musig2.Nonces

VerificationNonce returns the current verification nonce for the session.

func (*MusigSession) VerifyCommitSig

func (m *MusigSession) VerifyCommitSig(commitTx *wire.MsgTx,
	sig *lnwire.PartialSigWithNonce,
	musigOpts ...MusigSessionOpt) (*musig2.Nonces, error)

VerifyCommitSig attempts to verify the passed partial signature against the passed commitment transaction. A keyspend sighash is assumed to generate the signed message. As we never re-use nonces, a new verification nonce (our relative local nonce) returned to transmit to the remote party, which allows them to generate another signature.

type MusigSessionCfg

type MusigSessionCfg struct {
	// LocalKey is a key desc for the local key.
	LocalKey keychain.KeyDescriptor

	// RemoteKey is a key desc for the remote key.
	RemoteKey keychain.KeyDescriptor

	// LocalNonce is the local party's initial verification nonce.
	LocalNonce musig2.Nonces

	// RemoteNonce is the remote party's initial verification nonce.
	RemoteNonce musig2.Nonces

	// Signer is the signer that will be used to generate the session.
	Signer input.MuSig2Signer

	// InputTxOut is the output that we're signing for. This will be the
	// funding input.
	InputTxOut *wire.TxOut
}

MusigSessionCfg is used to create a new musig2 pair session. It contains the keys for both parties, as well as their initial verification nonces.

type MusigSessionOpt

type MusigSessionOpt func(*musigSessionOpts)

MusigSessionOpt is a functional option that can be used to modify calls to the musig session.

func WithLocalCounterNonce

func WithLocalCounterNonce(targetHeight uint64,
	shaGen shachain.Producer) MusigSessionOpt

WithLocalCounterNonce is used to generate local nonces based on the shachain producer and the current height. This allows us to not have to write secret nonce state to disk. Instead, we can use this to derive the nonce we need to sign and broadcast our own commitment transaction.

type NewCommitState

type NewCommitState struct {
	*CommitSigs

	// PendingHTLCs is the set of new/pending HTLCs produced by this
	// commitment state.
	PendingHTLCs []channeldb.HTLC
}

NewCommitState wraps the various signatures needed to properly propose/accept a new commitment state. This includes the signer's nonce for musig2 channels.

type OpenChannelDetails

type OpenChannelDetails struct {
	// Channel is the active channel created by an instance of a
	// ChannelReservation and the required funding workflow.
	Channel *LightningChannel

	// ConfirmationHeight is the block height within the chain that
	// included the channel.
	ConfirmationHeight uint32

	// TransactionIndex is the index within the confirming block that the
	// transaction resides.
	TransactionIndex uint32
}

OpenChannelDetails wraps the finalized fully confirmed channel which resulted from a ChannelReservation instance with details concerning exactly _where_ in the chain the channel was ultimately opened.

type OutgoingHtlcResolution

type OutgoingHtlcResolution struct {
	// Expiry the absolute timeout of the HTLC. This value is expressed in
	// block height, meaning after this height the HLTC can be swept.
	Expiry uint32

	// SignedTimeoutTx is the fully signed HTLC timeout transaction. This
	// must be broadcast immediately after timeout has passed. Once this
	// has been confirmed, the HTLC output will transition into the
	// delay+claim state.
	//
	// NOTE: If this field is nil, then this indicates that we don't need
	// to go to the second level to claim this HTLC. Instead, it can be
	// claimed directly from the outpoint listed below.
	SignedTimeoutTx *wire.MsgTx

	// SignDetails is non-nil if SignedTimeoutTx is non-nil, and the
	// channel is of the anchor type. As the above HTLC transaction will be
	// signed by the channel peer using SINGLE|ANYONECANPAY for such
	// channels, we can use the sign details to add the input-output pair
	// of the HTLC transaction to another transaction, thereby aggregating
	// multiple HTLC transactions together, and adding fees as needed.
	SignDetails *input.SignDetails

	// CsvDelay is the relative time lock (expressed in blocks) that must
	// pass after the SignedTimeoutTx is confirmed in the chain before the
	// output can be swept.
	//
	// NOTE: If SignedTimeoutTx is nil, then this field denotes the CSV
	// delay needed to spend from the commitment transaction.
	CsvDelay uint32

	// ClaimOutpoint is the final outpoint that needs to be spent in order
	// to fully sweep the HTLC. The SignDescriptor below should be used to
	// spend this outpoint. In the case of a second-level HTLC (non-nil
	// SignedTimeoutTx), then we'll be spending a new transaction.
	// Otherwise, it'll be an output in the commitment transaction.
	ClaimOutpoint wire.OutPoint

	// SweepSignDesc is a sign descriptor that has been populated with the
	// necessary items required to spend the sole output of the above
	// transaction.
	SweepSignDesc input.SignDescriptor
}

OutgoingHtlcResolution houses the information necessary to sweep any outgoing HTLC's after their contract has expired. This struct will be needed in one of two cases: the local party force closes the commitment transaction or the remote party unilaterally closes with their version of the commitment transaction.

func (*OutgoingHtlcResolution) HtlcPoint

func (r *OutgoingHtlcResolution) HtlcPoint() wire.OutPoint

HtlcPoint returns the htlc's outpoint on the commitment tx.

type OutputDetail

type OutputDetail struct {
	OutputType   txscript.ScriptClass
	Addresses    []btcutil.Address
	PkScript     []byte
	OutputIndex  int
	Value        btcutil.Amount
	IsOurAddress bool
}

OutputDetail contains additional information on a destination address.

type PaymentDescriptor

type PaymentDescriptor struct {
	// RHash is the payment hash for this HTLC. The HTLC can be settled iff
	// the preimage to this hash is presented.
	RHash PaymentHash

	// RPreimage is the preimage that settles the HTLC pointed to within the
	// log by the ParentIndex.
	RPreimage PaymentHash

	// Timeout is the absolute timeout in blocks, after which this HTLC
	// expires.
	Timeout uint32

	// Amount is the HTLC amount in milli-satoshis.
	Amount lnwire.MilliSatoshi

	// LogIndex is the log entry number that his HTLC update has within the
	// log. Depending on if IsIncoming is true, this is either an entry the
	// remote party added, or one that we added locally.
	LogIndex uint64

	// HtlcIndex is the index within the main update log for this HTLC.
	// Entries within the log of type Add will have this field populated,
	// as other entries will point to the entry via this counter.
	//
	// NOTE: This field will only be populate if EntryType is Add.
	HtlcIndex uint64

	// ParentIndex is the HTLC index of the entry that this update settles or
	// times out.
	//
	// NOTE: This field will only be populate if EntryType is Fail or
	// Settle.
	ParentIndex uint64

	// SourceRef points to an Add update in a forwarding package owned by
	// this channel.
	//
	// NOTE: This field will only be populated if EntryType is Fail or
	// Settle.
	SourceRef *channeldb.AddRef

	// DestRef points to a Fail/Settle update in another link's forwarding
	// package.
	//
	// NOTE: This field will only be populated if EntryType is Fail or
	// Settle, and the forwarded Add successfully included in an outgoing
	// link's commitment txn.
	DestRef *channeldb.SettleFailRef

	// OpenCircuitKey references the incoming Chan/HTLC ID of an Add HTLC
	// packet delivered by the switch.
	//
	// NOTE: This field is only populated for payment descriptors in the
	// *local* update log, and if the Add packet was delivered by the
	// switch.
	OpenCircuitKey *models.CircuitKey

	// ClosedCircuitKey references the incoming Chan/HTLC ID of the Add HTLC
	// that opened the circuit.
	//
	// NOTE: This field is only populated for payment descriptors in the
	// *local* update log, and if settle/fails have a committed circuit in
	// the circuit map.
	ClosedCircuitKey *models.CircuitKey

	// OnionBlob is an opaque blob which is used to complete multi-hop
	// routing.
	//
	// NOTE: Populated only on add payment descriptor entry types.
	OnionBlob []byte

	// ShaOnionBlob is a sha of the onion blob.
	//
	// NOTE: Populated only in payment descriptor with MalformedFail type.
	ShaOnionBlob [sha256.Size]byte

	// FailReason stores the reason why a particular payment was canceled.
	//
	// NOTE: Populate only in fail payment descriptor entry types.
	FailReason []byte

	// FailCode stores the code why a particular payment was canceled.
	//
	// NOTE: Populated only in payment descriptor with MalformedFail type.
	FailCode lnwire.FailCode

	// EntryType denotes the exact type of the PaymentDescriptor. In the
	// case of a Timeout, or Settle type, then the Parent field will point
	// into the log to the HTLC being modified.
	EntryType updateType

	// BlindingPoint is an optional ephemeral key used in route blinding.
	// This value is set for nodes that are relaying payments inside of a
	// blinded route (ie, not the introduction node) from update_add_htlc's
	// TLVs.
	BlindingPoint lnwire.BlindingPointRecord
	// contains filtered or unexported fields
}

PaymentDescriptor represents a commitment state update which either adds, settles, or removes an HTLC. PaymentDescriptors encapsulate all necessary metadata w.r.t to an HTLC, and additional data pairing a settle message to the original added HTLC.

TODO(roasbeef): LogEntry interface??

  • need to separate attrs for cancel/add/settle/feeupdate

func PayDescsFromRemoteLogUpdates

func PayDescsFromRemoteLogUpdates(chanID lnwire.ShortChannelID, height uint64,
	logUpdates []channeldb.LogUpdate) ([]*PaymentDescriptor, error)

PayDescsFromRemoteLogUpdates converts a slice of LogUpdates received from the remote peer into PaymentDescriptors to inform a link's forwarding decisions.

NOTE: The provided `logUpdates` MUST correspond exactly to either the Adds or SettleFails in this channel's forwarding package at `height`.

type PaymentHash

type PaymentHash [32]byte

PaymentHash represents the sha256 of a random value. This hash is used to uniquely track incoming/outgoing payments within this channel, as well as payments requested by the wallet/daemon.

type PreviousOutPoint

type PreviousOutPoint struct {
	// OutPoint is the transaction out point in the format txid:n.
	OutPoint string

	// IsOurOutput denotes if the previous output is controlled by the
	// internal wallet. The flag will only detect p2wkh, np2wkh and p2tr
	// inputs as its own.
	IsOurOutput bool
}

PreviousOutPoint contains information about the previous outpoint.

type PsbtFundingRequired

type PsbtFundingRequired struct {
	// Intent is the pending PSBT funding intent that needs to be funded
	// if the wrapping error is returned.
	Intent *chanfunding.PsbtIntent
}

PsbtFundingRequired is a type that implements the error interface and contains the information needed to construct a PSBT.

func (*PsbtFundingRequired) Error

func (p *PsbtFundingRequired) Error() string

Error returns the underlying error.

NOTE: This method is part of the error interface.

type Rebroadcaster

type Rebroadcaster interface {
	// Start launches all goroutines the rebroadcaster needs to operate.
	Start() error

	// Started returns true if the broadcaster is already active.
	Started() bool

	// Stop terminates the rebroadcaster and all goroutines it spawned.
	Stop()

	// Broadcast enqueues a transaction to be rebroadcast until it's been
	// confirmed.
	Broadcast(tx *wire.MsgTx) error

	// MarkAsConfirmed marks a transaction as confirmed, so it won't be
	// rebroadcast.
	MarkAsConfirmed(txid chainhash.Hash)
}

Rebroadcaster is an abstract rebroadcaster instance that'll continually rebroadcast transactions in the background until they're confirmed.

type ReservationError

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

ReservationError wraps certain errors returned during channel reservation that can be sent across the wire to the remote peer. Errors not being ReservationErrors will not be sent to the remote in case of a failed channel reservation, as they may contain private information.

func ErrChainMismatch

func ErrChainMismatch(knownChain,
	unknownChain *chainhash.Hash) ReservationError

ErrChainMismatch returns an error indicating that the initiator tried to open a channel for an unknown chain.

func ErrChanReserveTooLarge

func ErrChanReserveTooLarge(reserve,
	maxReserve btcutil.Amount) ReservationError

ErrChanReserveTooLarge returns an error indicating that the chan reserve the remote is requiring, is too large to be accepted.

func ErrChanReserveTooSmall

func ErrChanReserveTooSmall(reserve, dustLimit btcutil.Amount) ReservationError

ErrChanReserveTooSmall returns an error indicating that the channel reserve the remote is requiring is too small to be accepted.

func ErrChanTooLarge

func ErrChanTooLarge(chanSize, maxChanSize btcutil.Amount) ReservationError

ErrChanTooLarge returns an error indicating that an incoming channel request was too large. We'll reject any incoming channels if they're above our configured value for the max channel size we'll accept.

func ErrChanTooSmall

func ErrChanTooSmall(chanSize, minChanSize btcutil.Amount) ReservationError

ErrChanTooSmall returns an error indicating that an incoming channel request was too small. We'll reject any incoming channels if they're below our configured value for the min channel size we'll accept.

func ErrCsvDelayTooLarge

func ErrCsvDelayTooLarge(remoteDelay, maxDelay uint16) ReservationError

ErrCsvDelayTooLarge returns an error indicating that the CSV delay was to large to be accepted, along with the current max.

func ErrFunderBalanceDust

func ErrFunderBalanceDust(commitFee, funderBalance,
	minBalance int64) ReservationError

ErrFunderBalanceDust returns an error indicating the initial balance of the funder is considered dust at the current commitment fee.

func ErrInvalidDustLimit

func ErrInvalidDustLimit(dustLimit btcutil.Amount) ReservationError

ErrInvalidDustLimit returns an error indicating that a proposed DustLimit was rejected.

func ErrMaxHtlcNumTooLarge

func ErrMaxHtlcNumTooLarge(maxHtlc, maxMaxHtlc uint16) ReservationError

ErrMaxHtlcNumTooLarge returns an error indicating that the 'max HTLCs in flight' value the remote required is too large to be accepted.

func ErrMaxHtlcNumTooSmall

func ErrMaxHtlcNumTooSmall(maxHtlc, minMaxHtlc uint16) ReservationError

ErrMaxHtlcNumTooSmall returns an error indicating that the 'max HTLCs in flight' value the remote required is too small to be accepted.

func ErrMaxValueInFlightTooSmall

func ErrMaxValueInFlightTooSmall(maxValInFlight,
	minMaxValInFlight lnwire.MilliSatoshi) ReservationError

ErrMaxValueInFlightTooSmall returns an error indicating that the 'max HTLC value in flight' the remote required is too small to be accepted.

func ErrMinHtlcTooLarge

func ErrMinHtlcTooLarge(minHtlc,
	maxMinHtlc lnwire.MilliSatoshi) ReservationError

ErrMinHtlcTooLarge returns an error indicating that the MinHTLC value the remote required is too large to be accepted.

func ErrNonZeroPushAmount

func ErrNonZeroPushAmount() ReservationError

ErrNonZeroPushAmount is returned by a remote peer that receives a FundingOpen request for a channel with non-zero push amount while they have 'rejectpush' enabled.

func ErrZeroCapacity

func ErrZeroCapacity() ReservationError

ErrZeroCapacity returns an error indicating the funder attempted to put zero funds into the channel.

type SigPool

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

SigPool is a struct that is meant to allow the current channel state machine to parallelize all signature generation and verification. This struct is needed as _each_ HTLC when creating a commitment transaction requires a signature, and similarly a receiver of a new commitment must verify all the HTLC signatures included within the CommitSig message. A pool of workers will be maintained by the sigPool. Batches of jobs (either to sign or verify) can be sent to the pool of workers which will asynchronously perform the specified job.

func NewSigPool

func NewSigPool(numWorkers int, signer input.Signer) *SigPool

NewSigPool creates a new signature pool with the specified number of workers. The recommended parameter for the number of works is the number of physical CPU cores available on the target machine.

func (*SigPool) Start

func (s *SigPool) Start() error

Start starts of all goroutines that the sigPool sig pool needs to carry out its duties.

func (*SigPool) Stop

func (s *SigPool) Stop() error

Stop signals any active workers carrying out jobs to exit so the sigPool can gracefully shutdown.

func (*SigPool) SubmitSignBatch

func (s *SigPool) SubmitSignBatch(signJobs []SignJob)

SubmitSignBatch submits a batch of signature jobs to the sigPool. The response and cancel channels for each of the SignJob's are expected to be fully populated, as the response for each job will be sent over the response channel within the job itself.

func (*SigPool) SubmitVerifyBatch

func (s *SigPool) SubmitVerifyBatch(verifyJobs []VerifyJob,
	cancelChan chan struct{}) <-chan *HtlcIndexErr

SubmitVerifyBatch submits a batch of verification jobs to the sigPool. For each job submitted, an error will be passed into the returned channel denoting if signature verification was valid or not. The passed cancelChan allows the caller to cancel all pending jobs in the case that they wish to bail early.

type SignJob

type SignJob struct {
	// SignDesc is intended to be a full populated SignDescriptor which
	// encodes the necessary material (keys, witness script, etc) required
	// to generate a valid signature for the specified input.
	SignDesc input.SignDescriptor

	// Tx is the transaction to be signed. This is required to generate the
	// proper sighash for the input to be signed.
	Tx *wire.MsgTx

	// OutputIndex is the output index of the HTLC on the commitment
	// transaction being signed.
	OutputIndex int32

	// Cancel is a channel that should be closed if the caller wishes to
	// abandon all pending sign jobs part of a single batch.
	Cancel chan struct{}

	// Resp is the channel that the response to this particular SignJob
	// will be sent over.
	//
	// TODO(roasbeef): actually need to allow caller to set, need to retain
	// order mark commit sig as special
	Resp chan SignJobResp
}

SignJob is a job sent to the sigPool sig pool to generate a valid signature according to the passed SignDescriptor for the passed transaction. Jobs are intended to be sent in batches in order to parallelize the job of generating signatures for a new commitment transaction.

type SignJobResp

type SignJobResp struct {
	// Sig is the generated signature for a particular SignJob In the case
	// of an error during signature generation, then this value sent will
	// be nil.
	Sig lnwire.Sig

	// Err is the error that occurred when executing the specified
	// signature job. In the case that no error occurred, this value will
	// be nil.
	Err error
}

SignJobResp is the response to a sign job. Both channels are to be read in order to ensure no unnecessary goroutine blocking occurs. Additionally, both channels should be buffered.

type TransactionDetail

type TransactionDetail struct {
	// Hash is the transaction hash of the transaction.
	Hash chainhash.Hash

	// Value is the net value of this transaction (in satoshis) from the
	// PoV of the wallet. If this transaction purely spends from the
	// wallet's funds, then this value will be negative. Similarly, if this
	// transaction credits the wallet, then this value will be positive.
	Value btcutil.Amount

	// NumConfirmations is the number of confirmations this transaction
	// has. If the transaction is unconfirmed, then this value will be
	// zero.
	NumConfirmations int32

	// BlockHeight is the hash of the block which includes this
	// transaction. Unconfirmed transactions will have a nil value for this
	// field.
	BlockHash *chainhash.Hash

	// BlockHeight is the height of the block including this transaction.
	// Unconfirmed transaction will show a height of zero.
	BlockHeight int32

	// Timestamp is the unix timestamp of the block including this
	// transaction. If the transaction is unconfirmed, then this will be a
	// timestamp of txn creation.
	Timestamp int64

	// TotalFees is the total fee in satoshis paid by this transaction.
	TotalFees int64

	// OutputDetails contains output data for each destination address, such
	// as the output script and amount.
	OutputDetails []OutputDetail

	// RawTx returns the raw serialized transaction.
	RawTx []byte

	// Label is an optional transaction label.
	Label string

	// PreviousOutpoints are the inputs for a transaction.
	PreviousOutpoints []PreviousOutPoint
}

TransactionDetail describes a transaction with either inputs which belong to the wallet, or has outputs that pay to the wallet.

type TransactionSubscription

type TransactionSubscription interface {
	// ConfirmedTransactions returns a channel which will be sent on as new
	// relevant transactions are confirmed.
	ConfirmedTransactions() chan *TransactionDetail

	// UnconfirmedTransactions returns a channel which will be sent on as
	// new relevant transactions are seen within the network.
	UnconfirmedTransactions() chan *TransactionDetail

	// Cancel finalizes the subscription, cleaning up any resources
	// allocated.
	Cancel()
}

TransactionSubscription is an interface which describes an object capable of receiving notifications of new transaction related to the underlying wallet. TODO(roasbeef): add balance updates?

type UnilateralCloseSummary

type UnilateralCloseSummary struct {
	// SpendDetail is a struct that describes how and when the funding
	// output was spent.
	*chainntnfs.SpendDetail

	// ChannelCloseSummary is a struct describing the final state of the
	// channel and in which state is was closed.
	channeldb.ChannelCloseSummary

	// CommitResolution contains all the data required to sweep the output
	// to ourselves. If this is our commitment transaction, then we'll need
	// to wait a time delay before we can sweep the output.
	//
	// NOTE: If our commitment delivery output is below the dust limit,
	// then this will be nil.
	CommitResolution *CommitOutputResolution

	// HtlcResolutions contains a fully populated HtlcResolutions struct
	// which contains all the data required to sweep any outgoing HTLC's,
	// and also any incoming HTLC's that we know the pre-image to.
	HtlcResolutions *HtlcResolutions

	// RemoteCommit is the exact commitment state that the remote party
	// broadcast.
	RemoteCommit channeldb.ChannelCommitment

	// AnchorResolution contains the data required to sweep our anchor
	// output. If the channel type doesn't include anchors, the value of
	// this field will be nil.
	AnchorResolution *AnchorResolution
}

UnilateralCloseSummary describes the details of a detected unilateral channel closure. This includes the information about with which transactions, and block the channel was unilaterally closed, as well as summarization details concerning the _state_ of the channel at the point of channel closure. Additionally, if we had a commitment output above dust on the remote party's commitment transaction, the necessary a SignDescriptor with the material necessary to seep the output are returned. Finally, if we had any outgoing HTLC's within the commitment transaction, then an OutgoingHtlcResolution for each output will included.

func NewUnilateralCloseSummary

func NewUnilateralCloseSummary(chanState *channeldb.OpenChannel, signer input.Signer,
	commitSpend *chainntnfs.SpendDetail,
	remoteCommit channeldb.ChannelCommitment,
	commitPoint *btcec.PublicKey) (*UnilateralCloseSummary, error)

NewUnilateralCloseSummary creates a new summary that provides the caller with all the information required to claim all funds on chain in the event that the remote party broadcasts their commitment. The commitPoint argument should be set to the per_commitment_point corresponding to the spending commitment.

NOTE: The remoteCommit argument should be set to the stored commitment for this particular state. If we don't have the commitment stored (should only happen in case we have lost state) it should be set to an empty struct, in which case we will attempt to sweep the non-HTLC output using the passed commitPoint.

type Utxo

type Utxo struct {
	AddressType   AddressType
	Value         btcutil.Amount
	Confirmations int64
	PkScript      []byte
	wire.OutPoint
	Derivation *psbt.Bip32Derivation
	PrevTx     *wire.MsgTx
}

Utxo is an unspent output denoted by its outpoint, and output value of the original output.

type VerifyJob

type VerifyJob struct {
	// PubKey is the public key that was used to generate the purported
	// valid signature. Note that with the current channel construction,
	// this public key will likely have been tweaked using the current per
	// commitment point for a particular commitment transactions.
	PubKey *btcec.PublicKey

	// Sig is the raw signature generated using the above public key.  This
	// is the signature to be verified.
	Sig input.Signature

	// SigHash is a function closure generates the sighashes that the
	// passed signature is known to have signed.
	SigHash func() ([]byte, error)

	// HtlcIndex is the index of the HTLC from the PoV of the remote
	// party's update log.
	HtlcIndex uint64

	// Cancel is a channel that should be closed if the caller wishes to
	// cancel all pending verification jobs part of a single batch. This
	// channel is to be closed in the case that a single signature in a
	// batch has been returned as invalid, as there is no need to verify
	// the remainder of the signatures.
	Cancel chan struct{}

	// ErrResp is the channel that the result of the signature verification
	// is to be sent over. In the see that the signature is valid, a nil
	// error will be passed. Otherwise, a concrete error detailing the
	// issue will be passed.
	ErrResp chan *HtlcIndexErr
}

VerifyJob is a job sent to the sigPool sig pool to verify a signature on a transaction. The items contained in the struct are necessary and sufficient to verify the full signature. The passed sigHash closure function should be set to a function that generates the relevant sighash.

TODO(roasbeef): when we move to ecschnorr, make into batch signature verification using bos-coster (or pip?).

type WalletController

type WalletController interface {
	// FetchInputInfo queries for the WalletController's knowledge of the
	// passed outpoint. If the base wallet determines this output is under
	// its control, then the original txout should be returned.  Otherwise,
	// a non-nil error value of ErrNotMine should be returned instead.
	FetchInputInfo(prevOut *wire.OutPoint) (*Utxo, error)

	// ScriptForOutput returns the address, witness program and redeem
	// script for a given UTXO. An error is returned if the UTXO does not
	// belong to our wallet or it is not a managed pubKey address.
	ScriptForOutput(output *wire.TxOut) (waddrmgr.ManagedPubKeyAddress,
		[]byte, []byte, error)

	// ConfirmedBalance returns the sum of all the wallet's unspent outputs
	// that have at least confs confirmations. If confs is set to zero,
	// then all unspent outputs, including those currently in the mempool
	// will be included in the final sum. The account parameter serves as a
	// filter to retrieve the balance for a specific account. When empty,
	// the confirmed balance of all wallet accounts is returned.
	//
	// NOTE: Only witness outputs should be included in the computation of
	// the total spendable balance of the wallet. We require this as only
	// witness inputs can be used for funding channels.
	ConfirmedBalance(confs int32, accountFilter string) (btcutil.Amount,
		error)

	// NewAddress returns the next external or internal address for the
	// wallet dictated by the value of the `change` parameter. If change is
	// true, then an internal address should be used, otherwise an external
	// address should be returned. The type of address returned is dictated
	// by the wallet's capabilities, and may be of type: p2sh, p2wkh,
	// p2wsh, etc. The account parameter must be non-empty as it determines
	// which account the address should be generated from.
	NewAddress(addrType AddressType, change bool,
		account string) (btcutil.Address, error)

	// LastUnusedAddress returns the last *unused* address known by the
	// wallet. An address is unused if it hasn't received any payments.
	// This can be useful in UIs in order to continually show the
	// "freshest" address without having to worry about "address inflation"
	// caused by continual refreshing. Similar to NewAddress it can derive
	// a specified address type. By default, this is a non-change address.
	// The account parameter must be non-empty as it determines which
	// account the address should be generated from.
	LastUnusedAddress(addrType AddressType,
		account string) (btcutil.Address, error)

	// IsOurAddress checks if the passed address belongs to this wallet
	IsOurAddress(a btcutil.Address) bool

	// AddressInfo returns the information about an address, if it's known
	// to this wallet.
	AddressInfo(a btcutil.Address) (waddrmgr.ManagedAddress, error)

	// ListAccounts retrieves all accounts belonging to the wallet by
	// default. A name and key scope filter can be provided to filter
	// through all of the wallet accounts and return only those matching.
	ListAccounts(string, *waddrmgr.KeyScope) ([]*waddrmgr.AccountProperties,
		error)

	// RequiredReserve returns the minimum amount of satoshis that should be
	// kept in the wallet in order to fee bump anchor channels if necessary.
	// The value scales with the number of public anchor channels but is
	// capped at a maximum.
	RequiredReserve(uint32) btcutil.Amount

	// ListAddresses retrieves all the addresses along with their balance. An
	// account name filter can be provided to filter through all of the
	// wallet accounts and return the addresses of only those matching.
	ListAddresses(string, bool) (AccountAddressMap, error)

	// ImportAccount imports an account backed by an account extended public
	// key. The master key fingerprint denotes the fingerprint of the root
	// key corresponding to the account public key (also known as the key
	// with derivation path m/). This may be required by some hardware
	// wallets for proper identification and signing.
	//
	// The address type can usually be inferred from the key's version, but
	// may be required for certain keys to map them into the proper scope.
	//
	// For BIP-0044 keys, an address type must be specified as we intend to
	// not support importing BIP-0044 keys into the wallet using the legacy
	// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will
	// force the standard BIP-0049 derivation scheme, while a witness
	// address type will force the standard BIP-0084 derivation scheme.
	//
	// For BIP-0049 keys, an address type must also be specified to make a
	// distinction between the standard BIP-0049 address schema (nested
	// witness pubkeys everywhere) and our own BIP-0049Plus address schema
	// (nested pubkeys externally, witness pubkeys internally).
	ImportAccount(name string, accountPubKey *hdkeychain.ExtendedKey,
		masterKeyFingerprint uint32, addrType *waddrmgr.AddressType,
		dryRun bool) (*waddrmgr.AccountProperties, []btcutil.Address,
		[]btcutil.Address, error)

	// ImportPublicKey imports a single derived public key into the wallet.
	// The address type can usually be inferred from the key's version, but
	// in the case of legacy versions (xpub, tpub), an address type must be
	// specified as we intend to not support importing BIP-44 keys into the
	// wallet using the legacy pay-to-pubkey-hash (P2PKH) scheme.
	ImportPublicKey(pubKey *btcec.PublicKey,
		addrType waddrmgr.AddressType) error

	// ImportTaprootScript imports a user-provided taproot script into the
	// wallet. The imported script will act as a pay-to-taproot address.
	//
	// NOTE: Taproot keys imported through this RPC currently _cannot_ be
	// used for funding PSBTs. Only tracking the balance and UTXOs is
	// currently supported.
	ImportTaprootScript(scope waddrmgr.KeyScope,
		tapscript *waddrmgr.Tapscript) (waddrmgr.ManagedAddress, error)

	// SendOutputs funds, signs, and broadcasts a Bitcoin transaction paying
	// out to the specified outputs. In the case the wallet has insufficient
	// funds, or the outputs are non-standard, an error should be returned.
	// This method also takes the target fee expressed in sat/kw that should
	// be used when crafting the transaction.
	//
	// NOTE: This method requires the global coin selection lock to be held.
	SendOutputs(outputs []*wire.TxOut, feeRate chainfee.SatPerKWeight,
		minConfs int32, label string,
		strategy base.CoinSelectionStrategy) (*wire.MsgTx, error)

	// CreateSimpleTx creates a Bitcoin transaction paying to the specified
	// outputs. The transaction is not broadcasted to the network. In the
	// case the wallet has insufficient funds, or the outputs are
	// non-standard, an error should be returned. This method also takes
	// the target fee expressed in sat/kw that should be used when crafting
	// the transaction.
	//
	// NOTE: The dryRun argument can be set true to create a tx that
	// doesn't alter the database. A tx created with this set to true
	// SHOULD NOT be broadcasted.
	//
	// NOTE: This method requires the global coin selection lock to be held.
	CreateSimpleTx(outputs []*wire.TxOut, feeRate chainfee.SatPerKWeight,
		minConfs int32, strategy base.CoinSelectionStrategy,
		dryRun bool) (*txauthor.AuthoredTx, error)

	// GetTransactionDetails returns a detailed description of a transaction
	// given its transaction hash.
	GetTransactionDetails(txHash *chainhash.Hash) (
		*TransactionDetail, error)

	// ListUnspentWitness returns all unspent outputs which are version 0
	// witness programs. The 'minConfs' and 'maxConfs' parameters
	// indicate the minimum and maximum number of confirmations an output
	// needs in order to be returned by this method. Passing -1 as
	// 'minConfs' indicates that even unconfirmed outputs should be
	// returned. Using MaxInt32 as 'maxConfs' implies returning all
	// outputs with at least 'minConfs'. The account parameter serves as
	// a filter to retrieve the unspent outputs for a specific account.
	// When empty, the unspent outputs of all wallet accounts are returned.
	//
	// NOTE: This method requires the global coin selection lock to be held.
	ListUnspentWitness(minConfs, maxConfs int32,
		accountFilter string) ([]*Utxo, error)

	// ListTransactionDetails returns a list of all transactions which are
	// relevant to the wallet over [startHeight;endHeight]. If start height
	// is greater than end height, the transactions will be retrieved in
	// reverse order. To include unconfirmed transactions, endHeight should
	// be set to the special value -1. This will return transactions from
	// the tip of the chain until the start height (inclusive) and
	// unconfirmed transactions. The account parameter serves as a filter to
	// retrieve the transactions relevant to a specific account. When
	// empty, transactions of all wallet accounts are returned.
	ListTransactionDetails(startHeight, endHeight int32,
		accountFilter string) ([]*TransactionDetail, error)

	// LeaseOutput locks an output to the given ID, preventing it from being
	// available for any future coin selection attempts. The absolute time
	// of the lock's expiration is returned. The expiration of the lock can
	// be extended by successive invocations of this call. Outputs can be
	// unlocked before their expiration through `ReleaseOutput`.
	//
	// If the output is not known, wtxmgr.ErrUnknownOutput is returned. If
	// the output has already been locked to a different ID, then
	// wtxmgr.ErrOutputAlreadyLocked is returned.
	//
	// NOTE: This method requires the global coin selection lock to be held.
	LeaseOutput(id wtxmgr.LockID, op wire.OutPoint,
		duration time.Duration) (time.Time, []byte, btcutil.Amount,
		error)

	// ReleaseOutput unlocks an output, allowing it to be available for coin
	// selection if it remains unspent. The ID should match the one used to
	// originally lock the output.
	//
	// NOTE: This method requires the global coin selection lock to be held.
	ReleaseOutput(id wtxmgr.LockID, op wire.OutPoint) error

	// ListLeasedOutputs returns a list of all currently locked outputs.
	ListLeasedOutputs() ([]*base.ListLeasedOutputResult, error)

	// PublishTransaction performs cursory validation (dust checks, etc),
	// then finally broadcasts the passed transaction to the Bitcoin network.
	// If the transaction is rejected because it is conflicting with an
	// already known transaction, ErrDoubleSpend is returned. If the
	// transaction is already known (published already), no error will be
	// returned. Other error returned depends on the currently active chain
	// backend. It takes an optional label which will save a label with the
	// published transaction.
	PublishTransaction(tx *wire.MsgTx, label string) error

	// LabelTransaction adds a label to a transaction. If the tx already
	// has a label, this call will fail unless the overwrite parameter
	// is set. Labels must not be empty, and they are limited to 500 chars.
	LabelTransaction(hash chainhash.Hash, label string, overwrite bool) error

	// FetchTx attempts to fetch a transaction in the wallet's database
	// identified by the passed transaction hash. If the transaction can't
	// be found, then a nil pointer is returned.
	FetchTx(chainhash.Hash) (*wire.MsgTx, error)

	// RemoveDescendants attempts to remove any transaction from the
	// wallet's tx store (that may be unconfirmed) that spends outputs
	// created by the passed transaction. This remove propagates
	// recursively down the chain of descendent transactions.
	RemoveDescendants(*wire.MsgTx) error

	// FundPsbt creates a fully populated PSBT packet that contains enough
	// inputs to fund the outputs specified in the passed in packet with the
	// specified fee rate. If there is change left, a change output from the
	// internal wallet is added and the index of the change output is
	// returned. Otherwise no additional output is created and the index -1
	// is returned. If no custom change scope is specified, the BIP0084 will
	// be used for default accounts and single imported public keys. For
	// custom account, no key scope should be provided as the coin selection
	// key scope will always be used to generate the change address.
	//
	// NOTE: If the packet doesn't contain any inputs, coin selection is
	// performed automatically. The account parameter must be non-empty as
	// it determines which set of coins are eligible for coin selection. If
	// the packet does contain any inputs, it is assumed that full coin
	// selection happened externally and no additional inputs are added. If
	// the specified inputs aren't enough to fund the outputs with the given
	// fee rate, an error is returned. No lock lease is acquired for any of
	// the selected/validated inputs. It is in the caller's responsibility
	// to lock the inputs before handing them out.
	FundPsbt(packet *psbt.Packet, minConfs int32,
		feeRate chainfee.SatPerKWeight, account string,
		changeScope *waddrmgr.KeyScope,
		strategy base.CoinSelectionStrategy,
		allowUtxo func(wtxmgr.Credit) bool) (int32, error)

	// SignPsbt expects a partial transaction with all inputs and outputs
	// fully declared and tries to sign all unsigned inputs that have all
	// required fields (UTXO information, BIP32 derivation information,
	// witness or sig scripts) set.
	// If no error is returned, the PSBT is ready to be given to the next
	// signer or to be finalized if lnd was the last signer.
	//
	// NOTE: This method only signs inputs (and only those it can sign), it
	// does not perform any other tasks (such as coin selection, UTXO
	// locking or input/output/fee value validation, PSBT finalization). Any
	// input that is incomplete will be skipped.
	SignPsbt(packet *psbt.Packet) ([]uint32, error)

	// FinalizePsbt expects a partial transaction with all inputs and
	// outputs fully declared and tries to sign all inputs that belong to
	// the specified account. Lnd must be the last signer of the
	// transaction. That means, if there are any unsigned non-witness inputs
	// or inputs without UTXO information attached or inputs without witness
	// data that do not belong to lnd's wallet, this method will fail. If no
	// error is returned, the PSBT is ready to be extracted and the final TX
	// within to be broadcast.
	//
	// NOTE: This method does NOT publish the transaction after it's been
	// finalized successfully.
	FinalizePsbt(packet *psbt.Packet, account string) error

	// DecorateInputs fetches the UTXO information of all inputs it can
	// identify and adds the required information to the package's inputs.
	// The failOnUnknown boolean controls whether the method should return
	// an error if it cannot identify an input or if it should just skip it.
	DecorateInputs(packet *psbt.Packet, failOnUnknown bool) error

	// SubscribeTransactions returns a TransactionSubscription client which
	// is capable of receiving async notifications as new transactions
	// related to the wallet are seen within the network, or found in
	// blocks.
	//
	// NOTE: a non-nil error should be returned if notifications aren't
	// supported.
	//
	// TODO(roasbeef): make distinct interface?
	SubscribeTransactions() (TransactionSubscription, error)

	// IsSynced returns a boolean indicating if from the PoV of the wallet,
	// it has fully synced to the current best block in the main chain.
	// It also returns an int64 indicating the timestamp of the best block
	// known to the wallet, expressed in Unix epoch time
	IsSynced() (bool, int64, error)

	// GetRecoveryInfo returns a boolean indicating whether the wallet is
	// started in recovery mode. It also returns a float64 indicating the
	// recovery progress made so far.
	GetRecoveryInfo() (bool, float64, error)

	// Start initializes the wallet, making any necessary connections,
	// starting up required goroutines etc.
	Start() error

	// Stop signals the wallet for shutdown. Shutdown may entail closing
	// any active sockets, database handles, stopping goroutines, etc.
	Stop() error

	// BackEnd returns a name for the wallet's backing chain service,
	// which could be e.g. btcd, bitcoind, neutrino, or another consensus
	// service.
	BackEnd() string

	// CheckMempoolAcceptance checks whether a transaction follows mempool
	// policies and returns an error if it cannot be accepted into the
	// mempool.
	CheckMempoolAcceptance(tx *wire.MsgTx) error
}

WalletController defines an abstract interface for controlling a local Pure Go wallet, a local or remote wallet via an RPC mechanism, or possibly even a daemon assisted hardware wallet. This interface serves the purpose of allowing LightningWallet to be seamlessly compatible with several wallets such as: uspv, btcwallet, Bitcoin Core, Electrum, etc. This interface then serves as a "base wallet", with Lightning Network awareness taking place at a "higher" level of abstraction. Essentially, an overlay wallet. Implementors of this interface must closely adhere to the documented behavior of all interface methods in order to ensure identical behavior across all concrete implementations.

type WalletDriver

type WalletDriver struct {
	// WalletType is a string which uniquely identifies the
	// WalletController that this driver, drives.
	WalletType string

	// New creates a new instance of a concrete WalletController
	// implementation given a variadic set up arguments. The function takes
	// a variadic number of interface parameters in order to provide
	// initialization flexibility, thereby accommodating several potential
	// WalletController implementations.
	New func(args ...interface{}) (WalletController, error)

	// BackEnds returns a list of available chain service drivers for the
	// wallet driver. This could be e.g. bitcoind, btcd, neutrino, etc.
	BackEnds func() []string
}

WalletDriver represents a "driver" for a particular concrete WalletController implementation. A driver is identified by a globally unique string identifier along with a 'New()' method which is responsible for initializing a particular WalletController concrete implementation.

func RegisteredWallets

func RegisteredWallets() []*WalletDriver

RegisteredWallets returns a slice of all currently registered notifiers.

NOTE: This function is safe for concurrent access.

type WalletPrevOutputFetcher

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

WalletPrevOutputFetcher is a txscript.PrevOutputFetcher that can fetch outputs from a given wallet controller.

func NewWalletPrevOutputFetcher

func NewWalletPrevOutputFetcher(wc WalletController) *WalletPrevOutputFetcher

NewWalletPrevOutputFetcher creates a new WalletPrevOutputFetcher that fetches previous outputs from the given wallet controller.

func (*WalletPrevOutputFetcher) FetchPrevOutput

func (w *WalletPrevOutputFetcher) FetchPrevOutput(op wire.OutPoint) *wire.TxOut

FetchPrevOutput attempts to fetch the previous output referenced by the passed outpoint. A nil value will be returned if the passed outpoint doesn't exist.

type WitnessScriptDesc

type WitnessScriptDesc struct {
	// OutputScript is the output's PkScript.
	OutputScript []byte

	// WitnessScript is the full script required to properly redeem the
	// output. This field should be set to the full script if a p2wsh
	// output is being signed. For p2wkh it should be set equal to the
	// PkScript.
	WitnessScript []byte
}

WitnessScriptDesc holds the output script and the witness script for p2wsh outputs.

func (*WitnessScriptDesc) PkScript

func (w *WitnessScriptDesc) PkScript() []byte

PkScript is the public key script that commits to the final contract.

func (*WitnessScriptDesc) WitnessScriptForPath

func (w *WitnessScriptDesc) WitnessScriptForPath(_ input.ScriptPath,
) ([]byte, error)

WitnessScriptForPath returns the witness script for the given spending path. An error is returned if the path is unknown. This is useful as when constructing a contrl block for a given path, one also needs witness script being signed.

func (*WitnessScriptDesc) WitnessScriptToSign

func (w *WitnessScriptDesc) WitnessScriptToSign() []byte

WitnessScript returns the witness script that we'll use when signing for the remote party, and also verifying signatures on our transactions. As an example, when we create an outgoing HTLC for the remote party, we want to sign their success path.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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