2015-12-20 09:00:50 +03:00
|
|
|
package lnwallet
|
2015-10-28 01:50:30 +03:00
|
|
|
|
|
|
|
import (
|
2017-07-30 05:20:08 +03:00
|
|
|
"bytes"
|
2017-03-16 04:56:25 +03:00
|
|
|
"crypto/sha256"
|
2018-08-10 05:16:14 +03:00
|
|
|
"errors"
|
2015-11-05 23:36:19 +03:00
|
|
|
"fmt"
|
2021-01-11 13:03:00 +03:00
|
|
|
"math"
|
2016-10-27 00:56:48 +03:00
|
|
|
"net"
|
2015-10-28 01:50:30 +03:00
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
|
2018-07-18 05:20:05 +03:00
|
|
|
"github.com/btcsuite/btcd/blockchain"
|
2018-08-10 05:16:14 +03:00
|
|
|
"github.com/btcsuite/btcd/btcec"
|
2018-07-18 05:20:05 +03:00
|
|
|
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
2018-08-10 05:16:14 +03:00
|
|
|
"github.com/btcsuite/btcd/txscript"
|
|
|
|
"github.com/btcsuite/btcd/wire"
|
|
|
|
"github.com/btcsuite/btcutil"
|
2020-03-31 10:13:16 +03:00
|
|
|
"github.com/btcsuite/btcutil/psbt"
|
2018-08-10 05:16:14 +03:00
|
|
|
"github.com/btcsuite/btcutil/txsort"
|
2016-06-21 20:37:55 +03:00
|
|
|
"github.com/davecgh/go-spew/spew"
|
2016-01-16 21:45:54 +03:00
|
|
|
"github.com/lightningnetwork/lnd/channeldb"
|
2019-01-16 17:47:43 +03:00
|
|
|
"github.com/lightningnetwork/lnd/input"
|
2018-02-18 02:20:41 +03:00
|
|
|
"github.com/lightningnetwork/lnd/keychain"
|
2019-10-31 05:43:05 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
|
2019-11-01 07:14:02 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet/chanfunding"
|
2019-10-01 05:59:10 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet/chanvalidate"
|
2017-08-22 08:49:56 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwire"
|
2018-07-18 05:20:05 +03:00
|
|
|
"github.com/lightningnetwork/lnd/shachain"
|
2015-10-28 01:50:30 +03:00
|
|
|
)
|
|
|
|
|
2015-11-13 06:34:35 +03:00
|
|
|
const (
|
2016-05-04 05:49:58 +03:00
|
|
|
// The size of the buffered queue of requests to the wallet from the
|
2015-12-28 23:14:00 +03:00
|
|
|
// outside word.
|
2015-11-13 06:34:35 +03:00
|
|
|
msgBufferSize = 100
|
2021-01-11 13:03:00 +03:00
|
|
|
|
|
|
|
// anchorChanReservedValue is the amount we'll keep around in the
|
|
|
|
// wallet in case we have to fee bump anchor channels on force close.
|
|
|
|
// TODO(halseth): update constant to target a specific commit size at
|
|
|
|
// set fee rate.
|
|
|
|
anchorChanReservedValue = btcutil.Amount(10_000)
|
2015-11-05 23:36:19 +03:00
|
|
|
)
|
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
var (
|
|
|
|
// ErrPsbtFundingRequired is the error that is returned during the
|
|
|
|
// contribution handling process if the process should be paused for
|
|
|
|
// the construction of a PSBT outside of lnd's wallet.
|
|
|
|
ErrPsbtFundingRequired = errors.New("PSBT funding required")
|
2021-01-11 13:03:00 +03:00
|
|
|
|
|
|
|
// ErrReservedValueInvalidated is returned if we try to publish a
|
|
|
|
// transaction that would take the walletbalance below what we require
|
|
|
|
// to keep around to fee bump our open anchor channels.
|
|
|
|
ErrReservedValueInvalidated = errors.New("reserved wallet balance " +
|
|
|
|
"invalidated")
|
2020-03-31 10:13:16 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// PsbtFundingRequired is a type that implements the error interface and
|
|
|
|
// contains the information needed to construct a PSBT.
|
|
|
|
type PsbtFundingRequired struct {
|
|
|
|
// Intent is the pending PSBT funding intent that needs to be funded
|
|
|
|
// if the wrapping error is returned.
|
|
|
|
Intent *chanfunding.PsbtIntent
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error returns the underlying error.
|
|
|
|
//
|
|
|
|
// NOTE: This method is part of the error interface.
|
|
|
|
func (p *PsbtFundingRequired) Error() string {
|
|
|
|
return ErrPsbtFundingRequired.Error()
|
|
|
|
}
|
|
|
|
|
2018-08-10 05:15:18 +03:00
|
|
|
// InitFundingReserveMsg is the first message sent to initiate the workflow
|
2015-12-28 23:14:00 +03:00
|
|
|
// required to open a payment channel with a remote peer. The initial required
|
2016-10-15 16:18:38 +03:00
|
|
|
// parameters are configurable across channels. These parameters are to be
|
2017-07-30 05:20:08 +03:00
|
|
|
// chosen depending on the fee climate within the network, and time value of
|
|
|
|
// funds to be locked up within the channel. Upon success a ChannelReservation
|
|
|
|
// will be created in order to track the lifetime of this pending channel.
|
|
|
|
// Outputs selected will be 'locked', making them unavailable, for any other
|
|
|
|
// pending reservations. Therefore, all channels in reservation limbo will be
|
2018-03-10 18:21:10 +03:00
|
|
|
// periodically timed out after an idle period in order to avoid "exhaustion"
|
|
|
|
// attacks.
|
2018-08-10 05:15:18 +03:00
|
|
|
type InitFundingReserveMsg struct {
|
|
|
|
// ChainHash denotes that chain to be used to ultimately open the
|
2017-07-30 05:20:08 +03:00
|
|
|
// target channel.
|
2018-08-10 05:15:18 +03:00
|
|
|
ChainHash *chainhash.Hash
|
2017-07-30 05:20:08 +03:00
|
|
|
|
2019-11-01 07:45:44 +03:00
|
|
|
// PendingChanID is the pending channel ID for this funding flow as
|
|
|
|
// used in the wire protocol.
|
|
|
|
PendingChanID [32]byte
|
|
|
|
|
2018-08-10 05:15:18 +03:00
|
|
|
// NodeID is the ID of the remote node we would like to open a channel
|
2017-05-17 05:00:19 +03:00
|
|
|
// with.
|
2018-08-10 05:15:18 +03:00
|
|
|
NodeID *btcec.PublicKey
|
2016-10-27 00:56:48 +03:00
|
|
|
|
2018-08-10 05:15:18 +03:00
|
|
|
// NodeAddr is the address port that we used to either establish or
|
2018-02-03 09:24:43 +03:00
|
|
|
// accept the connection which led to the negotiation of this funding
|
|
|
|
// workflow.
|
2018-08-10 05:15:18 +03:00
|
|
|
NodeAddr net.Addr
|
2016-10-27 00:56:48 +03:00
|
|
|
|
2019-07-11 14:14:37 +03:00
|
|
|
// SubtractFees should be set if we intend to spend exactly
|
|
|
|
// LocalFundingAmt when opening the channel, subtracting the fees from
|
|
|
|
// the funding output. This can be used for instance to use all our
|
|
|
|
// remaining funds to open the channel, since it will take fees into
|
|
|
|
// account.
|
|
|
|
SubtractFees bool
|
|
|
|
|
2019-07-11 14:14:36 +03:00
|
|
|
// LocalFundingAmt is the amount of funds requested from us for this
|
|
|
|
// channel.
|
|
|
|
LocalFundingAmt btcutil.Amount
|
2015-11-05 23:36:19 +03:00
|
|
|
|
2019-07-11 14:14:36 +03:00
|
|
|
// RemoteFundingAmnt is the amount of funds the remote will contribute
|
|
|
|
// to this channel.
|
|
|
|
RemoteFundingAmt btcutil.Amount
|
2016-06-21 20:37:55 +03:00
|
|
|
|
2018-08-10 05:15:18 +03:00
|
|
|
// CommitFeePerKw is the starting accepted satoshis/Kw fee for the set
|
2017-11-23 09:30:57 +03:00
|
|
|
// of initial commitment transactions. In order to ensure timely
|
|
|
|
// confirmation, it is recommended that this fee should be generous,
|
|
|
|
// paying some multiple of the accepted base fee rate of the network.
|
2019-10-31 05:43:05 +03:00
|
|
|
CommitFeePerKw chainfee.SatPerKWeight
|
2017-11-23 09:30:57 +03:00
|
|
|
|
2018-08-10 05:15:18 +03:00
|
|
|
// FundingFeePerKw is the fee rate in sat/kw to use for the initial
|
2018-07-28 04:27:51 +03:00
|
|
|
// funding transaction.
|
2019-10-31 05:43:05 +03:00
|
|
|
FundingFeePerKw chainfee.SatPerKWeight
|
2015-12-28 23:14:00 +03:00
|
|
|
|
2018-08-10 05:15:18 +03:00
|
|
|
// PushMSat is the number of milli-satoshis that should be pushed over
|
2017-08-22 08:49:56 +03:00
|
|
|
// the responder as part of the initial channel creation.
|
2018-08-10 05:15:18 +03:00
|
|
|
PushMSat lnwire.MilliSatoshi
|
2017-01-10 04:24:13 +03:00
|
|
|
|
2018-08-10 05:15:18 +03:00
|
|
|
// Flags are the channel flags specified by the initiator in the
|
2017-11-14 04:15:27 +03:00
|
|
|
// open_channel message.
|
2018-08-10 05:15:18 +03:00
|
|
|
Flags lnwire.FundingFlag
|
2017-11-14 04:15:27 +03:00
|
|
|
|
2018-08-10 05:24:12 +03:00
|
|
|
// MinConfs indicates the minimum number of confirmations that each
|
|
|
|
// output selected to fund the channel should satisfy.
|
|
|
|
MinConfs int32
|
|
|
|
|
2020-03-06 18:11:48 +03:00
|
|
|
// CommitType indicates what type of commitment type the channel should
|
|
|
|
// be using, like tweakless or anchors.
|
|
|
|
CommitType CommitmentType
|
2019-08-01 06:16:52 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
// ChanFunder is an optional channel funder that allows the caller to
|
|
|
|
// control exactly how the channel funding is carried out. If not
|
|
|
|
// specified, then the default chanfunding.WalletAssembler will be
|
|
|
|
// used.
|
|
|
|
ChanFunder chanfunding.Assembler
|
|
|
|
|
2017-05-17 05:00:19 +03:00
|
|
|
// err is a channel in which all errors will be sent across. Will be
|
|
|
|
// nil if this initial set is successful.
|
|
|
|
//
|
2015-12-28 23:14:00 +03:00
|
|
|
// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
|
|
|
|
err chan error
|
2015-10-28 01:50:30 +03:00
|
|
|
|
2017-05-17 05:00:19 +03:00
|
|
|
// resp is channel in which a ChannelReservation with our contributions
|
|
|
|
// filled in will be sent across this channel in the case of a
|
|
|
|
// successfully reservation initiation. In the case of an error, this
|
|
|
|
// will read a nil pointer.
|
|
|
|
//
|
2015-12-28 23:14:00 +03:00
|
|
|
// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
|
|
|
|
resp chan *ChannelReservation
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// fundingReserveCancelMsg is a message reserved for cancelling an existing
|
|
|
|
// channel reservation identified by its reservation ID. Cancelling a reservation
|
|
|
|
// frees its locked outputs up, for inclusion within further reservations.
|
2015-11-05 23:36:19 +03:00
|
|
|
type fundingReserveCancelMsg struct {
|
|
|
|
pendingFundingID uint64
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
|
2015-12-16 23:40:44 +03:00
|
|
|
err chan error // Buffered
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// addContributionMsg represents a message executing the second phase of the
|
|
|
|
// channel reservation workflow. This message carries the counterparty's
|
|
|
|
// "contribution" to the payment channel. In the case that this message is
|
|
|
|
// processed without generating any errors, then channel reservation will then
|
|
|
|
// be able to construct the funding tx, both commitment transactions, and
|
|
|
|
// finally generate signatures for all our inputs to the funding transaction,
|
|
|
|
// and for the remote node's version of the commitment transaction.
|
2015-12-22 00:53:34 +03:00
|
|
|
type addContributionMsg struct {
|
2015-11-05 23:36:19 +03:00
|
|
|
pendingFundingID uint64
|
2015-10-28 01:50:30 +03:00
|
|
|
|
2015-11-05 23:36:19 +03:00
|
|
|
// TODO(roasbeef): Should also carry SPV proofs in we're in SPV mode
|
2015-12-23 07:31:17 +03:00
|
|
|
contribution *ChannelContribution
|
2015-10-28 01:50:30 +03:00
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
|
|
|
|
err chan error
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
// continueContributionMsg represents a message that signals that the
|
|
|
|
// interrupted funding process involving a PSBT can now be continued because the
|
|
|
|
// finalized transaction is now available.
|
|
|
|
type continueContributionMsg struct {
|
|
|
|
pendingFundingID uint64
|
|
|
|
|
|
|
|
// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
|
|
|
|
err chan error
|
|
|
|
}
|
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
// addSingleContributionMsg represents a message executing the second phase of
|
|
|
|
// a single funder channel reservation workflow. This messages carries the
|
|
|
|
// counterparty's "contribution" to the payment channel. As this message is
|
|
|
|
// sent when on the responding side to a single funder workflow, no further
|
|
|
|
// action apart from storing the provided contribution is carried out.
|
|
|
|
type addSingleContributionMsg struct {
|
|
|
|
pendingFundingID uint64
|
|
|
|
|
|
|
|
contribution *ChannelContribution
|
|
|
|
|
|
|
|
// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
|
|
|
|
err chan error
|
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// addCounterPartySigsMsg represents the final message required to complete,
|
|
|
|
// and 'open' a payment channel. This message carries the counterparty's
|
|
|
|
// signatures for each of their inputs to the funding transaction, and also a
|
|
|
|
// signature allowing us to spend our version of the commitment transaction.
|
|
|
|
// If we're able to verify all the signatures are valid, the funding transaction
|
|
|
|
// will be broadcast to the network. After the funding transaction gains a
|
|
|
|
// configurable number of confirmations, the channel is officially considered
|
|
|
|
// 'open'.
|
2015-11-05 23:36:19 +03:00
|
|
|
type addCounterPartySigsMsg struct {
|
|
|
|
pendingFundingID uint64
|
2015-10-28 01:50:30 +03:00
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// Should be order of sorted inputs that are theirs. Sorting is done
|
|
|
|
// in accordance to BIP-69:
|
|
|
|
// https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki.
|
2019-01-16 17:47:43 +03:00
|
|
|
theirFundingInputScripts []*input.Script
|
2015-12-22 00:54:33 +03:00
|
|
|
|
2018-02-07 06:11:11 +03:00
|
|
|
// This should be 1/2 of the signatures needed to successfully spend our
|
2015-12-22 00:54:33 +03:00
|
|
|
// version of the commitment transaction.
|
2020-04-06 03:06:38 +03:00
|
|
|
theirCommitmentSig input.Signature
|
2015-11-05 23:36:19 +03:00
|
|
|
|
2017-01-24 05:19:54 +03:00
|
|
|
// This channel is used to return the completed channel after the wallet
|
|
|
|
// has completed all of its stages in the funding process.
|
|
|
|
completeChan chan *channeldb.OpenChannel
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
|
|
|
|
err chan error
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
// addSingleFunderSigsMsg represents the next-to-last message required to
|
|
|
|
// complete a single-funder channel workflow. Once the initiator is able to
|
|
|
|
// construct the funding transaction, they send both the outpoint and a
|
|
|
|
// signature for our version of the commitment transaction. Once this message
|
|
|
|
// is processed we (the responder) are able to construct both commitment
|
|
|
|
// transactions, signing the remote party's version.
|
|
|
|
type addSingleFunderSigsMsg struct {
|
|
|
|
pendingFundingID uint64
|
|
|
|
|
2016-06-30 22:13:46 +03:00
|
|
|
// fundingOutpoint is the outpoint of the completed funding
|
2016-06-21 20:37:55 +03:00
|
|
|
// transaction as assembled by the workflow initiator.
|
|
|
|
fundingOutpoint *wire.OutPoint
|
|
|
|
|
2016-11-16 23:54:27 +03:00
|
|
|
// theirCommitmentSig are the 1/2 of the signatures needed to
|
2018-02-07 06:11:11 +03:00
|
|
|
// successfully spend our version of the commitment transaction.
|
2020-04-06 03:06:38 +03:00
|
|
|
theirCommitmentSig input.Signature
|
2016-06-21 20:37:55 +03:00
|
|
|
|
2017-01-24 05:19:54 +03:00
|
|
|
// This channel is used to return the completed channel after the wallet
|
|
|
|
// has completed all of its stages in the funding process.
|
|
|
|
completeChan chan *channeldb.OpenChannel
|
2016-06-21 20:37:55 +03:00
|
|
|
|
|
|
|
// NOTE: In order to avoid deadlocks, this channel MUST be buffered.
|
|
|
|
err chan error
|
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// LightningWallet is a domain specific, yet general Bitcoin wallet capable of
|
|
|
|
// executing workflow required to interact with the Lightning Network. It is
|
|
|
|
// domain specific in the sense that it understands all the fancy scripts used
|
2017-11-28 02:24:45 +03:00
|
|
|
// within the Lightning Network, channel lifetimes, etc. However, it embeds a
|
2017-07-30 05:02:38 +03:00
|
|
|
// general purpose Bitcoin wallet within it. Therefore, it is also able to
|
|
|
|
// serve as a regular Bitcoin wallet which uses HD keys. The wallet is highly
|
|
|
|
// concurrent internally. All communication, and requests towards the wallet
|
|
|
|
// are dispatched as messages over channels, ensuring thread safety across all
|
2017-01-13 08:01:50 +03:00
|
|
|
// operations. Interaction has been designed independent of any peer-to-peer
|
2017-07-30 05:02:38 +03:00
|
|
|
// communication protocol, allowing the wallet to be self-contained and
|
|
|
|
// embeddable within future projects interacting with the Lightning Network.
|
|
|
|
//
|
2017-01-13 08:01:50 +03:00
|
|
|
// NOTE: At the moment the wallet requires a btcd full node, as it's dependent
|
2017-11-28 02:24:45 +03:00
|
|
|
// on btcd's websockets notifications as event triggers during the lifetime of a
|
2017-07-30 05:02:38 +03:00
|
|
|
// channel. However, once the chainntnfs package is complete, the wallet will
|
|
|
|
// be compatible with multiple RPC/notification services such as Electrum,
|
2015-12-28 23:14:00 +03:00
|
|
|
// Bitcoin Core + ZeroMQ, etc. Eventually, the wallet won't require a full-node
|
2017-07-30 05:02:38 +03:00
|
|
|
// at all, as SPV support is integrated into btcwallet.
|
2015-10-28 01:50:30 +03:00
|
|
|
type LightningWallet struct {
|
2018-06-01 01:41:41 +03:00
|
|
|
started int32 // To be used atomically.
|
|
|
|
shutdown int32 // To be used atomically.
|
|
|
|
|
|
|
|
nextFundingID uint64 // To be used atomically.
|
|
|
|
|
2017-07-30 05:02:38 +03:00
|
|
|
// Cfg is the configuration struct that will be used by the wallet to
|
|
|
|
// access the necessary interfaces and default it needs to carry on its
|
|
|
|
// duties.
|
|
|
|
Cfg Config
|
|
|
|
|
|
|
|
// WalletController is the core wallet, all non Lightning Network
|
|
|
|
// specific interaction is proxied to the internal wallet.
|
|
|
|
WalletController
|
|
|
|
|
2018-02-18 02:20:41 +03:00
|
|
|
// SecretKeyRing is the interface we'll use to derive any keys related
|
|
|
|
// to our purpose within the network including: multi-sig keys, node
|
|
|
|
// keys, revocation keys, etc.
|
|
|
|
keychain.SecretKeyRing
|
|
|
|
|
2015-12-28 23:12:18 +03:00
|
|
|
// This mutex MUST be held when performing coin selection in order to
|
|
|
|
// avoid inadvertently creating multiple funding transaction which
|
2016-10-15 16:18:38 +03:00
|
|
|
// double spend inputs across each other.
|
2015-12-28 23:12:18 +03:00
|
|
|
coinSelectMtx sync.RWMutex
|
2015-10-28 01:50:30 +03:00
|
|
|
|
2016-10-15 16:18:38 +03:00
|
|
|
// All messages to the wallet are to be sent across this channel.
|
2015-10-28 01:50:30 +03:00
|
|
|
msgChan chan interface{}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// Incomplete payment channels are stored in the map below. An intent
|
|
|
|
// to create a payment channel is tracked as a "reservation" within
|
|
|
|
// limbo. Once the final signatures have been exchanged, a reservation
|
|
|
|
// is removed from limbo. Each reservation is tracked by a unique
|
|
|
|
// monotonically integer. All requests concerning the channel MUST
|
|
|
|
// carry a valid, active funding ID.
|
2018-07-18 05:20:05 +03:00
|
|
|
fundingLimbo map[uint64]*ChannelReservation
|
2021-01-11 10:47:38 +03:00
|
|
|
|
|
|
|
// reservationIDs maps a pending channel ID to the reservation ID used
|
|
|
|
// as key in the fundingLimbo map. Used to easily look up a channel
|
|
|
|
// reservation given a pending channel ID.
|
|
|
|
reservationIDs map[[32]byte]uint64
|
|
|
|
limboMtx sync.RWMutex
|
2015-11-19 01:38:57 +03:00
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
// lockedOutPoints is a set of the currently locked outpoint. This
|
|
|
|
// information is kept in order to provide an easy way to unlock all
|
|
|
|
// the currently locked outpoints.
|
|
|
|
lockedOutPoints map[wire.OutPoint]struct{}
|
|
|
|
|
2019-11-01 07:47:27 +03:00
|
|
|
// fundingIntents houses all the "interception" registered by a caller
|
|
|
|
// using the RegisterFundingIntent method.
|
|
|
|
intentMtx sync.RWMutex
|
|
|
|
fundingIntents map[[32]byte]chanfunding.Intent
|
|
|
|
|
2018-07-18 05:20:05 +03:00
|
|
|
quit chan struct{}
|
2015-10-28 01:50:30 +03:00
|
|
|
|
|
|
|
wg sync.WaitGroup
|
2015-11-19 01:38:57 +03:00
|
|
|
|
|
|
|
// TODO(roasbeef): handle wallet lock/unlock
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// NewLightningWallet creates/opens and initializes a LightningWallet instance.
|
|
|
|
// If the wallet has never been created (according to the passed dataDir), first-time
|
|
|
|
// setup is executed.
|
2017-07-30 05:02:38 +03:00
|
|
|
func NewLightningWallet(Cfg Config) (*LightningWallet, error) {
|
2016-08-04 08:31:20 +03:00
|
|
|
|
2015-11-13 06:34:35 +03:00
|
|
|
return &LightningWallet{
|
2017-07-30 05:02:38 +03:00
|
|
|
Cfg: Cfg,
|
2018-02-18 02:20:41 +03:00
|
|
|
SecretKeyRing: Cfg.SecretKeyRing,
|
2017-07-30 05:02:38 +03:00
|
|
|
WalletController: Cfg.WalletController,
|
2016-08-13 01:50:47 +03:00
|
|
|
msgChan: make(chan interface{}, msgBufferSize),
|
|
|
|
nextFundingID: 0,
|
|
|
|
fundingLimbo: make(map[uint64]*ChannelReservation),
|
2021-01-11 10:47:38 +03:00
|
|
|
reservationIDs: make(map[[32]byte]uint64),
|
2016-08-13 01:50:47 +03:00
|
|
|
lockedOutPoints: make(map[wire.OutPoint]struct{}),
|
2019-11-01 07:47:27 +03:00
|
|
|
fundingIntents: make(map[[32]byte]chanfunding.Intent),
|
2016-08-13 01:50:47 +03:00
|
|
|
quit: make(chan struct{}),
|
2016-03-23 04:48:18 +03:00
|
|
|
}, nil
|
2015-11-05 23:34:11 +03:00
|
|
|
}
|
|
|
|
|
2015-12-29 21:44:59 +03:00
|
|
|
// Startup establishes a connection to the RPC source, and spins up all
|
2015-12-28 23:14:00 +03:00
|
|
|
// goroutines required to handle incoming messages.
|
2015-12-29 21:44:59 +03:00
|
|
|
func (l *LightningWallet) Startup() error {
|
2015-10-28 01:50:30 +03:00
|
|
|
// Already started?
|
|
|
|
if atomic.AddInt32(&l.started, 1) != 1 {
|
|
|
|
return nil
|
|
|
|
}
|
2015-11-27 09:48:42 +03:00
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
// Start the underlying wallet controller.
|
|
|
|
if err := l.Start(); err != nil {
|
2015-11-27 09:48:42 +03:00
|
|
|
return err
|
|
|
|
}
|
2015-10-28 01:50:30 +03:00
|
|
|
|
|
|
|
l.wg.Add(1)
|
2015-11-27 09:50:17 +03:00
|
|
|
// TODO(roasbeef): multiple request handlers?
|
2015-10-28 01:50:30 +03:00
|
|
|
go l.requestHandler()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-12-29 21:44:59 +03:00
|
|
|
// Shutdown gracefully stops the wallet, and all active goroutines.
|
|
|
|
func (l *LightningWallet) Shutdown() error {
|
2015-10-28 01:50:30 +03:00
|
|
|
if atomic.AddInt32(&l.shutdown, 1) != 1 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-04-24 22:39:43 +03:00
|
|
|
// Signal the underlying wallet controller to shutdown, waiting until
|
|
|
|
// all active goroutines have been shutdown.
|
2016-08-13 01:50:47 +03:00
|
|
|
if err := l.Stop(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2015-11-28 03:07:22 +03:00
|
|
|
|
2015-10-28 01:50:30 +03:00
|
|
|
close(l.quit)
|
|
|
|
l.wg.Wait()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-08-13 23:01:00 +03:00
|
|
|
// ConfirmedBalance returns the current confirmed balance of the wallet. This
|
|
|
|
// methods wraps the interal WalletController method so we're able to properly
|
|
|
|
// hold the coin select mutex while we compute the balance.
|
|
|
|
func (l *LightningWallet) ConfirmedBalance(confs int32) (btcutil.Amount, error) {
|
|
|
|
l.coinSelectMtx.Lock()
|
|
|
|
defer l.coinSelectMtx.Unlock()
|
|
|
|
|
|
|
|
return l.WalletController.ConfirmedBalance(confs)
|
|
|
|
}
|
|
|
|
|
2017-02-23 22:56:47 +03:00
|
|
|
// LockedOutpoints returns a list of all currently locked outpoint.
|
2016-08-13 01:50:47 +03:00
|
|
|
func (l *LightningWallet) LockedOutpoints() []*wire.OutPoint {
|
|
|
|
outPoints := make([]*wire.OutPoint, 0, len(l.lockedOutPoints))
|
|
|
|
for outPoint := range l.lockedOutPoints {
|
2019-11-07 13:44:58 +03:00
|
|
|
outPoint := outPoint
|
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
outPoints = append(outPoints, &outPoint)
|
|
|
|
}
|
|
|
|
|
|
|
|
return outPoints
|
|
|
|
}
|
|
|
|
|
2017-12-18 05:40:05 +03:00
|
|
|
// ResetReservations reset the volatile wallet state which tracks all currently
|
2016-08-13 01:50:47 +03:00
|
|
|
// active reservations.
|
|
|
|
func (l *LightningWallet) ResetReservations() {
|
|
|
|
l.nextFundingID = 0
|
|
|
|
l.fundingLimbo = make(map[uint64]*ChannelReservation)
|
2021-01-11 10:47:38 +03:00
|
|
|
l.reservationIDs = make(map[[32]byte]uint64)
|
2016-08-13 01:50:47 +03:00
|
|
|
|
|
|
|
for outpoint := range l.lockedOutPoints {
|
|
|
|
l.UnlockOutpoint(outpoint)
|
|
|
|
}
|
|
|
|
l.lockedOutPoints = make(map[wire.OutPoint]struct{})
|
|
|
|
}
|
|
|
|
|
|
|
|
// ActiveReservations returns a slice of all the currently active
|
2019-10-03 18:22:43 +03:00
|
|
|
// (non-canceled) reservations.
|
2016-08-13 01:50:47 +03:00
|
|
|
func (l *LightningWallet) ActiveReservations() []*ChannelReservation {
|
|
|
|
reservations := make([]*ChannelReservation, 0, len(l.fundingLimbo))
|
|
|
|
for _, reservation := range l.fundingLimbo {
|
|
|
|
reservations = append(reservations, reservation)
|
|
|
|
}
|
|
|
|
|
|
|
|
return reservations
|
|
|
|
}
|
|
|
|
|
2016-10-15 16:18:38 +03:00
|
|
|
// requestHandler is the primary goroutine(s) responsible for handling, and
|
2018-03-10 18:21:10 +03:00
|
|
|
// dispatching replies to all messages.
|
2015-10-28 01:50:30 +03:00
|
|
|
func (l *LightningWallet) requestHandler() {
|
2019-07-09 18:26:27 +03:00
|
|
|
defer l.wg.Done()
|
|
|
|
|
2015-10-28 01:50:30 +03:00
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case m := <-l.msgChan:
|
|
|
|
switch msg := m.(type) {
|
2018-08-10 05:15:18 +03:00
|
|
|
case *InitFundingReserveMsg:
|
2015-10-28 01:50:30 +03:00
|
|
|
l.handleFundingReserveRequest(msg)
|
2015-11-05 23:36:19 +03:00
|
|
|
case *fundingReserveCancelMsg:
|
2015-10-28 01:50:30 +03:00
|
|
|
l.handleFundingCancelRequest(msg)
|
2016-06-21 20:37:55 +03:00
|
|
|
case *addSingleContributionMsg:
|
|
|
|
l.handleSingleContribution(msg)
|
2015-12-22 00:53:34 +03:00
|
|
|
case *addContributionMsg:
|
|
|
|
l.handleContributionMsg(msg)
|
2020-03-31 10:13:16 +03:00
|
|
|
case *continueContributionMsg:
|
|
|
|
l.handleChanPointReady(msg)
|
2016-06-21 20:37:55 +03:00
|
|
|
case *addSingleFunderSigsMsg:
|
|
|
|
l.handleSingleFunderSigs(msg)
|
2015-11-05 23:36:19 +03:00
|
|
|
case *addCounterPartySigsMsg:
|
|
|
|
l.handleFundingCounterPartySigs(msg)
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
case <-l.quit:
|
|
|
|
// TODO: do some clean up
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-15 16:18:38 +03:00
|
|
|
// InitChannelReservation kicks off the 3-step workflow required to successfully
|
2015-12-28 23:14:00 +03:00
|
|
|
// open a payment channel with a remote node. As part of the funding
|
|
|
|
// reservation, the inputs selected for the funding transaction are 'locked'.
|
|
|
|
// This ensures that multiple channel reservations aren't double spending the
|
|
|
|
// same inputs in the funding transaction. If reservation initialization is
|
2016-10-15 16:18:38 +03:00
|
|
|
// successful, a ChannelReservation containing our completed contribution is
|
|
|
|
// returned. Our contribution contains all the items necessary to allow the
|
2017-01-13 08:01:50 +03:00
|
|
|
// counterparty to build the funding transaction, and both versions of the
|
2018-03-10 18:21:10 +03:00
|
|
|
// commitment transaction. Otherwise, an error occurred and a nil pointer along
|
|
|
|
// with an error are returned.
|
2015-12-28 23:14:00 +03:00
|
|
|
//
|
2016-06-21 20:37:55 +03:00
|
|
|
// Once a ChannelReservation has been obtained, two additional steps must be
|
|
|
|
// processed before a payment channel can be considered 'open'. The second step
|
|
|
|
// validates, and processes the counterparty's channel contribution. The third,
|
|
|
|
// and final step verifies all signatures for the inputs of the funding
|
2018-03-10 18:21:10 +03:00
|
|
|
// transaction, and that the signature we record for our version of the
|
2016-06-21 20:37:55 +03:00
|
|
|
// commitment transaction is valid.
|
2017-07-30 05:20:08 +03:00
|
|
|
func (l *LightningWallet) InitChannelReservation(
|
2018-08-10 05:16:14 +03:00
|
|
|
req *InitFundingReserveMsg) (*ChannelReservation, error) {
|
|
|
|
|
|
|
|
req.resp = make(chan *ChannelReservation, 1)
|
|
|
|
req.err = make(chan error, 1)
|
|
|
|
|
|
|
|
select {
|
|
|
|
case l.msgChan <- req:
|
|
|
|
case <-l.quit:
|
|
|
|
return nil, errors.New("wallet shutting down")
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
|
|
|
|
2018-08-10 05:16:14 +03:00
|
|
|
return <-req.resp, <-req.err
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
|
|
|
|
2019-11-01 07:47:27 +03:00
|
|
|
// RegisterFundingIntent allows a caller to signal to the wallet that if a
|
|
|
|
// pending channel ID of expectedID is found, then it can skip constructing a
|
|
|
|
// new chanfunding.Assembler, and instead use the specified chanfunding.Intent.
|
|
|
|
// As an example, this lets some of the parameters for funding transaction to
|
|
|
|
// be negotiated outside the regular funding protocol.
|
|
|
|
func (l *LightningWallet) RegisterFundingIntent(expectedID [32]byte,
|
|
|
|
shimIntent chanfunding.Intent) error {
|
|
|
|
|
|
|
|
l.intentMtx.Lock()
|
2019-11-14 08:00:30 +03:00
|
|
|
defer l.intentMtx.Unlock()
|
|
|
|
|
|
|
|
if _, ok := l.fundingIntents[expectedID]; ok {
|
|
|
|
return fmt.Errorf("pendingChanID(%x) already has intent "+
|
|
|
|
"registered", expectedID[:])
|
|
|
|
}
|
|
|
|
|
2019-11-01 07:47:27 +03:00
|
|
|
l.fundingIntents[expectedID] = shimIntent
|
2019-11-14 08:00:30 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
// PsbtFundingVerify looks up a previously registered funding intent by its
|
|
|
|
// pending channel ID and tries to advance the state machine by verifying the
|
|
|
|
// passed PSBT.
|
2021-01-11 10:47:38 +03:00
|
|
|
func (l *LightningWallet) PsbtFundingVerify(pendingChanID [32]byte,
|
2020-03-31 10:13:16 +03:00
|
|
|
packet *psbt.Packet) error {
|
|
|
|
|
|
|
|
l.intentMtx.Lock()
|
|
|
|
defer l.intentMtx.Unlock()
|
|
|
|
|
2021-01-11 10:47:38 +03:00
|
|
|
intent, ok := l.fundingIntents[pendingChanID]
|
2020-03-31 10:13:16 +03:00
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("no funding intent found for "+
|
2021-01-11 10:47:38 +03:00
|
|
|
"pendingChannelID(%x)", pendingChanID[:])
|
2020-03-31 10:13:16 +03:00
|
|
|
}
|
|
|
|
psbtIntent, ok := intent.(*chanfunding.PsbtIntent)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("incompatible funding intent")
|
|
|
|
}
|
|
|
|
err := psbtIntent.Verify(packet)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error verifying PSBT: %v", err)
|
|
|
|
}
|
|
|
|
|
2021-01-11 10:47:38 +03:00
|
|
|
// Get the channel reservation for that corresponds to this pending
|
|
|
|
// channel ID.
|
|
|
|
l.limboMtx.Lock()
|
|
|
|
pid, ok := l.reservationIDs[pendingChanID]
|
|
|
|
if !ok {
|
|
|
|
l.limboMtx.Unlock()
|
|
|
|
return fmt.Errorf("no channel reservation found for "+
|
|
|
|
"pendingChannelID(%x)", pendingChanID[:])
|
|
|
|
}
|
|
|
|
|
|
|
|
pendingReservation, ok := l.fundingLimbo[pid]
|
|
|
|
l.limboMtx.Unlock()
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("no channel reservation found for "+
|
|
|
|
"reservation ID %v", pid)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now the the PSBT has been verified, we can again check whether the
|
|
|
|
// value reserved for anchor fee bumping is respected.
|
|
|
|
numAnchors, err := l.currentNumAnchorChans()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// If this commit type is an anchor channel we add that to our counter,
|
|
|
|
// but only if we are contributing funds to the channel. This is done
|
|
|
|
// to still allow incoming channels even though we have no UTXOs
|
|
|
|
// available, as in bootstrapping phases.
|
|
|
|
if pendingReservation.partialState.ChanType.HasAnchors() &&
|
|
|
|
intent.LocalFundingAmt() > 0 {
|
|
|
|
numAnchors++
|
|
|
|
}
|
|
|
|
|
|
|
|
// We check the reserve value again, this should already have been
|
|
|
|
// checked for regular FullIntents, but now the PSBT intent is also
|
|
|
|
// populated.
|
|
|
|
return l.WithCoinSelectLock(func() error {
|
|
|
|
_, err := l.CheckReservedValue(
|
|
|
|
intent.Inputs(), intent.Outputs(), numAnchors,
|
|
|
|
)
|
|
|
|
return err
|
|
|
|
})
|
2020-03-31 10:13:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// PsbtFundingFinalize looks up a previously registered funding intent by its
|
|
|
|
// pending channel ID and tries to advance the state machine by finalizing the
|
|
|
|
// passed PSBT.
|
2020-09-07 19:02:46 +03:00
|
|
|
func (l *LightningWallet) PsbtFundingFinalize(pid [32]byte, packet *psbt.Packet,
|
|
|
|
rawTx *wire.MsgTx) error {
|
2020-03-31 10:13:16 +03:00
|
|
|
|
|
|
|
l.intentMtx.Lock()
|
|
|
|
defer l.intentMtx.Unlock()
|
|
|
|
|
|
|
|
intent, ok := l.fundingIntents[pid]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("no funding intent found for "+
|
|
|
|
"pendingChannelID(%x)", pid[:])
|
|
|
|
}
|
|
|
|
psbtIntent, ok := intent.(*chanfunding.PsbtIntent)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("incompatible funding intent")
|
|
|
|
}
|
2020-09-07 19:02:46 +03:00
|
|
|
|
|
|
|
// Either the PSBT or the raw TX must be set.
|
|
|
|
switch {
|
|
|
|
case packet != nil && rawTx == nil:
|
|
|
|
err := psbtIntent.Finalize(packet)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error finalizing PSBT: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
case rawTx != nil && packet == nil:
|
|
|
|
err := psbtIntent.FinalizeRawTX(rawTx)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error finalizing raw TX: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("either a PSBT or raw TX must be specified")
|
2020-03-31 10:13:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-11-14 08:00:30 +03:00
|
|
|
// CancelFundingIntent allows a caller to cancel a previously registered
|
|
|
|
// funding intent. If no intent was found, then an error will be returned.
|
|
|
|
func (l *LightningWallet) CancelFundingIntent(pid [32]byte) error {
|
|
|
|
l.intentMtx.Lock()
|
|
|
|
defer l.intentMtx.Unlock()
|
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
intent, ok := l.fundingIntents[pid]
|
|
|
|
if !ok {
|
2019-11-14 08:00:30 +03:00
|
|
|
return fmt.Errorf("no funding intent found for "+
|
|
|
|
"pendingChannelID(%x)", pid[:])
|
|
|
|
}
|
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
// Give the intent a chance to clean up after itself, removing coin
|
|
|
|
// locks or similar reserved resources.
|
|
|
|
intent.Cancel()
|
|
|
|
|
2019-11-14 08:00:30 +03:00
|
|
|
delete(l.fundingIntents, pid)
|
2019-11-01 07:47:27 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// handleFundingReserveRequest processes a message intending to create, and
|
|
|
|
// validate a funding reservation request.
|
2018-08-10 05:15:18 +03:00
|
|
|
func (l *LightningWallet) handleFundingReserveRequest(req *InitFundingReserveMsg) {
|
2016-10-24 04:42:03 +03:00
|
|
|
// It isn't possible to create a channel with zero funds committed.
|
2019-07-11 14:14:36 +03:00
|
|
|
if req.LocalFundingAmt+req.RemoteFundingAmt == 0 {
|
2018-02-27 20:35:56 +03:00
|
|
|
err := ErrZeroCapacity()
|
|
|
|
req.err <- err
|
2016-10-24 04:42:03 +03:00
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// If the funding request is for a different chain than the one the
|
|
|
|
// wallet is aware of, then we'll reject the request.
|
2018-08-10 05:15:18 +03:00
|
|
|
if !bytes.Equal(l.Cfg.NetParams.GenesisHash[:], req.ChainHash[:]) {
|
|
|
|
err := ErrChainMismatch(
|
|
|
|
l.Cfg.NetParams.GenesisHash, req.ChainHash,
|
|
|
|
)
|
2018-02-27 20:35:56 +03:00
|
|
|
req.err <- err
|
2017-07-30 05:20:08 +03:00
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
// If no chanFunder was provided, then we'll assume the default
|
|
|
|
// assembler, which is backed by the wallet's internal coin selection.
|
|
|
|
if req.ChanFunder == nil {
|
|
|
|
cfg := chanfunding.WalletConfig{
|
|
|
|
CoinSource: &CoinSource{l},
|
|
|
|
CoinSelectLocker: l,
|
|
|
|
CoinLocker: l,
|
|
|
|
Signer: l.Cfg.Signer,
|
|
|
|
DustLimit: DefaultDustLimit(),
|
|
|
|
}
|
|
|
|
req.ChanFunder = chanfunding.NewWalletAssembler(cfg)
|
|
|
|
}
|
|
|
|
|
2019-07-11 14:14:36 +03:00
|
|
|
localFundingAmt := req.LocalFundingAmt
|
2019-11-01 07:39:17 +03:00
|
|
|
remoteFundingAmt := req.RemoteFundingAmt
|
2019-07-11 14:14:36 +03:00
|
|
|
|
2019-07-11 14:14:36 +03:00
|
|
|
var (
|
2019-11-01 07:39:17 +03:00
|
|
|
fundingIntent chanfunding.Intent
|
|
|
|
err error
|
2019-07-11 14:14:36 +03:00
|
|
|
)
|
|
|
|
|
2019-11-01 07:47:27 +03:00
|
|
|
// If we've just received an inbound funding request that we have a
|
|
|
|
// registered shim intent to, then we'll obtain the backing intent now.
|
|
|
|
// In this case, we're doing a special funding workflow that allows
|
|
|
|
// more advanced constructions such as channel factories to be
|
|
|
|
// instantiated.
|
|
|
|
l.intentMtx.Lock()
|
|
|
|
fundingIntent, ok := l.fundingIntents[req.PendingChanID]
|
|
|
|
l.intentMtx.Unlock()
|
|
|
|
|
|
|
|
// Otherwise, this is a normal funding flow, so we'll use the chan
|
|
|
|
// funder in the attached request to provision the inputs/outputs
|
|
|
|
// that'll ultimately be used to construct the funding transaction.
|
|
|
|
if !ok {
|
2019-07-11 14:14:36 +03:00
|
|
|
// Coin selection is done on the basis of sat/kw, so we'll use
|
|
|
|
// the fee rate passed in to perform coin selection.
|
|
|
|
var err error
|
2019-11-01 07:39:17 +03:00
|
|
|
fundingReq := &chanfunding.Request{
|
|
|
|
RemoteAmt: req.RemoteFundingAmt,
|
|
|
|
LocalAmt: req.LocalFundingAmt,
|
|
|
|
MinConfs: req.MinConfs,
|
|
|
|
SubtractFees: req.SubtractFees,
|
|
|
|
FeeRate: req.FundingFeePerKw,
|
|
|
|
ChangeAddr: func() (btcutil.Address, error) {
|
|
|
|
return l.NewAddress(WitnessPubKey, true)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
fundingIntent, err = req.ChanFunder.ProvisionChannel(
|
|
|
|
fundingReq,
|
2019-07-11 14:14:36 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
2019-07-11 14:14:37 +03:00
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
// Register the funding intent now in case we need to access it
|
|
|
|
// again later, as it's the case for the PSBT state machine for
|
|
|
|
// example.
|
|
|
|
err = l.RegisterFundingIntent(req.PendingChanID, fundingIntent)
|
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
localFundingAmt = fundingIntent.LocalFundingAmt()
|
|
|
|
remoteFundingAmt = fundingIntent.RemoteFundingAmt()
|
2019-07-11 14:14:36 +03:00
|
|
|
}
|
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
// At this point there _has_ to be a funding intent, otherwise something
|
|
|
|
// went really wrong.
|
|
|
|
if fundingIntent == nil {
|
|
|
|
req.err <- fmt.Errorf("no funding intent present")
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-03-14 02:57:48 +03:00
|
|
|
// If this is a shim intent, then it may be attempting to use an
|
|
|
|
// existing set of keys for the funding workflow. In this case, we'll
|
|
|
|
// make a simple wrapper keychain.KeyRing that will proxy certain
|
|
|
|
// derivation calls to future callers.
|
|
|
|
var (
|
|
|
|
keyRing keychain.KeyRing = l.SecretKeyRing
|
|
|
|
thawHeight uint32
|
|
|
|
)
|
|
|
|
if shimIntent, ok := fundingIntent.(*chanfunding.ShimIntent); ok {
|
|
|
|
keyRing = &shimKeyRing{
|
|
|
|
KeyRing: keyRing,
|
|
|
|
ShimIntent: shimIntent,
|
|
|
|
}
|
|
|
|
|
|
|
|
// As this was a registered shim intent, we'll obtain the thaw
|
|
|
|
// height of the intent, if present at all. If this is
|
|
|
|
// non-zero, then we'll mark this as the proper channel type.
|
|
|
|
thawHeight = shimIntent.ThawHeight()
|
|
|
|
}
|
|
|
|
|
2021-01-11 10:47:38 +03:00
|
|
|
// Now that we have a funding intent, we'll check whether funding a
|
|
|
|
// channel using it would violate our reserved value for anchor channel
|
|
|
|
// fee bumping. We first get our current number of anchor channels.
|
|
|
|
numAnchors, err := l.currentNumAnchorChans()
|
|
|
|
if err != nil {
|
|
|
|
fundingIntent.Cancel()
|
|
|
|
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// If this commit type is an anchor channel we add that to our counter,
|
|
|
|
// but only if we are contributing funds to the channel. This is done
|
|
|
|
// to still allow incoming channels even though we have no UTXOs
|
|
|
|
// available, as in bootstrapping phases.
|
|
|
|
if req.CommitType == CommitmentTypeAnchorsZeroFeeHtlcTx &&
|
|
|
|
fundingIntent.LocalFundingAmt() > 0 {
|
|
|
|
numAnchors++
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check the reserved value using the inputs and outputs given by the
|
|
|
|
// intent. Not that for the PSBT intent type we don't yet have the
|
|
|
|
// funding tx ready, so this will always pass. We'll do another check
|
|
|
|
// when the PSBT has been verified.
|
|
|
|
err = l.WithCoinSelectLock(func() error {
|
|
|
|
_, err := l.CheckReservedValue(
|
|
|
|
fundingIntent.Inputs(), fundingIntent.Outputs(),
|
|
|
|
numAnchors,
|
|
|
|
)
|
|
|
|
return err
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
fundingIntent.Cancel()
|
|
|
|
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-07-11 14:14:37 +03:00
|
|
|
// The total channel capacity will be the size of the funding output we
|
|
|
|
// created plus the remote contribution.
|
2019-11-01 07:39:17 +03:00
|
|
|
capacity := localFundingAmt + remoteFundingAmt
|
2019-07-11 14:14:37 +03:00
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
id := atomic.AddUint64(&l.nextFundingID, 1)
|
2018-08-10 05:15:18 +03:00
|
|
|
reservation, err := NewChannelReservation(
|
2019-07-11 14:14:36 +03:00
|
|
|
capacity, localFundingAmt, req.CommitFeePerKw, l, id,
|
2018-08-10 05:15:18 +03:00
|
|
|
req.PushMSat, l.Cfg.NetParams.GenesisHash, req.Flags,
|
2020-03-06 18:11:48 +03:00
|
|
|
req.CommitType, req.ChanFunder, req.PendingChanID,
|
2020-03-14 02:57:48 +03:00
|
|
|
thawHeight,
|
2018-08-10 05:15:18 +03:00
|
|
|
)
|
2017-11-26 22:32:57 +03:00
|
|
|
if err != nil {
|
2020-03-31 10:13:16 +03:00
|
|
|
fundingIntent.Cancel()
|
2019-11-01 07:39:17 +03:00
|
|
|
|
2017-11-26 22:32:57 +03:00
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
2015-10-28 01:50:30 +03:00
|
|
|
|
2019-07-11 14:14:37 +03:00
|
|
|
err = l.initOurContribution(
|
2019-11-01 07:44:16 +03:00
|
|
|
reservation, fundingIntent, req.NodeAddr, req.NodeID, keyRing,
|
2019-07-11 14:14:37 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
2020-03-31 10:13:16 +03:00
|
|
|
fundingIntent.Cancel()
|
2019-11-01 07:39:17 +03:00
|
|
|
|
2019-07-11 14:14:37 +03:00
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a limbo and record entry for this newly pending funding
|
|
|
|
// request.
|
|
|
|
l.limboMtx.Lock()
|
|
|
|
l.fundingLimbo[id] = reservation
|
2021-01-11 10:47:38 +03:00
|
|
|
l.reservationIDs[req.PendingChanID] = id
|
2019-07-11 14:14:37 +03:00
|
|
|
l.limboMtx.Unlock()
|
|
|
|
|
|
|
|
// Funding reservation request successfully handled. The funding inputs
|
|
|
|
// will be marked as unavailable until the reservation is either
|
2019-10-03 18:22:43 +03:00
|
|
|
// completed, or canceled.
|
2019-07-11 14:14:37 +03:00
|
|
|
req.resp <- reservation
|
|
|
|
req.err <- nil
|
|
|
|
}
|
|
|
|
|
2021-01-11 10:47:38 +03:00
|
|
|
// currentNumAnchorChans returns the current number of anchor channels the
|
|
|
|
// wallet should be ready to fee bump if needed.
|
|
|
|
func (l *LightningWallet) currentNumAnchorChans() (int, error) {
|
|
|
|
// Count all anchor channels that are open or pending
|
|
|
|
// open, or waiting close.
|
|
|
|
chans, err := l.Cfg.Database.FetchAllChannels()
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var numAnchors int
|
|
|
|
for _, c := range chans {
|
|
|
|
if c.ChanType.HasAnchors() {
|
|
|
|
numAnchors++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We also count pending close channels.
|
|
|
|
pendingClosed, err := l.Cfg.Database.FetchClosedChannels(
|
|
|
|
true,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, c := range pendingClosed {
|
|
|
|
c, err := l.Cfg.Database.FetchHistoricalChannel(
|
|
|
|
&c.ChanPoint,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
// We don't have a guarantee that all channels re found
|
|
|
|
// in the historical channels bucket, so we continue.
|
|
|
|
walletLog.Warnf("Unable to fetch historical "+
|
|
|
|
"channel: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.ChanType.HasAnchors() {
|
|
|
|
numAnchors++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return numAnchors, nil
|
|
|
|
}
|
|
|
|
|
2021-01-11 13:03:00 +03:00
|
|
|
// CheckReservedValue checks whether publishing a transaction with the given
|
|
|
|
// inputs and outputs would violate the value we reserve in the wallet for
|
|
|
|
// bumping the fee of anchor channels. The numAnchorChans argument should be
|
|
|
|
// set the the number of open anchor channels controlled by the wallet after
|
|
|
|
// the transaction has been published.
|
|
|
|
//
|
|
|
|
// If the reserved value is violated, the returned error will be
|
|
|
|
// ErrReservedValueInvalidated. The method will also return the current
|
|
|
|
// reserved value, both in case of success and in case of
|
|
|
|
// ErrReservedValueInvalidated.
|
|
|
|
//
|
|
|
|
// NOTE: This method should only be run with the CoinSelectLock held.
|
|
|
|
func (l *LightningWallet) CheckReservedValue(in []wire.OutPoint,
|
|
|
|
out []*wire.TxOut, numAnchorChans int) (btcutil.Amount, error) {
|
|
|
|
|
|
|
|
// Get all unspent coins in the wallet.
|
|
|
|
witnessOutputs, err := l.ListUnspentWitness(0, math.MaxInt32)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ourInput := make(map[wire.OutPoint]struct{})
|
|
|
|
for _, op := range in {
|
|
|
|
ourInput[op] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// When crafting a transaction with inputs from the wallet, these coins
|
|
|
|
// will usually be locked in the process, and not be returned when
|
|
|
|
// listing unspents. In this case they have already been deducted from
|
|
|
|
// the wallet balance. In case they haven't been properly locked, we
|
|
|
|
// check whether they are still listed among our unspents and deduct
|
|
|
|
// them.
|
|
|
|
var walletBalance btcutil.Amount
|
|
|
|
for _, in := range witnessOutputs {
|
|
|
|
// Spending an unlocked wallet UTXO, don't add it to the
|
|
|
|
// balance.
|
|
|
|
if _, ok := ourInput[in.OutPoint]; ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
walletBalance += in.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now we go through the outputs of the transaction, if any of the
|
|
|
|
// outputs are paying into the wallet (likely a change output), we add
|
|
|
|
// it to our final balance.
|
|
|
|
for _, txOut := range out {
|
|
|
|
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
|
|
|
|
txOut.PkScript, &l.Cfg.NetParams,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
// Non-standard outputs can safely be skipped because
|
|
|
|
// they're not supported by the wallet.
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, addr := range addrs {
|
|
|
|
if !l.IsOurAddress(addr) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
walletBalance += btcutil.Amount(txOut.Value)
|
|
|
|
|
|
|
|
// We break since we don't want to double count the output.
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We reserve a given amount for each anchor channel.
|
|
|
|
reserved := btcutil.Amount(numAnchorChans) * anchorChanReservedValue
|
|
|
|
|
|
|
|
if walletBalance < reserved {
|
|
|
|
walletLog.Debugf("Reserved value=%v above final "+
|
|
|
|
"walletbalance=%v with %d anchor channels open",
|
|
|
|
reserved, walletBalance, numAnchorChans)
|
|
|
|
return reserved, ErrReservedValueInvalidated
|
|
|
|
}
|
|
|
|
|
|
|
|
return reserved, nil
|
|
|
|
}
|
|
|
|
|
2021-01-10 21:54:49 +03:00
|
|
|
// CheckReservedValueTx calls CheckReservedValue with the inputs and outputs
|
|
|
|
// from the given tx, with the number of anchor channels currently open in the
|
|
|
|
// database.
|
|
|
|
//
|
|
|
|
// NOTE: This method should only be run with the CoinSelectLock held.
|
|
|
|
func (l *LightningWallet) CheckReservedValueTx(tx *wire.MsgTx) (btcutil.Amount,
|
|
|
|
error) {
|
|
|
|
|
|
|
|
numAnchors, err := l.currentNumAnchorChans()
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var inputs []wire.OutPoint
|
|
|
|
for _, txIn := range tx.TxIn {
|
|
|
|
inputs = append(inputs, txIn.PreviousOutPoint)
|
|
|
|
}
|
|
|
|
|
|
|
|
return l.CheckReservedValue(inputs, tx.TxOut, numAnchors)
|
|
|
|
}
|
|
|
|
|
2019-07-11 14:14:37 +03:00
|
|
|
// initOurContribution initializes the given ChannelReservation with our coins
|
|
|
|
// and change reserved for the channel, and derives the keys to use for this
|
|
|
|
// channel.
|
|
|
|
func (l *LightningWallet) initOurContribution(reservation *ChannelReservation,
|
2019-11-01 07:39:17 +03:00
|
|
|
fundingIntent chanfunding.Intent, nodeAddr net.Addr,
|
2019-11-01 07:44:16 +03:00
|
|
|
nodeID *btcec.PublicKey, keyRing keychain.KeyRing) error {
|
2019-07-11 14:14:37 +03:00
|
|
|
|
2016-10-15 16:18:38 +03:00
|
|
|
// Grab the mutex on the ChannelReservation to ensure thread-safety
|
2015-12-19 06:39:51 +03:00
|
|
|
reservation.Lock()
|
|
|
|
defer reservation.Unlock()
|
2015-11-14 22:52:07 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
// At this point, if we have a funding intent, we'll use it to populate
|
|
|
|
// the existing reservation state entries for our coin selection.
|
|
|
|
if fundingIntent != nil {
|
|
|
|
if intent, ok := fundingIntent.(*chanfunding.FullIntent); ok {
|
|
|
|
for _, coin := range intent.InputCoins {
|
|
|
|
reservation.ourContribution.Inputs = append(
|
|
|
|
reservation.ourContribution.Inputs,
|
|
|
|
&wire.TxIn{
|
|
|
|
PreviousOutPoint: coin.OutPoint,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|
|
|
|
reservation.ourContribution.ChangeOutputs = intent.ChangeOutputs
|
|
|
|
}
|
|
|
|
|
|
|
|
reservation.fundingIntent = fundingIntent
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2019-07-11 14:14:37 +03:00
|
|
|
reservation.nodeAddr = nodeAddr
|
|
|
|
reservation.partialState.IdentityPub = nodeID
|
2019-07-11 14:14:36 +03:00
|
|
|
|
2019-07-11 14:14:37 +03:00
|
|
|
var err error
|
2019-11-01 07:44:16 +03:00
|
|
|
reservation.ourContribution.MultiSigKey, err = keyRing.DeriveNextKey(
|
2018-02-18 02:20:41 +03:00
|
|
|
keychain.KeyFamilyMultiSig,
|
|
|
|
)
|
2017-07-30 05:20:08 +03:00
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2017-07-30 05:20:08 +03:00
|
|
|
}
|
2019-11-01 07:44:16 +03:00
|
|
|
reservation.ourContribution.RevocationBasePoint, err = keyRing.DeriveNextKey(
|
2018-02-18 02:20:41 +03:00
|
|
|
keychain.KeyFamilyRevocationBase,
|
|
|
|
)
|
2017-07-30 05:20:08 +03:00
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2017-07-30 05:20:08 +03:00
|
|
|
}
|
2019-11-01 07:44:16 +03:00
|
|
|
reservation.ourContribution.HtlcBasePoint, err = keyRing.DeriveNextKey(
|
2018-02-18 02:20:41 +03:00
|
|
|
keychain.KeyFamilyHtlcBase,
|
|
|
|
)
|
2017-11-15 07:32:39 +03:00
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2017-11-15 07:32:39 +03:00
|
|
|
}
|
2019-11-01 07:44:16 +03:00
|
|
|
reservation.ourContribution.PaymentBasePoint, err = keyRing.DeriveNextKey(
|
2018-02-18 02:20:41 +03:00
|
|
|
keychain.KeyFamilyPaymentBase,
|
|
|
|
)
|
2015-12-21 02:13:14 +03:00
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2015-12-21 02:13:14 +03:00
|
|
|
}
|
2019-11-01 07:44:16 +03:00
|
|
|
reservation.ourContribution.DelayBasePoint, err = keyRing.DeriveNextKey(
|
2018-02-18 02:20:41 +03:00
|
|
|
keychain.KeyFamilyDelayBase,
|
|
|
|
)
|
2015-11-05 23:36:19 +03:00
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
|
|
|
|
// With the above keys created, we'll also need to initialization our
|
2018-02-18 02:24:43 +03:00
|
|
|
// initial revocation tree state.
|
2019-11-01 07:44:16 +03:00
|
|
|
nextRevocationKeyDesc, err := keyRing.DeriveNextKey(
|
2018-02-18 02:24:43 +03:00
|
|
|
keychain.KeyFamilyRevocationRoot,
|
|
|
|
)
|
2015-12-21 02:13:14 +03:00
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2015-12-21 02:13:14 +03:00
|
|
|
}
|
2018-02-18 02:24:43 +03:00
|
|
|
revocationRoot, err := l.DerivePrivKey(nextRevocationKeyDesc)
|
2016-03-24 10:01:35 +03:00
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2016-03-24 10:01:35 +03:00
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
|
|
|
|
// Once we have the root, we can then generate our shachain producer
|
|
|
|
// and from that generate the per-commitment point.
|
2018-02-18 02:24:43 +03:00
|
|
|
revRoot, err := chainhash.NewHash(revocationRoot.Serialize())
|
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2018-02-18 02:24:43 +03:00
|
|
|
}
|
|
|
|
producer := shachain.NewRevocationProducer(*revRoot)
|
2017-07-30 05:20:08 +03:00
|
|
|
firstPreimage, err := producer.AtIndex(0)
|
|
|
|
if err != nil {
|
2019-07-11 14:14:37 +03:00
|
|
|
return err
|
2017-07-30 05:20:08 +03:00
|
|
|
}
|
2019-01-16 17:47:43 +03:00
|
|
|
reservation.ourContribution.FirstCommitmentPoint = input.ComputeCommitmentPoint(
|
2017-07-30 05:20:08 +03:00
|
|
|
firstPreimage[:],
|
|
|
|
)
|
|
|
|
|
|
|
|
reservation.partialState.RevocationProducer = producer
|
|
|
|
reservation.ourContribution.ChannelConstraints = l.Cfg.DefaultConstraints
|
|
|
|
|
2019-07-11 14:14:37 +03:00
|
|
|
return nil
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// handleFundingReserveCancel cancels an existing channel reservation. As part
|
|
|
|
// of the cancellation, outputs previously selected as inputs for the funding
|
|
|
|
// transaction via coin selection are freed allowing future reservations to
|
|
|
|
// include them.
|
2015-11-05 23:36:19 +03:00
|
|
|
func (l *LightningWallet) handleFundingCancelRequest(req *fundingReserveCancelMsg) {
|
|
|
|
// TODO(roasbeef): holding lock too long
|
|
|
|
l.limboMtx.Lock()
|
|
|
|
defer l.limboMtx.Unlock()
|
|
|
|
|
|
|
|
pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
|
|
|
|
if !ok {
|
2017-12-14 04:15:36 +03:00
|
|
|
// TODO(roasbeef): make new error, "unknown funding state" or something
|
2017-09-25 21:25:58 +03:00
|
|
|
req.err <- fmt.Errorf("attempted to cancel non-existent funding state")
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
2015-11-05 23:36:19 +03:00
|
|
|
|
2017-12-14 04:15:36 +03:00
|
|
|
// Grab the mutex on the ChannelReservation to ensure thread-safety
|
2015-11-14 22:52:07 +03:00
|
|
|
pendingReservation.Lock()
|
|
|
|
defer pendingReservation.Unlock()
|
|
|
|
|
2017-12-14 04:15:36 +03:00
|
|
|
// Mark all previously locked outpoints as useable for future funding
|
2015-11-05 23:36:19 +03:00
|
|
|
// requests.
|
2015-12-23 07:31:17 +03:00
|
|
|
for _, unusedInput := range pendingReservation.ourContribution.Inputs {
|
2016-08-13 01:50:47 +03:00
|
|
|
delete(l.lockedOutPoints, unusedInput.PreviousOutPoint)
|
2015-12-29 21:44:59 +03:00
|
|
|
l.UnlockOutpoint(unusedInput.PreviousOutPoint)
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
|
|
|
|
2017-12-14 04:15:36 +03:00
|
|
|
// TODO(roasbeef): is it even worth it to keep track of unused keys?
|
2015-11-05 23:36:19 +03:00
|
|
|
|
|
|
|
// TODO(roasbeef): Is it possible to mark the unused change also as
|
|
|
|
// available?
|
|
|
|
|
|
|
|
delete(l.fundingLimbo, req.pendingFundingID)
|
|
|
|
|
2019-11-01 07:47:27 +03:00
|
|
|
pid := pendingReservation.pendingChanID
|
2021-01-11 10:47:38 +03:00
|
|
|
delete(l.reservationIDs, pid)
|
2019-11-01 07:47:27 +03:00
|
|
|
|
|
|
|
l.intentMtx.Lock()
|
|
|
|
if intent, ok := l.fundingIntents[pid]; ok {
|
|
|
|
intent.Cancel()
|
|
|
|
|
|
|
|
delete(l.fundingIntents, pendingReservation.pendingChanID)
|
|
|
|
}
|
|
|
|
l.intentMtx.Unlock()
|
|
|
|
|
2015-11-05 23:36:19 +03:00
|
|
|
req.err <- nil
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2017-07-30 05:18:46 +03:00
|
|
|
// CreateCommitmentTxns is a helper function that creates the initial
|
|
|
|
// commitment transaction for both parties. This function is used during the
|
|
|
|
// initial funding workflow as both sides must generate a signature for the
|
|
|
|
// remote party's commitment transaction, and verify the signature for their
|
|
|
|
// version of the commitment transaction.
|
|
|
|
func CreateCommitmentTxns(localBalance, remoteBalance btcutil.Amount,
|
|
|
|
ourChanCfg, theirChanCfg *channeldb.ChannelConfig,
|
|
|
|
localCommitPoint, remoteCommitPoint *btcec.PublicKey,
|
2020-01-06 13:42:04 +03:00
|
|
|
fundingTxIn wire.TxIn, chanType channeldb.ChannelType) (
|
|
|
|
*wire.MsgTx, *wire.MsgTx, error) {
|
2017-07-30 05:18:46 +03:00
|
|
|
|
2019-09-17 05:06:19 +03:00
|
|
|
localCommitmentKeys := DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
localCommitPoint, true, chanType, ourChanCfg, theirChanCfg,
|
2019-08-01 06:10:45 +03:00
|
|
|
)
|
2019-09-17 05:06:19 +03:00
|
|
|
remoteCommitmentKeys := DeriveCommitmentKeys(
|
2020-01-06 13:42:04 +03:00
|
|
|
remoteCommitPoint, false, chanType, ourChanCfg, theirChanCfg,
|
2019-08-01 06:10:45 +03:00
|
|
|
)
|
2017-07-30 05:18:46 +03:00
|
|
|
|
2020-01-06 13:42:03 +03:00
|
|
|
ourCommitTx, err := CreateCommitTx(
|
2020-01-06 13:42:04 +03:00
|
|
|
chanType, fundingTxIn, localCommitmentKeys, ourChanCfg,
|
2020-03-06 18:11:46 +03:00
|
|
|
theirChanCfg, localBalance, remoteBalance, 0,
|
2020-01-06 13:42:03 +03:00
|
|
|
)
|
2017-07-30 05:18:46 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
otxn := btcutil.NewTx(ourCommitTx)
|
|
|
|
if err := blockchain.CheckTransactionSanity(otxn); err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
2020-01-06 13:42:03 +03:00
|
|
|
theirCommitTx, err := CreateCommitTx(
|
2020-01-06 13:42:04 +03:00
|
|
|
chanType, fundingTxIn, remoteCommitmentKeys, theirChanCfg,
|
2020-03-06 18:11:46 +03:00
|
|
|
ourChanCfg, remoteBalance, localBalance, 0,
|
2020-01-06 13:42:03 +03:00
|
|
|
)
|
2017-07-30 05:18:46 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ttxn := btcutil.NewTx(theirCommitTx)
|
|
|
|
if err := blockchain.CheckTransactionSanity(ttxn); err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return ourCommitTx, theirCommitTx, nil
|
|
|
|
}
|
|
|
|
|
2016-10-24 04:42:03 +03:00
|
|
|
// handleContributionMsg processes the second workflow step for the lifetime of
|
|
|
|
// a channel reservation. Upon completion, the reservation will carry a
|
|
|
|
// completed funding transaction (minus the counterparty's input signatures),
|
|
|
|
// both versions of the commitment transaction, and our signature for their
|
|
|
|
// version of the commitment transaction.
|
2015-12-22 00:53:34 +03:00
|
|
|
func (l *LightningWallet) handleContributionMsg(req *addContributionMsg) {
|
2017-07-30 05:20:08 +03:00
|
|
|
|
2015-11-27 09:48:20 +03:00
|
|
|
l.limboMtx.Lock()
|
2015-11-05 23:36:19 +03:00
|
|
|
pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
|
2015-11-27 09:48:20 +03:00
|
|
|
l.limboMtx.Unlock()
|
2015-11-05 23:36:19 +03:00
|
|
|
if !ok {
|
2017-09-25 21:25:58 +03:00
|
|
|
req.err <- fmt.Errorf("attempted to update non-existent funding state")
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
|
|
|
}
|
2015-11-05 23:32:15 +03:00
|
|
|
|
2018-05-22 02:52:51 +03:00
|
|
|
// Grab the mutex on the ChannelReservation to ensure thread-safety
|
2015-11-14 22:52:07 +03:00
|
|
|
pendingReservation.Lock()
|
|
|
|
defer pendingReservation.Unlock()
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// Some temporary variables to cut down on the resolution verbosity.
|
2015-12-23 07:31:17 +03:00
|
|
|
pendingReservation.theirContribution = req.contribution
|
|
|
|
theirContribution := req.contribution
|
|
|
|
ourContribution := pendingReservation.ourContribution
|
2015-11-05 23:32:15 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
var (
|
|
|
|
chanPoint *wire.OutPoint
|
|
|
|
err error
|
2018-02-18 02:20:41 +03:00
|
|
|
)
|
2015-12-24 21:42:29 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
// At this point, we can now construct our channel point. Depending on
|
|
|
|
// which type of intent we obtained from our chanfunding.Assembler,
|
|
|
|
// we'll carry out a distinct set of steps.
|
|
|
|
switch fundingIntent := pendingReservation.fundingIntent.(type) {
|
2020-03-31 10:13:16 +03:00
|
|
|
// The transaction was created outside of the wallet and might already
|
|
|
|
// be published. Nothing left to do other than using the correct
|
|
|
|
// outpoint.
|
2019-11-01 07:44:16 +03:00
|
|
|
case *chanfunding.ShimIntent:
|
|
|
|
chanPoint, err = fundingIntent.ChanPoint()
|
|
|
|
if err != nil {
|
|
|
|
req.err <- fmt.Errorf("unable to obtain chan point: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
pendingReservation.partialState.FundingOutpoint = *chanPoint
|
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
// The user has signaled that they want to use a PSBT to construct the
|
|
|
|
// funding transaction. Because we now have the multisig keys from both
|
|
|
|
// parties, we can create the multisig script that needs to be funded
|
|
|
|
// and then pause the process until the user supplies the PSBT
|
|
|
|
// containing the eventual funding transaction.
|
|
|
|
case *chanfunding.PsbtIntent:
|
|
|
|
if fundingIntent.PendingPsbt != nil {
|
|
|
|
req.err <- fmt.Errorf("PSBT funding already in" +
|
|
|
|
"progress")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that we know our contribution, we can bind both the local
|
|
|
|
// and remote key which will be needed to calculate the multisig
|
|
|
|
// funding output in a next step.
|
|
|
|
pendingChanID := pendingReservation.pendingChanID
|
|
|
|
walletLog.Debugf("Advancing PSBT funding flow for "+
|
|
|
|
"pending_id(%x), binding keys local_key=%v, "+
|
|
|
|
"remote_key=%x", pendingChanID,
|
|
|
|
&ourContribution.MultiSigKey,
|
|
|
|
theirContribution.MultiSigKey.PubKey.SerializeCompressed())
|
|
|
|
fundingIntent.BindKeys(
|
|
|
|
&ourContribution.MultiSigKey,
|
|
|
|
theirContribution.MultiSigKey.PubKey,
|
|
|
|
)
|
|
|
|
|
|
|
|
// Exit early because we can't continue the funding flow yet.
|
|
|
|
req.err <- &PsbtFundingRequired{
|
|
|
|
Intent: fundingIntent,
|
|
|
|
}
|
|
|
|
return
|
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
case *chanfunding.FullIntent:
|
|
|
|
// Now that we know their public key, we can bind theirs as
|
|
|
|
// well as ours to the funding intent.
|
|
|
|
fundingIntent.BindKeys(
|
|
|
|
&pendingReservation.ourContribution.MultiSigKey,
|
|
|
|
theirContribution.MultiSigKey.PubKey,
|
|
|
|
)
|
2015-11-05 23:36:19 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
// With our keys bound, we can now construct+sign the final
|
|
|
|
// funding transaction and also obtain the chanPoint that
|
|
|
|
// creates the channel.
|
|
|
|
fundingTx, err := fundingIntent.CompileFundingTx(
|
|
|
|
theirContribution.Inputs,
|
|
|
|
theirContribution.ChangeOutputs,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
req.err <- fmt.Errorf("unable to construct funding "+
|
|
|
|
"tx: %v", err)
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
|
|
|
}
|
2019-11-01 07:39:17 +03:00
|
|
|
chanPoint, err = fundingIntent.ChanPoint()
|
2015-10-28 01:50:30 +03:00
|
|
|
if err != nil {
|
2019-11-01 07:39:17 +03:00
|
|
|
req.err <- fmt.Errorf("unable to obtain chan "+
|
|
|
|
"point: %v", err)
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
// Finally, we'll populate the relevant information in our
|
|
|
|
// pendingReservation so the rest of the funding flow can
|
|
|
|
// continue as normal.
|
|
|
|
pendingReservation.fundingTx = fundingTx
|
|
|
|
pendingReservation.partialState.FundingOutpoint = *chanPoint
|
|
|
|
pendingReservation.ourFundingInputScripts = make(
|
|
|
|
[]*input.Script, 0, len(ourContribution.Inputs),
|
2016-05-04 05:49:58 +03:00
|
|
|
)
|
2019-11-01 07:39:17 +03:00
|
|
|
for _, txIn := range fundingTx.TxIn {
|
|
|
|
_, err := l.FetchInputInfo(&txIn.PreviousOutPoint)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2015-10-28 01:50:30 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
pendingReservation.ourFundingInputScripts = append(
|
|
|
|
pendingReservation.ourFundingInputScripts,
|
|
|
|
&input.Script{
|
|
|
|
Witness: txIn.Witness,
|
|
|
|
SigScript: txIn.SignatureScript,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|
2016-06-21 20:37:55 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
walletLog.Debugf("Funding tx for ChannelPoint(%v) "+
|
|
|
|
"generated: %v", chanPoint, spew.Sdump(fundingTx))
|
|
|
|
}
|
2018-02-01 01:00:01 +03:00
|
|
|
|
2020-03-31 10:13:16 +03:00
|
|
|
// If we landed here and didn't exit early, it means we already have
|
|
|
|
// the channel point ready. We can jump directly to the next step.
|
|
|
|
l.handleChanPointReady(&continueContributionMsg{
|
|
|
|
pendingFundingID: req.pendingFundingID,
|
|
|
|
err: req.err,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleChanPointReady continues the funding process once the channel point
|
|
|
|
// is known and the funding transaction can be completed.
|
|
|
|
func (l *LightningWallet) handleChanPointReady(req *continueContributionMsg) {
|
|
|
|
l.limboMtx.Lock()
|
|
|
|
pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
|
|
|
|
l.limboMtx.Unlock()
|
|
|
|
if !ok {
|
|
|
|
req.err <- fmt.Errorf("attempted to update non-existent " +
|
|
|
|
"funding state")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ourContribution := pendingReservation.ourContribution
|
|
|
|
theirContribution := pendingReservation.theirContribution
|
|
|
|
chanPoint := pendingReservation.partialState.FundingOutpoint
|
|
|
|
|
|
|
|
// If we're in the PSBT funding flow, we now should have everything that
|
|
|
|
// is needed to construct and publish the full funding transaction.
|
|
|
|
intent := pendingReservation.fundingIntent
|
|
|
|
if psbtIntent, ok := intent.(*chanfunding.PsbtIntent); ok {
|
|
|
|
// With our keys bound, we can now construct+sign the final
|
|
|
|
// funding transaction and also obtain the chanPoint that
|
|
|
|
// creates the channel.
|
|
|
|
fundingTx, err := psbtIntent.CompileFundingTx()
|
|
|
|
if err != nil {
|
|
|
|
req.err <- fmt.Errorf("unable to construct funding "+
|
|
|
|
"tx: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
chanPointPtr, err := psbtIntent.ChanPoint()
|
|
|
|
if err != nil {
|
|
|
|
req.err <- fmt.Errorf("unable to obtain chan "+
|
|
|
|
"point: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, we'll populate the relevant information in our
|
|
|
|
// pendingReservation so the rest of the funding flow can
|
|
|
|
// continue as normal.
|
|
|
|
pendingReservation.fundingTx = fundingTx
|
|
|
|
pendingReservation.partialState.FundingOutpoint = *chanPointPtr
|
|
|
|
chanPoint = *chanPointPtr
|
|
|
|
pendingReservation.ourFundingInputScripts = make(
|
|
|
|
[]*input.Script, 0, len(ourContribution.Inputs),
|
|
|
|
)
|
|
|
|
for _, txIn := range fundingTx.TxIn {
|
|
|
|
pendingReservation.ourFundingInputScripts = append(
|
|
|
|
pendingReservation.ourFundingInputScripts,
|
|
|
|
&input.Script{
|
|
|
|
Witness: txIn.Witness,
|
|
|
|
SigScript: txIn.SignatureScript,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-22 00:53:34 +03:00
|
|
|
// Initialize an empty sha-chain for them, tracking the current pending
|
2017-01-13 08:01:50 +03:00
|
|
|
// revocation hash (we don't yet know the preimage so we can't add it
|
2015-12-22 00:53:34 +03:00
|
|
|
// to the chain).
|
2016-12-14 17:01:48 +03:00
|
|
|
s := shachain.NewRevocationStore()
|
|
|
|
pendingReservation.partialState.RevocationStore = s
|
2016-08-13 01:43:16 +03:00
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Store their current commitment point. We'll need this after the
|
|
|
|
// first state transition in order to verify the authenticity of the
|
|
|
|
// revocation.
|
|
|
|
chanState := pendingReservation.partialState
|
|
|
|
chanState.RemoteCurrentRevocation = theirContribution.FirstCommitmentPoint
|
2015-12-22 00:53:34 +03:00
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Create the txin to our commitment transaction; required to construct
|
2016-06-21 20:37:55 +03:00
|
|
|
// the commitment transactions.
|
2017-12-22 21:26:16 +03:00
|
|
|
fundingTxIn := wire.TxIn{
|
2020-03-31 10:13:16 +03:00
|
|
|
PreviousOutPoint: chanPoint,
|
2017-07-30 05:20:08 +03:00
|
|
|
}
|
2015-12-22 00:53:34 +03:00
|
|
|
|
|
|
|
// With the funding tx complete, create both commitment transactions.
|
2017-11-11 01:18:41 +03:00
|
|
|
localBalance := pendingReservation.partialState.LocalCommitment.LocalBalance.ToSatoshis()
|
|
|
|
remoteBalance := pendingReservation.partialState.LocalCommitment.RemoteBalance.ToSatoshis()
|
2017-07-30 05:20:08 +03:00
|
|
|
ourCommitTx, theirCommitTx, err := CreateCommitmentTxns(
|
|
|
|
localBalance, remoteBalance, ourContribution.ChannelConfig,
|
|
|
|
theirContribution.ChannelConfig,
|
|
|
|
ourContribution.FirstCommitmentPoint,
|
|
|
|
theirContribution.FirstCommitmentPoint, fundingTxIn,
|
2020-01-06 13:42:04 +03:00
|
|
|
pendingReservation.partialState.ChanType,
|
2017-07-30 05:20:08 +03:00
|
|
|
)
|
2015-12-22 00:53:34 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-11-16 23:54:27 +03:00
|
|
|
// With both commitment transactions constructed, generate the state
|
2017-09-25 21:25:58 +03:00
|
|
|
// obfuscator then use it to encode the current state number within
|
2017-07-30 05:20:08 +03:00
|
|
|
// both commitment transactions.
|
2017-09-25 21:25:58 +03:00
|
|
|
var stateObfuscator [StateHintSize]byte
|
2019-08-01 06:16:52 +03:00
|
|
|
if chanState.ChanType.IsSingleFunder() {
|
2018-01-19 00:45:30 +03:00
|
|
|
stateObfuscator = DeriveStateHintObfuscator(
|
2018-02-18 02:20:41 +03:00
|
|
|
ourContribution.PaymentBasePoint.PubKey,
|
|
|
|
theirContribution.PaymentBasePoint.PubKey,
|
2017-07-30 05:20:08 +03:00
|
|
|
)
|
|
|
|
} else {
|
2018-02-18 02:20:41 +03:00
|
|
|
ourSer := ourContribution.PaymentBasePoint.PubKey.SerializeCompressed()
|
|
|
|
theirSer := theirContribution.PaymentBasePoint.PubKey.SerializeCompressed()
|
2017-07-30 05:20:08 +03:00
|
|
|
switch bytes.Compare(ourSer, theirSer) {
|
|
|
|
case -1:
|
2018-01-19 00:45:30 +03:00
|
|
|
stateObfuscator = DeriveStateHintObfuscator(
|
2018-02-18 02:20:41 +03:00
|
|
|
ourContribution.PaymentBasePoint.PubKey,
|
|
|
|
theirContribution.PaymentBasePoint.PubKey,
|
2017-07-30 05:20:08 +03:00
|
|
|
)
|
|
|
|
default:
|
2018-01-19 00:45:30 +03:00
|
|
|
stateObfuscator = DeriveStateHintObfuscator(
|
2018-02-18 02:20:41 +03:00
|
|
|
theirContribution.PaymentBasePoint.PubKey,
|
|
|
|
ourContribution.PaymentBasePoint.PubKey,
|
2017-07-30 05:20:08 +03:00
|
|
|
)
|
2016-11-16 23:54:27 +03:00
|
|
|
}
|
|
|
|
}
|
2017-09-25 21:25:58 +03:00
|
|
|
err = initStateHints(ourCommitTx, theirCommitTx, stateObfuscator)
|
2016-11-16 23:54:27 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Sort both transactions according to the agreed upon canonical
|
2015-12-31 09:36:01 +03:00
|
|
|
// ordering. This lets us skip sending the entire transaction over,
|
|
|
|
// instead we'll just send signatures.
|
|
|
|
txsort.InPlaceSort(ourCommitTx)
|
|
|
|
txsort.InPlaceSort(theirCommitTx)
|
|
|
|
|
2018-02-01 01:00:01 +03:00
|
|
|
walletLog.Debugf("Local commit tx for ChannelPoint(%v): %v",
|
2019-11-01 07:39:17 +03:00
|
|
|
chanPoint, spew.Sdump(ourCommitTx))
|
2018-02-01 01:00:01 +03:00
|
|
|
walletLog.Debugf("Remote commit tx for ChannelPoint(%v): %v",
|
2019-11-01 07:39:17 +03:00
|
|
|
chanPoint, spew.Sdump(theirCommitTx))
|
2018-02-01 01:00:01 +03:00
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Record newly available information within the open channel state.
|
2020-03-31 10:13:16 +03:00
|
|
|
chanState.FundingOutpoint = chanPoint
|
2017-11-11 01:18:41 +03:00
|
|
|
chanState.LocalCommitment.CommitTx = ourCommitTx
|
|
|
|
chanState.RemoteCommitment.CommitTx = theirCommitTx
|
2015-12-22 00:53:34 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
// Next, we'll obtain the funding witness script, and the funding
|
|
|
|
// output itself so we can generate a valid signature for the remote
|
|
|
|
// party.
|
|
|
|
fundingIntent := pendingReservation.fundingIntent
|
|
|
|
fundingWitnessScript, fundingOutput, err := fundingIntent.FundingOutput()
|
|
|
|
if err != nil {
|
|
|
|
req.err <- fmt.Errorf("unable to obtain funding output")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-12-22 00:53:34 +03:00
|
|
|
// Generate a signature for their version of the initial commitment
|
|
|
|
// transaction.
|
2019-11-01 07:39:17 +03:00
|
|
|
ourKey := ourContribution.MultiSigKey
|
|
|
|
signDesc := input.SignDescriptor{
|
|
|
|
WitnessScript: fundingWitnessScript,
|
2018-02-18 02:20:41 +03:00
|
|
|
KeyDesc: ourKey,
|
2019-11-01 07:39:17 +03:00
|
|
|
Output: fundingOutput,
|
2016-10-24 04:42:03 +03:00
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
SigHashes: txscript.NewTxSigHashes(theirCommitTx),
|
|
|
|
InputIndex: 0,
|
2016-08-13 01:50:47 +03:00
|
|
|
}
|
2017-07-30 05:02:38 +03:00
|
|
|
sigTheirCommit, err := l.Cfg.Signer.SignOutputRaw(theirCommitTx, &signDesc)
|
2015-12-22 00:53:34 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
return
|
|
|
|
}
|
2015-12-23 07:31:17 +03:00
|
|
|
pendingReservation.ourCommitmentSig = sigTheirCommit
|
2015-12-22 00:53:34 +03:00
|
|
|
|
2015-11-05 23:36:19 +03:00
|
|
|
req.err <- nil
|
|
|
|
}
|
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
// handleSingleContribution is called as the second step to a single funder
|
|
|
|
// workflow to which we are the responder. It simply saves the remote peer's
|
|
|
|
// contribution to the channel, as solely the remote peer will contribute any
|
|
|
|
// funds to the channel.
|
|
|
|
func (l *LightningWallet) handleSingleContribution(req *addSingleContributionMsg) {
|
|
|
|
l.limboMtx.Lock()
|
|
|
|
pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
|
|
|
|
l.limboMtx.Unlock()
|
|
|
|
if !ok {
|
2017-07-30 05:20:08 +03:00
|
|
|
req.err <- fmt.Errorf("attempted to update non-existent funding state")
|
2016-06-21 20:37:55 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Grab the mutex on the channelReservation to ensure thread-safety.
|
2016-06-21 20:37:55 +03:00
|
|
|
pendingReservation.Lock()
|
|
|
|
defer pendingReservation.Unlock()
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// TODO(roasbeef): verify sanity of remote party's parameters, fail if
|
|
|
|
// disagree
|
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
// Simply record the counterparty's contribution into the pending
|
|
|
|
// reservation data as they'll be solely funding the channel entirely.
|
|
|
|
pendingReservation.theirContribution = req.contribution
|
|
|
|
theirContribution := pendingReservation.theirContribution
|
2017-07-30 05:20:08 +03:00
|
|
|
chanState := pendingReservation.partialState
|
2016-06-30 22:13:46 +03:00
|
|
|
|
|
|
|
// Initialize an empty sha-chain for them, tracking the current pending
|
2017-01-13 08:01:50 +03:00
|
|
|
// revocation hash (we don't yet know the preimage so we can't add it
|
2016-06-30 22:13:46 +03:00
|
|
|
// to the chain).
|
2016-12-14 17:01:48 +03:00
|
|
|
remotePreimageStore := shachain.NewRevocationStore()
|
2017-07-30 05:20:08 +03:00
|
|
|
chanState.RevocationStore = remotePreimageStore
|
2016-06-21 20:37:55 +03:00
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Now that we've received their first commitment point, we'll store it
|
|
|
|
// within the channel state so we can sync it to disk once the funding
|
|
|
|
// process is complete.
|
|
|
|
chanState.RemoteCurrentRevocation = theirContribution.FirstCommitmentPoint
|
2016-06-21 20:37:55 +03:00
|
|
|
|
|
|
|
req.err <- nil
|
|
|
|
}
|
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
// verifyFundingInputs attempts to verify all remote inputs to the funding
|
|
|
|
// transaction.
|
|
|
|
func (l *LightningWallet) verifyFundingInputs(fundingTx *wire.MsgTx,
|
|
|
|
remoteInputScripts []*input.Script) error {
|
2016-12-25 03:47:09 +03:00
|
|
|
|
2016-02-03 10:59:27 +03:00
|
|
|
sigIndex := 0
|
2016-05-04 05:49:58 +03:00
|
|
|
fundingHashCache := txscript.NewTxSigHashes(fundingTx)
|
2019-11-01 07:39:17 +03:00
|
|
|
inputScripts := remoteInputScripts
|
2015-12-03 03:51:46 +03:00
|
|
|
for i, txin := range fundingTx.TxIn {
|
2016-06-21 20:37:55 +03:00
|
|
|
if len(inputScripts) != 0 && len(txin.Witness) == 0 {
|
2016-05-04 05:49:58 +03:00
|
|
|
// Attach the input scripts so we can verify it below.
|
|
|
|
txin.Witness = inputScripts[sigIndex].Witness
|
2018-11-18 07:46:51 +03:00
|
|
|
txin.SignatureScript = inputScripts[sigIndex].SigScript
|
2016-02-03 10:43:12 +03:00
|
|
|
|
2016-01-07 03:15:49 +03:00
|
|
|
// Fetch the alleged previous output along with the
|
2015-12-03 03:51:46 +03:00
|
|
|
// pkscript referenced by this input.
|
2018-07-18 05:20:05 +03:00
|
|
|
//
|
|
|
|
// TODO(roasbeef): when dual funder pass actual
|
|
|
|
// height-hint
|
2019-11-21 06:54:47 +03:00
|
|
|
//
|
|
|
|
// TODO(roasbeef): this fails for neutrino always as it
|
|
|
|
// treats the height hint as an exact birthday of the
|
|
|
|
// utxo rather than a lower bound
|
|
|
|
pkScript, err := txscript.ComputePkScript(
|
|
|
|
txin.SignatureScript, txin.Witness,
|
2018-07-18 05:20:05 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
2019-11-01 07:39:17 +03:00
|
|
|
return fmt.Errorf("cannot create script: %v", err)
|
2018-07-18 05:20:05 +03:00
|
|
|
}
|
|
|
|
output, err := l.Cfg.ChainIO.GetUtxo(
|
|
|
|
&txin.PreviousOutPoint,
|
2019-11-21 06:54:47 +03:00
|
|
|
pkScript.Script(), 0, l.quit,
|
2018-07-18 05:20:05 +03:00
|
|
|
)
|
2016-01-07 03:15:49 +03:00
|
|
|
if output == nil {
|
2019-11-01 07:39:17 +03:00
|
|
|
return fmt.Errorf("input to funding tx does "+
|
|
|
|
"not exist: %v", err)
|
2015-12-03 03:51:46 +03:00
|
|
|
}
|
2016-05-04 05:49:58 +03:00
|
|
|
|
|
|
|
// Ensure that the witness+sigScript combo is valid.
|
2019-11-01 07:39:17 +03:00
|
|
|
vm, err := txscript.NewEngine(
|
|
|
|
output.PkScript, fundingTx, i,
|
|
|
|
txscript.StandardVerifyFlags, nil,
|
|
|
|
fundingHashCache, output.Value,
|
|
|
|
)
|
2015-12-03 03:51:46 +03:00
|
|
|
if err != nil {
|
2019-11-01 07:39:17 +03:00
|
|
|
return fmt.Errorf("cannot create script "+
|
2017-04-14 10:46:31 +03:00
|
|
|
"engine: %s", err)
|
2015-12-03 03:51:46 +03:00
|
|
|
}
|
|
|
|
if err = vm.Execute(); err != nil {
|
2019-11-01 07:39:17 +03:00
|
|
|
return fmt.Errorf("cannot validate "+
|
2017-04-14 10:46:31 +03:00
|
|
|
"transaction: %s", err)
|
2016-01-07 03:15:49 +03:00
|
|
|
}
|
2016-02-03 10:59:27 +03:00
|
|
|
|
|
|
|
sigIndex++
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleFundingCounterPartySigs is the final step in the channel reservation
|
|
|
|
// workflow. During this step, we validate *all* the received signatures for
|
|
|
|
// inputs to the funding transaction. If any of these are invalid, we bail,
|
|
|
|
// and forcibly cancel this funding request. Additionally, we ensure that the
|
|
|
|
// signature we received from the counterparty for our version of the commitment
|
|
|
|
// transaction allows us to spend from the funding output with the addition of
|
|
|
|
// our signature.
|
|
|
|
func (l *LightningWallet) handleFundingCounterPartySigs(msg *addCounterPartySigsMsg) {
|
|
|
|
l.limboMtx.RLock()
|
|
|
|
res, ok := l.fundingLimbo[msg.pendingFundingID]
|
|
|
|
l.limboMtx.RUnlock()
|
|
|
|
if !ok {
|
|
|
|
msg.err <- fmt.Errorf("attempted to update non-existent funding state")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Grab the mutex on the ChannelReservation to ensure thread-safety
|
|
|
|
res.Lock()
|
|
|
|
defer res.Unlock()
|
|
|
|
|
|
|
|
// Now we can complete the funding transaction by adding their
|
|
|
|
// signatures to their inputs.
|
|
|
|
res.theirFundingInputScripts = msg.theirFundingInputScripts
|
|
|
|
inputScripts := msg.theirFundingInputScripts
|
|
|
|
|
|
|
|
// Only if we have the final funding transaction do we need to verify
|
|
|
|
// the final set of inputs. Otherwise, it may be the case that the
|
|
|
|
// channel was funded via an external wallet.
|
|
|
|
fundingTx := res.fundingTx
|
|
|
|
if res.partialState.ChanType.HasFundingTx() {
|
|
|
|
err := l.verifyFundingInputs(fundingTx, inputScripts)
|
|
|
|
if err != nil {
|
|
|
|
msg.err <- err
|
|
|
|
msg.completeChan <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-28 23:13:41 +03:00
|
|
|
// At this point, we can also record and verify their signature for our
|
2015-12-22 00:54:33 +03:00
|
|
|
// commitment transaction.
|
2016-10-27 00:56:48 +03:00
|
|
|
res.theirCommitmentSig = msg.theirCommitmentSig
|
2017-11-11 01:18:41 +03:00
|
|
|
commitTx := res.partialState.LocalCommitment.CommitTx
|
2017-07-30 05:20:08 +03:00
|
|
|
ourKey := res.ourContribution.MultiSigKey
|
2016-10-27 00:56:48 +03:00
|
|
|
theirKey := res.theirContribution.MultiSigKey
|
2015-12-28 23:13:41 +03:00
|
|
|
|
2016-10-16 02:02:09 +03:00
|
|
|
// Re-generate both the witnessScript and p2sh output. We sign the
|
|
|
|
// witnessScript script, but include the p2sh output as the subscript
|
2015-12-28 23:13:41 +03:00
|
|
|
// for verification.
|
2019-01-16 17:47:43 +03:00
|
|
|
witnessScript, _, err := input.GenFundingPkScript(
|
2018-02-18 02:20:41 +03:00
|
|
|
ourKey.PubKey.SerializeCompressed(),
|
|
|
|
theirKey.PubKey.SerializeCompressed(),
|
|
|
|
int64(res.partialState.Capacity),
|
|
|
|
)
|
2017-07-30 05:20:08 +03:00
|
|
|
if err != nil {
|
|
|
|
msg.err <- err
|
|
|
|
msg.completeChan <- nil
|
|
|
|
return
|
|
|
|
}
|
2015-12-28 23:13:41 +03:00
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
// Next, create the spending scriptSig, and then verify that the script
|
|
|
|
// is complete, allowing us to spend from the funding transaction.
|
2016-10-27 00:56:48 +03:00
|
|
|
channelValue := int64(res.partialState.Capacity)
|
2017-11-11 01:18:41 +03:00
|
|
|
hashCache := txscript.NewTxSigHashes(commitTx)
|
2019-11-01 07:39:17 +03:00
|
|
|
sigHash, err := txscript.CalcWitnessSigHash(
|
|
|
|
witnessScript, hashCache, txscript.SigHashAll, commitTx,
|
|
|
|
0, channelValue,
|
|
|
|
)
|
2015-12-28 23:13:41 +03:00
|
|
|
if err != nil {
|
2017-09-26 04:45:46 +03:00
|
|
|
msg.err <- err
|
2017-04-14 10:46:31 +03:00
|
|
|
msg.completeChan <- nil
|
2015-12-28 23:13:41 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
// Verify that we've received a valid signature from the remote party
|
|
|
|
// for our version of the commitment transaction.
|
2020-04-06 03:06:38 +03:00
|
|
|
if !msg.theirCommitmentSig.Verify(sigHash, theirKey.PubKey) {
|
2016-08-13 01:50:47 +03:00
|
|
|
msg.err <- fmt.Errorf("counterparty's commitment signature is invalid")
|
2017-04-14 10:46:31 +03:00
|
|
|
msg.completeChan <- nil
|
2015-12-28 23:13:41 +03:00
|
|
|
return
|
|
|
|
}
|
2020-04-06 03:06:38 +03:00
|
|
|
theirCommitSigBytes := msg.theirCommitmentSig.Serialize()
|
|
|
|
res.partialState.LocalCommitment.CommitSig = theirCommitSigBytes
|
2016-07-06 02:53:55 +03:00
|
|
|
|
2015-12-19 06:39:51 +03:00
|
|
|
// Funding complete, this entry can be removed from limbo.
|
2015-11-13 05:43:32 +03:00
|
|
|
l.limboMtx.Lock()
|
2016-10-27 00:56:48 +03:00
|
|
|
delete(l.fundingLimbo, res.reservationID)
|
2021-01-11 10:47:38 +03:00
|
|
|
delete(l.reservationIDs, res.pendingChanID)
|
2015-11-13 05:43:32 +03:00
|
|
|
l.limboMtx.Unlock()
|
2015-11-05 23:36:19 +03:00
|
|
|
|
2019-11-01 07:47:27 +03:00
|
|
|
l.intentMtx.Lock()
|
|
|
|
delete(l.fundingIntents, res.pendingChanID)
|
|
|
|
l.intentMtx.Unlock()
|
|
|
|
|
2017-06-06 01:05:35 +03:00
|
|
|
// As we're about to broadcast the funding transaction, we'll take note
|
|
|
|
// of the current height for record keeping purposes.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): this info can also be piped into light client's
|
|
|
|
// basic fee estimation?
|
2017-07-30 05:02:38 +03:00
|
|
|
_, bestHeight, err := l.Cfg.ChainIO.GetBestBlock()
|
2017-06-06 01:05:35 +03:00
|
|
|
if err != nil {
|
|
|
|
msg.err <- err
|
|
|
|
msg.completeChan <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// As we've completed the funding process, we'll no convert the
|
|
|
|
// contribution structs into their underlying channel config objects to
|
|
|
|
// he stored within the database.
|
|
|
|
res.partialState.LocalChanCfg = res.ourContribution.toChanConfig()
|
|
|
|
res.partialState.RemoteChanCfg = res.theirContribution.toChanConfig()
|
2016-06-21 20:37:55 +03:00
|
|
|
|
2018-03-11 04:28:17 +03:00
|
|
|
// We'll also record the finalized funding txn, which will allow us to
|
|
|
|
// rebroadcast on startup in case we fail.
|
|
|
|
res.partialState.FundingTxn = fundingTx
|
|
|
|
|
2019-12-03 12:38:29 +03:00
|
|
|
// Set optional upfront shutdown scripts on the channel state so that they
|
|
|
|
// are persisted. These values may be nil.
|
|
|
|
res.partialState.LocalShutdownScript =
|
|
|
|
res.ourContribution.UpfrontShutdown
|
|
|
|
res.partialState.RemoteShutdownScript =
|
|
|
|
res.theirContribution.UpfrontShutdown
|
|
|
|
|
2018-02-07 06:13:07 +03:00
|
|
|
// Add the complete funding transaction to the DB, in its open bucket
|
2015-12-03 03:51:21 +03:00
|
|
|
// which will be used for the lifetime of this channel.
|
2016-10-27 00:56:48 +03:00
|
|
|
nodeAddr := res.nodeAddr
|
2017-06-06 01:05:35 +03:00
|
|
|
err = res.partialState.SyncPending(nodeAddr, uint32(bestHeight))
|
|
|
|
if err != nil {
|
2016-03-24 10:01:35 +03:00
|
|
|
msg.err <- err
|
2017-04-14 10:46:31 +03:00
|
|
|
msg.completeChan <- nil
|
2016-03-24 10:01:35 +03:00
|
|
|
return
|
|
|
|
}
|
2015-12-03 03:51:21 +03:00
|
|
|
|
2017-01-24 05:19:54 +03:00
|
|
|
msg.completeChan <- res.partialState
|
2016-03-24 10:01:35 +03:00
|
|
|
msg.err <- nil
|
2015-11-13 05:43:32 +03:00
|
|
|
}
|
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
// handleSingleFunderSigs is called once the remote peer who initiated the
|
|
|
|
// single funder workflow has assembled the funding transaction, and generated
|
|
|
|
// a signature for our version of the commitment transaction. This method
|
|
|
|
// progresses the workflow by generating a signature for the remote peer's
|
|
|
|
// version of the commitment transaction.
|
|
|
|
func (l *LightningWallet) handleSingleFunderSigs(req *addSingleFunderSigsMsg) {
|
|
|
|
l.limboMtx.RLock()
|
|
|
|
pendingReservation, ok := l.fundingLimbo[req.pendingFundingID]
|
|
|
|
l.limboMtx.RUnlock()
|
|
|
|
if !ok {
|
2017-09-25 21:25:58 +03:00
|
|
|
req.err <- fmt.Errorf("attempted to update non-existent funding state")
|
2017-04-14 10:46:31 +03:00
|
|
|
req.completeChan <- nil
|
2016-06-21 20:37:55 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-07-30 05:02:38 +03:00
|
|
|
// Grab the mutex on the ChannelReservation to ensure thread-safety
|
2016-06-21 20:37:55 +03:00
|
|
|
pendingReservation.Lock()
|
|
|
|
defer pendingReservation.Unlock()
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
chanState := pendingReservation.partialState
|
|
|
|
chanState.FundingOutpoint = *req.fundingOutpoint
|
2016-06-21 20:37:55 +03:00
|
|
|
fundingTxIn := wire.NewTxIn(req.fundingOutpoint, nil, nil)
|
|
|
|
|
|
|
|
// Now that we have the funding outpoint, we can generate both versions
|
|
|
|
// of the commitment transaction, and generate a signature for the
|
|
|
|
// remote node's commitment transactions.
|
2017-11-11 01:18:41 +03:00
|
|
|
localBalance := pendingReservation.partialState.LocalCommitment.LocalBalance.ToSatoshis()
|
|
|
|
remoteBalance := pendingReservation.partialState.LocalCommitment.RemoteBalance.ToSatoshis()
|
2017-07-30 05:20:08 +03:00
|
|
|
ourCommitTx, theirCommitTx, err := CreateCommitmentTxns(
|
|
|
|
localBalance, remoteBalance,
|
|
|
|
pendingReservation.ourContribution.ChannelConfig,
|
|
|
|
pendingReservation.theirContribution.ChannelConfig,
|
|
|
|
pendingReservation.ourContribution.FirstCommitmentPoint,
|
|
|
|
pendingReservation.theirContribution.FirstCommitmentPoint,
|
2020-01-06 13:42:04 +03:00
|
|
|
*fundingTxIn, pendingReservation.partialState.ChanType,
|
2017-07-30 05:20:08 +03:00
|
|
|
)
|
2017-12-15 01:04:30 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.completeChan <- nil
|
|
|
|
return
|
|
|
|
}
|
2016-06-21 20:37:55 +03:00
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// With both commitment transactions constructed, we can now use the
|
|
|
|
// generator state obfuscator to encode the current state number within
|
2016-11-16 23:54:27 +03:00
|
|
|
// both commitment transactions.
|
2018-01-19 00:45:30 +03:00
|
|
|
stateObfuscator := DeriveStateHintObfuscator(
|
2018-02-18 02:20:41 +03:00
|
|
|
pendingReservation.theirContribution.PaymentBasePoint.PubKey,
|
|
|
|
pendingReservation.ourContribution.PaymentBasePoint.PubKey,
|
|
|
|
)
|
2017-09-25 21:25:58 +03:00
|
|
|
err = initStateHints(ourCommitTx, theirCommitTx, stateObfuscator)
|
2016-11-16 23:54:27 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
2017-04-14 10:46:31 +03:00
|
|
|
req.completeChan <- nil
|
2016-11-16 23:54:27 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Sort both transactions according to the agreed upon canonical
|
2016-06-21 20:37:55 +03:00
|
|
|
// ordering. This ensures that both parties sign the same sighash
|
|
|
|
// without further synchronization.
|
|
|
|
txsort.InPlaceSort(ourCommitTx)
|
|
|
|
txsort.InPlaceSort(theirCommitTx)
|
2017-11-11 01:18:41 +03:00
|
|
|
chanState.LocalCommitment.CommitTx = ourCommitTx
|
|
|
|
chanState.RemoteCommitment.CommitTx = theirCommitTx
|
2016-06-21 20:37:55 +03:00
|
|
|
|
2018-02-01 01:00:01 +03:00
|
|
|
walletLog.Debugf("Local commit tx for ChannelPoint(%v): %v",
|
|
|
|
req.fundingOutpoint, spew.Sdump(ourCommitTx))
|
|
|
|
walletLog.Debugf("Remote commit tx for ChannelPoint(%v): %v",
|
|
|
|
req.fundingOutpoint, spew.Sdump(theirCommitTx))
|
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
channelValue := int64(pendingReservation.partialState.Capacity)
|
|
|
|
hashCache := txscript.NewTxSigHashes(ourCommitTx)
|
|
|
|
theirKey := pendingReservation.theirContribution.MultiSigKey
|
2017-07-30 05:20:08 +03:00
|
|
|
ourKey := pendingReservation.ourContribution.MultiSigKey
|
2019-01-16 17:47:43 +03:00
|
|
|
witnessScript, _, err := input.GenFundingPkScript(
|
2018-02-18 02:20:41 +03:00
|
|
|
ourKey.PubKey.SerializeCompressed(),
|
|
|
|
theirKey.PubKey.SerializeCompressed(), channelValue,
|
|
|
|
)
|
2017-07-30 05:20:08 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.completeChan <- nil
|
|
|
|
return
|
|
|
|
}
|
2016-08-13 01:50:47 +03:00
|
|
|
|
2019-11-01 07:39:17 +03:00
|
|
|
sigHash, err := txscript.CalcWitnessSigHash(
|
|
|
|
witnessScript, hashCache, txscript.SigHashAll, ourCommitTx, 0,
|
|
|
|
channelValue,
|
|
|
|
)
|
2016-06-21 20:37:55 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
2017-04-14 10:46:31 +03:00
|
|
|
req.completeChan <- nil
|
2016-06-21 20:37:55 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
// Verify that we've received a valid signature from the remote party
|
|
|
|
// for our version of the commitment transaction.
|
2020-04-06 03:06:38 +03:00
|
|
|
if !req.theirCommitmentSig.Verify(sigHash, theirKey.PubKey) {
|
2018-02-18 02:20:41 +03:00
|
|
|
req.err <- fmt.Errorf("counterparty's commitment signature " +
|
|
|
|
"is invalid")
|
2017-04-14 10:46:31 +03:00
|
|
|
req.completeChan <- nil
|
2016-06-21 20:37:55 +03:00
|
|
|
return
|
|
|
|
}
|
2020-04-06 03:06:38 +03:00
|
|
|
theirCommitSigBytes := req.theirCommitmentSig.Serialize()
|
|
|
|
chanState.LocalCommitment.CommitSig = theirCommitSigBytes
|
2016-07-06 02:53:55 +03:00
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
// With their signature for our version of the commitment transactions
|
|
|
|
// verified, we can now generate a signature for their version,
|
|
|
|
// allowing the funding transaction to be safely broadcast.
|
2019-01-16 17:47:43 +03:00
|
|
|
p2wsh, err := input.WitnessScriptHash(witnessScript)
|
2016-08-13 01:50:47 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
2017-04-14 10:46:31 +03:00
|
|
|
req.completeChan <- nil
|
2016-08-13 01:50:47 +03:00
|
|
|
return
|
|
|
|
}
|
2019-01-16 17:47:43 +03:00
|
|
|
signDesc := input.SignDescriptor{
|
2016-10-16 02:02:09 +03:00
|
|
|
WitnessScript: witnessScript,
|
2018-02-18 02:20:41 +03:00
|
|
|
KeyDesc: ourKey,
|
2016-08-13 01:50:47 +03:00
|
|
|
Output: &wire.TxOut{
|
|
|
|
PkScript: p2wsh,
|
|
|
|
Value: channelValue,
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
SigHashes: txscript.NewTxSigHashes(theirCommitTx),
|
|
|
|
InputIndex: 0,
|
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
sigTheirCommit, err := l.Cfg.Signer.SignOutputRaw(theirCommitTx, &signDesc)
|
2016-06-21 20:37:55 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
2017-04-14 10:46:31 +03:00
|
|
|
req.completeChan <- nil
|
2016-06-21 20:37:55 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
pendingReservation.ourCommitmentSig = sigTheirCommit
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
_, bestHeight, err := l.Cfg.ChainIO.GetBestBlock()
|
2017-06-06 01:05:35 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.completeChan <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-12-03 12:38:29 +03:00
|
|
|
// Set optional upfront shutdown scripts on the channel state so that they
|
|
|
|
// are persisted. These values may be nil.
|
|
|
|
chanState.LocalShutdownScript =
|
|
|
|
pendingReservation.ourContribution.UpfrontShutdown
|
|
|
|
chanState.RemoteShutdownScript =
|
|
|
|
pendingReservation.theirContribution.UpfrontShutdown
|
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
// Add the complete funding transaction to the DB, in it's open bucket
|
|
|
|
// which will be used for the lifetime of this channel.
|
2017-07-30 05:20:08 +03:00
|
|
|
chanState.LocalChanCfg = pendingReservation.ourContribution.toChanConfig()
|
|
|
|
chanState.RemoteChanCfg = pendingReservation.theirContribution.toChanConfig()
|
|
|
|
err = chanState.SyncPending(pendingReservation.nodeAddr, uint32(bestHeight))
|
2017-05-17 05:00:19 +03:00
|
|
|
if err != nil {
|
2017-01-23 02:06:28 +03:00
|
|
|
req.err <- err
|
2017-04-14 10:46:31 +03:00
|
|
|
req.completeChan <- nil
|
2017-01-23 02:06:28 +03:00
|
|
|
return
|
|
|
|
}
|
2016-06-21 20:37:55 +03:00
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
req.completeChan <- chanState
|
2017-01-23 02:06:28 +03:00
|
|
|
req.err <- nil
|
2017-01-31 07:21:52 +03:00
|
|
|
|
|
|
|
l.limboMtx.Lock()
|
|
|
|
delete(l.fundingLimbo, req.pendingFundingID)
|
|
|
|
l.limboMtx.Unlock()
|
2019-11-01 07:47:27 +03:00
|
|
|
|
|
|
|
l.intentMtx.Lock()
|
|
|
|
delete(l.fundingIntents, pendingReservation.pendingChanID)
|
|
|
|
l.intentMtx.Unlock()
|
2016-01-07 03:17:18 +03:00
|
|
|
}
|
|
|
|
|
2018-11-18 08:06:59 +03:00
|
|
|
// WithCoinSelectLock will execute the passed function closure in a
|
|
|
|
// synchronized manner preventing any coin selection operations from proceeding
|
2020-03-19 07:43:49 +03:00
|
|
|
// while the closure is executing. This can be seen as the ability to execute a
|
2018-11-18 08:06:59 +03:00
|
|
|
// function closure under an exclusive coin selection lock.
|
|
|
|
func (l *LightningWallet) WithCoinSelectLock(f func() error) error {
|
|
|
|
l.coinSelectMtx.Lock()
|
|
|
|
defer l.coinSelectMtx.Unlock()
|
|
|
|
|
|
|
|
return f()
|
|
|
|
}
|
|
|
|
|
2018-01-19 00:45:30 +03:00
|
|
|
// DeriveStateHintObfuscator derives the bytes to be used for obfuscating the
|
2018-02-07 06:11:11 +03:00
|
|
|
// state hints from the root to be used for a new channel. The obfuscator is
|
2017-07-30 04:39:58 +03:00
|
|
|
// generated via the following computation:
|
|
|
|
//
|
2017-09-12 18:38:26 +03:00
|
|
|
// * sha256(initiatorKey || responderKey)[26:]
|
2017-07-30 04:39:58 +03:00
|
|
|
// * where both keys are the multi-sig keys of the respective parties
|
|
|
|
//
|
|
|
|
// The first 6 bytes of the resulting hash are used as the state hint.
|
2018-01-19 00:45:30 +03:00
|
|
|
func DeriveStateHintObfuscator(key1, key2 *btcec.PublicKey) [StateHintSize]byte {
|
2017-07-30 04:39:58 +03:00
|
|
|
h := sha256.New()
|
|
|
|
h.Write(key1.SerializeCompressed())
|
|
|
|
h.Write(key2.SerializeCompressed())
|
2016-11-16 23:54:27 +03:00
|
|
|
|
2017-07-30 04:39:58 +03:00
|
|
|
sha := h.Sum(nil)
|
2016-11-16 23:54:27 +03:00
|
|
|
|
2017-07-30 04:39:58 +03:00
|
|
|
var obfuscator [StateHintSize]byte
|
2017-09-12 18:38:26 +03:00
|
|
|
copy(obfuscator[:], sha[26:])
|
2016-11-16 23:54:27 +03:00
|
|
|
|
2017-07-30 04:39:58 +03:00
|
|
|
return obfuscator
|
2016-11-16 23:54:27 +03:00
|
|
|
}
|
|
|
|
|
2018-02-07 06:11:11 +03:00
|
|
|
// initStateHints properly sets the obfuscated state hints on both commitment
|
2017-09-25 21:25:58 +03:00
|
|
|
// transactions using the passed obfuscator.
|
2016-11-16 23:54:27 +03:00
|
|
|
func initStateHints(commit1, commit2 *wire.MsgTx,
|
2016-12-14 17:01:48 +03:00
|
|
|
obfuscator [StateHintSize]byte) error {
|
2016-11-16 23:54:27 +03:00
|
|
|
|
2016-12-14 17:01:48 +03:00
|
|
|
if err := SetStateNumHint(commit1, 0, obfuscator); err != nil {
|
2016-11-16 23:54:27 +03:00
|
|
|
return err
|
|
|
|
}
|
2016-12-14 17:01:48 +03:00
|
|
|
if err := SetStateNumHint(commit2, 0, obfuscator); err != nil {
|
2016-11-16 23:54:27 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-10-01 05:59:10 +03:00
|
|
|
// ValidateChannel will attempt to fully validate a newly mined channel, given
|
|
|
|
// its funding transaction and existing channel state. If this method returns
|
|
|
|
// an error, then the mined channel is invalid, and shouldn't be used.
|
|
|
|
func (l *LightningWallet) ValidateChannel(channelState *channeldb.OpenChannel,
|
|
|
|
fundingTx *wire.MsgTx) error {
|
|
|
|
|
|
|
|
// First, we'll obtain a fully signed commitment transaction so we can
|
|
|
|
// pass into it on the chanvalidate package for verification.
|
|
|
|
channel, err := NewLightningChannel(l.Cfg.Signer, channelState, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
signedCommitTx, err := channel.getSignedCommitTx()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// We'll also need the multi-sig witness script itself so the
|
|
|
|
// chanvalidate package can check it for correctness against the
|
|
|
|
// funding transaction, and also commitment validity.
|
|
|
|
localKey := channelState.LocalChanCfg.MultiSigKey.PubKey
|
|
|
|
remoteKey := channelState.RemoteChanCfg.MultiSigKey.PubKey
|
|
|
|
witnessScript, err := input.GenMultiSigScript(
|
|
|
|
localKey.SerializeCompressed(),
|
|
|
|
remoteKey.SerializeCompressed(),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
pkScript, err := input.WitnessScriptHash(witnessScript)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, we'll pass in all the necessary context needed to fully
|
|
|
|
// validate that this channel is indeed what we expect, and can be
|
|
|
|
// used.
|
|
|
|
_, err = chanvalidate.Validate(&chanvalidate.Context{
|
|
|
|
Locator: &chanvalidate.OutPointChanLocator{
|
|
|
|
ChanPoint: channelState.FundingOutpoint,
|
|
|
|
},
|
|
|
|
MultiSigPkScript: pkScript,
|
|
|
|
FundingTx: fundingTx,
|
|
|
|
CommitCtx: &chanvalidate.CommitmentContext{
|
|
|
|
Value: channel.Capacity,
|
|
|
|
FullySignedCommitTx: signedCommitTx,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2019-11-01 07:39:17 +03:00
|
|
|
|
|
|
|
// CoinSource is a wrapper around the wallet that implements the
|
|
|
|
// chanfunding.CoinSource interface.
|
|
|
|
type CoinSource struct {
|
|
|
|
wallet *LightningWallet
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewCoinSource creates a new instance of the CoinSource wrapper struct.
|
|
|
|
func NewCoinSource(w *LightningWallet) *CoinSource {
|
|
|
|
return &CoinSource{wallet: w}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ListCoins returns all UTXOs from the source that have between
|
|
|
|
// minConfs and maxConfs number of confirmations.
|
|
|
|
func (c *CoinSource) ListCoins(minConfs int32,
|
|
|
|
maxConfs int32) ([]chanfunding.Coin, error) {
|
|
|
|
|
|
|
|
utxos, err := c.wallet.ListUnspentWitness(minConfs, maxConfs)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var coins []chanfunding.Coin
|
|
|
|
for _, utxo := range utxos {
|
|
|
|
coins = append(coins, chanfunding.Coin{
|
|
|
|
TxOut: wire.TxOut{
|
|
|
|
Value: int64(utxo.Value),
|
|
|
|
PkScript: utxo.PkScript,
|
|
|
|
},
|
|
|
|
OutPoint: utxo.OutPoint,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return coins, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// CoinFromOutPoint attempts to locate details pertaining to a coin based on
|
|
|
|
// its outpoint. If the coin isn't under the control of the backing CoinSource,
|
|
|
|
// then an error should be returned.
|
|
|
|
func (c *CoinSource) CoinFromOutPoint(op wire.OutPoint) (*chanfunding.Coin, error) {
|
|
|
|
inputInfo, err := c.wallet.FetchInputInfo(&op)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &chanfunding.Coin{
|
|
|
|
TxOut: wire.TxOut{
|
|
|
|
Value: int64(inputInfo.Value),
|
|
|
|
PkScript: inputInfo.PkScript,
|
|
|
|
},
|
|
|
|
OutPoint: inputInfo.OutPoint,
|
|
|
|
}, nil
|
|
|
|
}
|
2019-11-01 07:44:16 +03:00
|
|
|
|
|
|
|
// shimKeyRing is a wrapper struct that's used to provide the proper multi-sig
|
|
|
|
// key for an initiated external funding flow.
|
|
|
|
type shimKeyRing struct {
|
|
|
|
keychain.KeyRing
|
|
|
|
|
|
|
|
*chanfunding.ShimIntent
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeriveNextKey intercepts the normal DeriveNextKey call to a keychain.KeyRing
|
|
|
|
// instance, and supplies the multi-sig key specified by the ShimIntent. This
|
|
|
|
// allows us to transparently insert new keys into the existing funding flow,
|
|
|
|
// as these keys may not come from the wallet itself.
|
|
|
|
func (s *shimKeyRing) DeriveNextKey(keyFam keychain.KeyFamily) (keychain.KeyDescriptor, error) {
|
|
|
|
if keyFam != keychain.KeyFamilyMultiSig {
|
|
|
|
return s.KeyRing.DeriveNextKey(keyFam)
|
|
|
|
}
|
|
|
|
|
|
|
|
fundingKeys, err := s.ShimIntent.MultiSigKeys()
|
|
|
|
if err != nil {
|
|
|
|
return keychain.KeyDescriptor{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return *fundingKeys.LocalKey, nil
|
|
|
|
}
|