github.com/decred/dcrlnd@v0.7.6/lnwallet/wallet.go (about)

     1  package lnwallet
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/sha256"
     6  	"errors"
     7  	"fmt"
     8  	"math"
     9  	"net"
    10  	"sync"
    11  	"sync/atomic"
    12  
    13  	"github.com/davecgh/go-spew/spew"
    14  	"github.com/decred/dcrd/blockchain/standalone/v2"
    15  	"github.com/decred/dcrd/chaincfg/chainhash"
    16  	"github.com/decred/dcrd/chaincfg/v3"
    17  	"github.com/decred/dcrd/dcrec/secp256k1/v4"
    18  	"github.com/decred/dcrd/dcrutil/v4"
    19  	"github.com/decred/dcrd/dcrutil/v4/txsort"
    20  	"github.com/decred/dcrd/txscript/v4"
    21  	"github.com/decred/dcrd/txscript/v4/stdaddr"
    22  	"github.com/decred/dcrd/txscript/v4/stdscript"
    23  	"github.com/decred/dcrd/wire"
    24  	"github.com/decred/dcrlnd/channeldb"
    25  	"github.com/decred/dcrlnd/input"
    26  	"github.com/decred/dcrlnd/internal/psbt"
    27  	"github.com/decred/dcrlnd/keychain"
    28  	"github.com/decred/dcrlnd/lnwallet/chainfee"
    29  	"github.com/decred/dcrlnd/lnwallet/chanfunding"
    30  	"github.com/decred/dcrlnd/lnwallet/chanvalidate"
    31  	"github.com/decred/dcrlnd/lnwire"
    32  	"github.com/decred/dcrlnd/shachain"
    33  )
    34  
    35  const (
    36  	// The size of the buffered queue of requests to the wallet from the
    37  	// outside word.
    38  	msgBufferSize = 100
    39  
    40  	// anchorChanReservedValue is the amount we'll keep around in the
    41  	// wallet in case we have to fee bump anchor channels on force close.
    42  	// TODO(halseth): update constant to target a specific commit size at
    43  	// set fee rate.
    44  	anchorChanReservedValue = dcrutil.Amount(10_000)
    45  
    46  	// maxAnchorChanReservedValue is the maximum value we'll reserve for
    47  	// anchor channel fee bumping. We cap it at 10 times the per-channel
    48  	// amount such that nodes with a high number of channels don't have to
    49  	// keep around a very large amount for the unlikely scenario that they
    50  	// all close at the same time.
    51  	maxAnchorChanReservedValue = 10 * anchorChanReservedValue
    52  )
    53  
    54  var (
    55  	// ErrPsbtFundingRequired is the error that is returned during the
    56  	// contribution handling process if the process should be paused for
    57  	// the construction of a PSBT outside of lnd's wallet.
    58  	ErrPsbtFundingRequired = errors.New("PSBT funding required")
    59  
    60  	// ErrReservedValueInvalidated is returned if we try to publish a
    61  	// transaction that would take the walletbalance below what we require
    62  	// to keep around to fee bump our open anchor channels.
    63  	ErrReservedValueInvalidated = errors.New("reserved wallet balance " +
    64  		"invalidated: transaction would leave insufficient funds for " +
    65  		"fee bumping anchor channel closings (see debug log for details)")
    66  )
    67  
    68  // PsbtFundingRequired is a type that implements the error interface and
    69  // contains the information needed to construct a PSBT.
    70  type PsbtFundingRequired struct {
    71  	// Intent is the pending PSBT funding intent that needs to be funded
    72  	// if the wrapping error is returned.
    73  	Intent *chanfunding.PsbtIntent
    74  }
    75  
    76  // Error returns the underlying error.
    77  //
    78  // NOTE: This method is part of the error interface.
    79  func (p *PsbtFundingRequired) Error() string {
    80  	return ErrPsbtFundingRequired.Error()
    81  }
    82  
    83  // InitFundingReserveMsg is the first message sent to initiate the workflow
    84  // required to open a payment channel with a remote peer. The initial required
    85  // parameters are configurable across channels. These parameters are to be
    86  // chosen depending on the fee climate within the network, and time value of
    87  // funds to be locked up within the channel. Upon success a ChannelReservation
    88  // will be created in order to track the lifetime of this pending channel.
    89  // Outputs selected will be 'locked', making them unavailable, for any other
    90  // pending reservations. Therefore, all channels in reservation limbo will be
    91  // periodically timed out after an idle period in order to avoid "exhaustion"
    92  // attacks.
    93  type InitFundingReserveMsg struct {
    94  	// ChainHash denotes that chain to be used to ultimately open the
    95  	// target channel.
    96  	ChainHash *chainhash.Hash
    97  
    98  	// PendingChanID is the pending channel ID for this funding flow as
    99  	// used in the wire protocol.
   100  	PendingChanID [32]byte
   101  
   102  	// NodeID is the ID of the remote node we would like to open a channel
   103  	// with.
   104  	NodeID *secp256k1.PublicKey
   105  
   106  	// NodeAddr is the address port that we used to either establish or
   107  	// accept the connection which led to the negotiation of this funding
   108  	// workflow.
   109  	NodeAddr net.Addr
   110  
   111  	// SubtractFees should be set if we intend to spend exactly
   112  	// LocalFundingAmt when opening the channel, subtracting the fees from
   113  	// the funding output. This can be used for instance to use all our
   114  	// remaining funds to open the channel, since it will take fees into
   115  	// account.
   116  	SubtractFees bool
   117  
   118  	// LocalFundingAmt is the amount of funds requested from us for this
   119  	// channel.
   120  	LocalFundingAmt dcrutil.Amount
   121  
   122  	// RemoteFundingAmt is the amount of funds the remote will contribute
   123  	// to this channel.
   124  	RemoteFundingAmt dcrutil.Amount
   125  
   126  	// CommitFeePerKB is the starting accepted atom/kB fee for the set of
   127  	// initial commitment transactions. In order to ensure timely
   128  	// confirmation, it is recommended that this fee should be generous,
   129  	// paying some multiple of the accepted base fee rate of the network.
   130  	CommitFeePerKB chainfee.AtomPerKByte
   131  
   132  	// FundingFeePerKB is the fee rate in atom/kB to use for the initial
   133  	// funding transaction.
   134  	FundingFeePerKB chainfee.AtomPerKByte
   135  
   136  	// PushMAtoms is the number of milli-atoms that should be pushed over
   137  	// the responder as part of the initial channel creation.
   138  	PushMAtoms lnwire.MilliAtom
   139  
   140  	// Flags are the channel flags specified by the initiator in the
   141  	// open_channel message.
   142  	Flags lnwire.FundingFlag
   143  
   144  	// MinConfs indicates the minimum number of confirmations that each
   145  	// output selected to fund the channel should satisfy.
   146  	MinConfs int32
   147  
   148  	// CommitType indicates what type of commitment type the channel should
   149  	// be using, like tweakless or anchors.
   150  	CommitType CommitmentType
   151  
   152  	// ChanFunder is an optional channel funder that allows the caller to
   153  	// control exactly how the channel funding is carried out. If not
   154  	// specified, then the default chanfunding.WalletAssembler will be
   155  	// used.
   156  	ChanFunder chanfunding.Assembler
   157  
   158  	// err is a channel in which all errors will be sent across. Will be
   159  	// nil if this initial set is successful.
   160  	//
   161  	// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
   162  	err chan error
   163  
   164  	// resp is channel in which a ChannelReservation with our contributions
   165  	// filled in will be sent across this channel in the case of a
   166  	// successfully reservation initiation. In the case of an error, this
   167  	// will read a nil pointer.
   168  	//
   169  	// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
   170  	resp chan *ChannelReservation
   171  }
   172  
   173  // fundingReserveCancelMsg is a message reserved for cancelling an existing
   174  // channel reservation identified by its reservation ID. Cancelling a reservation
   175  // frees its locked outputs up, for inclusion within further reservations.
   176  type fundingReserveCancelMsg struct {
   177  	pendingFundingID uint64
   178  
   179  	// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
   180  	err chan error // Buffered
   181  }
   182  
   183  // addContributionMsg represents a message executing the second phase of the
   184  // channel reservation workflow. This message carries the counterparty's
   185  // "contribution" to the payment channel. In the case that this message is
   186  // processed without generating any errors, then channel reservation will then
   187  // be able to construct the funding tx, both commitment transactions, and
   188  // finally generate signatures for all our inputs to the funding transaction,
   189  // and for the remote node's version of the commitment transaction.
   190  type addContributionMsg struct {
   191  	pendingFundingID uint64
   192  
   193  	// TODO(roasbeef): Should also carry SPV proofs in we're in SPV mode
   194  	contribution *ChannelContribution
   195  
   196  	// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
   197  	err chan error
   198  }
   199  
   200  // continueContributionMsg represents a message that signals that the
   201  // interrupted funding process involving a PSBT can now be continued because the
   202  // finalized transaction is now available.
   203  type continueContributionMsg struct {
   204  	pendingFundingID uint64
   205  
   206  	// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
   207  	err chan error
   208  }
   209  
   210  // addSingleContributionMsg represents a message executing the second phase of
   211  // a single funder channel reservation workflow. This messages carries the
   212  // counterparty's "contribution" to the payment channel. As this message is
   213  // sent when on the responding side to a single funder workflow, no further
   214  // action apart from storing the provided contribution is carried out.
   215  type addSingleContributionMsg struct {
   216  	pendingFundingID uint64
   217  
   218  	contribution *ChannelContribution
   219  
   220  	// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
   221  	err chan error
   222  }
   223  
   224  // addCounterPartySigsMsg represents the final message required to complete,
   225  // and 'open' a payment channel. This message carries the counterparty's
   226  // signatures for each of their inputs to the funding transaction, and also a
   227  // signature allowing us to spend our version of the commitment transaction.
   228  // If we're able to verify all the signatures are valid, the funding transaction
   229  // will be broadcast to the network. After the funding transaction gains a
   230  // configurable number of confirmations, the channel is officially considered
   231  // 'open'.
   232  type addCounterPartySigsMsg struct {
   233  	pendingFundingID uint64
   234  
   235  	// Should be order of sorted inputs that are theirs. Sorting is done
   236  	// in accordance to BIP-69:
   237  	// https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki.
   238  	theirFundingInputScripts []*input.Script
   239  
   240  	// This should be 1/2 of the signatures needed to successfully spend our
   241  	// version of the commitment transaction.
   242  	theirCommitmentSig input.Signature
   243  
   244  	// This channel is used to return the completed channel after the wallet
   245  	// has completed all of its stages in the funding process.
   246  	completeChan chan *channeldb.OpenChannel
   247  
   248  	// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
   249  	err chan error
   250  }
   251  
   252  // addSingleFunderSigsMsg represents the next-to-last message required to
   253  // complete a single-funder channel workflow. Once the initiator is able to
   254  // construct the funding transaction, they send both the outpoint and a
   255  // signature for our version of the commitment transaction. Once this message
   256  // is processed we (the responder) are able to construct both commitment
   257  // transactions, signing the remote party's version.
   258  type addSingleFunderSigsMsg struct {
   259  	pendingFundingID uint64
   260  
   261  	// fundingOutpoint is the outpoint of the completed funding
   262  	// transaction as assembled by the workflow initiator.
   263  	fundingOutpoint *wire.OutPoint
   264  
   265  	// theirCommitmentSig are the 1/2 of the signatures needed to
   266  	// successfully spend our version of the commitment transaction.
   267  	theirCommitmentSig input.Signature
   268  
   269  	// This channel is used to return the completed channel after the wallet
   270  	// has completed all of its stages in the funding process.
   271  	completeChan chan *channeldb.OpenChannel
   272  
   273  	// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
   274  	err chan error
   275  }
   276  
   277  // CheckReservedValueTxReq is the request struct used to call
   278  // CheckReservedValueTx with. It contains the transaction to check as well as
   279  // an optional explicitly defined index to denote a change output that is not
   280  // watched by the wallet.
   281  type CheckReservedValueTxReq struct {
   282  	// Tx is the transaction to check the outputs for.
   283  	Tx *wire.MsgTx
   284  
   285  	// ChangeIndex denotes an optional output index that can be explicitly
   286  	// set for a change that is not being watched by the wallet and would
   287  	// otherwise not be recognized as a change output.
   288  	ChangeIndex *int
   289  }
   290  
   291  // LightningWallet is a domain specific, yet general wallet capable of executing
   292  // workflow required to interact with the Lightning Network. It is domain
   293  // specific in the sense that it understands all the fancy scripts used within
   294  // the Lightning Network, channel lifetimes, etc. However, it embeds a general
   295  // purpose wallet within it. Therefore, it is also able to serve as a regular
   296  // wallet which uses HD keys. The wallet is highly concurrent internally. All
   297  // communication, and requests towards the wallet are dispatched as messages
   298  // over channels, ensuring thread safety across all operations. Interaction has
   299  // been designed independent of any peer-to-peer communication protocol,
   300  // allowing the wallet to be self-contained and embeddable within future
   301  // projects interacting with the Lightning Network.
   302  //
   303  // NOTE: At the moment the wallet requires a dcrd full node, as it's dependent
   304  // on dcrd's websockets notifications as event triggers during the lifetime of a
   305  // channel. Eventually, the wallet won't require a full-node at all, as SPV
   306  // support is integrated into dcrwallet.
   307  type LightningWallet struct {
   308  	started  int32 // To be used atomically.
   309  	shutdown int32 // To be used atomically.
   310  
   311  	nextFundingID uint64 // To be used atomically.
   312  
   313  	// Cfg is the configuration struct that will be used by the wallet to
   314  	// access the necessary interfaces and default it needs to carry on its
   315  	// duties.
   316  	Cfg Config
   317  
   318  	// WalletController is the core wallet, all non Lightning Network
   319  	// specific interaction is proxied to the internal wallet.
   320  	WalletController
   321  
   322  	// SecretKeyRing is the interface we'll use to derive any keys related
   323  	// to our purpose within the network including: multi-sig keys, node
   324  	// keys, revocation keys, etc.
   325  	keychain.SecretKeyRing
   326  
   327  	// This mutex MUST be held when performing coin selection in order to
   328  	// avoid inadvertently creating multiple funding transaction which
   329  	// double spend inputs across each other.
   330  	coinSelectMtx sync.RWMutex
   331  
   332  	// All messages to the wallet are to be sent across this channel.
   333  	msgChan chan interface{}
   334  
   335  	// Incomplete payment channels are stored in the map below. An intent
   336  	// to create a payment channel is tracked as a "reservation" within
   337  	// limbo. Once the final signatures have been exchanged, a reservation
   338  	// is removed from limbo. Each reservation is tracked by a unique
   339  	// monotonically integer. All requests concerning the channel MUST
   340  	// carry a valid, active funding ID.
   341  	fundingLimbo map[uint64]*ChannelReservation
   342  
   343  	// reservationIDs maps a pending channel ID to the reservation ID used
   344  	// as key in the fundingLimbo map. Used to easily look up a channel
   345  	// reservation given a pending channel ID.
   346  	reservationIDs map[[32]byte]uint64
   347  	limboMtx       sync.RWMutex
   348  
   349  	// lockedOutPoints is a set of the currently locked outpoint. This
   350  	// information is kept in order to provide an easy way to unlock all
   351  	// the currently locked outpoints.
   352  	lockedOutPoints map[wire.OutPoint]struct{}
   353  
   354  	// fundingIntents houses all the "interception" registered by a caller
   355  	// using the RegisterFundingIntent method.
   356  	intentMtx      sync.RWMutex
   357  	fundingIntents map[[32]byte]chanfunding.Intent
   358  
   359  	quit chan struct{}
   360  
   361  	wg sync.WaitGroup
   362  
   363  	// TODO(roasbeef): handle wallet lock/unlock
   364  }
   365  
   366  // NewLightningWallet creates/opens and initializes a LightningWallet instance.
   367  // If the wallet has never been created (according to the passed dataDir),
   368  // first-time setup is executed.
   369  func NewLightningWallet(cfg Config) (*LightningWallet, error) {
   370  	return &LightningWallet{
   371  		Cfg:              cfg,
   372  		SecretKeyRing:    cfg.SecretKeyRing,
   373  		WalletController: cfg.WalletController,
   374  		msgChan:          make(chan interface{}, msgBufferSize),
   375  		nextFundingID:    0,
   376  		fundingLimbo:     make(map[uint64]*ChannelReservation),
   377  		reservationIDs:   make(map[[32]byte]uint64),
   378  		lockedOutPoints:  make(map[wire.OutPoint]struct{}),
   379  		fundingIntents:   make(map[[32]byte]chanfunding.Intent),
   380  		quit:             make(chan struct{}),
   381  	}, nil
   382  }
   383  
   384  // Startup establishes a connection to the RPC source, and spins up all
   385  // goroutines required to handle incoming messages.
   386  func (l *LightningWallet) Startup() error {
   387  	// Already started?
   388  	if atomic.AddInt32(&l.started, 1) != 1 {
   389  		return nil
   390  	}
   391  
   392  	// Start the underlying wallet controller.
   393  	if err := l.Start(); err != nil {
   394  		return err
   395  	}
   396  
   397  	l.wg.Add(1)
   398  	// TODO(roasbeef): multiple request handlers?
   399  	go l.requestHandler()
   400  
   401  	return nil
   402  }
   403  
   404  // Shutdown gracefully stops the wallet, and all active goroutines.
   405  func (l *LightningWallet) Shutdown() error {
   406  	if atomic.AddInt32(&l.shutdown, 1) != 1 {
   407  		return nil
   408  	}
   409  
   410  	// Signal the underlying wallet controller to shutdown, waiting until
   411  	// all active goroutines have been shutdown.
   412  	if err := l.Stop(); err != nil {
   413  		return err
   414  	}
   415  
   416  	close(l.quit)
   417  	l.wg.Wait()
   418  	return nil
   419  }
   420  
   421  // ConfirmedBalance returns the current confirmed balance of a wallet account.
   422  // This methods wraps the internal WalletController method so we're able to
   423  // properly hold the coin select mutex while we compute the balance.
   424  func (l *LightningWallet) ConfirmedBalance(confs int32,
   425  	account string) (dcrutil.Amount, error) {
   426  
   427  	l.coinSelectMtx.Lock()
   428  	defer l.coinSelectMtx.Unlock()
   429  
   430  	return l.WalletController.ConfirmedBalance(confs, account)
   431  }
   432  
   433  // ListUnspentWitnessFromDefaultAccount returns all unspent outputs from the
   434  // default wallet account which are version 0 witness programs. The 'minConfs'
   435  // and 'maxConfs' parameters indicate the minimum and maximum number of
   436  // confirmations an output needs in order to be returned by this method. Passing
   437  // -1 as 'minConfs' indicates that even unconfirmed outputs should be returned.
   438  // Using MaxInt32 as 'maxConfs' implies returning all outputs with at least
   439  // 'minConfs'.
   440  //
   441  // NOTE: This method requires the global coin selection lock to be held.
   442  func (l *LightningWallet) ListUnspentWitnessFromDefaultAccount(
   443  	minConfs, maxConfs int32) ([]*Utxo, error) {
   444  
   445  	return l.WalletController.ListUnspentWitness(
   446  		minConfs, maxConfs, DefaultAccountName,
   447  	)
   448  }
   449  
   450  // LockedOutpoints returns a list of all currently locked outpoint.
   451  func (l *LightningWallet) LockedOutpoints() []*wire.OutPoint {
   452  	outPoints := make([]*wire.OutPoint, 0, len(l.lockedOutPoints))
   453  	for outPoint := range l.lockedOutPoints {
   454  		outPoint := outPoint
   455  
   456  		outPoints = append(outPoints, &outPoint)
   457  	}
   458  
   459  	return outPoints
   460  }
   461  
   462  // ResetReservations reset the volatile wallet state which tracks all currently
   463  // active reservations.
   464  func (l *LightningWallet) ResetReservations() {
   465  	l.nextFundingID = 0
   466  	l.fundingLimbo = make(map[uint64]*ChannelReservation)
   467  	l.reservationIDs = make(map[[32]byte]uint64)
   468  
   469  	for outpoint := range l.lockedOutPoints {
   470  		l.UnlockOutpoint(outpoint)
   471  	}
   472  	l.lockedOutPoints = make(map[wire.OutPoint]struct{})
   473  }
   474  
   475  // ActiveReservations returns a slice of all the currently active
   476  // (non-canceled) reservations.
   477  func (l *LightningWallet) ActiveReservations() []*ChannelReservation {
   478  	reservations := make([]*ChannelReservation, 0, len(l.fundingLimbo))
   479  	for _, reservation := range l.fundingLimbo {
   480  		reservations = append(reservations, reservation)
   481  	}
   482  
   483  	return reservations
   484  }
   485  
   486  // requestHandler is the primary goroutine(s) responsible for handling, and
   487  // dispatching replies to all messages.
   488  func (l *LightningWallet) requestHandler() {
   489  	defer l.wg.Done()
   490  
   491  out:
   492  	for {
   493  		select {
   494  		case m := <-l.msgChan:
   495  			switch msg := m.(type) {
   496  			case *InitFundingReserveMsg:
   497  				l.handleFundingReserveRequest(msg)
   498  			case *fundingReserveCancelMsg:
   499  				l.handleFundingCancelRequest(msg)
   500  			case *addSingleContributionMsg:
   501  				l.handleSingleContribution(msg)
   502  			case *addContributionMsg:
   503  				l.handleContributionMsg(msg)
   504  			case *continueContributionMsg:
   505  				l.handleChanPointReady(msg)
   506  			case *addSingleFunderSigsMsg:
   507  				l.handleSingleFunderSigs(msg)
   508  			case *addCounterPartySigsMsg:
   509  				l.handleFundingCounterPartySigs(msg)
   510  			}
   511  		case <-l.quit:
   512  			// TODO: do some clean up
   513  			break out
   514  		}
   515  	}
   516  }
   517  
   518  // InitChannelReservation kicks off the 3-step workflow required to successfully
   519  // open a payment channel with a remote node. As part of the funding
   520  // reservation, the inputs selected for the funding transaction are 'locked'.
   521  // This ensures that multiple channel reservations aren't double spending the
   522  // same inputs in the funding transaction. If reservation initialization is
   523  // successful, a ChannelReservation containing our completed contribution is
   524  // returned. Our contribution contains all the items necessary to allow the
   525  // counterparty to build the funding transaction, and both versions of the
   526  // commitment transaction. Otherwise, an error occurred and a nil pointer along
   527  // with an error are returned.
   528  //
   529  // Once a ChannelReservation has been obtained, two additional steps must be
   530  // processed before a payment channel can be considered 'open'. The second step
   531  // validates, and processes the counterparty's channel contribution. The third,
   532  // and final step verifies all signatures for the inputs of the funding
   533  // transaction, and that the signature we record for our version of the
   534  // commitment transaction is valid.
   535  func (l *LightningWallet) InitChannelReservation(
   536  	req *InitFundingReserveMsg) (*ChannelReservation, error) {
   537  
   538  	req.resp = make(chan *ChannelReservation, 1)
   539  	req.err = make(chan error, 1)
   540  
   541  	select {
   542  	case l.msgChan <- req:
   543  	case <-l.quit:
   544  		return nil, errors.New("wallet shutting down")
   545  	}
   546  
   547  	return <-req.resp, <-req.err
   548  }
   549  
   550  // RegisterFundingIntent allows a caller to signal to the wallet that if a
   551  // pending channel ID of expectedID is found, then it can skip constructing a
   552  // new chanfunding.Assembler, and instead use the specified chanfunding.Intent.
   553  // As an example, this lets some of the parameters for funding transaction to
   554  // be negotiated outside the regular funding protocol.
   555  func (l *LightningWallet) RegisterFundingIntent(expectedID [32]byte,
   556  	shimIntent chanfunding.Intent) error {
   557  
   558  	l.intentMtx.Lock()
   559  	defer l.intentMtx.Unlock()
   560  
   561  	if _, ok := l.fundingIntents[expectedID]; ok {
   562  		return fmt.Errorf("pendingChanID(%x) already has intent "+
   563  			"registered", expectedID[:])
   564  	}
   565  
   566  	l.fundingIntents[expectedID] = shimIntent
   567  
   568  	return nil
   569  }
   570  
   571  // PsbtFundingVerify looks up a previously registered funding intent by its
   572  // pending channel ID and tries to advance the state machine by verifying the
   573  // passed PSBT.
   574  func (l *LightningWallet) PsbtFundingVerify(pendingChanID [32]byte,
   575  	packet *psbt.Packet, skipFinalize bool) error {
   576  
   577  	l.intentMtx.Lock()
   578  	defer l.intentMtx.Unlock()
   579  
   580  	intent, ok := l.fundingIntents[pendingChanID]
   581  	if !ok {
   582  		return fmt.Errorf("no funding intent found for "+
   583  			"pendingChannelID(%x)", pendingChanID[:])
   584  	}
   585  	psbtIntent, ok := intent.(*chanfunding.PsbtIntent)
   586  	if !ok {
   587  		return fmt.Errorf("incompatible funding intent")
   588  	}
   589  
   590  	if skipFinalize && psbtIntent.ShouldPublishFundingTX() {
   591  		return fmt.Errorf("cannot set skip_finalize for channel that " +
   592  			"did not set no_publish")
   593  	}
   594  
   595  	err := psbtIntent.Verify(packet, skipFinalize)
   596  	if err != nil {
   597  		return fmt.Errorf("error verifying PSBT: %v", err)
   598  	}
   599  
   600  	// Get the channel reservation for that corresponds to this pending
   601  	// channel ID.
   602  	l.limboMtx.Lock()
   603  	pid, ok := l.reservationIDs[pendingChanID]
   604  	if !ok {
   605  		l.limboMtx.Unlock()
   606  		return fmt.Errorf("no channel reservation found for "+
   607  			"pendingChannelID(%x)", pendingChanID[:])
   608  	}
   609  
   610  	pendingReservation, ok := l.fundingLimbo[pid]
   611  	l.limboMtx.Unlock()
   612  
   613  	if !ok {
   614  		return fmt.Errorf("no channel reservation found for "+
   615  			"reservation ID %v", pid)
   616  	}
   617  
   618  	// Now the the PSBT has been populated and verified, we can again check
   619  	// whether the value reserved for anchor fee bumping is respected.
   620  	isPublic := pendingReservation.partialState.ChannelFlags&lnwire.FFAnnounceChannel != 0
   621  	hasAnchors := pendingReservation.partialState.ChanType.HasAnchors()
   622  	return l.enforceNewReservedValue(intent, isPublic, hasAnchors)
   623  }
   624  
   625  // PsbtFundingFinalize looks up a previously registered funding intent by its
   626  // pending channel ID and tries to advance the state machine by finalizing the
   627  // passed PSBT.
   628  func (l *LightningWallet) PsbtFundingFinalize(pid [32]byte, packet *psbt.Packet,
   629  	rawTx *wire.MsgTx) error {
   630  
   631  	l.intentMtx.Lock()
   632  	defer l.intentMtx.Unlock()
   633  
   634  	intent, ok := l.fundingIntents[pid]
   635  	if !ok {
   636  		return fmt.Errorf("no funding intent found for "+
   637  			"pendingChannelID(%x)", pid[:])
   638  	}
   639  	psbtIntent, ok := intent.(*chanfunding.PsbtIntent)
   640  	if !ok {
   641  		return fmt.Errorf("incompatible funding intent")
   642  	}
   643  
   644  	// Either the PSBT or the raw TX must be set.
   645  	switch {
   646  	case packet != nil && rawTx == nil:
   647  		err := psbtIntent.Finalize(packet)
   648  		if err != nil {
   649  			return fmt.Errorf("error finalizing PSBT: %v", err)
   650  		}
   651  
   652  	case rawTx != nil && packet == nil:
   653  		err := psbtIntent.FinalizeRawTX(rawTx)
   654  		if err != nil {
   655  			return fmt.Errorf("error finalizing raw TX: %v", err)
   656  		}
   657  
   658  	default:
   659  		return fmt.Errorf("either a PSBT or raw TX must be specified")
   660  	}
   661  
   662  	return nil
   663  }
   664  
   665  // CancelFundingIntent allows a caller to cancel a previously registered
   666  // funding intent. If no intent was found, then an error will be returned.
   667  func (l *LightningWallet) CancelFundingIntent(pid [32]byte) error {
   668  	l.intentMtx.Lock()
   669  	defer l.intentMtx.Unlock()
   670  
   671  	intent, ok := l.fundingIntents[pid]
   672  	if !ok {
   673  		return fmt.Errorf("no funding intent found for "+
   674  			"pendingChannelID(%x)", pid[:])
   675  	}
   676  
   677  	// Give the intent a chance to clean up after itself, removing coin
   678  	// locks or similar reserved resources.
   679  	intent.Cancel()
   680  
   681  	delete(l.fundingIntents, pid)
   682  
   683  	return nil
   684  }
   685  
   686  // handleFundingReserveRequest processes a message intending to create, and
   687  // validate a funding reservation request.
   688  func (l *LightningWallet) handleFundingReserveRequest(req *InitFundingReserveMsg) {
   689  	// It isn't possible to create a channel with zero funds committed.
   690  	if req.LocalFundingAmt+req.RemoteFundingAmt == 0 {
   691  		err := ErrZeroCapacity()
   692  		req.err <- err
   693  		req.resp <- nil
   694  		return
   695  	}
   696  
   697  	// If the funding request is for a different chain than the one the
   698  	// wallet is aware of, then we'll reject the request.
   699  	if !bytes.Equal(l.Cfg.NetParams.GenesisHash[:], req.ChainHash[:]) {
   700  		err := ErrChainMismatch(
   701  			&l.Cfg.NetParams.GenesisHash, req.ChainHash,
   702  		)
   703  		req.err <- err
   704  		req.resp <- nil
   705  		return
   706  	}
   707  
   708  	// We need to avoid enforcing reserved value in the middle of PSBT
   709  	// funding because some of the following steps may add UTXOs funding
   710  	// the on-chain wallet.
   711  	// The enforcement still happens at the last step - in PsbtFundingVerify
   712  	enforceNewReservedValue := true
   713  
   714  	// If no chanFunder was provided, then we'll assume the default
   715  	// assembler, which is backed by the wallet's internal coin selection.
   716  	if req.ChanFunder == nil {
   717  		cfg := chanfunding.WalletConfig{
   718  			CoinSource:       &CoinSource{l},
   719  			CoinSelectLocker: l,
   720  			CoinLocker:       l,
   721  			Signer:           l.Cfg.Signer,
   722  			DustLimit:        DustLimitForSize(input.P2SHPkScriptSize),
   723  		}
   724  		req.ChanFunder = chanfunding.NewWalletAssembler(cfg)
   725  	} else {
   726  		_, isPsbtFunder := req.ChanFunder.(*chanfunding.PsbtAssembler)
   727  		enforceNewReservedValue = !isPsbtFunder
   728  	}
   729  
   730  	localFundingAmt := req.LocalFundingAmt
   731  	remoteFundingAmt := req.RemoteFundingAmt
   732  
   733  	var (
   734  		fundingIntent chanfunding.Intent
   735  		err           error
   736  	)
   737  
   738  	// If we've just received an inbound funding request that we have a
   739  	// registered shim intent to, then we'll obtain the backing intent now.
   740  	// In this case, we're doing a special funding workflow that allows
   741  	// more advanced constructions such as channel factories to be
   742  	// instantiated.
   743  	l.intentMtx.Lock()
   744  	fundingIntent, ok := l.fundingIntents[req.PendingChanID]
   745  	l.intentMtx.Unlock()
   746  
   747  	// Otherwise, this is a normal funding flow, so we'll use the chan
   748  	// funder in the attached request to provision the inputs/outputs
   749  	// that'll ultimately be used to construct the funding transaction.
   750  	if !ok {
   751  		// Coin selection is done on the basis of sat/kw, so we'll use
   752  		// the fee rate passed in to perform coin selection.
   753  		var err error
   754  		fundingReq := &chanfunding.Request{
   755  			RemoteAmt:    req.RemoteFundingAmt,
   756  			LocalAmt:     req.LocalFundingAmt,
   757  			MinConfs:     req.MinConfs,
   758  			SubtractFees: req.SubtractFees,
   759  			FeeRate:      req.FundingFeePerKB,
   760  			ChangeAddr: func() (stdaddr.Address, error) {
   761  				return l.NewAddress(
   762  					PubKeyHash, true, DefaultAccountName,
   763  				)
   764  			},
   765  		}
   766  		fundingIntent, err = req.ChanFunder.ProvisionChannel(
   767  			fundingReq,
   768  		)
   769  		if err != nil {
   770  			req.err <- err
   771  			req.resp <- nil
   772  			return
   773  		}
   774  
   775  		// Register the funding intent now in case we need to access it
   776  		// again later, as it's the case for the PSBT state machine for
   777  		// example.
   778  		err = l.RegisterFundingIntent(req.PendingChanID, fundingIntent)
   779  		if err != nil {
   780  			req.err <- err
   781  			req.resp <- nil
   782  			return
   783  		}
   784  
   785  		localFundingAmt = fundingIntent.LocalFundingAmt()
   786  		remoteFundingAmt = fundingIntent.RemoteFundingAmt()
   787  	}
   788  
   789  	// At this point there _has_ to be a funding intent, otherwise something
   790  	// went really wrong.
   791  	if fundingIntent == nil {
   792  		req.err <- fmt.Errorf("no funding intent present")
   793  		req.resp <- nil
   794  		return
   795  	}
   796  
   797  	// If this is a shim intent, then it may be attempting to use an
   798  	// existing set of keys for the funding workflow. In this case, we'll
   799  	// make a simple wrapper keychain.KeyRing that will proxy certain
   800  	// derivation calls to future callers.
   801  	var (
   802  		keyRing    keychain.KeyRing = l.SecretKeyRing
   803  		thawHeight uint32
   804  	)
   805  	if shimIntent, ok := fundingIntent.(*chanfunding.ShimIntent); ok {
   806  		keyRing = &shimKeyRing{
   807  			KeyRing:    keyRing,
   808  			ShimIntent: shimIntent,
   809  		}
   810  
   811  		// As this was a registered shim intent, we'll obtain the thaw
   812  		// height of the intent, if present at all. If this is
   813  		// non-zero, then we'll mark this as the proper channel type.
   814  		thawHeight = shimIntent.ThawHeight()
   815  	}
   816  
   817  	// Now that we have a funding intent, we'll check whether funding a
   818  	// channel using it would violate our reserved value for anchor channel
   819  	// fee bumping.
   820  	//
   821  	// Check the reserved value using the inputs and outputs given by the
   822  	// intent. Note that for the PSBT intent type we don't yet have the
   823  	// funding tx ready, so this will always pass.  We'll do another check
   824  	// when the PSBT has been verified.
   825  	isPublic := req.Flags&lnwire.FFAnnounceChannel != 0
   826  	hasAnchors := req.CommitType.HasAnchors()
   827  	if enforceNewReservedValue {
   828  		err = l.enforceNewReservedValue(fundingIntent, isPublic, hasAnchors)
   829  		if err != nil {
   830  			fundingIntent.Cancel()
   831  
   832  			req.err <- err
   833  			req.resp <- nil
   834  			return
   835  		}
   836  	}
   837  
   838  	// The total channel capacity will be the size of the funding output we
   839  	// created plus the remote contribution.
   840  	capacity := localFundingAmt + remoteFundingAmt
   841  
   842  	id := atomic.AddUint64(&l.nextFundingID, 1)
   843  	reservation, err := NewChannelReservation(
   844  		capacity, localFundingAmt, req.CommitFeePerKB, l, id,
   845  		req.PushMAtoms, &l.Cfg.NetParams.GenesisHash, req.Flags,
   846  		req.CommitType, req.ChanFunder, req.PendingChanID,
   847  		thawHeight,
   848  	)
   849  	if err != nil {
   850  		fundingIntent.Cancel()
   851  
   852  		req.err <- err
   853  		req.resp <- nil
   854  		return
   855  	}
   856  
   857  	err = l.initOurContribution(
   858  		reservation, fundingIntent, req.NodeAddr, req.NodeID, keyRing,
   859  	)
   860  	if err != nil {
   861  		fundingIntent.Cancel()
   862  
   863  		req.err <- err
   864  		req.resp <- nil
   865  		return
   866  	}
   867  
   868  	// Create a limbo and record entry for this newly pending funding
   869  	// request.
   870  	l.limboMtx.Lock()
   871  	l.fundingLimbo[id] = reservation
   872  	l.reservationIDs[req.PendingChanID] = id
   873  	l.limboMtx.Unlock()
   874  
   875  	// Funding reservation request successfully handled. The funding inputs
   876  	// will be marked as unavailable until the reservation is either
   877  	// completed, or canceled.
   878  	req.resp <- reservation
   879  	req.err <- nil
   880  }
   881  
   882  // enforceReservedValue enforces that the wallet, upon a new channel being
   883  // opened, meets the minimum amount of funds required for each advertised anchor
   884  // channel.
   885  //
   886  // We only enforce the reserve if we are contributing funds to the channel. This
   887  // is done to still allow incoming channels even though we have no UTXOs
   888  // available, as in bootstrapping phases.
   889  func (l *LightningWallet) enforceNewReservedValue(fundingIntent chanfunding.Intent,
   890  	isPublic, hasAnchors bool) error {
   891  
   892  	// Only enforce the reserve when an advertised channel is being opened
   893  	// in which we are contributing funds to. This ensures we never dip
   894  	// below the reserve.
   895  	if !isPublic || fundingIntent.LocalFundingAmt() == 0 {
   896  		return nil
   897  	}
   898  
   899  	numAnchors, err := l.currentNumAnchorChans()
   900  	if err != nil {
   901  		return err
   902  	}
   903  
   904  	// Add the to-be-opened channel.
   905  	if hasAnchors {
   906  		numAnchors++
   907  	}
   908  
   909  	return l.WithCoinSelectLock(func() error {
   910  		_, err := l.CheckReservedValue(
   911  			fundingIntent.Inputs(), fundingIntent.Outputs(),
   912  			numAnchors,
   913  		)
   914  		return err
   915  	})
   916  }
   917  
   918  // currentNumAnchorChans returns the current number of non-private anchor
   919  // channels the wallet should be ready to fee bump if needed.
   920  func (l *LightningWallet) currentNumAnchorChans() (int, error) {
   921  	// Count all anchor channels that are open or pending
   922  	// open, or waiting close.
   923  	chans, err := l.Cfg.Database.FetchAllChannels()
   924  	if err != nil {
   925  		return 0, err
   926  	}
   927  
   928  	var numAnchors int
   929  	cntChannel := func(c *channeldb.OpenChannel) {
   930  		// We skip private channels, as we assume they won't be used
   931  		// for routing.
   932  		if c.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
   933  			return
   934  		}
   935  
   936  		// Count anchor channels.
   937  		if c.ChanType.HasAnchors() {
   938  			numAnchors++
   939  		}
   940  
   941  	}
   942  
   943  	for _, c := range chans {
   944  		cntChannel(c)
   945  	}
   946  
   947  	// We also count pending close channels.
   948  	pendingClosed, err := l.Cfg.Database.FetchClosedChannels(
   949  		true,
   950  	)
   951  	if err != nil {
   952  		return 0, err
   953  	}
   954  
   955  	for _, c := range pendingClosed {
   956  		c, err := l.Cfg.Database.FetchHistoricalChannel(
   957  			&c.ChanPoint,
   958  		)
   959  		if err != nil {
   960  			// We don't have a guarantee that all channels re found
   961  			// in the historical channels bucket, so we continue.
   962  			walletLog.Warnf("Unable to fetch historical "+
   963  				"channel: %v", err)
   964  			continue
   965  		}
   966  
   967  		cntChannel(c)
   968  	}
   969  
   970  	return numAnchors, nil
   971  }
   972  
   973  // CheckReservedValue checks whether publishing a transaction with the given
   974  // inputs and outputs would violate the value we reserve in the wallet for
   975  // bumping the fee of anchor channels. The numAnchorChans argument should be
   976  // set the the number of open anchor channels controlled by the wallet after
   977  // the transaction has been published.
   978  //
   979  // If the reserved value is violated, the returned error will be
   980  // ErrReservedValueInvalidated. The method will also return the current
   981  // reserved value, both in case of success and in case of
   982  // ErrReservedValueInvalidated.
   983  //
   984  // NOTE: This method should only be run with the CoinSelectLock held.
   985  func (l *LightningWallet) CheckReservedValue(in []wire.OutPoint,
   986  	out []*wire.TxOut, numAnchorChans int) (dcrutil.Amount, error) {
   987  
   988  	// Get all unspent coins in the wallet.
   989  	witnessOutputs, err := l.ListUnspentWitness(0, math.MaxInt32, "")
   990  	if err != nil {
   991  		return 0, err
   992  	}
   993  
   994  	ourInput := make(map[wire.OutPoint]struct{})
   995  	for _, op := range in {
   996  		ourInput[op] = struct{}{}
   997  	}
   998  
   999  	// When crafting a transaction with inputs from the wallet, these coins
  1000  	// will usually be locked in the process, and not be returned when
  1001  	// listing unspents. In this case they have already been deducted from
  1002  	// the wallet balance. In case they haven't been properly locked, we
  1003  	// check whether they are still listed among our unspents and deduct
  1004  	// them.
  1005  	var walletBalance dcrutil.Amount
  1006  	for _, in := range witnessOutputs {
  1007  		// Spending an unlocked wallet UTXO, don't add it to the
  1008  		// balance.
  1009  		if _, ok := ourInput[in.OutPoint]; ok {
  1010  			continue
  1011  		}
  1012  
  1013  		walletBalance += in.Value
  1014  	}
  1015  
  1016  	// Now we go through the outputs of the transaction, if any of the
  1017  	// outputs are paying into the wallet (likely a change output), we add
  1018  	// it to our final balance.
  1019  	for _, txOut := range out {
  1020  		_, addrs := stdscript.ExtractAddrs(
  1021  			txOut.Version, txOut.PkScript, &l.Cfg.NetParams,
  1022  		)
  1023  
  1024  		for _, addr := range addrs {
  1025  			if !l.IsOurAddress(addr) {
  1026  				continue
  1027  			}
  1028  
  1029  			walletBalance += dcrutil.Amount(txOut.Value)
  1030  
  1031  			// We break since we don't want to double count the output.
  1032  			break
  1033  		}
  1034  	}
  1035  
  1036  	// We reserve a given amount for each anchor channel.
  1037  	reserved := dcrutil.Amount(numAnchorChans) * anchorChanReservedValue
  1038  	if reserved > maxAnchorChanReservedValue {
  1039  		reserved = maxAnchorChanReservedValue
  1040  	}
  1041  
  1042  	if walletBalance < reserved {
  1043  		walletLog.Debugf("Reserved value=%v above final "+
  1044  			"walletbalance=%v with %d anchor channels open",
  1045  			reserved, walletBalance, numAnchorChans)
  1046  		return reserved, ErrReservedValueInvalidated
  1047  	}
  1048  
  1049  	return reserved, nil
  1050  }
  1051  
  1052  // CheckReservedValueTx calls CheckReservedValue with the inputs and outputs
  1053  // from the given tx, with the number of anchor channels currently open in the
  1054  // database.
  1055  //
  1056  // NOTE: This method should only be run with the CoinSelectLock held.
  1057  func (l *LightningWallet) CheckReservedValueTx(req CheckReservedValueTxReq) (
  1058  	dcrutil.Amount, error) {
  1059  
  1060  	numAnchors, err := l.currentNumAnchorChans()
  1061  	if err != nil {
  1062  		return 0, err
  1063  	}
  1064  
  1065  	var inputs []wire.OutPoint
  1066  	for _, txIn := range req.Tx.TxIn {
  1067  		inputs = append(inputs, txIn.PreviousOutPoint)
  1068  	}
  1069  
  1070  	reservedVal, err := l.CheckReservedValue(
  1071  		inputs, req.Tx.TxOut, numAnchors,
  1072  	)
  1073  	switch {
  1074  
  1075  	// If the error returned from CheckReservedValue is
  1076  	// ErrReservedValueInvalidated, then it did nonetheless return
  1077  	// the required reserved value and we check for the optional
  1078  	// change index.
  1079  	case errors.Is(err, ErrReservedValueInvalidated):
  1080  		// Without a change index provided there is nothing more to
  1081  		// check and the error is returned.
  1082  		if req.ChangeIndex == nil {
  1083  			return reservedVal, err
  1084  		}
  1085  
  1086  		// If a change index was provided we make only sure that it
  1087  		// would leave sufficient funds for the reserved balance value.
  1088  		//
  1089  		// Note: This is used if a change output index is explicitly set
  1090  		// but that may not be watched by the wallet and therefore is
  1091  		// not picked up by the call to CheckReservedValue above.
  1092  		chIdx := *req.ChangeIndex
  1093  		if chIdx < 0 || chIdx >= len(req.Tx.TxOut) ||
  1094  			req.Tx.TxOut[chIdx].Value < int64(reservedVal) {
  1095  
  1096  			return reservedVal, err
  1097  		}
  1098  
  1099  	case err != nil:
  1100  		return reservedVal, err
  1101  	}
  1102  
  1103  	return reservedVal, nil
  1104  }
  1105  
  1106  // initOurContribution initializes the given ChannelReservation with our coins
  1107  // and change reserved for the channel, and derives the keys to use for this
  1108  // channel.
  1109  func (l *LightningWallet) initOurContribution(reservation *ChannelReservation,
  1110  	fundingIntent chanfunding.Intent, nodeAddr net.Addr,
  1111  	nodeID *secp256k1.PublicKey, keyRing keychain.KeyRing) error {
  1112  
  1113  	// Grab the mutex on the ChannelReservation to ensure thread-safety
  1114  	reservation.Lock()
  1115  	defer reservation.Unlock()
  1116  
  1117  	// At this point, if we have a funding intent, we'll use it to populate
  1118  	// the existing reservation state entries for our coin selection.
  1119  	if fundingIntent != nil {
  1120  		if intent, ok := fundingIntent.(*chanfunding.FullIntent); ok {
  1121  			for _, coin := range intent.InputCoins {
  1122  				reservation.ourContribution.Inputs = append(
  1123  					reservation.ourContribution.Inputs,
  1124  					&wire.TxIn{
  1125  						PreviousOutPoint: coin.OutPoint,
  1126  					},
  1127  				)
  1128  			}
  1129  			reservation.ourContribution.ChangeOutputs = intent.ChangeOutputs
  1130  		}
  1131  
  1132  		reservation.fundingIntent = fundingIntent
  1133  	}
  1134  
  1135  	reservation.nodeAddr = nodeAddr
  1136  	reservation.partialState.IdentityPub = nodeID
  1137  
  1138  	var err error
  1139  	reservation.ourContribution.MultiSigKey, err = keyRing.DeriveNextKey(
  1140  		keychain.KeyFamilyMultiSig,
  1141  	)
  1142  	if err != nil {
  1143  		return err
  1144  	}
  1145  	reservation.ourContribution.RevocationBasePoint, err = keyRing.DeriveNextKey(
  1146  		keychain.KeyFamilyRevocationBase,
  1147  	)
  1148  	if err != nil {
  1149  		return err
  1150  	}
  1151  	reservation.ourContribution.HtlcBasePoint, err = keyRing.DeriveNextKey(
  1152  		keychain.KeyFamilyHtlcBase,
  1153  	)
  1154  	if err != nil {
  1155  		return err
  1156  	}
  1157  	reservation.ourContribution.PaymentBasePoint, err = keyRing.DeriveNextKey(
  1158  		keychain.KeyFamilyPaymentBase,
  1159  	)
  1160  	if err != nil {
  1161  		return err
  1162  	}
  1163  	reservation.ourContribution.DelayBasePoint, err = keyRing.DeriveNextKey(
  1164  		keychain.KeyFamilyDelayBase,
  1165  	)
  1166  	if err != nil {
  1167  		return err
  1168  	}
  1169  
  1170  	// With the above keys created, we'll also need to initialize our
  1171  	// revocation tree state, and from that generate the per-commitment point.
  1172  	producer, err := l.nextRevocationProducer(reservation, keyRing)
  1173  	if err != nil {
  1174  		return err
  1175  	}
  1176  
  1177  	firstPreimage, err := producer.AtIndex(0)
  1178  	if err != nil {
  1179  		return err
  1180  	}
  1181  	reservation.ourContribution.FirstCommitmentPoint = input.ComputeCommitmentPoint(
  1182  		firstPreimage[:],
  1183  	)
  1184  
  1185  	reservation.partialState.RevocationProducer = producer
  1186  	reservation.ourContribution.ChannelConstraints = l.Cfg.DefaultConstraints
  1187  
  1188  	return nil
  1189  }
  1190  
  1191  // handleFundingReserveCancel cancels an existing channel reservation. As part
  1192  // of the cancellation, outputs previously selected as inputs for the funding
  1193  // transaction via coin selection are freed allowing future reservations to
  1194  // include them.
  1195  func (l *LightningWallet) handleFundingCancelRequest(req *fundingReserveCancelMsg) {
  1196  	// TODO(roasbeef): holding lock too long
  1197  	l.limboMtx.Lock()
  1198  	defer l.limboMtx.Unlock()
  1199  
  1200  	pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
  1201  	if !ok {
  1202  		// TODO(roasbeef): make new error, "unknown funding state" or something
  1203  		req.err <- fmt.Errorf("attempted to cancel non-existent funding state")
  1204  		return
  1205  	}
  1206  
  1207  	// Grab the mutex on the ChannelReservation to ensure thread-safety
  1208  	pendingReservation.Lock()
  1209  	defer pendingReservation.Unlock()
  1210  
  1211  	// Mark all previously locked outpoints as useable for future funding
  1212  	// requests.
  1213  	for _, unusedInput := range pendingReservation.ourContribution.Inputs {
  1214  		delete(l.lockedOutPoints, unusedInput.PreviousOutPoint)
  1215  		l.UnlockOutpoint(unusedInput.PreviousOutPoint)
  1216  	}
  1217  
  1218  	// TODO(roasbeef): is it even worth it to keep track of unused keys?
  1219  
  1220  	// TODO(roasbeef): Is it possible to mark the unused change also as
  1221  	// available?
  1222  
  1223  	delete(l.fundingLimbo, req.pendingFundingID)
  1224  
  1225  	pid := pendingReservation.pendingChanID
  1226  	delete(l.reservationIDs, pid)
  1227  
  1228  	l.intentMtx.Lock()
  1229  	if intent, ok := l.fundingIntents[pid]; ok {
  1230  		intent.Cancel()
  1231  
  1232  		delete(l.fundingIntents, pendingReservation.pendingChanID)
  1233  	}
  1234  	l.intentMtx.Unlock()
  1235  
  1236  	req.err <- nil
  1237  }
  1238  
  1239  // CreateCommitmentTxns is a helper function that creates the initial
  1240  // commitment transaction for both parties. This function is used during the
  1241  // initial funding workflow as both sides must generate a signature for the
  1242  // remote party's commitment transaction, and verify the signature for their
  1243  // version of the commitment transaction.
  1244  func CreateCommitmentTxns(localBalance, remoteBalance dcrutil.Amount,
  1245  	ourChanCfg, theirChanCfg *channeldb.ChannelConfig,
  1246  	localCommitPoint, remoteCommitPoint *secp256k1.PublicKey,
  1247  	fundingTxIn wire.TxIn, chanType channeldb.ChannelType, initiator bool,
  1248  	leaseExpiry uint32, chainParams *chaincfg.Params) (*wire.MsgTx, *wire.MsgTx, error) {
  1249  
  1250  	localCommitmentKeys := DeriveCommitmentKeys(
  1251  		localCommitPoint, true, chanType, ourChanCfg, theirChanCfg,
  1252  	)
  1253  	remoteCommitmentKeys := DeriveCommitmentKeys(
  1254  		remoteCommitPoint, false, chanType, ourChanCfg, theirChanCfg,
  1255  	)
  1256  
  1257  	ourCommitTx, err := CreateCommitTx(
  1258  		chanType, fundingTxIn, localCommitmentKeys, ourChanCfg,
  1259  		theirChanCfg, localBalance, remoteBalance, 0, initiator,
  1260  		leaseExpiry,
  1261  	)
  1262  	if err != nil {
  1263  		return nil, nil, err
  1264  	}
  1265  
  1266  	maxTxSize := uint64(chainParams.MaxTxSize)
  1267  	err = standalone.CheckTransactionSanity(ourCommitTx, maxTxSize)
  1268  	if err != nil {
  1269  		return nil, nil, err
  1270  	}
  1271  
  1272  	theirCommitTx, err := CreateCommitTx(
  1273  		chanType, fundingTxIn, remoteCommitmentKeys, theirChanCfg,
  1274  		ourChanCfg, remoteBalance, localBalance, 0, !initiator,
  1275  		leaseExpiry,
  1276  	)
  1277  	if err != nil {
  1278  		return nil, nil, err
  1279  	}
  1280  
  1281  	err = standalone.CheckTransactionSanity(theirCommitTx, maxTxSize)
  1282  	if err != nil {
  1283  		return nil, nil, err
  1284  	}
  1285  
  1286  	return ourCommitTx, theirCommitTx, nil
  1287  }
  1288  
  1289  // handleContributionMsg processes the second workflow step for the lifetime of
  1290  // a channel reservation. Upon completion, the reservation will carry a
  1291  // completed funding transaction (minus the counterparty's input signatures),
  1292  // both versions of the commitment transaction, and our signature for their
  1293  // version of the commitment transaction.
  1294  func (l *LightningWallet) handleContributionMsg(req *addContributionMsg) {
  1295  
  1296  	l.limboMtx.Lock()
  1297  	pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
  1298  	l.limboMtx.Unlock()
  1299  	if !ok {
  1300  		req.err <- fmt.Errorf("attempted to update non-existent funding state")
  1301  		return
  1302  	}
  1303  
  1304  	// Grab the mutex on the ChannelReservation to ensure thread-safety
  1305  	pendingReservation.Lock()
  1306  	defer pendingReservation.Unlock()
  1307  
  1308  	// If UpfrontShutdownScript is set, validate that it is a valid script.
  1309  	shutdown := req.contribution.UpfrontShutdown
  1310  	if len(shutdown) > 0 {
  1311  		// Validate the shutdown script.
  1312  		if !validateUpfrontShutdown(shutdown, &l.Cfg.NetParams) {
  1313  			req.err <- fmt.Errorf("invalid shutdown script")
  1314  			return
  1315  		}
  1316  	}
  1317  
  1318  	// Some temporary variables to cut down on the resolution verbosity.
  1319  	pendingReservation.theirContribution = req.contribution
  1320  	theirContribution := req.contribution
  1321  	ourContribution := pendingReservation.ourContribution
  1322  
  1323  	// Perform bounds-checking on both ChannelReserve and DustLimit
  1324  	// parameters.
  1325  	if !pendingReservation.validateReserveBounds() {
  1326  		req.err <- fmt.Errorf("invalid reserve and dust bounds")
  1327  		return
  1328  	}
  1329  
  1330  	var (
  1331  		chanPoint *wire.OutPoint
  1332  		err       error
  1333  	)
  1334  
  1335  	// At this point, we can now construct our channel point. Depending on
  1336  	// which type of intent we obtained from our chanfunding.Assembler,
  1337  	// we'll carry out a distinct set of steps.
  1338  	switch fundingIntent := pendingReservation.fundingIntent.(type) {
  1339  	// The transaction was created outside of the wallet and might already
  1340  	// be published. Nothing left to do other than using the correct
  1341  	// outpoint.
  1342  	case *chanfunding.ShimIntent:
  1343  		chanPoint, err = fundingIntent.ChanPoint()
  1344  		if err != nil {
  1345  			req.err <- fmt.Errorf("unable to obtain chan point: %v", err)
  1346  			return
  1347  		}
  1348  
  1349  		pendingReservation.partialState.FundingOutpoint = *chanPoint
  1350  
  1351  	// The user has signaled that they want to use a PSBT to construct the
  1352  	// funding transaction. Because we now have the multisig keys from both
  1353  	// parties, we can create the multisig script that needs to be funded
  1354  	// and then pause the process until the user supplies the PSBT
  1355  	// containing the eventual funding transaction.
  1356  	case *chanfunding.PsbtIntent:
  1357  		if fundingIntent.PendingPsbt != nil {
  1358  			req.err <- fmt.Errorf("PSBT funding already in" +
  1359  				"progress")
  1360  			return
  1361  		}
  1362  
  1363  		// Now that we know our contribution, we can bind both the local
  1364  		// and remote key which will be needed to calculate the multisig
  1365  		// funding output in a next step.
  1366  		pendingChanID := pendingReservation.pendingChanID
  1367  		walletLog.Debugf("Advancing PSBT funding flow for "+
  1368  			"pending_id(%x), binding keys local_key=%v, "+
  1369  			"remote_key=%x", pendingChanID,
  1370  			&ourContribution.MultiSigKey,
  1371  			theirContribution.MultiSigKey.PubKey.SerializeCompressed())
  1372  		fundingIntent.BindKeys(
  1373  			&ourContribution.MultiSigKey,
  1374  			theirContribution.MultiSigKey.PubKey,
  1375  		)
  1376  
  1377  		// Exit early because we can't continue the funding flow yet.
  1378  		req.err <- &PsbtFundingRequired{
  1379  			Intent: fundingIntent,
  1380  		}
  1381  		return
  1382  
  1383  	case *chanfunding.FullIntent:
  1384  		// Now that we know their public key, we can bind theirs as
  1385  		// well as ours to the funding intent.
  1386  		fundingIntent.BindKeys(
  1387  			&pendingReservation.ourContribution.MultiSigKey,
  1388  			theirContribution.MultiSigKey.PubKey,
  1389  		)
  1390  
  1391  		// With our keys bound, we can now construct+sign the final
  1392  		// funding transaction and also obtain the chanPoint that
  1393  		// creates the channel.
  1394  		fundingTx, err := fundingIntent.CompileFundingTx(
  1395  			theirContribution.Inputs,
  1396  			theirContribution.ChangeOutputs,
  1397  		)
  1398  		if err != nil {
  1399  			req.err <- fmt.Errorf("unable to construct funding "+
  1400  				"tx: %v", err)
  1401  			return
  1402  		}
  1403  		chanPoint, err = fundingIntent.ChanPoint()
  1404  		if err != nil {
  1405  			req.err <- fmt.Errorf("unable to obtain chan "+
  1406  				"point: %v", err)
  1407  			return
  1408  		}
  1409  
  1410  		// Finally, we'll populate the relevant information in our
  1411  		// pendingReservation so the rest of the funding flow can
  1412  		// continue as normal.
  1413  		pendingReservation.fundingTx = fundingTx
  1414  		pendingReservation.partialState.FundingOutpoint = *chanPoint
  1415  		pendingReservation.ourFundingInputScripts = make(
  1416  			[]*input.Script, 0, len(ourContribution.Inputs),
  1417  		)
  1418  		for _, txIn := range fundingTx.TxIn {
  1419  			_, err := l.FetchInputInfo(&txIn.PreviousOutPoint)
  1420  			if err != nil {
  1421  				continue
  1422  			}
  1423  
  1424  			// Re-split the original sigScript into a witness
  1425  			// stack.
  1426  			witness, err := input.SigScriptToWitnessStack(txIn.SignatureScript)
  1427  			if err != nil {
  1428  				req.err <- fmt.Errorf("unable to re-split witness stack: %v", err)
  1429  				return
  1430  			}
  1431  			pendingReservation.ourFundingInputScripts = append(
  1432  				pendingReservation.ourFundingInputScripts,
  1433  				&input.Script{
  1434  					Witness: witness,
  1435  				},
  1436  			)
  1437  		}
  1438  
  1439  		walletLog.Tracef("Funding tx for ChannelPoint(%v) "+
  1440  			"generated: %v", chanPoint, spew.Sdump(fundingTx))
  1441  	}
  1442  
  1443  	// If we landed here and didn't exit early, it means we already have
  1444  	// the channel point ready. We can jump directly to the next step.
  1445  	l.handleChanPointReady(&continueContributionMsg{
  1446  		pendingFundingID: req.pendingFundingID,
  1447  		err:              req.err,
  1448  	})
  1449  }
  1450  
  1451  // handleChanPointReady continues the funding process once the channel point
  1452  // is known and the funding transaction can be completed.
  1453  func (l *LightningWallet) handleChanPointReady(req *continueContributionMsg) {
  1454  	l.limboMtx.Lock()
  1455  	pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
  1456  	l.limboMtx.Unlock()
  1457  	if !ok {
  1458  		req.err <- fmt.Errorf("attempted to update non-existent " +
  1459  			"funding state")
  1460  		return
  1461  	}
  1462  	ourContribution := pendingReservation.ourContribution
  1463  	theirContribution := pendingReservation.theirContribution
  1464  	chanPoint := pendingReservation.partialState.FundingOutpoint
  1465  
  1466  	// If we're in the PSBT funding flow, we now should have everything that
  1467  	// is needed to construct and publish the full funding transaction.
  1468  	intent := pendingReservation.fundingIntent
  1469  	if psbtIntent, ok := intent.(*chanfunding.PsbtIntent); ok {
  1470  		// With our keys bound, we can now construct and possibly sign
  1471  		// the final funding transaction and also obtain the chanPoint
  1472  		// that creates the channel. We _have_ to call CompileFundingTx
  1473  		// even if we don't publish ourselves as that sets the actual
  1474  		// funding outpoint in stone for this channel.
  1475  		fundingTx, err := psbtIntent.CompileFundingTx()
  1476  		if err != nil {
  1477  			req.err <- fmt.Errorf("unable to construct funding "+
  1478  				"tx: %v", err)
  1479  			return
  1480  		}
  1481  		chanPointPtr, err := psbtIntent.ChanPoint()
  1482  		if err != nil {
  1483  			req.err <- fmt.Errorf("unable to obtain chan "+
  1484  				"point: %v", err)
  1485  			return
  1486  		}
  1487  
  1488  		pendingReservation.partialState.FundingOutpoint = *chanPointPtr
  1489  		chanPoint = *chanPointPtr
  1490  
  1491  		// Finally, we'll populate the relevant information in our
  1492  		// pendingReservation so the rest of the funding flow can
  1493  		// continue as normal in case we are going to publish ourselves.
  1494  		if psbtIntent.ShouldPublishFundingTX() {
  1495  			pendingReservation.fundingTx = fundingTx
  1496  			pendingReservation.ourFundingInputScripts = make(
  1497  				[]*input.Script, 0, len(ourContribution.Inputs),
  1498  			)
  1499  			for _, txIn := range fundingTx.TxIn {
  1500  				pendingReservation.ourFundingInputScripts = append(
  1501  					pendingReservation.ourFundingInputScripts,
  1502  					&input.Script{
  1503  						// TODO(decred) fill witness from
  1504  						// exploded sigScript?
  1505  						SigScript: txIn.SignatureScript,
  1506  					},
  1507  				)
  1508  			}
  1509  		}
  1510  	}
  1511  
  1512  	// Initialize an empty sha-chain for them, tracking the current pending
  1513  	// revocation hash (we don't yet know the preimage so we can't add it
  1514  	// to the chain).
  1515  	s := shachain.NewRevocationStore()
  1516  	pendingReservation.partialState.RevocationStore = s
  1517  
  1518  	// Store their current commitment point. We'll need this after the
  1519  	// first state transition in order to verify the authenticity of the
  1520  	// revocation.
  1521  	chanState := pendingReservation.partialState
  1522  	chanState.RemoteCurrentRevocation = theirContribution.FirstCommitmentPoint
  1523  
  1524  	// Create the txin to our commitment transaction; required to construct
  1525  	// the commitment transactions.
  1526  	fundingTxIn := wire.TxIn{
  1527  		PreviousOutPoint: chanPoint,
  1528  	}
  1529  
  1530  	// With the funding tx complete, create both commitment transactions.
  1531  	localBalance := pendingReservation.partialState.LocalCommitment.LocalBalance.ToAtoms()
  1532  	remoteBalance := pendingReservation.partialState.LocalCommitment.RemoteBalance.ToAtoms()
  1533  	var leaseExpiry uint32
  1534  	if pendingReservation.partialState.ChanType.HasLeaseExpiration() {
  1535  		leaseExpiry = pendingReservation.partialState.ThawHeight
  1536  	}
  1537  	ourCommitTx, theirCommitTx, err := CreateCommitmentTxns(
  1538  		localBalance, remoteBalance, ourContribution.ChannelConfig,
  1539  		theirContribution.ChannelConfig,
  1540  		ourContribution.FirstCommitmentPoint,
  1541  		theirContribution.FirstCommitmentPoint, fundingTxIn,
  1542  		pendingReservation.partialState.ChanType,
  1543  		pendingReservation.partialState.IsInitiator, leaseExpiry,
  1544  		&l.Cfg.NetParams,
  1545  	)
  1546  	if err != nil {
  1547  		req.err <- err
  1548  		return
  1549  	}
  1550  
  1551  	// With both commitment transactions constructed, generate the state
  1552  	// obfuscator then use it to encode the current state number within
  1553  	// both commitment transactions.
  1554  	var stateObfuscator [StateHintSize]byte
  1555  	if chanState.ChanType.IsSingleFunder() {
  1556  		stateObfuscator = DeriveStateHintObfuscator(
  1557  			ourContribution.PaymentBasePoint.PubKey,
  1558  			theirContribution.PaymentBasePoint.PubKey,
  1559  		)
  1560  	} else {
  1561  		ourSer := ourContribution.PaymentBasePoint.PubKey.SerializeCompressed()
  1562  		theirSer := theirContribution.PaymentBasePoint.PubKey.SerializeCompressed()
  1563  		switch bytes.Compare(ourSer, theirSer) {
  1564  		case -1:
  1565  			stateObfuscator = DeriveStateHintObfuscator(
  1566  				ourContribution.PaymentBasePoint.PubKey,
  1567  				theirContribution.PaymentBasePoint.PubKey,
  1568  			)
  1569  		default:
  1570  			stateObfuscator = DeriveStateHintObfuscator(
  1571  				theirContribution.PaymentBasePoint.PubKey,
  1572  				ourContribution.PaymentBasePoint.PubKey,
  1573  			)
  1574  		}
  1575  	}
  1576  	err = initStateHints(ourCommitTx, theirCommitTx, stateObfuscator)
  1577  	if err != nil {
  1578  		req.err <- err
  1579  		return
  1580  	}
  1581  
  1582  	// Sort both transactions according to the agreed upon canonical
  1583  	// ordering. This lets us skip sending the entire transaction over,
  1584  	// instead we'll just send signatures.
  1585  	txsort.InPlaceSort(ourCommitTx)
  1586  	txsort.InPlaceSort(theirCommitTx)
  1587  
  1588  	walletLog.Tracef("Local commit tx for ChannelPoint(%v): %v",
  1589  		chanPoint, spew.Sdump(ourCommitTx))
  1590  	walletLog.Tracef("Remote commit tx for ChannelPoint(%v): %v",
  1591  		chanPoint, spew.Sdump(theirCommitTx))
  1592  
  1593  	// Record newly available information within the open channel state.
  1594  	chanState.FundingOutpoint = chanPoint
  1595  	chanState.LocalCommitment.CommitTx = ourCommitTx
  1596  	chanState.RemoteCommitment.CommitTx = theirCommitTx
  1597  
  1598  	// Next, we'll obtain the funding witness script, and the funding
  1599  	// output itself so we can generate a valid signature for the remote
  1600  	// party.
  1601  	fundingIntent := pendingReservation.fundingIntent
  1602  	fundingWitnessScript, fundingOutput, err := fundingIntent.FundingOutput()
  1603  	if err != nil {
  1604  		req.err <- fmt.Errorf("unable to obtain funding output")
  1605  		return
  1606  	}
  1607  
  1608  	// Generate a signature for their version of the initial commitment
  1609  	// transaction.
  1610  	ourKey := ourContribution.MultiSigKey
  1611  	signDesc := input.SignDescriptor{
  1612  		WitnessScript: fundingWitnessScript,
  1613  		KeyDesc:       ourKey,
  1614  		Output:        fundingOutput,
  1615  		HashType:      txscript.SigHashAll,
  1616  		InputIndex:    0,
  1617  	}
  1618  	sigTheirCommit, err := l.Cfg.Signer.SignOutputRaw(theirCommitTx, &signDesc)
  1619  	if err != nil {
  1620  		req.err <- err
  1621  		return
  1622  	}
  1623  	pendingReservation.ourCommitmentSig = sigTheirCommit
  1624  
  1625  	req.err <- nil
  1626  }
  1627  
  1628  // handleSingleContribution is called as the second step to a single funder
  1629  // workflow to which we are the responder. It simply saves the remote peer's
  1630  // contribution to the channel, as solely the remote peer will contribute any
  1631  // funds to the channel.
  1632  func (l *LightningWallet) handleSingleContribution(req *addSingleContributionMsg) {
  1633  	l.limboMtx.Lock()
  1634  	pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
  1635  	l.limboMtx.Unlock()
  1636  	if !ok {
  1637  		req.err <- fmt.Errorf("attempted to update non-existent funding state")
  1638  		return
  1639  	}
  1640  
  1641  	// Grab the mutex on the channelReservation to ensure thread-safety.
  1642  	pendingReservation.Lock()
  1643  	defer pendingReservation.Unlock()
  1644  
  1645  	// Validate that the remote's UpfrontShutdownScript is a valid script
  1646  	// if it's set.
  1647  	shutdown := req.contribution.UpfrontShutdown
  1648  	if len(shutdown) > 0 {
  1649  		// Validate the shutdown script.
  1650  		if !validateUpfrontShutdown(shutdown, &l.Cfg.NetParams) {
  1651  			req.err <- fmt.Errorf("invalid shutdown script")
  1652  			return
  1653  		}
  1654  	}
  1655  
  1656  	// Simply record the counterparty's contribution into the pending
  1657  	// reservation data as they'll be solely funding the channel entirely.
  1658  	pendingReservation.theirContribution = req.contribution
  1659  	theirContribution := pendingReservation.theirContribution
  1660  	chanState := pendingReservation.partialState
  1661  
  1662  	// Perform bounds checking on both ChannelReserve and DustLimit
  1663  	// parameters. The ChannelReserve may have been changed by the
  1664  	// ChannelAcceptor RPC, so this is necessary.
  1665  	if !pendingReservation.validateReserveBounds() {
  1666  		req.err <- fmt.Errorf("invalid reserve and dust bounds")
  1667  		return
  1668  	}
  1669  
  1670  	// Initialize an empty sha-chain for them, tracking the current pending
  1671  	// revocation hash (we don't yet know the preimage so we can't add it
  1672  	// to the chain).
  1673  	remotePreimageStore := shachain.NewRevocationStore()
  1674  	chanState.RevocationStore = remotePreimageStore
  1675  
  1676  	// Now that we've received their first commitment point, we'll store it
  1677  	// within the channel state so we can sync it to disk once the funding
  1678  	// process is complete.
  1679  	chanState.RemoteCurrentRevocation = theirContribution.FirstCommitmentPoint
  1680  
  1681  	req.err <- nil
  1682  }
  1683  
  1684  // verifyFundingInputs attempts to verify all remote inputs to the funding
  1685  // transaction.
  1686  func (l *LightningWallet) verifyFundingInputs(fundingTx *wire.MsgTx,
  1687  	remoteInputScripts []*input.Script) error {
  1688  
  1689  	sigIndex := 0
  1690  	inputScripts := remoteInputScripts
  1691  	for i, txin := range fundingTx.TxIn {
  1692  		if len(inputScripts) != 0 && len(txin.SignatureScript) == 0 {
  1693  			// Attach the input scripts so we can verify it below.
  1694  			txin.SignatureScript = inputScripts[sigIndex].SigScript
  1695  
  1696  			// If the SigScript field is empty but Witness is
  1697  			// filled, calculate the correct SigScript.
  1698  			if len(txin.SignatureScript) == 0 && len(inputScripts[sigIndex].Witness) > 0 {
  1699  				sigScript, err := input.WitnessStackToSigScript(inputScripts[sigIndex].Witness)
  1700  				if err != nil {
  1701  					return fmt.Errorf("error assembling "+
  1702  						"final sigScript for remote "+
  1703  						"txin %d: %v", i, err)
  1704  				}
  1705  				txin.SignatureScript = sigScript
  1706  			}
  1707  
  1708  			// Fetch the alleged previous output along with the
  1709  			// pkscript referenced by this input.
  1710  			//
  1711  			// TODO(roasbeef): when dual funder pass actual
  1712  			// height-hint
  1713  			//
  1714  			// TODO(roasbeef): this fails for neutrino always as it
  1715  			// treats the height hint as an exact birthday of the
  1716  			// utxo rather than a lower bound
  1717  			//
  1718  			// TODO(decred): The pkscript is only used on neutrino
  1719  			// clients and is overwritten by the current GetUTXO()
  1720  			// implementations, so we can ignore this for now.
  1721  			var pkScript []byte
  1722  			output, err := l.Cfg.ChainIO.GetUtxo(
  1723  				&txin.PreviousOutPoint,
  1724  				pkScript, 0, l.quit,
  1725  			)
  1726  			if output == nil {
  1727  				return fmt.Errorf("input to funding tx does "+
  1728  					"not exist: %v", err)
  1729  			}
  1730  
  1731  			// Ensure that the witness+sigScript combo is valid.
  1732  			vm, err := txscript.NewEngine(
  1733  				output.PkScript, fundingTx, i,
  1734  				input.ScriptVerifyFlags, output.Version, nil,
  1735  			)
  1736  			if err != nil {
  1737  				return fmt.Errorf("cannot create script "+
  1738  					"engine: %s", err)
  1739  			}
  1740  			if err = vm.Execute(); err != nil {
  1741  				return fmt.Errorf("cannot validate "+
  1742  					"transaction: %s", err)
  1743  			}
  1744  
  1745  			sigIndex++
  1746  		}
  1747  	}
  1748  
  1749  	return nil
  1750  }
  1751  
  1752  // handleFundingCounterPartySigs is the final step in the channel reservation
  1753  // workflow. During this step, we validate *all* the received signatures for
  1754  // inputs to the funding transaction. If any of these are invalid, we bail,
  1755  // and forcibly cancel this funding request. Additionally, we ensure that the
  1756  // signature we received from the counterparty for our version of the commitment
  1757  // transaction allows us to spend from the funding output with the addition of
  1758  // our signature.
  1759  func (l *LightningWallet) handleFundingCounterPartySigs(msg *addCounterPartySigsMsg) {
  1760  	l.limboMtx.RLock()
  1761  	res, ok := l.fundingLimbo[msg.pendingFundingID]
  1762  	l.limboMtx.RUnlock()
  1763  	if !ok {
  1764  		msg.err <- fmt.Errorf("attempted to update non-existent funding state")
  1765  		return
  1766  	}
  1767  
  1768  	// Grab the mutex on the ChannelReservation to ensure thread-safety
  1769  	res.Lock()
  1770  	defer res.Unlock()
  1771  
  1772  	// Now we can complete the funding transaction by adding their
  1773  	// signatures to their inputs.
  1774  	res.theirFundingInputScripts = msg.theirFundingInputScripts
  1775  	inputScripts := msg.theirFundingInputScripts
  1776  
  1777  	// Only if we have the final funding transaction do we need to verify
  1778  	// the final set of inputs. Otherwise, it may be the case that the
  1779  	// channel was funded via an external wallet.
  1780  	fundingTx := res.fundingTx
  1781  	if res.partialState.ChanType.HasFundingTx() {
  1782  		err := l.verifyFundingInputs(fundingTx, inputScripts)
  1783  		if err != nil {
  1784  			msg.err <- err
  1785  			msg.completeChan <- nil
  1786  			return
  1787  		}
  1788  	}
  1789  
  1790  	// At this point, we can also record and verify their signature for our
  1791  	// commitment transaction.
  1792  	res.theirCommitmentSig = msg.theirCommitmentSig
  1793  	commitTx := res.partialState.LocalCommitment.CommitTx
  1794  	ourKey := res.ourContribution.MultiSigKey
  1795  	theirKey := res.theirContribution.MultiSigKey
  1796  
  1797  	// Re-generate both the witnessScript and p2sh output. We sign the
  1798  	// witnessScript script, but include the p2sh output as the subscript
  1799  	// for verification.
  1800  	witnessScript, _, err := input.GenFundingPkScript(
  1801  		ourKey.PubKey.SerializeCompressed(),
  1802  		theirKey.PubKey.SerializeCompressed(),
  1803  		int64(res.partialState.Capacity),
  1804  	)
  1805  	if err != nil {
  1806  		msg.err <- err
  1807  		msg.completeChan <- nil
  1808  		return
  1809  	}
  1810  
  1811  	// Next, create the spending scriptSig, and then verify that the script
  1812  	// is complete, allowing us to spend from the funding transaction.
  1813  	sigHash, err := txscript.CalcSignatureHash(
  1814  		witnessScript, txscript.SigHashAll, commitTx, 0, nil,
  1815  	)
  1816  	if err != nil {
  1817  		msg.err <- err
  1818  		msg.completeChan <- nil
  1819  		return
  1820  	}
  1821  
  1822  	// Verify that we've received a valid signature from the remote party
  1823  	// for our version of the commitment transaction.
  1824  	if !msg.theirCommitmentSig.Verify(sigHash, theirKey.PubKey) {
  1825  		msg.err <- fmt.Errorf("counterparty's commitment signature is invalid")
  1826  		msg.completeChan <- nil
  1827  		return
  1828  	}
  1829  	theirCommitSigBytes := msg.theirCommitmentSig.Serialize()
  1830  	res.partialState.LocalCommitment.CommitSig = theirCommitSigBytes
  1831  
  1832  	// Funding complete, this entry can be removed from limbo.
  1833  	l.limboMtx.Lock()
  1834  	delete(l.fundingLimbo, res.reservationID)
  1835  	delete(l.reservationIDs, res.pendingChanID)
  1836  	l.limboMtx.Unlock()
  1837  
  1838  	l.intentMtx.Lock()
  1839  	delete(l.fundingIntents, res.pendingChanID)
  1840  	l.intentMtx.Unlock()
  1841  
  1842  	// As we're about to broadcast the funding transaction, we'll take note
  1843  	// of the current height for record keeping purposes.
  1844  	//
  1845  	// TODO(roasbeef): this info can also be piped into light client's
  1846  	// basic fee estimation?
  1847  	_, bestHeight, err := l.Cfg.ChainIO.GetBestBlock()
  1848  	if err != nil {
  1849  		msg.err <- err
  1850  		msg.completeChan <- nil
  1851  		return
  1852  	}
  1853  
  1854  	// As we've completed the funding process, we'll no convert the
  1855  	// contribution structs into their underlying channel config objects to
  1856  	// he stored within the database.
  1857  	res.partialState.LocalChanCfg = res.ourContribution.toChanConfig()
  1858  	res.partialState.RemoteChanCfg = res.theirContribution.toChanConfig()
  1859  
  1860  	// We'll also record the finalized funding txn, which will allow us to
  1861  	// rebroadcast on startup in case we fail.
  1862  	res.partialState.FundingTxn = fundingTx
  1863  
  1864  	// Set optional upfront shutdown scripts on the channel state so that they
  1865  	// are persisted. These values may be nil.
  1866  	res.partialState.LocalShutdownScript =
  1867  		res.ourContribution.UpfrontShutdown
  1868  	res.partialState.RemoteShutdownScript =
  1869  		res.theirContribution.UpfrontShutdown
  1870  
  1871  	res.partialState.RevocationKeyLocator = res.nextRevocationKeyLoc
  1872  
  1873  	// Add the complete funding transaction to the DB, in its open bucket
  1874  	// which will be used for the lifetime of this channel.
  1875  	nodeAddr := res.nodeAddr
  1876  	err = res.partialState.SyncPending(nodeAddr, uint32(bestHeight))
  1877  	if err != nil {
  1878  		msg.err <- err
  1879  		msg.completeChan <- nil
  1880  		return
  1881  	}
  1882  
  1883  	msg.completeChan <- res.partialState
  1884  	msg.err <- nil
  1885  }
  1886  
  1887  // handleSingleFunderSigs is called once the remote peer who initiated the
  1888  // single funder workflow has assembled the funding transaction, and generated
  1889  // a signature for our version of the commitment transaction. This method
  1890  // progresses the workflow by generating a signature for the remote peer's
  1891  // version of the commitment transaction.
  1892  func (l *LightningWallet) handleSingleFunderSigs(req *addSingleFunderSigsMsg) {
  1893  	l.limboMtx.RLock()
  1894  	pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
  1895  	l.limboMtx.RUnlock()
  1896  	if !ok {
  1897  		req.err <- fmt.Errorf("attempted to update non-existent funding state")
  1898  		req.completeChan <- nil
  1899  		return
  1900  	}
  1901  
  1902  	// Grab the mutex on the ChannelReservation to ensure thread-safety
  1903  	pendingReservation.Lock()
  1904  	defer pendingReservation.Unlock()
  1905  
  1906  	chanState := pendingReservation.partialState
  1907  	chanState.FundingOutpoint = *req.fundingOutpoint
  1908  	fundingTxIn := wire.NewTxIn(req.fundingOutpoint, int64(chanState.Capacity),
  1909  		nil)
  1910  
  1911  	// Now that we have the funding outpoint, we can generate both versions
  1912  	// of the commitment transaction, and generate a signature for the
  1913  	// remote node's commitment transactions.
  1914  	localBalance := pendingReservation.partialState.LocalCommitment.LocalBalance.ToAtoms()
  1915  	remoteBalance := pendingReservation.partialState.LocalCommitment.RemoteBalance.ToAtoms()
  1916  	var leaseExpiry uint32
  1917  	if pendingReservation.partialState.ChanType.HasLeaseExpiration() {
  1918  		leaseExpiry = pendingReservation.partialState.ThawHeight
  1919  
  1920  	}
  1921  	ourCommitTx, theirCommitTx, err := CreateCommitmentTxns(
  1922  		localBalance, remoteBalance,
  1923  		pendingReservation.ourContribution.ChannelConfig,
  1924  		pendingReservation.theirContribution.ChannelConfig,
  1925  		pendingReservation.ourContribution.FirstCommitmentPoint,
  1926  		pendingReservation.theirContribution.FirstCommitmentPoint,
  1927  		*fundingTxIn, pendingReservation.partialState.ChanType,
  1928  		pendingReservation.partialState.IsInitiator, leaseExpiry,
  1929  		&l.Cfg.NetParams,
  1930  	)
  1931  	if err != nil {
  1932  		req.err <- err
  1933  		req.completeChan <- nil
  1934  		return
  1935  	}
  1936  
  1937  	// With both commitment transactions constructed, we can now use the
  1938  	// generator state obfuscator to encode the current state number within
  1939  	// both commitment transactions.
  1940  	stateObfuscator := DeriveStateHintObfuscator(
  1941  		pendingReservation.theirContribution.PaymentBasePoint.PubKey,
  1942  		pendingReservation.ourContribution.PaymentBasePoint.PubKey,
  1943  	)
  1944  	err = initStateHints(ourCommitTx, theirCommitTx, stateObfuscator)
  1945  	if err != nil {
  1946  		req.err <- err
  1947  		req.completeChan <- nil
  1948  		return
  1949  	}
  1950  
  1951  	// Sort both transactions according to the agreed upon canonical
  1952  	// ordering. This ensures that both parties sign the same sighash
  1953  	// without further synchronization.
  1954  	txsort.InPlaceSort(ourCommitTx)
  1955  	txsort.InPlaceSort(theirCommitTx)
  1956  	chanState.LocalCommitment.CommitTx = ourCommitTx
  1957  	chanState.RemoteCommitment.CommitTx = theirCommitTx
  1958  
  1959  	walletLog.Debugf("Local commit tx for ChannelPoint(%v): %v",
  1960  		req.fundingOutpoint, spew.Sdump(ourCommitTx))
  1961  	walletLog.Debugf("Remote commit tx for ChannelPoint(%v): %v",
  1962  		req.fundingOutpoint, spew.Sdump(theirCommitTx))
  1963  
  1964  	channelValue := int64(pendingReservation.partialState.Capacity)
  1965  	theirKey := pendingReservation.theirContribution.MultiSigKey
  1966  	ourKey := pendingReservation.ourContribution.MultiSigKey
  1967  	witnessScript, _, err := input.GenFundingPkScript(
  1968  		ourKey.PubKey.SerializeCompressed(),
  1969  		theirKey.PubKey.SerializeCompressed(), channelValue,
  1970  	)
  1971  	if err != nil {
  1972  		req.err <- err
  1973  		req.completeChan <- nil
  1974  		return
  1975  	}
  1976  
  1977  	sigHash, err := txscript.CalcSignatureHash(
  1978  		witnessScript, txscript.SigHashAll, ourCommitTx, 0, nil,
  1979  	)
  1980  	if err != nil {
  1981  		req.err <- err
  1982  		req.completeChan <- nil
  1983  		return
  1984  	}
  1985  
  1986  	// Verify that we've received a valid signature from the remote party
  1987  	// for our version of the commitment transaction.
  1988  	if !req.theirCommitmentSig.Verify(sigHash, theirKey.PubKey) {
  1989  		req.err <- fmt.Errorf("counterparty's commitment signature " +
  1990  			"is invalid")
  1991  		req.completeChan <- nil
  1992  		return
  1993  	}
  1994  	theirCommitSigBytes := req.theirCommitmentSig.Serialize()
  1995  	chanState.LocalCommitment.CommitSig = theirCommitSigBytes
  1996  
  1997  	// With their signature for our version of the commitment transactions
  1998  	// verified, we can now generate a signature for their version,
  1999  	// allowing the funding transaction to be safely broadcast.
  2000  	p2sh, err := input.ScriptHashPkScript(witnessScript)
  2001  	if err != nil {
  2002  		req.err <- err
  2003  		req.completeChan <- nil
  2004  		return
  2005  	}
  2006  	signDesc := input.SignDescriptor{
  2007  		WitnessScript: witnessScript,
  2008  		KeyDesc:       ourKey,
  2009  		Output: &wire.TxOut{
  2010  			PkScript: p2sh,
  2011  			Value:    channelValue,
  2012  		},
  2013  		HashType:   txscript.SigHashAll,
  2014  		InputIndex: 0,
  2015  	}
  2016  	sigTheirCommit, err := l.Cfg.Signer.SignOutputRaw(theirCommitTx, &signDesc)
  2017  	if err != nil {
  2018  		req.err <- err
  2019  		req.completeChan <- nil
  2020  		return
  2021  	}
  2022  	pendingReservation.ourCommitmentSig = sigTheirCommit
  2023  
  2024  	_, bestHeight, err := l.Cfg.ChainIO.GetBestBlock()
  2025  	if err != nil {
  2026  		req.err <- err
  2027  		req.completeChan <- nil
  2028  		return
  2029  	}
  2030  
  2031  	// Set optional upfront shutdown scripts on the channel state so that they
  2032  	// are persisted. These values may be nil.
  2033  	chanState.LocalShutdownScript =
  2034  		pendingReservation.ourContribution.UpfrontShutdown
  2035  	chanState.RemoteShutdownScript =
  2036  		pendingReservation.theirContribution.UpfrontShutdown
  2037  
  2038  	// Add the complete funding transaction to the DB, in it's open bucket
  2039  	// which will be used for the lifetime of this channel.
  2040  	chanState.LocalChanCfg = pendingReservation.ourContribution.toChanConfig()
  2041  	chanState.RemoteChanCfg = pendingReservation.theirContribution.toChanConfig()
  2042  
  2043  	chanState.RevocationKeyLocator = pendingReservation.nextRevocationKeyLoc
  2044  
  2045  	err = chanState.SyncPending(pendingReservation.nodeAddr, uint32(bestHeight))
  2046  	if err != nil {
  2047  		req.err <- err
  2048  		req.completeChan <- nil
  2049  		return
  2050  	}
  2051  
  2052  	req.completeChan <- chanState
  2053  	req.err <- nil
  2054  
  2055  	l.limboMtx.Lock()
  2056  	delete(l.fundingLimbo, req.pendingFundingID)
  2057  	l.limboMtx.Unlock()
  2058  
  2059  	l.intentMtx.Lock()
  2060  	delete(l.fundingIntents, pendingReservation.pendingChanID)
  2061  	l.intentMtx.Unlock()
  2062  }
  2063  
  2064  // WithCoinSelectLock will execute the passed function closure in a
  2065  // synchronized manner preventing any coin selection operations from proceeding
  2066  // while the closure is executing. This can be seen as the ability to execute a
  2067  // function closure under an exclusive coin selection lock.
  2068  func (l *LightningWallet) WithCoinSelectLock(f func() error) error {
  2069  	l.coinSelectMtx.Lock()
  2070  	defer l.coinSelectMtx.Unlock()
  2071  
  2072  	return f()
  2073  }
  2074  
  2075  // DeriveStateHintObfuscator derives the bytes to be used for obfuscating the
  2076  // state hints from the root to be used for a new channel. The obfuscator is
  2077  // generated via the following computation:
  2078  //
  2079  //   - sha256(initiatorKey || responderKey)[26:]
  2080  //   - where both keys are the multi-sig keys of the respective parties
  2081  //
  2082  // The first 6 bytes of the resulting hash are used as the state hint.
  2083  func DeriveStateHintObfuscator(key1, key2 *secp256k1.PublicKey) [StateHintSize]byte {
  2084  	h := sha256.New()
  2085  	h.Write(key1.SerializeCompressed())
  2086  	h.Write(key2.SerializeCompressed())
  2087  
  2088  	sha := h.Sum(nil)
  2089  
  2090  	var obfuscator [StateHintSize]byte
  2091  	copy(obfuscator[:], sha[26:])
  2092  
  2093  	return obfuscator
  2094  }
  2095  
  2096  // initStateHints properly sets the obfuscated state hints on both commitment
  2097  // transactions using the passed obfuscator.
  2098  func initStateHints(commit1, commit2 *wire.MsgTx,
  2099  	obfuscator [StateHintSize]byte) error {
  2100  
  2101  	if err := SetStateNumHint(commit1, 0, obfuscator); err != nil {
  2102  		return err
  2103  	}
  2104  	if err := SetStateNumHint(commit2, 0, obfuscator); err != nil {
  2105  		return err
  2106  	}
  2107  
  2108  	return nil
  2109  }
  2110  
  2111  // ValidateChannel will attempt to fully validate a newly mined channel, given
  2112  // its funding transaction and existing channel state. If this method returns
  2113  // an error, then the mined channel is invalid, and shouldn't be used.
  2114  func (l *LightningWallet) ValidateChannel(channelState *channeldb.OpenChannel,
  2115  	fundingTx *wire.MsgTx) error {
  2116  
  2117  	// First, we'll obtain a fully signed commitment transaction so we can
  2118  	// pass into it on the chanvalidate package for verification.
  2119  	channel, err := NewLightningChannel(l.Cfg.Signer, channelState, nil,
  2120  		&l.Cfg.NetParams)
  2121  	if err != nil {
  2122  		return err
  2123  	}
  2124  	signedCommitTx, err := channel.getSignedCommitTx()
  2125  	if err != nil {
  2126  		return err
  2127  	}
  2128  
  2129  	// We'll also need the multi-sig witness script itself so the
  2130  	// chanvalidate package can check it for correctness against the
  2131  	// funding transaction, and also commitment validity.
  2132  	localKey := channelState.LocalChanCfg.MultiSigKey.PubKey
  2133  	remoteKey := channelState.RemoteChanCfg.MultiSigKey.PubKey
  2134  	witnessScript, err := input.GenMultiSigScript(
  2135  		localKey.SerializeCompressed(),
  2136  		remoteKey.SerializeCompressed(),
  2137  	)
  2138  	if err != nil {
  2139  		return err
  2140  	}
  2141  	pkScript, err := input.ScriptHashPkScript(witnessScript)
  2142  	if err != nil {
  2143  		return err
  2144  	}
  2145  
  2146  	// Finally, we'll pass in all the necessary context needed to fully
  2147  	// validate that this channel is indeed what we expect, and can be
  2148  	// used.
  2149  	_, err = chanvalidate.Validate(&chanvalidate.Context{
  2150  		Locator: &chanvalidate.OutPointChanLocator{
  2151  			ChanPoint: channelState.FundingOutpoint,
  2152  		},
  2153  		MultiSigPkScript: pkScript,
  2154  		FundingTx:        fundingTx,
  2155  		CommitCtx: &chanvalidate.CommitmentContext{
  2156  			Value:               channel.Capacity,
  2157  			FullySignedCommitTx: signedCommitTx,
  2158  		},
  2159  	})
  2160  	if err != nil {
  2161  		return err
  2162  	}
  2163  
  2164  	return nil
  2165  }
  2166  
  2167  // CoinSource is a wrapper around the wallet that implements the
  2168  // chanfunding.CoinSource interface.
  2169  type CoinSource struct {
  2170  	wallet *LightningWallet
  2171  }
  2172  
  2173  // NewCoinSource creates a new instance of the CoinSource wrapper struct.
  2174  func NewCoinSource(w *LightningWallet) *CoinSource {
  2175  	return &CoinSource{wallet: w}
  2176  }
  2177  
  2178  // ListCoins returns all UTXOs from the source that have between
  2179  // minConfs and maxConfs number of confirmations.
  2180  func (c *CoinSource) ListCoins(minConfs int32,
  2181  	maxConfs int32) ([]chanfunding.Coin, error) {
  2182  
  2183  	utxos, err := c.wallet.ListUnspentWitnessFromDefaultAccount(
  2184  		minConfs, maxConfs,
  2185  	)
  2186  	if err != nil {
  2187  		return nil, err
  2188  	}
  2189  
  2190  	var coins []chanfunding.Coin
  2191  	for _, utxo := range utxos {
  2192  		coins = append(coins, chanfunding.Coin{
  2193  			TxOut: wire.TxOut{
  2194  				Value:    int64(utxo.Value),
  2195  				PkScript: utxo.PkScript,
  2196  			},
  2197  			OutPoint: utxo.OutPoint,
  2198  		})
  2199  	}
  2200  
  2201  	return coins, nil
  2202  }
  2203  
  2204  // CoinFromOutPoint attempts to locate details pertaining to a coin based on
  2205  // its outpoint. If the coin isn't under the control of the backing CoinSource,
  2206  // then an error should be returned.
  2207  func (c *CoinSource) CoinFromOutPoint(op wire.OutPoint) (*chanfunding.Coin, error) {
  2208  	inputInfo, err := c.wallet.FetchInputInfo(&op)
  2209  	if err != nil {
  2210  		return nil, err
  2211  	}
  2212  
  2213  	return &chanfunding.Coin{
  2214  		TxOut: wire.TxOut{
  2215  			Value:    int64(inputInfo.Value),
  2216  			PkScript: inputInfo.PkScript,
  2217  		},
  2218  		OutPoint: inputInfo.OutPoint,
  2219  	}, nil
  2220  }
  2221  
  2222  // shimKeyRing is a wrapper struct that's used to provide the proper multi-sig
  2223  // key for an initiated external funding flow.
  2224  type shimKeyRing struct {
  2225  	keychain.KeyRing
  2226  
  2227  	*chanfunding.ShimIntent
  2228  }
  2229  
  2230  // DeriveNextKey intercepts the normal DeriveNextKey call to a keychain.KeyRing
  2231  // instance, and supplies the multi-sig key specified by the ShimIntent. This
  2232  // allows us to transparently insert new keys into the existing funding flow,
  2233  // as these keys may not come from the wallet itself.
  2234  func (s *shimKeyRing) DeriveNextKey(keyFam keychain.KeyFamily) (keychain.KeyDescriptor, error) {
  2235  	if keyFam != keychain.KeyFamilyMultiSig {
  2236  		return s.KeyRing.DeriveNextKey(keyFam)
  2237  	}
  2238  
  2239  	fundingKeys, err := s.ShimIntent.MultiSigKeys()
  2240  	if err != nil {
  2241  		return keychain.KeyDescriptor{}, err
  2242  	}
  2243  
  2244  	return *fundingKeys.LocalKey, nil
  2245  }
  2246  
  2247  // validateUpfrontShutdown checks whether the provided upfront_shutdown_script
  2248  // is of a valid type that we accept.
  2249  func validateUpfrontShutdown(shutdown lnwire.DeliveryAddress,
  2250  	params *chaincfg.Params) bool {
  2251  
  2252  	// We don't need to worry about a large UpfrontShutdownScript since it
  2253  	// was already checked in lnwire when decoding from the wire.
  2254  	scriptClass := stdscript.DetermineScriptType(0, shutdown)
  2255  
  2256  	switch scriptClass {
  2257  	case stdscript.STPubKeyHashEcdsaSecp256k1,
  2258  		stdscript.STScriptHash:
  2259  		// The above two types are permitted according to BOLT#02.
  2260  		// Everything else is disallowed.
  2261  		return true
  2262  
  2263  	default:
  2264  		return false
  2265  	}
  2266  }