2019-12-10 17:04:10 +03:00
|
|
|
package sweep
|
|
|
|
|
|
|
|
import (
|
2019-12-10 18:06:45 +03:00
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
|
|
|
|
"github.com/btcsuite/btcd/txscript"
|
|
|
|
"github.com/btcsuite/btcd/wire"
|
2019-12-10 17:04:10 +03:00
|
|
|
"github.com/btcsuite/btcutil"
|
|
|
|
"github.com/btcsuite/btcwallet/wallet/txrules"
|
|
|
|
"github.com/lightningnetwork/lnd/input"
|
2019-12-10 18:06:45 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet"
|
2019-12-10 17:04:10 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
|
|
|
|
)
|
|
|
|
|
2019-12-13 17:04:32 +03:00
|
|
|
// addConstraints defines the constraints to apply when adding an input.
|
|
|
|
type addConstraints uint8
|
|
|
|
|
|
|
|
const (
|
|
|
|
// constraintsRegular is for regular input sweeps that should have a positive
|
|
|
|
// yield.
|
|
|
|
constraintsRegular addConstraints = iota
|
|
|
|
|
|
|
|
// constraintsWallet is for wallet inputs that are only added to bring up the tx
|
|
|
|
// output value.
|
|
|
|
constraintsWallet
|
2019-12-09 17:40:05 +03:00
|
|
|
|
|
|
|
// constraintsForce is for inputs that should be swept even with a negative
|
|
|
|
// yield at the set fee rate.
|
|
|
|
constraintsForce
|
2019-12-13 17:04:32 +03:00
|
|
|
)
|
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
type txInputSetState struct {
|
2020-11-06 21:58:05 +03:00
|
|
|
// feeRate is the fee rate to use for the sweep transaction.
|
|
|
|
feeRate chainfee.SatPerKWeight
|
2019-12-10 17:04:10 +03:00
|
|
|
|
|
|
|
// inputTotal is the total value of all inputs.
|
|
|
|
inputTotal btcutil.Amount
|
|
|
|
|
2020-11-06 21:58:05 +03:00
|
|
|
// requiredOutput is the sum of the outputs committed to by the inputs.
|
|
|
|
requiredOutput btcutil.Amount
|
|
|
|
|
|
|
|
// changeOutput is the value of the change output. This will be what is
|
|
|
|
// left over after subtracting the requiredOutput and the tx fee from
|
|
|
|
// the inputTotal.
|
|
|
|
//
|
|
|
|
// NOTE: This might be below the dust limit, or even negative since it
|
|
|
|
// is the change remaining in csse we pay the fee for a change output.
|
|
|
|
changeOutput btcutil.Amount
|
2019-12-10 17:04:10 +03:00
|
|
|
|
|
|
|
// inputs is the set of tx inputs.
|
|
|
|
inputs []input.Input
|
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
// walletInputTotal is the total value of inputs coming from the wallet.
|
|
|
|
walletInputTotal btcutil.Amount
|
|
|
|
|
|
|
|
// force indicates that this set must be swept even if the total yield
|
|
|
|
// is negative.
|
|
|
|
force bool
|
|
|
|
}
|
|
|
|
|
2020-11-06 21:58:05 +03:00
|
|
|
// weightEstimate is the (worst case) tx weight with the current set of
|
|
|
|
// inputs. It takes a parameter whether to add a change output or not.
|
|
|
|
func (t *txInputSetState) weightEstimate(change bool) *weightEstimator {
|
|
|
|
weightEstimate := newWeightEstimator(t.feeRate)
|
|
|
|
for _, i := range t.inputs {
|
|
|
|
// Can ignore error, because it has already been checked when
|
|
|
|
// calculating the yields.
|
|
|
|
_ = weightEstimate.add(i)
|
|
|
|
|
|
|
|
r := i.RequiredTxOut()
|
|
|
|
if r != nil {
|
|
|
|
weightEstimate.addOutput(r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add a change output to the weight estimate if requested.
|
|
|
|
if change {
|
|
|
|
weightEstimate.addP2WKHOutput()
|
|
|
|
}
|
|
|
|
|
|
|
|
return weightEstimate
|
|
|
|
}
|
|
|
|
|
|
|
|
// totalOutput is the total amount left for us after paying fees.
|
|
|
|
//
|
|
|
|
// NOTE: This might be dust.
|
|
|
|
func (t *txInputSetState) totalOutput() btcutil.Amount {
|
|
|
|
return t.requiredOutput + t.changeOutput
|
|
|
|
}
|
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
func (t *txInputSetState) clone() txInputSetState {
|
|
|
|
s := txInputSetState{
|
2020-11-06 21:58:05 +03:00
|
|
|
feeRate: t.feeRate,
|
2020-09-04 14:04:18 +03:00
|
|
|
inputTotal: t.inputTotal,
|
2020-11-06 21:58:05 +03:00
|
|
|
changeOutput: t.changeOutput,
|
|
|
|
requiredOutput: t.requiredOutput,
|
2020-09-04 14:04:18 +03:00
|
|
|
walletInputTotal: t.walletInputTotal,
|
|
|
|
force: t.force,
|
|
|
|
inputs: make([]input.Input, len(t.inputs)),
|
|
|
|
}
|
|
|
|
copy(s.inputs, t.inputs)
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
// txInputSet is an object that accumulates tx inputs and keeps running counters
|
|
|
|
// on various properties of the tx.
|
|
|
|
type txInputSet struct {
|
|
|
|
txInputSetState
|
|
|
|
|
2019-12-10 17:04:10 +03:00
|
|
|
// dustLimit is the minimum output value of the tx.
|
|
|
|
dustLimit btcutil.Amount
|
|
|
|
|
|
|
|
// maxInputs is the maximum number of inputs that will be accepted in
|
|
|
|
// the set.
|
|
|
|
maxInputs int
|
2019-12-10 18:06:45 +03:00
|
|
|
|
|
|
|
// wallet contains wallet functionality required by the input set to
|
|
|
|
// retrieve utxos.
|
|
|
|
wallet Wallet
|
2019-12-10 17:04:10 +03:00
|
|
|
}
|
|
|
|
|
2020-11-06 21:44:12 +03:00
|
|
|
func dustLimit(relayFee chainfee.SatPerKWeight) btcutil.Amount {
|
|
|
|
return txrules.GetDustThreshold(
|
|
|
|
input.P2WPKHSize,
|
|
|
|
btcutil.Amount(relayFee.FeePerKVByte()),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2019-12-10 17:04:10 +03:00
|
|
|
// newTxInputSet constructs a new, empty input set.
|
2019-12-10 18:06:45 +03:00
|
|
|
func newTxInputSet(wallet Wallet, feePerKW,
|
|
|
|
relayFee chainfee.SatPerKWeight, maxInputs int) *txInputSet {
|
2019-12-10 17:04:10 +03:00
|
|
|
|
2020-11-06 21:44:12 +03:00
|
|
|
dustLimit := dustLimit(relayFee)
|
2019-12-10 17:04:10 +03:00
|
|
|
|
2020-09-04 15:03:14 +03:00
|
|
|
state := txInputSetState{
|
2020-11-06 21:58:05 +03:00
|
|
|
feeRate: feePerKW,
|
2020-09-04 15:03:14 +03:00
|
|
|
}
|
|
|
|
|
2019-12-10 17:04:10 +03:00
|
|
|
b := txInputSet{
|
2020-09-04 15:03:14 +03:00
|
|
|
dustLimit: dustLimit,
|
|
|
|
maxInputs: maxInputs,
|
|
|
|
wallet: wallet,
|
|
|
|
txInputSetState: state,
|
2019-12-10 17:04:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return &b
|
|
|
|
}
|
|
|
|
|
2020-11-06 21:58:05 +03:00
|
|
|
// enoughInput returns true if we've accumulated enough inputs to pay the fees
|
|
|
|
// and have at least one output that meets the dust limit.
|
|
|
|
func (t *txInputSet) enoughInput() bool {
|
|
|
|
// If we have a change output above dust, then we certainly have enough
|
|
|
|
// inputs to the transaction.
|
|
|
|
if t.changeOutput >= t.dustLimit {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// We did not have enough input for a change output. Check if we have
|
|
|
|
// enough input to pay the fees for a transaction with no change
|
|
|
|
// output.
|
|
|
|
fee := t.weightEstimate(false).fee()
|
|
|
|
if t.inputTotal < t.requiredOutput+fee {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// We could pay the fees, but we still need at least one output to be
|
|
|
|
// above the dust limit for the tx to be valid (we assume that these
|
|
|
|
// required outputs only get added if they are above dust)
|
|
|
|
for _, inp := range t.inputs {
|
|
|
|
if inp.RequiredTxOut() != nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
2019-12-10 17:04:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// add adds a new input to the set. It returns a bool indicating whether the
|
|
|
|
// input was added to the set. An input is rejected if it decreases the tx
|
|
|
|
// output value after paying fees.
|
2020-09-04 14:04:18 +03:00
|
|
|
func (t *txInputSet) addToState(inp input.Input, constraints addConstraints) *txInputSetState {
|
2019-12-10 18:06:45 +03:00
|
|
|
// Stop if max inputs is reached. Do not count additional wallet inputs,
|
|
|
|
// because we don't know in advance how many we may need.
|
2019-12-13 17:04:32 +03:00
|
|
|
if constraints != constraintsWallet &&
|
|
|
|
len(t.inputs) >= t.maxInputs {
|
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
return nil
|
2019-12-10 17:04:10 +03:00
|
|
|
}
|
|
|
|
|
2020-11-06 21:58:05 +03:00
|
|
|
// If the input comes with a required tx out that is below dust, we
|
|
|
|
// won't add it.
|
|
|
|
reqOut := inp.RequiredTxOut()
|
|
|
|
if reqOut != nil && btcutil.Amount(reqOut.Value) < t.dustLimit {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
// Clone the current set state.
|
|
|
|
s := t.clone()
|
2019-12-10 17:04:10 +03:00
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
// Add the new input.
|
|
|
|
s.inputs = append(s.inputs, inp)
|
|
|
|
|
|
|
|
// Add the value of the new input.
|
|
|
|
value := btcutil.Amount(inp.SignDesc().Output.Value)
|
|
|
|
s.inputTotal += value
|
2019-12-10 17:04:10 +03:00
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
// Recalculate the tx fee.
|
2020-11-06 21:58:05 +03:00
|
|
|
fee := s.weightEstimate(true).fee()
|
2019-12-10 17:04:10 +03:00
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
// Calculate the new output value.
|
2020-11-06 21:58:05 +03:00
|
|
|
if reqOut != nil {
|
|
|
|
s.requiredOutput += btcutil.Amount(reqOut.Value)
|
|
|
|
}
|
|
|
|
s.changeOutput = s.inputTotal - s.requiredOutput - fee
|
2019-12-13 17:04:32 +03:00
|
|
|
|
2020-11-06 21:58:05 +03:00
|
|
|
// Calculate the yield of this input from the change in total tx output
|
|
|
|
// value.
|
|
|
|
inputYield := s.totalOutput() - t.totalOutput()
|
2019-12-13 17:04:32 +03:00
|
|
|
|
|
|
|
switch constraints {
|
|
|
|
|
|
|
|
// Don't sweep inputs that cost us more to sweep than they give us.
|
|
|
|
case constraintsRegular:
|
|
|
|
if inputYield <= 0 {
|
2020-09-04 14:04:18 +03:00
|
|
|
return nil
|
2019-12-13 17:04:32 +03:00
|
|
|
}
|
|
|
|
|
2019-12-09 17:40:05 +03:00
|
|
|
// For force adds, no further constraints apply.
|
|
|
|
case constraintsForce:
|
2020-09-04 14:04:18 +03:00
|
|
|
s.force = true
|
2019-12-09 17:40:05 +03:00
|
|
|
|
2019-12-13 17:04:32 +03:00
|
|
|
// We are attaching a wallet input to raise the tx output value above
|
|
|
|
// the dust limit.
|
|
|
|
case constraintsWallet:
|
|
|
|
// Skip this wallet input if adding it would lower the output
|
|
|
|
// value.
|
|
|
|
if inputYield <= 0 {
|
2020-09-04 14:04:18 +03:00
|
|
|
return nil
|
2019-12-13 17:04:32 +03:00
|
|
|
}
|
2019-12-10 17:04:10 +03:00
|
|
|
|
2019-12-10 18:06:45 +03:00
|
|
|
// Calculate the total value that we spend in this tx from the
|
|
|
|
// wallet if we'd add this wallet input.
|
2020-09-04 14:04:18 +03:00
|
|
|
s.walletInputTotal += value
|
2019-12-10 18:06:45 +03:00
|
|
|
|
|
|
|
// In any case, we don't want to lose money by sweeping. If we
|
|
|
|
// don't get more out of the tx then we put in ourselves, do not
|
2019-12-09 17:40:05 +03:00
|
|
|
// add this wallet input. If there is at least one force sweep
|
|
|
|
// in the set, this does no longer apply.
|
2019-12-10 18:06:45 +03:00
|
|
|
//
|
|
|
|
// We should only add wallet inputs to get the tx output value
|
|
|
|
// above the dust limit, otherwise we'd only burn into fees.
|
|
|
|
// This is guarded by tryAddWalletInputsIfNeeded.
|
|
|
|
//
|
|
|
|
// TODO(joostjager): Possibly require a max ratio between the
|
|
|
|
// value of the wallet input and what we get out of this
|
|
|
|
// transaction. To prevent attaching and locking a big utxo for
|
|
|
|
// very little benefit.
|
2020-11-06 21:58:05 +03:00
|
|
|
if !s.force && s.walletInputTotal >= s.totalOutput() {
|
2019-12-10 18:06:45 +03:00
|
|
|
log.Debugf("Rejecting wallet input of %v, because it "+
|
|
|
|
"would make a negative yielding transaction "+
|
|
|
|
"(%v)",
|
2020-11-06 21:58:05 +03:00
|
|
|
value, s.totalOutput()-s.walletInputTotal)
|
2019-12-10 18:06:45 +03:00
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
return nil
|
2019-12-10 18:06:45 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-04 14:04:18 +03:00
|
|
|
return &s
|
|
|
|
}
|
|
|
|
|
|
|
|
// add adds a new input to the set. It returns a bool indicating whether the
|
|
|
|
// input was added to the set. An input is rejected if it decreases the tx
|
|
|
|
// output value after paying fees.
|
|
|
|
func (t *txInputSet) add(input input.Input, constraints addConstraints) bool {
|
|
|
|
newState := t.addToState(input, constraints)
|
|
|
|
if newState == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
t.txInputSetState = *newState
|
2019-12-10 17:04:10 +03:00
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// addPositiveYieldInputs adds sweepableInputs that have a positive yield to the
|
|
|
|
// input set. This function assumes that the list of inputs is sorted descending
|
|
|
|
// by yield.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): Consider including some negative yield inputs too to clean
|
|
|
|
// up the utxo set even if it costs us some fees up front. In the spirit of
|
|
|
|
// minimizing any negative externalities we cause for the Bitcoin system as a
|
|
|
|
// whole.
|
|
|
|
func (t *txInputSet) addPositiveYieldInputs(sweepableInputs []txInput) {
|
2020-12-09 14:24:01 +03:00
|
|
|
for i, inp := range sweepableInputs {
|
2019-12-09 17:40:05 +03:00
|
|
|
// Apply relaxed constraints for force sweeps.
|
|
|
|
constraints := constraintsRegular
|
2020-12-09 14:24:01 +03:00
|
|
|
if inp.parameters().Force {
|
2019-12-09 17:40:05 +03:00
|
|
|
constraints = constraintsForce
|
|
|
|
}
|
|
|
|
|
2019-12-10 17:04:10 +03:00
|
|
|
// Try to add the input to the transaction. If that doesn't
|
|
|
|
// succeed because it wouldn't increase the output value,
|
|
|
|
// return. Assuming inputs are sorted by yield, any further
|
|
|
|
// inputs wouldn't increase the output value either.
|
2020-12-09 14:24:01 +03:00
|
|
|
if !t.add(inp, constraints) {
|
|
|
|
var rem []input.Input
|
|
|
|
for j := i; j < len(sweepableInputs); j++ {
|
|
|
|
rem = append(rem, sweepableInputs[j])
|
|
|
|
}
|
|
|
|
log.Debugf("%d negative yield inputs not added to "+
|
|
|
|
"input set: %v", len(rem),
|
|
|
|
inputTypeSummary(rem))
|
2019-12-10 17:04:10 +03:00
|
|
|
return
|
|
|
|
}
|
2020-12-09 14:24:01 +03:00
|
|
|
|
|
|
|
log.Debugf("Added positive yield input %v to input set",
|
|
|
|
inputTypeSummary([]input.Input{inp}))
|
2019-12-10 17:04:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// We managed to add all inputs to the set.
|
|
|
|
}
|
2019-12-10 18:06:45 +03:00
|
|
|
|
2020-12-09 14:24:01 +03:00
|
|
|
// tryAddWalletInputsIfNeeded retrieves utxos from the wallet and tries adding
|
|
|
|
// as many as required to bring the tx output value above the given minimum.
|
2019-12-10 18:06:45 +03:00
|
|
|
func (t *txInputSet) tryAddWalletInputsIfNeeded() error {
|
2020-11-06 21:58:05 +03:00
|
|
|
// If we've already have enough to pay the transaction fees and have at
|
|
|
|
// least one output materialize, no action is needed.
|
|
|
|
if t.enoughInput() {
|
2019-12-10 18:06:45 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Retrieve wallet utxos. Only consider confirmed utxos to prevent
|
|
|
|
// problems around RBF rules for unconfirmed inputs.
|
2021-02-20 04:41:50 +03:00
|
|
|
utxos, err := t.wallet.ListUnspentWitnessFromDefaultAccount(
|
|
|
|
1, math.MaxInt32,
|
|
|
|
)
|
2019-12-10 18:06:45 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, utxo := range utxos {
|
|
|
|
input, err := createWalletTxInput(utxo)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the wallet input isn't positively-yielding at this fee
|
|
|
|
// rate, skip it.
|
2019-12-13 17:04:32 +03:00
|
|
|
if !t.add(input, constraintsWallet) {
|
2019-12-10 18:06:45 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return if we've reached the minimum output amount.
|
2020-11-06 21:58:05 +03:00
|
|
|
if t.enoughInput() {
|
2019-12-10 18:06:45 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We were not able to reach the minimum output amount.
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// createWalletTxInput converts a wallet utxo into an object that can be added
|
|
|
|
// to the other inputs to sweep.
|
|
|
|
func createWalletTxInput(utxo *lnwallet.Utxo) (input.Input, error) {
|
|
|
|
var witnessType input.WitnessType
|
|
|
|
switch utxo.AddressType {
|
|
|
|
case lnwallet.WitnessPubKey:
|
|
|
|
witnessType = input.WitnessKeyHash
|
|
|
|
case lnwallet.NestedWitnessPubKey:
|
|
|
|
witnessType = input.NestedWitnessKeyHash
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unknown address type %v",
|
|
|
|
utxo.AddressType)
|
|
|
|
}
|
|
|
|
|
|
|
|
signDesc := &input.SignDescriptor{
|
|
|
|
Output: &wire.TxOut{
|
|
|
|
PkScript: utxo.PkScript,
|
|
|
|
Value: int64(utxo.Value),
|
|
|
|
},
|
|
|
|
HashType: txscript.SigHashAll,
|
|
|
|
}
|
|
|
|
|
|
|
|
// A height hint doesn't need to be set, because we don't monitor these
|
|
|
|
// inputs for spend.
|
|
|
|
heightHint := uint32(0)
|
|
|
|
|
|
|
|
return input.NewBaseInput(
|
|
|
|
&utxo.OutPoint, witnessType, signDesc, heightHint,
|
|
|
|
), nil
|
|
|
|
}
|