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"
|
2015-11-05 23:36:19 +03:00
|
|
|
"fmt"
|
2016-10-27 00:56:48 +03:00
|
|
|
"net"
|
2017-07-30 05:20:08 +03:00
|
|
|
"strings"
|
2015-10-28 01:50:30 +03:00
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
|
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"
|
2017-08-22 08:49:56 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwire"
|
2017-07-30 05:20:08 +03:00
|
|
|
"github.com/roasbeef/btcd/blockchain"
|
|
|
|
"github.com/roasbeef/btcd/chaincfg/chainhash"
|
2016-08-13 01:50:47 +03:00
|
|
|
"github.com/roasbeef/btcutil/hdkeychain"
|
2015-12-21 02:13:14 +03:00
|
|
|
|
2016-12-14 17:01:48 +03:00
|
|
|
"github.com/lightningnetwork/lnd/shachain"
|
2016-05-15 17:17:44 +03:00
|
|
|
"github.com/roasbeef/btcd/btcec"
|
|
|
|
"github.com/roasbeef/btcd/txscript"
|
|
|
|
"github.com/roasbeef/btcd/wire"
|
|
|
|
"github.com/roasbeef/btcutil"
|
|
|
|
"github.com/roasbeef/btcutil/txsort"
|
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
|
2016-08-13 01:43:16 +03:00
|
|
|
|
2016-12-14 17:01:48 +03:00
|
|
|
// revocationRootIndex is the top level HD key index from which secrets
|
|
|
|
// used to generate producer roots should be derived from.
|
|
|
|
revocationRootIndex = hdkeychain.HardenedKeyStart + 1
|
2016-08-13 01:50:47 +03:00
|
|
|
|
|
|
|
// identityKeyIndex is the top level HD key index which is used to
|
|
|
|
// generate/rotate identity keys.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): should instead be child to make room for future
|
|
|
|
// rotations, etc.
|
|
|
|
identityKeyIndex = hdkeychain.HardenedKeyStart + 2
|
2016-09-13 05:05:56 +03:00
|
|
|
|
2017-08-01 07:02:22 +03:00
|
|
|
commitWeight int64 = 724
|
|
|
|
htlcWeight int64 = 172
|
2015-11-13 06:34:35 +03:00
|
|
|
)
|
|
|
|
|
2015-10-28 01:50:30 +03:00
|
|
|
var (
|
2015-12-26 21:35:15 +03:00
|
|
|
// Namespace bucket keys.
|
|
|
|
lightningNamespaceKey = []byte("ln-wallet")
|
|
|
|
waddrmgrNamespaceKey = []byte("waddrmgr")
|
|
|
|
wtxmgrNamespaceKey = []byte("wtxmgr")
|
2015-11-05 23:36:19 +03:00
|
|
|
)
|
|
|
|
|
2016-09-26 22:16:12 +03:00
|
|
|
// ErrInsufficientFunds is a type matching the error interface which is
|
|
|
|
// returned when coin selection for a new funding transaction fails to due
|
|
|
|
// having an insufficient amount of confirmed funds.
|
|
|
|
type ErrInsufficientFunds struct {
|
|
|
|
amountAvailable btcutil.Amount
|
|
|
|
amountSelected btcutil.Amount
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *ErrInsufficientFunds) Error() string {
|
|
|
|
return fmt.Sprintf("not enough outputs to create funding transaction,"+
|
|
|
|
" need %v only have %v available", e.amountAvailable,
|
|
|
|
e.amountSelected)
|
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// initFundingReserveReq is the first message sent to initiate the workflow
|
|
|
|
// 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
|
|
|
|
// periodically after a timeout period in order to avoid "exhaustion" attacks.
|
2016-10-27 00:56:48 +03:00
|
|
|
//
|
2015-12-28 23:14:00 +03:00
|
|
|
// TODO(roasbeef): zombie reservation sweeper goroutine.
|
2015-11-05 23:36:19 +03:00
|
|
|
type initFundingReserveMsg struct {
|
2017-07-30 05:20:08 +03:00
|
|
|
// chainHash denotes that chain to be used to ultimately open the
|
|
|
|
// target channel.
|
|
|
|
chainHash *chainhash.Hash
|
|
|
|
|
2017-05-17 05:00:19 +03:00
|
|
|
// nodeId is the ID of the remote node we would like to open a channel
|
|
|
|
// with.
|
2016-10-27 00:56:48 +03:00
|
|
|
nodeID *btcec.PublicKey
|
|
|
|
|
2017-05-17 05:00:19 +03:00
|
|
|
// nodeAddr is the IP address plus port that we used to either
|
|
|
|
// establish or accept the connection which led to the negotiation of
|
|
|
|
// this funding workflow.
|
2016-10-27 00:56:48 +03:00
|
|
|
nodeAddr *net.TCPAddr
|
|
|
|
|
2017-05-17 05:00:19 +03:00
|
|
|
// fundingAmount is the amount of funds requested for this channel.
|
2015-10-28 01:50:30 +03:00
|
|
|
fundingAmount btcutil.Amount
|
2015-11-05 23:36:19 +03:00
|
|
|
|
2017-05-17 05:00:19 +03:00
|
|
|
// capacity is the total capacity of the channel which includes the
|
|
|
|
// amount of funds the remote party contributes (if any).
|
2016-06-21 20:37:55 +03:00
|
|
|
capacity btcutil.Amount
|
|
|
|
|
2017-05-17 05:00:19 +03:00
|
|
|
// feePerKw is the accepted satoshis/Kw fee for the funding
|
|
|
|
// transaction. 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.
|
|
|
|
feePerKw btcutil.Amount
|
2015-12-28 23:14:00 +03:00
|
|
|
|
2017-08-22 08:49:56 +03:00
|
|
|
// pushMSat is the number of milli-satoshis that should be pushed over
|
|
|
|
// the responder as part of the initial channel creation.
|
|
|
|
pushMSat lnwire.MilliSatoshi
|
2017-01-10 04:24:13 +03:00
|
|
|
|
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
|
|
|
}
|
|
|
|
|
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.
|
2016-05-04 05:49:58 +03:00
|
|
|
theirFundingInputScripts []*InputScript
|
2015-12-22 00:54:33 +03:00
|
|
|
|
|
|
|
// This should be 1/2 of the signatures needed to succesfully spend our
|
|
|
|
// version of the commitment transaction.
|
|
|
|
theirCommitmentSig []byte
|
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
|
|
|
|
// succesfully spend our version of the commitment transaction.
|
2016-06-21 20:37:55 +03:00
|
|
|
theirCommitmentSig []byte
|
|
|
|
|
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
|
|
|
|
// within the Lightning Network, channel lifetimes, etc. However, it embedds 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-07-30 05:02:38 +03:00
|
|
|
// on btcd's websockets notifications as even triggers during the lifetime of a
|
|
|
|
// channel. However, once the chainntnfs package is complete, the wallet will
|
|
|
|
// be compatible with multiple RPC/notification services such as Electrum,
|
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 {
|
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
|
|
|
|
|
|
|
|
// This mutex is to be held when generating external keys to be used as
|
|
|
|
// multi-sig, and commitment keys within the channel.
|
2016-08-13 01:50:47 +03:00
|
|
|
keyGenMtx sync.RWMutex
|
2015-10-28 01:50:30 +03:00
|
|
|
|
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
|
|
|
// rootKey is the root HD key derived from a WalletController private
|
2016-08-13 01:43:16 +03:00
|
|
|
// key. This rootKey is used to derive all LN specific secrets.
|
|
|
|
rootKey *hdkeychain.ExtendedKey
|
2015-12-28 23:14:00 +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.
|
|
|
|
fundingLimbo map[uint64]*ChannelReservation
|
|
|
|
nextFundingID uint64
|
|
|
|
limboMtx sync.RWMutex
|
2015-11-05 23:34:11 +03:00
|
|
|
// TODO(roasbeef): zombie garbage collection routine to solve
|
|
|
|
// lost-object/starvation problem/attack.
|
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{}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
started int32
|
2015-10-28 01:50:30 +03:00
|
|
|
shutdown int32
|
2015-12-28 23:14:00 +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,
|
|
|
|
WalletController: Cfg.WalletController,
|
2016-08-13 01:50:47 +03:00
|
|
|
msgChan: make(chan interface{}, msgBufferSize),
|
|
|
|
nextFundingID: 0,
|
|
|
|
fundingLimbo: make(map[uint64]*ChannelReservation),
|
|
|
|
lockedOutPoints: make(map[wire.OutPoint]struct{}),
|
|
|
|
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
|
|
|
|
2017-04-24 05:15:26 +03:00
|
|
|
// Fetch the root derivation key from the wallet's HD chain. We'll use
|
|
|
|
// this to generate specific Lightning related secrets on the fly.
|
|
|
|
rootKey, err := l.FetchRootKey()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(roasbeef): always re-derive on the fly?
|
|
|
|
rootKeyRaw := rootKey.Serialize()
|
2017-07-30 05:02:38 +03:00
|
|
|
l.rootKey, err = hdkeychain.NewMaster(rootKeyRaw, &l.Cfg.NetParams)
|
2017-04-24 05:15:26 +03:00
|
|
|
if err != nil {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
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 {
|
|
|
|
outPoints = append(outPoints, &outPoint)
|
|
|
|
}
|
|
|
|
|
|
|
|
return outPoints
|
|
|
|
}
|
|
|
|
|
|
|
|
// ResetReservations reset the volatile wallet state which trakcs all currently
|
|
|
|
// active reservations.
|
|
|
|
func (l *LightningWallet) ResetReservations() {
|
|
|
|
l.nextFundingID = 0
|
|
|
|
l.fundingLimbo = make(map[uint64]*ChannelReservation)
|
|
|
|
|
|
|
|
for outpoint := range l.lockedOutPoints {
|
|
|
|
l.UnlockOutpoint(outpoint)
|
|
|
|
}
|
|
|
|
l.lockedOutPoints = make(map[wire.OutPoint]struct{})
|
|
|
|
}
|
|
|
|
|
|
|
|
// ActiveReservations returns a slice of all the currently active
|
|
|
|
// (non-cancalled) reservations.
|
|
|
|
func (l *LightningWallet) ActiveReservations() []*ChannelReservation {
|
|
|
|
reservations := make([]*ChannelReservation, 0, len(l.fundingLimbo))
|
|
|
|
for _, reservation := range l.fundingLimbo {
|
|
|
|
reservations = append(reservations, reservation)
|
|
|
|
}
|
|
|
|
|
|
|
|
return reservations
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetIdentitykey returns the identity private key of the wallet.
|
|
|
|
// TODO(roasbeef): should be moved elsewhere
|
|
|
|
func (l *LightningWallet) GetIdentitykey() (*btcec.PrivateKey, error) {
|
|
|
|
identityKey, err := l.rootKey.Child(identityKeyIndex)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return identityKey.ECPrivKey()
|
|
|
|
}
|
|
|
|
|
2016-10-15 16:18:38 +03:00
|
|
|
// requestHandler is the primary goroutine(s) responsible for handling, and
|
2015-12-28 23:14:00 +03:00
|
|
|
// dispatching relies to all messages.
|
2015-10-28 01:50:30 +03:00
|
|
|
func (l *LightningWallet) requestHandler() {
|
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case m := <-l.msgChan:
|
|
|
|
switch msg := m.(type) {
|
2015-11-05 23:36:19 +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)
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
l.wg.Done()
|
|
|
|
}
|
|
|
|
|
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
|
2016-10-15 16:18:38 +03:00
|
|
|
// commitment transaction. Otherwise, an error occurred a nil pointer along with
|
2015-12-28 23:14:00 +03:00
|
|
|
// an error are returned.
|
|
|
|
//
|
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
|
|
|
|
// transaction, and that the signature we records for our version of the
|
|
|
|
// commitment transaction is valid.
|
2017-07-30 05:20:08 +03:00
|
|
|
func (l *LightningWallet) InitChannelReservation(
|
2017-08-22 08:49:56 +03:00
|
|
|
capacity, ourFundAmt btcutil.Amount, pushMSat lnwire.MilliSatoshi,
|
|
|
|
feePerKw btcutil.Amount,
|
2017-07-30 05:20:08 +03:00
|
|
|
theirID *btcec.PublicKey, theirAddr *net.TCPAddr,
|
|
|
|
chainHash *chainhash.Hash) (*ChannelReservation, error) {
|
2015-12-28 23:14:00 +03:00
|
|
|
|
2015-11-05 23:36:19 +03:00
|
|
|
errChan := make(chan error, 1)
|
2015-11-13 05:43:32 +03:00
|
|
|
respChan := make(chan *ChannelReservation, 1)
|
2015-11-05 23:36:19 +03:00
|
|
|
|
|
|
|
l.msgChan <- &initFundingReserveMsg{
|
2017-07-30 05:20:08 +03:00
|
|
|
chainHash: chainHash,
|
|
|
|
nodeID: theirID,
|
|
|
|
nodeAddr: theirAddr,
|
2016-06-21 20:37:55 +03:00
|
|
|
fundingAmount: ourFundAmt,
|
2017-07-30 05:20:08 +03:00
|
|
|
capacity: capacity,
|
2017-05-17 05:00:19 +03:00
|
|
|
feePerKw: feePerKw,
|
2017-08-22 08:49:56 +03:00
|
|
|
pushMSat: pushMSat,
|
2015-11-05 23:36:19 +03:00
|
|
|
err: errChan,
|
|
|
|
resp: respChan,
|
|
|
|
}
|
|
|
|
|
|
|
|
return <-respChan, <-errChan
|
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// handleFundingReserveRequest processes a message intending to create, and
|
|
|
|
// validate a funding reservation request.
|
2015-11-05 23:36:19 +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.
|
|
|
|
if req.fundingAmount+req.capacity == 0 {
|
|
|
|
req.err <- fmt.Errorf("cannot have channel with zero " +
|
|
|
|
"satoshis funded")
|
|
|
|
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.
|
|
|
|
if *l.Cfg.NetParams.GenesisHash != *req.chainHash {
|
|
|
|
req.err <- fmt.Errorf("unable to create channel reservation "+
|
|
|
|
"for chain=%v, wallet is on chain=%v",
|
|
|
|
req.chainHash, l.Cfg.NetParams.GenesisHash)
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
id := atomic.AddUint64(&l.nextFundingID, 1)
|
2017-05-01 21:45:02 +03:00
|
|
|
reservation := NewChannelReservation(req.capacity, req.fundingAmount,
|
2017-08-22 08:49:56 +03:00
|
|
|
req.feePerKw, l, id, req.pushMSat, l.Cfg.NetParams.GenesisHash)
|
2015-10-28 01:50:30 +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
|
|
|
|
2016-10-27 00:56:48 +03:00
|
|
|
reservation.nodeAddr = req.nodeAddr
|
2016-12-06 17:05:46 +03:00
|
|
|
reservation.partialState.IdentityPub = req.nodeID
|
2015-12-28 23:14:00 +03:00
|
|
|
|
2016-06-21 20:33:14 +03:00
|
|
|
// If we're on the receiving end of a single funder channel then we
|
|
|
|
// don't need to perform any coin selection. Otherwise, attempt to
|
|
|
|
// obtain enough coins to meet the required funding amount.
|
|
|
|
if req.fundingAmount != 0 {
|
2017-05-17 05:00:19 +03:00
|
|
|
// Coin selection is done on the basis of sat-per-byte, so
|
|
|
|
// we'll query the fee estimator for a fee to use to ensure the
|
|
|
|
// funding transaction gets into the _next_ block.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): shouldn't be targeting next block
|
2017-07-30 05:20:08 +03:00
|
|
|
satPerByte := l.Cfg.FeeEstimator.EstimateFeePerByte(1)
|
2017-05-17 05:00:19 +03:00
|
|
|
err := l.selectCoinsAndChange(satPerByte, req.fundingAmount,
|
2017-07-30 05:20:08 +03:00
|
|
|
reservation.ourContribution)
|
2016-09-13 05:05:56 +03:00
|
|
|
if err != nil {
|
2015-10-28 01:50:30 +03:00
|
|
|
req.err <- err
|
2015-11-27 09:50:17 +03:00
|
|
|
req.resp <- nil
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Next, we'll grab a series of keys from the wallet which will be used
|
|
|
|
// for the duration of the channel. The keys include: our multi-sig
|
|
|
|
// key, the base revocation key, the base payment key, and the delayed
|
|
|
|
// payment key.
|
|
|
|
var err error
|
|
|
|
reservation.ourContribution.MultiSigKey, err = l.NewRawKey()
|
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
reservation.ourContribution.RevocationBasePoint, err = l.NewRawKey()
|
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
reservation.ourContribution.PaymentBasePoint, err = l.NewRawKey()
|
2015-12-21 02:13:14 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
reservation.ourContribution.DelayBasePoint, err = l.NewRawKey()
|
2015-11-05 23:36:19 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
2015-11-27 09:50:17 +03:00
|
|
|
req.resp <- nil
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
|
|
|
|
// With the above keys created, we'll also need to initialization our
|
|
|
|
// initial revocation tree state. In order to do so in a deterministic
|
|
|
|
// manner (for recovery purposes), we'll use the current block hash
|
|
|
|
// along with the identity public key of the node we're creating the
|
|
|
|
// channel with. In the event of a recovery, given these two items and
|
|
|
|
// the initialize wallet HD seed, we can derive all of our revocation
|
|
|
|
// secrets.
|
|
|
|
masterElkremRoot, err := l.deriveMasterRevocationRoot()
|
2015-12-21 02:13:14 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
bestHash, _, err := l.Cfg.ChainIO.GetBestBlock()
|
2016-03-24 10:01:35 +03:00
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
revocationRoot := DeriveRevocationRoot(masterElkremRoot, *bestHash,
|
|
|
|
req.nodeID)
|
|
|
|
|
|
|
|
// Once we have the root, we can then generate our shachain producer
|
|
|
|
// and from that generate the per-commitment point.
|
|
|
|
producer := shachain.NewRevocationProducer(revocationRoot)
|
|
|
|
firstPreimage, err := producer.AtIndex(0)
|
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.resp <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
reservation.ourContribution.FirstCommitmentPoint = ComputeCommitmentPoint(
|
|
|
|
firstPreimage[:],
|
|
|
|
)
|
|
|
|
|
|
|
|
reservation.partialState.RevocationProducer = producer
|
|
|
|
reservation.ourContribution.ChannelConstraints = l.Cfg.DefaultConstraints
|
|
|
|
|
|
|
|
// TODO(roasbeef): turn above into: initContributio()
|
2015-12-21 02:13:14 +03:00
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
// Create a limbo and record entry for this newly pending funding
|
|
|
|
// request.
|
|
|
|
l.limboMtx.Lock()
|
|
|
|
l.fundingLimbo[id] = reservation
|
|
|
|
l.limboMtx.Unlock()
|
|
|
|
|
2016-10-15 16:18:38 +03:00
|
|
|
// Funding reservation request successfully handled. The funding inputs
|
2015-10-28 01:50:30 +03:00
|
|
|
// will be marked as unavailable until the reservation is either
|
2017-01-13 08:01:50 +03:00
|
|
|
// completed, or cancelled.
|
2015-12-19 06:39:51 +03:00
|
|
|
req.resp <- reservation
|
2015-10-28 01:50:30 +03:00
|
|
|
req.err <- 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 {
|
|
|
|
// TODO(roasbeef): make new error, "unkown funding state" or something
|
|
|
|
req.err <- fmt.Errorf("attempted to cancel non-existant funding state")
|
|
|
|
return
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
2015-11-05 23:36:19 +03:00
|
|
|
|
2015-11-14 22:52:07 +03:00
|
|
|
// Grab the mutex on the ChannelReservation to ensure thead-safety
|
|
|
|
pendingReservation.Lock()
|
|
|
|
defer pendingReservation.Unlock()
|
|
|
|
|
2015-11-05 23:36:19 +03:00
|
|
|
// Mark all previously locked outpoints as usuable for future funding
|
|
|
|
// 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
|
|
|
}
|
|
|
|
|
2015-11-13 04:45:09 +03:00
|
|
|
// TODO(roasbeef): is it even worth it to keep track of unsed 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)
|
|
|
|
|
|
|
|
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,
|
|
|
|
fundingTxIn *wire.TxIn) (*wire.MsgTx, *wire.MsgTx, error) {
|
|
|
|
|
|
|
|
remoteRevocation := DeriveRevocationPubkey(
|
|
|
|
ourChanCfg.RevocationBasePoint,
|
|
|
|
remoteCommitPoint,
|
|
|
|
)
|
|
|
|
localRevocation := DeriveRevocationPubkey(
|
|
|
|
theirChanCfg.RevocationBasePoint,
|
|
|
|
localCommitPoint,
|
|
|
|
)
|
|
|
|
|
|
|
|
remoteDelayKey := TweakPubKey(theirChanCfg.DelayBasePoint,
|
|
|
|
remoteCommitPoint)
|
|
|
|
localDelayKey := TweakPubKey(ourChanCfg.DelayBasePoint,
|
|
|
|
localCommitPoint)
|
|
|
|
|
|
|
|
// The payment keys go on the opposite commitment transaction, so we'll
|
|
|
|
// swap the commitment points we use. As in the remote payment key will
|
|
|
|
// be used within our commitment transaction, and the local payment key
|
|
|
|
// used within the remote commitment transaction.
|
|
|
|
remotePaymentKey := TweakPubKey(theirChanCfg.PaymentBasePoint,
|
|
|
|
localCommitPoint)
|
|
|
|
localPaymentKey := TweakPubKey(ourChanCfg.PaymentBasePoint,
|
|
|
|
remoteCommitPoint)
|
|
|
|
|
|
|
|
ourCommitTx, err := CreateCommitTx(fundingTxIn,
|
|
|
|
localDelayKey, remotePaymentKey, localRevocation,
|
|
|
|
uint32(ourChanCfg.CsvDelay), localBalance, remoteBalance,
|
|
|
|
ourChanCfg.DustLimit)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
otxn := btcutil.NewTx(ourCommitTx)
|
|
|
|
if err := blockchain.CheckTransactionSanity(otxn); err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
theirCommitTx, err := CreateCommitTx(fundingTxIn,
|
|
|
|
remoteDelayKey, localPaymentKey, remoteRevocation,
|
|
|
|
uint32(theirChanCfg.CsvDelay), remoteBalance, localBalance,
|
|
|
|
theirChanCfg.DustLimit)
|
|
|
|
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 {
|
|
|
|
req.err <- fmt.Errorf("attempted to update non-existant funding state")
|
|
|
|
return
|
|
|
|
}
|
2015-11-05 23:32:15 +03:00
|
|
|
|
2015-11-14 22:52:07 +03:00
|
|
|
// Grab the mutex on the ChannelReservation to ensure thead-safety
|
|
|
|
pendingReservation.Lock()
|
|
|
|
defer pendingReservation.Unlock()
|
|
|
|
|
2015-11-05 23:36:19 +03:00
|
|
|
// Create a blank, fresh transaction. Soon to be a complete funding
|
|
|
|
// transaction which will allow opening a lightning channel.
|
2017-01-06 00:56:27 +03:00
|
|
|
pendingReservation.fundingTx = wire.NewMsgTx(1)
|
2016-06-21 20:37:55 +03:00
|
|
|
fundingTx := pendingReservation.fundingTx
|
2015-12-23 07:31:17 +03:00
|
|
|
|
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
|
|
|
|
2016-05-04 05:49:58 +03:00
|
|
|
// Add all multi-party inputs and outputs to the transaction.
|
2015-12-23 07:31:17 +03:00
|
|
|
for _, ourInput := range ourContribution.Inputs {
|
|
|
|
fundingTx.AddTxIn(ourInput)
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
2015-12-23 07:31:17 +03:00
|
|
|
for _, theirInput := range theirContribution.Inputs {
|
|
|
|
fundingTx.AddTxIn(theirInput)
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
2015-12-23 07:31:17 +03:00
|
|
|
for _, ourChangeOutput := range ourContribution.ChangeOutputs {
|
|
|
|
fundingTx.AddTxOut(ourChangeOutput)
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
2015-12-23 07:31:17 +03:00
|
|
|
for _, theirChangeOutput := range theirContribution.ChangeOutputs {
|
|
|
|
fundingTx.AddTxOut(theirChangeOutput)
|
2015-11-05 23:36:19 +03:00
|
|
|
}
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
ourKey := pendingReservation.ourContribution.MultiSigKey
|
2015-12-23 07:31:17 +03:00
|
|
|
theirKey := theirContribution.MultiSigKey
|
2015-12-21 02:11:21 +03:00
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// Finally, add the 2-of-2 multi-sig output which will set up the lightning
|
|
|
|
// channel.
|
2015-12-24 21:41:15 +03:00
|
|
|
channelCapacity := int64(pendingReservation.partialState.Capacity)
|
2016-10-16 02:02:09 +03:00
|
|
|
witnessScript, multiSigOut, err := GenFundingPkScript(ourKey.SerializeCompressed(),
|
2015-12-22 00:53:34 +03:00
|
|
|
theirKey.SerializeCompressed(), channelCapacity)
|
2015-10-28 01:50:30 +03:00
|
|
|
if err != nil {
|
2015-11-05 23:36:19 +03:00
|
|
|
req.err <- err
|
|
|
|
return
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
2015-12-24 21:42:29 +03:00
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Sort the transaction. Since both side agree to a canonical ordering,
|
|
|
|
// by sorting we no longer need to send the entire transaction. Only
|
|
|
|
// signatures will be exchanged.
|
2016-06-21 20:37:55 +03:00
|
|
|
fundingTx.AddTxOut(multiSigOut)
|
|
|
|
txsort.InPlaceSort(pendingReservation.fundingTx)
|
2015-11-05 23:36:19 +03:00
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// Next, sign all inputs that are ours, collecting the signatures in
|
2015-11-05 23:36:19 +03:00
|
|
|
// order of the inputs.
|
2017-07-30 05:20:08 +03:00
|
|
|
pendingReservation.ourFundingInputScripts = make([]*InputScript, 0,
|
|
|
|
len(ourContribution.Inputs))
|
2016-08-13 01:50:47 +03:00
|
|
|
signDesc := SignDescriptor{
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
SigHashes: txscript.NewTxSigHashes(fundingTx),
|
|
|
|
}
|
2015-12-23 07:31:17 +03:00
|
|
|
for i, txIn := range fundingTx.TxIn {
|
2016-08-13 01:50:47 +03:00
|
|
|
info, err := l.FetchInputInfo(&txIn.PreviousOutPoint)
|
|
|
|
if err == ErrNotMine {
|
2015-11-05 23:36:19 +03:00
|
|
|
continue
|
2016-08-13 01:50:47 +03:00
|
|
|
} else if err != nil {
|
|
|
|
req.err <- err
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
|
|
|
}
|
2015-10-28 01:50:30 +03:00
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
signDesc.Output = info
|
|
|
|
signDesc.InputIndex = i
|
2016-05-04 05:49:58 +03:00
|
|
|
|
2017-07-30 05:02:38 +03:00
|
|
|
inputScript, err := l.Cfg.Signer.ComputeInputScript(fundingTx,
|
|
|
|
&signDesc)
|
2015-10-28 01:50:30 +03:00
|
|
|
if err != nil {
|
2016-08-13 01:50:47 +03:00
|
|
|
req.err <- err
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2016-08-13 01:50:47 +03:00
|
|
|
txIn.SignatureScript = inputScript.ScriptSig
|
|
|
|
txIn.Witness = inputScript.Witness
|
2016-05-04 05:49:58 +03:00
|
|
|
pendingReservation.ourFundingInputScripts = append(
|
|
|
|
pendingReservation.ourFundingInputScripts,
|
|
|
|
inputScript,
|
|
|
|
)
|
2015-10-28 01:50:30 +03:00
|
|
|
}
|
|
|
|
|
2016-06-21 20:37:55 +03:00
|
|
|
// Locate the index of the multi-sig outpoint in order to record it
|
2016-10-16 02:02:09 +03:00
|
|
|
// since the outputs are canonically sorted. If this is a single funder
|
2016-06-21 20:37:55 +03:00
|
|
|
// workflow, then we'll also need to send this to the remote node.
|
2017-01-06 00:56:27 +03:00
|
|
|
fundingTxID := fundingTx.TxHash()
|
2016-08-13 01:50:47 +03:00
|
|
|
_, multiSigIndex := FindScriptOutputIndex(fundingTx, multiSigOut.PkScript)
|
2016-06-21 20:37:55 +03:00
|
|
|
fundingOutpoint := wire.NewOutPoint(&fundingTxID, multiSigIndex)
|
2017-07-30 05:20:08 +03:00
|
|
|
pendingReservation.partialState.FundingOutpoint = *fundingOutpoint
|
2016-06-21 20:37:55 +03:00
|
|
|
|
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-07-30 05:20:08 +03:00
|
|
|
fundingTxIn := &wire.TxIn{
|
|
|
|
PreviousOutPoint: wire.OutPoint{
|
|
|
|
Hash: fundingTxID,
|
|
|
|
Index: multiSigIndex,
|
|
|
|
},
|
|
|
|
}
|
2015-12-22 00:53:34 +03:00
|
|
|
|
|
|
|
// With the funding tx complete, create both commitment transactions.
|
2017-08-22 08:49:56 +03:00
|
|
|
localBalance := pendingReservation.partialState.LocalBalance.ToSatoshis()
|
|
|
|
remoteBalance := pendingReservation.partialState.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,
|
|
|
|
)
|
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-07-30 05:20:08 +03:00
|
|
|
// obsfucator then use it to encode the current state number within
|
|
|
|
// both commitment transactions.
|
2016-11-16 23:54:27 +03:00
|
|
|
var stateObsfucator [StateHintSize]byte
|
2017-07-30 05:20:08 +03:00
|
|
|
if chanState.ChanType == channeldb.SingleFunder {
|
|
|
|
stateObsfucator = deriveStateHintObfuscator(
|
|
|
|
ourContribution.PaymentBasePoint,
|
|
|
|
theirContribution.PaymentBasePoint,
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
ourSer := ourContribution.PaymentBasePoint.SerializeCompressed()
|
|
|
|
theirSer := theirContribution.PaymentBasePoint.SerializeCompressed()
|
|
|
|
switch bytes.Compare(ourSer, theirSer) {
|
|
|
|
case -1:
|
|
|
|
stateObsfucator = deriveStateHintObfuscator(
|
|
|
|
ourContribution.PaymentBasePoint,
|
|
|
|
theirContribution.PaymentBasePoint,
|
|
|
|
)
|
|
|
|
default:
|
|
|
|
stateObsfucator = deriveStateHintObfuscator(
|
|
|
|
theirContribution.PaymentBasePoint,
|
|
|
|
ourContribution.PaymentBasePoint,
|
|
|
|
)
|
2016-11-16 23:54:27 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
err = initStateHints(ourCommitTx, theirCommitTx, stateObsfucator)
|
|
|
|
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)
|
|
|
|
|
2017-07-30 05:20:08 +03:00
|
|
|
// Record newly available information within the open channel state.
|
|
|
|
chanState.FundingOutpoint = *fundingOutpoint
|
|
|
|
chanState.CommitTx = *ourCommitTx
|
2015-12-22 00:53:34 +03:00
|
|
|
|
|
|
|
// Generate a signature for their version of the initial commitment
|
|
|
|
// transaction.
|
2016-08-13 01:50:47 +03:00
|
|
|
signDesc = SignDescriptor{
|
2016-10-16 02:02:09 +03:00
|
|
|
WitnessScript: witnessScript,
|
2016-10-24 04:42:03 +03:00
|
|
|
PubKey: ourKey,
|
|
|
|
Output: multiSigOut,
|
|
|
|
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
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-12-25 03:47:09 +03:00
|
|
|
// openChanDetails contains a "finalized" channel which can be considered
|
|
|
|
// "open" according to the requested confirmation depth at reservation
|
|
|
|
// initialization. Additionally, the struct contains additional details
|
|
|
|
// pertaining to the exact location in the main chain in-which the transaction
|
|
|
|
// was confirmed.
|
|
|
|
type openChanDetails struct {
|
|
|
|
channel *LightningChannel
|
|
|
|
blockHeight uint32
|
|
|
|
txIndex uint32
|
|
|
|
}
|
|
|
|
|
2015-12-28 23:14:00 +03:00
|
|
|
// handleFundingCounterPartySigs is the final step in the channel reservation
|
2016-10-16 02:02:09 +03:00
|
|
|
// workflow. During this step, we validate *all* the received signatures for
|
2015-12-28 23:14:00 +03:00
|
|
|
// 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.
|
2015-11-05 23:36:19 +03:00
|
|
|
func (l *LightningWallet) handleFundingCounterPartySigs(msg *addCounterPartySigsMsg) {
|
2015-11-13 05:43:32 +03:00
|
|
|
l.limboMtx.RLock()
|
2016-10-27 00:56:48 +03:00
|
|
|
res, ok := l.fundingLimbo[msg.pendingFundingID]
|
2015-11-13 05:43:32 +03:00
|
|
|
l.limboMtx.RUnlock()
|
2015-11-05 23:36:19 +03:00
|
|
|
if !ok {
|
2017-07-30 05:20:08 +03:00
|
|
|
msg.err <- fmt.Errorf("attempted to update non-existent funding state")
|
2015-11-05 23:36:19 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-07-30 05:02:38 +03:00
|
|
|
// Grab the mutex on the ChannelReservation to ensure thread-safety
|
2016-10-27 00:56:48 +03:00
|
|
|
res.Lock()
|
|
|
|
defer res.Unlock()
|
2015-11-14 22:52:07 +03:00
|
|
|
|
2015-11-05 23:36:19 +03:00
|
|
|
// Now we can complete the funding transaction by adding their
|
|
|
|
// signatures to their inputs.
|
2016-10-27 00:56:48 +03:00
|
|
|
res.theirFundingInputScripts = msg.theirFundingInputScripts
|
2016-06-21 20:37:55 +03:00
|
|
|
inputScripts := msg.theirFundingInputScripts
|
2016-10-27 00:56:48 +03:00
|
|
|
fundingTx := res.fundingTx
|
2016-02-03 10:59:27 +03:00
|
|
|
sigIndex := 0
|
2016-05-04 05:49:58 +03:00
|
|
|
fundingHashCache := txscript.NewTxSigHashes(fundingTx)
|
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
|
|
|
|
txin.SignatureScript = inputScripts[sigIndex].ScriptSig
|
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.
|
2017-05-11 02:37:14 +03:00
|
|
|
// TODO(roasbeef): when dual funder pass actual height-hint
|
2017-07-30 05:02:38 +03:00
|
|
|
output, err := l.Cfg.ChainIO.GetUtxo(&txin.PreviousOutPoint, 0)
|
2016-01-07 03:15:49 +03:00
|
|
|
if output == nil {
|
2017-04-14 10:46:31 +03:00
|
|
|
msg.err <- fmt.Errorf("input to funding tx "+
|
|
|
|
"does not exist: %v", err)
|
|
|
|
msg.completeChan <- nil
|
2015-12-03 03:51:46 +03:00
|
|
|
return
|
|
|
|
}
|
2016-05-04 05:49:58 +03:00
|
|
|
|
|
|
|
// Ensure that the witness+sigScript combo is valid.
|
2016-08-13 01:50:47 +03:00
|
|
|
vm, err := txscript.NewEngine(output.PkScript,
|
2016-05-04 05:49:58 +03:00
|
|
|
fundingTx, i, txscript.StandardVerifyFlags, nil,
|
2016-08-13 01:50:47 +03:00
|
|
|
fundingHashCache, output.Value)
|
2015-12-03 03:51:46 +03:00
|
|
|
if err != nil {
|
2017-04-14 10:46:31 +03:00
|
|
|
msg.err <- fmt.Errorf("cannot create script "+
|
|
|
|
"engine: %s", err)
|
|
|
|
msg.completeChan <- nil
|
2015-12-03 03:51:46 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if err = vm.Execute(); err != nil {
|
2017-04-14 10:46:31 +03:00
|
|
|
msg.err <- fmt.Errorf("cannot validate "+
|
|
|
|
"transaction: %s", err)
|
|
|
|
msg.completeChan <- nil
|
2015-12-03 03:51:46 +03:00
|
|
|
return
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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-07-30 05:20:08 +03:00
|
|
|
commitTx := res.partialState.CommitTx
|
|
|
|
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.
|
2017-07-30 05:20:08 +03:00
|
|
|
witnessScript, _, err := GenFundingPkScript(ourKey.SerializeCompressed(),
|
|
|
|
theirKey.SerializeCompressed(), int64(res.partialState.Capacity))
|
|
|
|
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.
|
|
|
|
theirCommitSig := msg.theirCommitmentSig
|
2016-10-27 00:56:48 +03:00
|
|
|
channelValue := int64(res.partialState.Capacity)
|
2017-07-30 05:20:08 +03:00
|
|
|
hashCache := txscript.NewTxSigHashes(&commitTx)
|
2016-10-16 02:02:09 +03:00
|
|
|
sigHash, err := txscript.CalcWitnessSigHash(witnessScript, hashCache,
|
2017-07-30 05:20:08 +03:00
|
|
|
txscript.SigHashAll, &commitTx, 0, channelValue)
|
2015-12-28 23:13:41 +03:00
|
|
|
if err != nil {
|
2017-04-14 10:46:31 +03:00
|
|
|
msg.err <- fmt.Errorf("counterparty's commitment signature is "+
|
|
|
|
"invalid: %v", err)
|
|
|
|
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.
|
|
|
|
sig, err := btcec.ParseSignature(theirCommitSig, btcec.S256())
|
2015-12-28 23:13:41 +03:00
|
|
|
if err != nil {
|
|
|
|
msg.err <- err
|
2017-07-30 05:02:38 +03:00
|
|
|
msg.completeChan <- nil
|
2015-12-28 23:13:41 +03:00
|
|
|
return
|
2016-08-13 01:50:47 +03:00
|
|
|
} else if !sig.Verify(sigHash, theirKey) {
|
|
|
|
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
|
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
res.partialState.CommitSig = theirCommitSig
|
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)
|
2015-11-13 05:43:32 +03:00
|
|
|
l.limboMtx.Unlock()
|
2015-11-05 23:36:19 +03:00
|
|
|
|
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
|
|
|
|
2015-12-03 03:51:21 +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
|
|
|
// TODO(roasbeef):
|
|
|
|
// * attempt to retransmit funding transactions on re-start
|
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-07-30 05:20:08 +03:00
|
|
|
walletLog.Infof("Broadcasting funding tx for ChannelPoint(%v): %v",
|
|
|
|
res.partialState.FundingOutpoint, spew.Sdump(fundingTx))
|
|
|
|
|
|
|
|
// Broadcast the finalized funding transaction to the network.
|
|
|
|
if err := l.PublishTransaction(fundingTx); err != nil {
|
|
|
|
// TODO(roasbeef): need to make this into a concrete error
|
|
|
|
if !strings.Contains(err.Error(), "already have") {
|
|
|
|
msg.err <- err
|
|
|
|
msg.completeChan <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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 {
|
|
|
|
req.err <- fmt.Errorf("attempted to update non-existant 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-08-22 08:49:56 +03:00
|
|
|
localBalance := pendingReservation.partialState.LocalBalance.ToSatoshis()
|
|
|
|
remoteBalance := pendingReservation.partialState.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,
|
|
|
|
fundingTxIn,
|
|
|
|
)
|
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.
|
2017-07-30 05:20:08 +03:00
|
|
|
stateObsfucator := deriveStateHintObfuscator(
|
|
|
|
pendingReservation.theirContribution.PaymentBasePoint,
|
|
|
|
pendingReservation.ourContribution.PaymentBasePoint)
|
|
|
|
err = initStateHints(ourCommitTx, theirCommitTx, stateObsfucator)
|
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-07-30 05:20:08 +03:00
|
|
|
chanState.CommitTx = *ourCommitTx
|
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
|
|
|
|
witnessScript, _, err := GenFundingPkScript(ourKey.SerializeCompressed(),
|
|
|
|
theirKey.SerializeCompressed(), channelValue)
|
|
|
|
if err != nil {
|
|
|
|
req.err <- err
|
|
|
|
req.completeChan <- nil
|
|
|
|
return
|
|
|
|
}
|
2016-08-13 01:50:47 +03:00
|
|
|
|
2016-10-16 02:02:09 +03:00
|
|
|
sigHash, err := txscript.CalcWitnessSigHash(witnessScript, hashCache,
|
2016-08-13 01:50:47 +03:00
|
|
|
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.
|
|
|
|
sig, err := btcec.ParseSignature(req.theirCommitmentSig, btcec.S256())
|
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
|
|
|
} else if !sig.Verify(sigHash, theirKey) {
|
|
|
|
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
|
|
|
|
}
|
2017-07-30 05:20:08 +03:00
|
|
|
chanState.CommitSig = req.theirCommitmentSig
|
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.
|
2016-10-16 02:02:09 +03:00
|
|
|
p2wsh, err := 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
|
|
|
|
}
|
|
|
|
signDesc := SignDescriptor{
|
2016-10-16 02:02:09 +03:00
|
|
|
WitnessScript: witnessScript,
|
2016-10-24 04:42:03 +03:00
|
|
|
PubKey: 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
|
|
|
|
}
|
|
|
|
|
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()
|
2016-01-07 03:17:18 +03:00
|
|
|
}
|
|
|
|
|
2016-06-21 20:33:14 +03:00
|
|
|
// selectCoinsAndChange performs coin selection in order to obtain witness
|
|
|
|
// outputs which sum to at least 'numCoins' amount of satoshis. If coin
|
2016-10-16 02:02:09 +03:00
|
|
|
// selection is successful/possible, then the selected coins are available
|
2016-09-13 05:05:56 +03:00
|
|
|
// within the passed contribution's inputs. If necessary, a change address will
|
|
|
|
// also be generated.
|
2016-06-21 20:33:14 +03:00
|
|
|
// TODO(roasbeef): remove hardcoded fees and req'd confs for outputs.
|
2016-08-13 01:35:33 +03:00
|
|
|
func (l *LightningWallet) selectCoinsAndChange(feeRate uint64, amt btcutil.Amount,
|
2016-06-21 20:33:14 +03:00
|
|
|
contribution *ChannelContribution) error {
|
|
|
|
|
|
|
|
// We hold the coin select mutex while querying for outputs, and
|
2016-09-13 05:05:56 +03:00
|
|
|
// performing coin selection in order to avoid inadvertent double
|
2016-10-16 02:02:09 +03:00
|
|
|
// spends across funding transactions.
|
2016-06-21 20:33:14 +03:00
|
|
|
l.coinSelectMtx.Lock()
|
2016-09-13 05:05:56 +03:00
|
|
|
defer l.coinSelectMtx.Unlock()
|
2016-06-21 20:33:14 +03:00
|
|
|
|
2017-05-17 05:00:19 +03:00
|
|
|
walletLog.Infof("Performing coin selection using %v sat/byte as fee "+
|
|
|
|
"rate", feeRate)
|
|
|
|
|
2016-06-21 20:33:14 +03:00
|
|
|
// Find all unlocked unspent witness outputs with greater than 1
|
|
|
|
// confirmation.
|
2017-05-17 05:00:19 +03:00
|
|
|
// TODO(roasbeef): make num confs a configuration parameter
|
2016-08-13 01:35:33 +03:00
|
|
|
coins, err := l.ListUnspentWitness(1)
|
2016-06-21 20:33:14 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-10-16 02:02:09 +03:00
|
|
|
// Perform coin selection over our available, unlocked unspent outputs
|
2016-09-13 05:05:56 +03:00
|
|
|
// in order to find enough coins to meet the funding amount
|
|
|
|
// requirements.
|
2016-08-13 01:35:33 +03:00
|
|
|
selectedCoins, changeAmt, err := coinSelect(feeRate, amt, coins)
|
2016-06-21 20:33:14 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lock the selected coins. These coins are now "reserved", this
|
|
|
|
// prevents concurrent funding requests from referring to and this
|
|
|
|
// double-spending the same set of coins.
|
2016-08-13 01:35:33 +03:00
|
|
|
contribution.Inputs = make([]*wire.TxIn, len(selectedCoins))
|
|
|
|
for i, coin := range selectedCoins {
|
|
|
|
l.lockedOutPoints[*coin] = struct{}{}
|
|
|
|
l.LockOutpoint(*coin)
|
2016-06-21 20:33:14 +03:00
|
|
|
|
|
|
|
// Empty sig script, we'll actually sign if this reservation is
|
|
|
|
// queued up to be completed (the other side accepts).
|
2016-08-13 01:35:33 +03:00
|
|
|
contribution.Inputs[i] = wire.NewTxIn(coin, nil, nil)
|
2016-06-21 20:33:14 +03:00
|
|
|
}
|
|
|
|
|
2016-08-13 01:35:33 +03:00
|
|
|
// Record any change output(s) generated as a result of the coin
|
|
|
|
// selection.
|
|
|
|
if changeAmt != 0 {
|
|
|
|
changeAddr, err := l.NewAddress(WitnessPubKey, true)
|
2016-06-21 20:33:14 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-08-13 01:35:33 +03:00
|
|
|
changeScript, err := txscript.PayToAddrScript(changeAddr)
|
2016-06-21 20:33:14 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-08-13 01:35:33 +03:00
|
|
|
contribution.ChangeOutputs = make([]*wire.TxOut, 1)
|
|
|
|
contribution.ChangeOutputs[0] = &wire.TxOut{
|
|
|
|
Value: int64(changeAmt),
|
|
|
|
PkScript: changeScript,
|
|
|
|
}
|
2016-06-21 20:33:14 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-12-14 17:01:48 +03:00
|
|
|
// deriveMasterRevocationRoot derives the private key which serves as the master
|
|
|
|
// producer root. This master secret is used as the secret input to a HKDF to
|
|
|
|
// generate revocation secrets based on random, but public data.
|
|
|
|
func (l *LightningWallet) deriveMasterRevocationRoot() (*btcec.PrivateKey, error) {
|
|
|
|
masterElkremRoot, err := l.rootKey.Child(revocationRootIndex)
|
2016-08-13 01:43:16 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-03-24 10:01:35 +03:00
|
|
|
|
2016-08-13 01:43:16 +03:00
|
|
|
return masterElkremRoot.ECPrivKey()
|
2016-03-24 10:01:35 +03:00
|
|
|
}
|
|
|
|
|
2016-12-14 17:01:48 +03:00
|
|
|
// deriveStateHintObfuscator derives the bytes to be used for obfuscating the
|
2017-07-30 04:39:58 +03:00
|
|
|
// state hints from the root to be used for a new channel. The obsfucsator is
|
|
|
|
// generated via the following computation:
|
|
|
|
//
|
|
|
|
// * sha256(initiatorKey || responderKey)[:6]
|
|
|
|
// * where both keys are the multi-sig keys of the respective parties
|
|
|
|
//
|
|
|
|
// The first 6 bytes of the resulting hash are used as the state hint.
|
|
|
|
func deriveStateHintObfuscator(key1, key2 *btcec.PublicKey) [StateHintSize]byte {
|
|
|
|
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
|
|
|
|
copy(obfuscator[:], sha[:])
|
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
|
|
|
}
|
|
|
|
|
2017-01-04 18:15:50 +03:00
|
|
|
// initStateHints properly sets the obsfucated state hints on both commitment
|
2016-11-16 23:54:27 +03:00
|
|
|
// transactions using the passed obsfucator.
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2016-08-13 01:35:33 +03:00
|
|
|
// selectInputs selects a slice of inputs necessary to meet the specified
|
2016-12-14 17:01:48 +03:00
|
|
|
// selection amount. If input selection is unable to succeed to to insufficient
|
2016-08-13 01:35:33 +03:00
|
|
|
// funds, a non-nil error is returned. Additionally, the total amount of the
|
|
|
|
// selected coins are returned in order for the caller to properly handle
|
|
|
|
// change+fees.
|
|
|
|
func selectInputs(amt btcutil.Amount, coins []*Utxo) (btcutil.Amount, []*wire.OutPoint, error) {
|
|
|
|
var (
|
|
|
|
selectedUtxos []*wire.OutPoint
|
|
|
|
satSelected btcutil.Amount
|
|
|
|
)
|
|
|
|
|
|
|
|
i := 0
|
|
|
|
for satSelected < amt {
|
|
|
|
// If we're about to go past the number of available coins,
|
|
|
|
// then exit with an error.
|
|
|
|
if i > len(coins)-1 {
|
2016-09-26 22:16:12 +03:00
|
|
|
return 0, nil, &ErrInsufficientFunds{amt, satSelected}
|
2016-08-13 01:35:33 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, collect this new coin as it may be used for final
|
|
|
|
// coin selection.
|
|
|
|
coin := coins[i]
|
|
|
|
utxo := &wire.OutPoint{
|
|
|
|
Hash: coin.Hash,
|
|
|
|
Index: coin.Index,
|
|
|
|
}
|
|
|
|
|
|
|
|
selectedUtxos = append(selectedUtxos, utxo)
|
|
|
|
satSelected += coin.Value
|
|
|
|
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
|
|
|
return satSelected, selectedUtxos, nil
|
2016-03-24 10:01:35 +03:00
|
|
|
}
|
|
|
|
|
2017-07-30 04:39:58 +03:00
|
|
|
// coinSelect attempts to select a sufficient amount of coins, including a
|
|
|
|
// change output to fund amt satoshis, adhering to the specified fee rate. The
|
2016-08-13 01:35:33 +03:00
|
|
|
// specified fee rate should be expressed in sat/byte for coin selection to
|
|
|
|
// function properly.
|
|
|
|
func coinSelect(feeRate uint64, amt btcutil.Amount,
|
|
|
|
coins []*Utxo) ([]*wire.OutPoint, btcutil.Amount, error) {
|
|
|
|
|
|
|
|
const (
|
|
|
|
// txOverhead is the overhead of a transaction residing within
|
|
|
|
// the version number and lock time.
|
|
|
|
txOverhead = 8
|
|
|
|
|
|
|
|
// p2wkhSpendSize an estimate of the number of bytes it takes
|
|
|
|
// to spend a p2wkh output.
|
|
|
|
//
|
|
|
|
// (p2wkh witness) + txid + index + varint script size + sequence
|
|
|
|
// TODO(roasbeef): div by 3 due to witness size?
|
|
|
|
p2wkhSpendSize = (1 + 73 + 1 + 33) + 32 + 4 + 1 + 4
|
|
|
|
|
|
|
|
// p2wkhOutputSize is an estimate of the size of a regualr
|
|
|
|
// p2wkh output.
|
|
|
|
//
|
|
|
|
// 8 (output) + 1 (var int script) + 22 (p2wkh output)
|
|
|
|
p2wkhOutputSize = 8 + 1 + 22
|
|
|
|
|
|
|
|
// p2wkhOutputSize is an estimate of the p2wsh funding uotput.
|
|
|
|
p2wshOutputSize = 8 + 1 + 34
|
|
|
|
)
|
|
|
|
|
|
|
|
var estimatedSize int
|
|
|
|
|
|
|
|
amtNeeded := amt
|
|
|
|
for {
|
|
|
|
// First perform an initial round of coin selection to estimate
|
|
|
|
// the required fee.
|
|
|
|
totalSat, selectedUtxos, err := selectInputs(amtNeeded, coins)
|
|
|
|
if err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Based on the selected coins, estimate the size of the final
|
|
|
|
// fully signed transaction.
|
|
|
|
estimatedSize = ((len(selectedUtxos) * p2wkhSpendSize) +
|
|
|
|
p2wshOutputSize + txOverhead)
|
|
|
|
|
2017-06-09 08:24:10 +03:00
|
|
|
// The difference between the selected amount and the amount
|
2016-08-13 01:35:33 +03:00
|
|
|
// requested will be used to pay fees, and generate a change
|
|
|
|
// output with the remaining.
|
|
|
|
overShootAmt := totalSat - amtNeeded
|
|
|
|
|
|
|
|
// Based on the estimated size and fee rate, if the excess
|
|
|
|
// amount isn't enough to pay fees, then increase the requested
|
|
|
|
// coin amount by the estimate required fee, performing another
|
|
|
|
// round of coin selection.
|
|
|
|
requiredFee := btcutil.Amount(uint64(estimatedSize) * feeRate)
|
|
|
|
if overShootAmt < requiredFee {
|
|
|
|
amtNeeded += requiredFee
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-06-09 08:24:10 +03:00
|
|
|
// If the fee is sufficient, then calculate the size of the
|
|
|
|
// change output.
|
2016-08-13 01:35:33 +03:00
|
|
|
changeAmt := overShootAmt - requiredFee
|
|
|
|
|
|
|
|
return selectedUtxos, changeAmt, nil
|
|
|
|
}
|
2016-03-24 10:01:35 +03:00
|
|
|
}
|
2017-05-01 10:27:12 +03:00
|
|
|
|
|
|
|
// StaticFeeEstimator will return a static value for all fee calculation
|
2017-05-17 05:00:19 +03:00
|
|
|
// requests. It is designed to be replaced by a proper fee calculation
|
2017-05-01 10:27:12 +03:00
|
|
|
// implementation.
|
|
|
|
type StaticFeeEstimator struct {
|
|
|
|
FeeRate uint64
|
|
|
|
Confirmation uint32
|
|
|
|
}
|
|
|
|
|
|
|
|
// EstimateFeePerByte will return a static value for fee calculations.
|
|
|
|
func (e StaticFeeEstimator) EstimateFeePerByte(numBlocks uint32) uint64 {
|
|
|
|
return e.FeeRate
|
|
|
|
}
|
|
|
|
|
|
|
|
// EstimateFeePerWeight will return a static value for fee calculations.
|
|
|
|
func (e StaticFeeEstimator) EstimateFeePerWeight(numBlocks uint32) uint64 {
|
2017-05-17 05:01:57 +03:00
|
|
|
return e.FeeRate / 4
|
2017-05-01 10:27:12 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// EstimateConfirmation will return a static value representing the estimated
|
|
|
|
// number of blocks that will be required to confirm a transaction for the
|
|
|
|
// given fee rate.
|
|
|
|
func (e StaticFeeEstimator) EstimateConfirmation(satPerByte int64) uint32 {
|
|
|
|
return e.Confirmation
|
|
|
|
}
|