2019-01-24 16:28:25 +03:00
|
|
|
package lnd
|
2016-09-12 22:37:51 +03:00
|
|
|
|
|
|
|
import (
|
2016-12-14 02:32:44 +03:00
|
|
|
"bytes"
|
|
|
|
"encoding/binary"
|
2017-05-05 01:51:57 +03:00
|
|
|
"fmt"
|
2016-12-14 02:32:44 +03:00
|
|
|
"io"
|
2016-09-12 22:37:51 +03:00
|
|
|
"sync"
|
2016-11-29 03:53:15 +03:00
|
|
|
"sync/atomic"
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2018-06-05 04:34:16 +03:00
|
|
|
"github.com/btcsuite/btcd/txscript"
|
|
|
|
"github.com/btcsuite/btcd/wire"
|
|
|
|
"github.com/btcsuite/btcutil"
|
2018-07-25 07:22:13 +03:00
|
|
|
"github.com/davecgh/go-spew/spew"
|
2018-09-20 13:23:01 +03:00
|
|
|
|
2018-07-25 07:22:13 +03:00
|
|
|
"github.com/lightningnetwork/lnd/chainntnfs"
|
|
|
|
"github.com/lightningnetwork/lnd/channeldb"
|
2019-01-16 17:47:43 +03:00
|
|
|
"github.com/lightningnetwork/lnd/input"
|
2018-07-25 07:22:13 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet"
|
2019-01-16 17:47:43 +03:00
|
|
|
"github.com/lightningnetwork/lnd/sweep"
|
2016-09-12 22:37:51 +03:00
|
|
|
)
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// SUMMARY OF OUTPUT STATES
|
|
|
|
//
|
|
|
|
// - CRIB
|
|
|
|
// - SerializedType: babyOutput
|
|
|
|
// - OriginalOutputType: HTLC
|
|
|
|
// - Awaiting: First-stage HTLC CLTV expiry
|
|
|
|
// - HeightIndexEntry: Absolute block height of CLTV expiry.
|
|
|
|
// - NextState: KNDR
|
|
|
|
// - PSCL
|
|
|
|
// - SerializedType: kidOutput
|
|
|
|
// - OriginalOutputType: Commitment
|
|
|
|
// - Awaiting: Confirmation of commitment txn
|
|
|
|
// - HeightIndexEntry: None.
|
|
|
|
// - NextState: KNDR
|
|
|
|
// - KNDR
|
|
|
|
// - SerializedType: kidOutput
|
|
|
|
// - OriginalOutputType: Commitment or HTLC
|
|
|
|
// - Awaiting: Commitment CSV expiry or second-stage HTLC CSV expiry.
|
|
|
|
// - HeightIndexEntry: Input confirmation height + relative CSV delay
|
|
|
|
// - NextState: GRAD
|
|
|
|
// - GRAD:
|
|
|
|
// - SerializedType: kidOutput
|
|
|
|
// - OriginalOutputType: Commitment or HTLC
|
|
|
|
// - Awaiting: All other outputs in channel to become GRAD.
|
|
|
|
// - NextState: Mark channel fully closed in channeldb and remove.
|
|
|
|
//
|
|
|
|
// DESCRIPTION OF OUTPUT STATES
|
|
|
|
//
|
2018-01-17 07:52:23 +03:00
|
|
|
// TODO(roasbeef): update comment with both new output types
|
|
|
|
//
|
2017-10-07 02:44:05 +03:00
|
|
|
// - CRIB (babyOutput) outputs are two-stage htlc outputs that are initially
|
|
|
|
// locked using a CLTV delay, followed by a CSV delay. The first stage of a
|
|
|
|
// crib output requires broadcasting a presigned htlc timeout txn generated
|
|
|
|
// by the wallet after an absolute expiry height. Since the timeout txns are
|
|
|
|
// predetermined, they cannot be batched after-the-fact, meaning that all
|
|
|
|
// CRIB outputs are broadcast and confirmed independently. After the first
|
|
|
|
// stage is complete, a CRIB output is moved to the KNDR state, which will
|
|
|
|
// finishing sweeping the second-layer CSV delay.
|
|
|
|
//
|
|
|
|
// - PSCL (kidOutput) outputs are commitment outputs locked under a CSV delay.
|
|
|
|
// These outputs are stored temporarily in this state until the commitment
|
|
|
|
// transaction confirms, as this solidifies an absolute height that the
|
|
|
|
// relative time lock will expire. Once this maturity height is determined,
|
|
|
|
// the PSCL output is moved into KNDR.
|
|
|
|
//
|
|
|
|
// - KNDR (kidOutput) outputs are CSV delayed outputs for which the maturity
|
|
|
|
// height has been fully determined. This results from having received
|
|
|
|
// confirmation of the UTXO we are trying to spend, contained in either the
|
|
|
|
// commitment txn or htlc timeout txn. Once the maturity height is reached,
|
|
|
|
// the utxo nursery will sweep all KNDR outputs scheduled for that height
|
|
|
|
// using a single txn.
|
|
|
|
//
|
|
|
|
// - GRAD (kidOutput) outputs are KNDR outputs that have successfully been
|
|
|
|
// swept into the user's wallet. A channel is considered mature once all of
|
|
|
|
// its outputs, including two-stage htlcs, have entered the GRAD state,
|
|
|
|
// indicating that it safe to mark the channel as fully closed.
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// OUTPUT STATE TRANSITIONS IN UTXO NURSERY
|
|
|
|
//
|
|
|
|
// ┌────────────────┐ ┌──────────────┐
|
|
|
|
// │ Commit Outputs │ │ HTLC Outputs │
|
|
|
|
// └────────────────┘ └──────────────┘
|
|
|
|
// │ │
|
|
|
|
// │ │
|
|
|
|
// │ │ UTXO NURSERY
|
|
|
|
// ┌───────────┼────────────────┬───────────┼───────────────────────────────┐
|
|
|
|
// │ │ │ │
|
|
|
|
// │ │ │ │ │
|
|
|
|
// │ │ │ CLTV-Delayed │
|
|
|
|
// │ │ │ V babyOutputs │
|
|
|
|
// │ │ ┌──────┐ │
|
|
|
|
// │ │ │ │ CRIB │ │
|
|
|
|
// │ │ └──────┘ │
|
|
|
|
// │ │ │ │ │
|
|
|
|
// │ │ │ │
|
|
|
|
// │ │ │ | │
|
|
|
|
// │ │ V Wait CLTV │
|
|
|
|
// │ │ │ [ ] + │
|
|
|
|
// │ │ | Publish Txn │
|
|
|
|
// │ │ │ │ │
|
|
|
|
// │ │ │ │
|
|
|
|
// │ │ │ V ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐ │
|
|
|
|
// │ │ ( ) waitForTimeoutConf │
|
|
|
|
// │ │ │ | └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘ │
|
|
|
|
// │ │ │ │
|
|
|
|
// │ │ │ │ │
|
|
|
|
// │ │ │ │
|
|
|
|
// │ V │ │ │
|
|
|
|
// │ ┌──────┐ │ │
|
|
|
|
// │ │ PSCL │ └ ── ── ─┼ ── ── ── ── ── ── ── ─┤
|
|
|
|
// │ └──────┘ │ │
|
|
|
|
// │ │ │ │
|
|
|
|
// │ │ │ │
|
|
|
|
// │ V ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐ │ CSV-Delayed │
|
|
|
|
// │ ( ) waitForCommitConf │ kidOutputs │
|
|
|
|
// │ | └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘ │ │
|
|
|
|
// │ │ │ │
|
|
|
|
// │ │ │ │
|
|
|
|
// │ │ V │
|
|
|
|
// │ │ ┌──────┐ │
|
|
|
|
// │ └─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─▶│ KNDR │ │
|
|
|
|
// │ └──────┘ │
|
|
|
|
// │ │ │
|
|
|
|
// │ │ │
|
|
|
|
// │ | │
|
|
|
|
// │ V Wait CSV │
|
|
|
|
// │ [ ] + │
|
|
|
|
// │ | Publish Txn │
|
|
|
|
// │ │ │
|
|
|
|
// │ │ │
|
|
|
|
// │ V ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │
|
|
|
|
// │ ( ) waitForSweepConf │
|
|
|
|
// │ | └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ │
|
|
|
|
// │ │ │
|
|
|
|
// │ │ │
|
|
|
|
// │ V │
|
|
|
|
// │ ┌──────┐ │
|
|
|
|
// │ │ GRAD │ │
|
|
|
|
// │ └──────┘ │
|
|
|
|
// │ │ │
|
|
|
|
// │ │ │
|
|
|
|
// │ │ │
|
|
|
|
// └────────────────────────────────────────┼───────────────────────────────┘
|
|
|
|
// │
|
|
|
|
// │
|
|
|
|
// │
|
|
|
|
// │
|
|
|
|
// V
|
|
|
|
// ┌────────────────┐
|
|
|
|
// │ Wallet Outputs │
|
|
|
|
// └────────────────┘
|
|
|
|
|
|
|
|
var byteOrder = binary.BigEndian
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2017-05-15 05:20:26 +03:00
|
|
|
var (
|
|
|
|
// ErrContractNotFound is returned when the nursery is unable to
|
2017-12-18 05:40:05 +03:00
|
|
|
// retrieve information about a queried contract.
|
2017-05-15 05:20:26 +03:00
|
|
|
ErrContractNotFound = fmt.Errorf("unable to locate contract")
|
|
|
|
)
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// NurseryConfig abstracts the required subsystems used by the utxo nursery. An
|
2017-12-18 05:40:05 +03:00
|
|
|
// instance of NurseryConfig is passed to newUtxoNursery during instantiation.
|
2017-10-07 02:44:05 +03:00
|
|
|
type NurseryConfig struct {
|
|
|
|
// ChainIO is used by the utxo nursery to determine the current block
|
|
|
|
// height, which drives the incubation of the nursery's outputs.
|
|
|
|
ChainIO lnwallet.BlockChainIO
|
|
|
|
|
|
|
|
// ConfDepth is the number of blocks the nursery store waits before
|
|
|
|
// determining outputs in the chain as confirmed.
|
|
|
|
ConfDepth uint32
|
|
|
|
|
2018-09-12 23:23:06 +03:00
|
|
|
// FetchClosedChannels provides access to a user's channels, such that
|
|
|
|
// they can be marked fully closed after incubation has concluded.
|
|
|
|
FetchClosedChannels func(pendingOnly bool) (
|
|
|
|
[]*channeldb.ChannelCloseSummary, error)
|
|
|
|
|
|
|
|
// FetchClosedChannel provides access to the close summary to extract a
|
|
|
|
// height hint from.
|
|
|
|
FetchClosedChannel func(chanID *wire.OutPoint) (
|
|
|
|
*channeldb.ChannelCloseSummary, error)
|
2017-10-07 02:44:05 +03:00
|
|
|
|
|
|
|
// Notifier provides the utxo nursery the ability to subscribe to
|
|
|
|
// transaction confirmation events, which advance outputs through their
|
|
|
|
// persistence state transitions.
|
|
|
|
Notifier chainntnfs.ChainNotifier
|
|
|
|
|
|
|
|
// PublishTransaction facilitates the process of broadcasting a signed
|
|
|
|
// transaction to the appropriate network.
|
|
|
|
PublishTransaction func(*wire.MsgTx) error
|
|
|
|
|
|
|
|
// Store provides access to and modification of the persistent state
|
|
|
|
// maintained about the utxo nursery's incubating outputs.
|
|
|
|
Store NurseryStore
|
2018-09-26 08:03:16 +03:00
|
|
|
|
2018-12-19 14:49:01 +03:00
|
|
|
// Sweep sweeps an input back to the wallet.
|
2019-01-16 17:47:43 +03:00
|
|
|
SweepInput func(input input.Input) (chan sweep.Result, error)
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
|
|
|
|
2016-09-12 22:37:51 +03:00
|
|
|
// utxoNursery is a system dedicated to incubating time-locked outputs created
|
|
|
|
// by the broadcast of a commitment transaction either by us, or the remote
|
|
|
|
// peer. The nursery accepts outputs and "incubates" them until they've reached
|
|
|
|
// maturity, then sweep the outputs into the source wallet. An output is
|
|
|
|
// considered mature after the relative time-lock within the pkScript has
|
2016-11-21 22:27:50 +03:00
|
|
|
// passed. As outputs reach their maturity age, they're swept in batches into
|
2016-09-12 22:37:51 +03:00
|
|
|
// the source wallet, returning the outputs so they can be used within future
|
|
|
|
// channels, or regular Bitcoin transactions.
|
|
|
|
type utxoNursery struct {
|
2018-06-01 01:41:41 +03:00
|
|
|
started uint32 // To be used atomically.
|
|
|
|
stopped uint32 // To be used atomically.
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
cfg *NurseryConfig
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
mu sync.Mutex
|
|
|
|
bestHeight uint32
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
quit chan struct{}
|
|
|
|
wg sync.WaitGroup
|
2016-09-12 22:37:51 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// newUtxoNursery creates a new instance of the utxoNursery from a
|
|
|
|
// ChainNotifier and LightningWallet instance.
|
2017-10-07 02:44:05 +03:00
|
|
|
func newUtxoNursery(cfg *NurseryConfig) *utxoNursery {
|
2016-09-12 22:37:51 +03:00
|
|
|
return &utxoNursery{
|
2017-10-07 02:44:05 +03:00
|
|
|
cfg: cfg,
|
|
|
|
quit: make(chan struct{}),
|
2016-09-12 22:37:51 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start launches all goroutines the utxoNursery needs to properly carry out
|
|
|
|
// its duties.
|
|
|
|
func (u *utxoNursery) Start() error {
|
2016-11-29 03:53:15 +03:00
|
|
|
if !atomic.CompareAndSwapUint32(&u.started, 0, 1) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
utxnLog.Tracef("Starting UTXO nursery")
|
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
// Retrieve the currently best known block. This is needed to have the
|
|
|
|
// state machine catch up with the blocks we missed when we were down.
|
|
|
|
bestHash, bestHeight, err := u.cfg.ChainIO.GetBestBlock()
|
2017-05-11 03:23:22 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
// Set best known height to schedule late registrations properly.
|
|
|
|
atomic.StoreUint32(&u.bestHeight, uint32(bestHeight))
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// 2. Flush all fully-graduated channels from the pipeline.
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// Load any pending close channels, which represents the super set of
|
|
|
|
// all channels that may still be incubating.
|
2018-09-12 23:23:06 +03:00
|
|
|
pendingCloseChans, err := u.cfg.FetchClosedChannels(true)
|
2016-12-14 02:32:44 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// Ensure that all mature channels have been marked as fully closed in
|
|
|
|
// the channeldb.
|
|
|
|
for _, pendingClose := range pendingCloseChans {
|
|
|
|
err := u.closeAndRemoveIfMature(&pendingClose.ChanPoint)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
2017-01-06 00:25:47 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// TODO(conner): check if any fully closed channels can be removed from
|
|
|
|
// utxn.
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// 2. Restart spend ntfns for any preschool outputs, which are waiting
|
2018-01-17 07:33:55 +03:00
|
|
|
// for the force closed commitment txn to confirm, or any second-layer
|
|
|
|
// HTLC success transactions.
|
2017-10-07 02:44:05 +03:00
|
|
|
//
|
|
|
|
// NOTE: The next two steps *may* spawn go routines, thus from this
|
|
|
|
// point forward, we must close the nursery's quit channel if we detect
|
|
|
|
// any failures during startup to ensure they terminate.
|
2018-01-23 07:39:54 +03:00
|
|
|
if err := u.reloadPreschool(); err != nil {
|
2017-10-07 02:44:05 +03:00
|
|
|
close(u.quit)
|
|
|
|
return err
|
2017-01-06 00:25:47 +03:00
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
// 3. Replay all crib and kindergarten outputs up to the current best
|
|
|
|
// height.
|
|
|
|
if err := u.reloadClasses(uint32(bestHeight)); err != nil {
|
|
|
|
close(u.quit)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start watching for new blocks, as this will drive the nursery store's
|
|
|
|
// state machine.
|
|
|
|
newBlockChan, err := u.cfg.Notifier.RegisterBlockEpochNtfn(&chainntnfs.BlockEpoch{
|
|
|
|
Height: bestHeight,
|
|
|
|
Hash: bestHash,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2017-10-07 02:44:05 +03:00
|
|
|
close(u.quit)
|
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
u.wg.Add(1)
|
|
|
|
go u.incubator(newBlockChan)
|
2017-01-17 07:41:32 +03:00
|
|
|
|
2016-12-14 02:32:44 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop gracefully shuts down any lingering goroutines launched during normal
|
2016-09-12 22:37:51 +03:00
|
|
|
// operation of the utxoNursery.
|
|
|
|
func (u *utxoNursery) Stop() error {
|
2016-11-29 03:53:15 +03:00
|
|
|
if !atomic.CompareAndSwapUint32(&u.stopped, 0, 1) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
utxnLog.Infof("UTXO nursery shutting down")
|
|
|
|
|
2016-09-12 22:37:51 +03:00
|
|
|
close(u.quit)
|
|
|
|
u.wg.Wait()
|
2016-11-21 22:27:50 +03:00
|
|
|
|
2016-09-12 22:37:51 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:33:55 +03:00
|
|
|
// IncubateOutputs sends a request to the utxoNursery to incubate a set of
|
|
|
|
// outputs from an existing commitment transaction. Outputs need to incubate if
|
|
|
|
// they're CLTV absolute time locked, or if they're CSV relative time locked.
|
|
|
|
// Once all outputs reach maturity, they'll be swept back into the wallet.
|
|
|
|
func (u *utxoNursery) IncubateOutputs(chanPoint wire.OutPoint,
|
|
|
|
commitResolution *lnwallet.CommitOutputResolution,
|
|
|
|
outgoingHtlcs []lnwallet.OutgoingHtlcResolution,
|
2018-09-05 16:49:35 +03:00
|
|
|
incomingHtlcs []lnwallet.IncomingHtlcResolution,
|
|
|
|
broadcastHeight uint32) error {
|
2017-01-24 13:12:32 +03:00
|
|
|
|
2018-09-12 23:23:06 +03:00
|
|
|
// Add to wait group because nursery might shut down during execution of
|
|
|
|
// this function. Otherwise it could happen that nursery thinks it is
|
|
|
|
// shut down, but in this function new goroutines were started and stay
|
|
|
|
// around.
|
|
|
|
u.wg.Add(1)
|
|
|
|
defer u.wg.Done()
|
|
|
|
|
2018-09-25 06:40:23 +03:00
|
|
|
// Check quit channel for the case where the waitgroup wait was finished
|
|
|
|
// right before this function's add call was made.
|
|
|
|
select {
|
|
|
|
case <-u.quit:
|
|
|
|
return fmt.Errorf("nursery shutting down")
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:33:55 +03:00
|
|
|
numHtlcs := len(incomingHtlcs) + len(outgoingHtlcs)
|
2017-10-07 02:44:05 +03:00
|
|
|
var (
|
2018-01-17 07:33:55 +03:00
|
|
|
hasCommit bool
|
|
|
|
|
|
|
|
// Kid outputs can be swept after an initial confirmation
|
|
|
|
// followed by a maturity period.Baby outputs are two stage and
|
2018-04-18 05:02:04 +03:00
|
|
|
// will need to wait for an absolute time out to reach a
|
2018-01-17 07:33:55 +03:00
|
|
|
// confirmation, then require a relative confirmation delay.
|
|
|
|
kidOutputs = make([]kidOutput, 0, 1+len(incomingHtlcs))
|
|
|
|
babyOutputs = make([]babyOutput, 0, len(outgoingHtlcs))
|
2017-10-07 02:44:05 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// 1. Build all the spendable outputs that we will try to incubate.
|
|
|
|
|
2018-01-17 07:33:55 +03:00
|
|
|
// It could be that our to-self output was below the dust limit. In
|
|
|
|
// that case the commit resolution would be nil and we would not have
|
|
|
|
// that output to incubate.
|
|
|
|
if commitResolution != nil {
|
|
|
|
hasCommit = true
|
2017-09-29 04:26:42 +03:00
|
|
|
selfOutput := makeKidOutput(
|
2018-01-17 07:33:55 +03:00
|
|
|
&commitResolution.SelfOutPoint,
|
|
|
|
&chanPoint,
|
|
|
|
commitResolution.MaturityDelay,
|
2019-01-16 17:47:43 +03:00
|
|
|
input.CommitmentTimeLock,
|
2018-01-17 07:33:55 +03:00
|
|
|
&commitResolution.SelfOutputSignDesc,
|
|
|
|
0,
|
2017-09-29 04:26:42 +03:00
|
|
|
)
|
|
|
|
|
2018-02-07 06:11:11 +03:00
|
|
|
// We'll skip any zero valued outputs as this indicates we
|
2017-10-07 02:44:05 +03:00
|
|
|
// don't have a settled balance within the commitment
|
|
|
|
// transaction.
|
|
|
|
if selfOutput.Amount() > 0 {
|
2018-01-17 07:33:55 +03:00
|
|
|
kidOutputs = append(kidOutputs, selfOutput)
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
2016-09-12 22:37:51 +03:00
|
|
|
}
|
2017-01-18 03:21:51 +03:00
|
|
|
|
2018-01-17 07:33:55 +03:00
|
|
|
// TODO(roasbeef): query and see if we already have, if so don't add?
|
2017-05-05 01:51:57 +03:00
|
|
|
|
2018-01-17 07:33:55 +03:00
|
|
|
// For each incoming HTLC, we'll register a kid output marked as a
|
|
|
|
// second-layer HTLC output. We effectively skip the baby stage (as the
|
|
|
|
// timelock is zero), and enter the kid stage.
|
|
|
|
for _, htlcRes := range incomingHtlcs {
|
|
|
|
htlcOutput := makeKidOutput(
|
|
|
|
&htlcRes.ClaimOutpoint, &chanPoint, htlcRes.CsvDelay,
|
2019-01-16 17:47:43 +03:00
|
|
|
input.HtlcAcceptedSuccessSecondLevel,
|
2018-01-17 07:33:55 +03:00
|
|
|
&htlcRes.SweepSignDesc, 0,
|
2017-10-07 02:44:05 +03:00
|
|
|
)
|
2016-12-16 00:55:15 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
if htlcOutput.Amount() > 0 {
|
2018-01-17 07:33:55 +03:00
|
|
|
kidOutputs = append(kidOutputs, htlcOutput)
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
|
|
|
}
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2018-01-17 07:33:55 +03:00
|
|
|
// For each outgoing HTLC, we'll create a baby output. If this is our
|
|
|
|
// commitment transaction, then we'll broadcast a second-layer
|
|
|
|
// transaction to transition to a kid output. Otherwise, we'll directly
|
|
|
|
// spend once the CLTV delay us up.
|
|
|
|
for _, htlcRes := range outgoingHtlcs {
|
|
|
|
// If this HTLC is on our commitment transaction, then it'll be
|
|
|
|
// a baby output as we need to go to the second level to sweep
|
|
|
|
// it.
|
|
|
|
if htlcRes.SignedTimeoutTx != nil {
|
|
|
|
htlcOutput := makeBabyOutput(&chanPoint, &htlcRes)
|
|
|
|
|
|
|
|
if htlcOutput.Amount() > 0 {
|
|
|
|
babyOutputs = append(babyOutputs, htlcOutput)
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, this is actually a kid output as we can sweep it
|
|
|
|
// once the commitment transaction confirms, and the absolute
|
|
|
|
// CLTV lock has expired. We set the CSV delay to zero to
|
|
|
|
// indicate this is actually a CLTV output.
|
|
|
|
htlcOutput := makeKidOutput(
|
|
|
|
&htlcRes.ClaimOutpoint, &chanPoint, 0,
|
2019-01-16 17:47:43 +03:00
|
|
|
input.HtlcOfferedRemoteTimeout,
|
2018-01-17 07:33:55 +03:00
|
|
|
&htlcRes.SweepSignDesc, htlcRes.Expiry,
|
|
|
|
)
|
|
|
|
kidOutputs = append(kidOutputs, htlcOutput)
|
2016-09-12 22:37:51 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 07:33:55 +03:00
|
|
|
// TODO(roasbeef): if want to handle outgoing on remote commit
|
|
|
|
// * need ability to cancel in the case that we learn of pre-image or
|
|
|
|
// remote party pulls
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
utxnLog.Infof("Incubating Channel(%s) has-commit=%v, num-htlcs=%d",
|
2018-01-17 07:33:55 +03:00
|
|
|
chanPoint, hasCommit, numHtlcs)
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
u.mu.Lock()
|
|
|
|
defer u.mu.Unlock()
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// 2. Persist the outputs we intended to sweep in the nursery store
|
2018-01-17 07:33:55 +03:00
|
|
|
if err := u.cfg.Store.Incubate(kidOutputs, babyOutputs); err != nil {
|
2017-10-07 02:44:05 +03:00
|
|
|
utxnLog.Errorf("unable to begin incubation of Channel(%s): %v",
|
2018-01-17 07:33:55 +03:00
|
|
|
chanPoint, err)
|
2017-10-07 02:44:05 +03:00
|
|
|
return err
|
|
|
|
}
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2018-01-17 07:33:55 +03:00
|
|
|
// As an intermediate step, we'll now check to see if any of the baby
|
|
|
|
// outputs has actually _already_ expired. This may be the case if
|
|
|
|
// blocks were mined while we processed this message.
|
|
|
|
_, bestHeight, err := u.cfg.ChainIO.GetBestBlock()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// We'll examine all the baby outputs just inserted into the database,
|
|
|
|
// if the output has already expired, then we'll *immediately* sweep
|
|
|
|
// it. This may happen if the caller raced a block to call this method.
|
2019-05-17 06:37:30 +03:00
|
|
|
for i, babyOutput := range babyOutputs {
|
2018-01-17 07:33:55 +03:00
|
|
|
if uint32(bestHeight) >= babyOutput.expiry {
|
2019-05-17 06:37:30 +03:00
|
|
|
err = u.sweepCribOutput(
|
|
|
|
babyOutput.expiry, &babyOutputs[i],
|
|
|
|
)
|
2018-01-17 07:33:55 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 3. If we are incubating any preschool outputs, register for a
|
|
|
|
// confirmation notification that will transition it to the
|
|
|
|
// kindergarten bucket.
|
|
|
|
if len(kidOutputs) != 0 {
|
2019-05-17 06:37:30 +03:00
|
|
|
for i := range kidOutputs {
|
2018-09-05 16:49:35 +03:00
|
|
|
err := u.registerPreschoolConf(
|
2019-05-17 06:37:30 +03:00
|
|
|
&kidOutputs[i], broadcastHeight,
|
2018-09-05 16:49:35 +03:00
|
|
|
)
|
2018-01-17 07:33:55 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
return nil
|
2017-05-05 01:54:50 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NurseryReport attempts to return a nursery report stored for the target
|
|
|
|
// outpoint. A nursery report details the maturity/sweeping progress for a
|
|
|
|
// contract that was previously force closed. If a report entry for the target
|
|
|
|
// chanPoint is unable to be constructed, then an error will be returned.
|
2017-10-07 02:44:05 +03:00
|
|
|
func (u *utxoNursery) NurseryReport(
|
|
|
|
chanPoint *wire.OutPoint) (*contractMaturityReport, error) {
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
u.mu.Lock()
|
|
|
|
defer u.mu.Unlock()
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
utxnLog.Infof("NurseryReport: building nursery report for channel %v",
|
|
|
|
chanPoint)
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2019-01-07 12:05:30 +03:00
|
|
|
report := &contractMaturityReport{}
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
if err := u.cfg.Store.ForChanOutputs(chanPoint, func(k, v []byte) error {
|
|
|
|
switch {
|
|
|
|
case bytes.HasPrefix(k, cribPrefix):
|
|
|
|
// Cribs outputs are the only kind currently stored as
|
|
|
|
// baby outputs.
|
|
|
|
var baby babyOutput
|
|
|
|
err := baby.Decode(bytes.NewReader(v))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2017-05-05 01:54:50 +03:00
|
|
|
}
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// Each crib output represents a stage one htlc, and
|
|
|
|
// will contribute towards the limbo balance.
|
2018-01-17 07:46:55 +03:00
|
|
|
report.AddLimboStage1TimeoutHtlc(&baby)
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
case bytes.HasPrefix(k, psclPrefix),
|
|
|
|
bytes.HasPrefix(k, kndrPrefix),
|
|
|
|
bytes.HasPrefix(k, gradPrefix):
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// All others states can be deserialized as kid outputs.
|
|
|
|
var kid kidOutput
|
|
|
|
err := kid.Decode(bytes.NewReader(v))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:46:55 +03:00
|
|
|
// Now, use the state prefixes to determine how the
|
|
|
|
// this output should be represented in the nursery
|
|
|
|
// report. An output's funds are always in limbo until
|
|
|
|
// reaching the graduate state.
|
2017-10-07 02:44:05 +03:00
|
|
|
switch {
|
|
|
|
case bytes.HasPrefix(k, psclPrefix):
|
|
|
|
// Preschool outputs are awaiting the
|
|
|
|
// confirmation of the commitment transaction.
|
2018-01-17 07:46:55 +03:00
|
|
|
switch kid.WitnessType() {
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.CommitmentTimeLock:
|
2018-01-17 07:46:55 +03:00
|
|
|
report.AddLimboCommitment(&kid)
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.HtlcAcceptedSuccessSecondLevel:
|
2018-09-12 17:46:28 +03:00
|
|
|
// An HTLC output on our commitment transaction
|
|
|
|
// where the second-layer transaction hasn't
|
|
|
|
// yet confirmed.
|
2018-01-17 07:46:55 +03:00
|
|
|
report.AddLimboStage1SuccessHtlc(&kid)
|
2018-09-12 17:46:28 +03:00
|
|
|
|
|
|
|
case input.HtlcOfferedRemoteTimeout:
|
|
|
|
// This is an HTLC output on the
|
|
|
|
// commitment transaction of the remote
|
|
|
|
// party. We are waiting for the CLTV
|
|
|
|
// timelock expire.
|
|
|
|
report.AddLimboDirectHtlc(&kid)
|
2018-01-17 07:46:55 +03:00
|
|
|
}
|
2017-10-07 02:44:05 +03:00
|
|
|
|
|
|
|
case bytes.HasPrefix(k, kndrPrefix):
|
|
|
|
// Kindergarten outputs may originate from
|
|
|
|
// either the commitment transaction or an htlc.
|
|
|
|
// We can distinguish them via their witness
|
|
|
|
// types.
|
|
|
|
switch kid.WitnessType() {
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.CommitmentTimeLock:
|
2017-10-07 02:44:05 +03:00
|
|
|
// The commitment transaction has been
|
|
|
|
// confirmed, and we are waiting the CSV
|
|
|
|
// delay to expire.
|
|
|
|
report.AddLimboCommitment(&kid)
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.HtlcOfferedRemoteTimeout:
|
2018-01-17 07:46:55 +03:00
|
|
|
// This is an HTLC output on the
|
|
|
|
// commitment transaction of the remote
|
|
|
|
// party. The CLTV timelock has
|
|
|
|
// expired, and we only need to sweep
|
|
|
|
// it.
|
|
|
|
report.AddLimboDirectHtlc(&kid)
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.HtlcAcceptedSuccessSecondLevel:
|
2018-01-17 07:46:55 +03:00
|
|
|
fallthrough
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.HtlcOfferedTimeoutSecondLevel:
|
2018-01-17 07:46:55 +03:00
|
|
|
// The htlc timeout or success
|
|
|
|
// transaction has confirmed, and the
|
|
|
|
// CSV delay has begun ticking.
|
2017-10-07 02:44:05 +03:00
|
|
|
report.AddLimboStage2Htlc(&kid)
|
|
|
|
}
|
2017-05-05 01:54:50 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
case bytes.HasPrefix(k, gradPrefix):
|
|
|
|
// Graduate outputs are those whose funds have
|
|
|
|
// been swept back into the wallet. Each output
|
|
|
|
// will contribute towards the recovered
|
|
|
|
// balance.
|
|
|
|
switch kid.WitnessType() {
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.CommitmentTimeLock:
|
2017-10-07 02:44:05 +03:00
|
|
|
// The commitment output was
|
|
|
|
// successfully swept back into a
|
|
|
|
// regular p2wkh output.
|
|
|
|
report.AddRecoveredCommitment(&kid)
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.HtlcAcceptedSuccessSecondLevel:
|
2018-01-17 07:46:55 +03:00
|
|
|
fallthrough
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.HtlcOfferedTimeoutSecondLevel:
|
2018-01-17 07:46:55 +03:00
|
|
|
fallthrough
|
2019-01-16 17:47:43 +03:00
|
|
|
case input.HtlcOfferedRemoteTimeout:
|
2018-01-17 07:46:55 +03:00
|
|
|
// This htlc output successfully
|
|
|
|
// resides in a p2wkh output belonging
|
|
|
|
// to the user.
|
2017-10-07 02:44:05 +03:00
|
|
|
report.AddRecoveredHtlc(&kid)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
default:
|
2017-05-05 01:54:50 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return report, nil
|
|
|
|
}
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// reloadPreschool re-initializes the chain notifier with all of the outputs
|
|
|
|
// that had been saved to the "preschool" database bucket prior to shutdown.
|
2018-01-23 07:39:54 +03:00
|
|
|
func (u *utxoNursery) reloadPreschool() error {
|
2017-10-07 02:44:05 +03:00
|
|
|
psclOutputs, err := u.cfg.Store.FetchPreschools()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2018-01-23 07:39:54 +03:00
|
|
|
// For each of the preschool outputs stored in the nursery store, load
|
2018-02-07 06:13:07 +03:00
|
|
|
// its close summary from disk so that we can get an accurate height
|
2018-01-23 07:39:54 +03:00
|
|
|
// hint from which to start our range for spend notifications.
|
2017-10-07 02:44:05 +03:00
|
|
|
for i := range psclOutputs {
|
2018-01-23 07:39:54 +03:00
|
|
|
kid := &psclOutputs[i]
|
|
|
|
chanPoint := kid.OriginChanPoint()
|
|
|
|
|
|
|
|
// Load the close summary for this output's channel point.
|
2018-09-12 23:23:06 +03:00
|
|
|
closeSummary, err := u.cfg.FetchClosedChannel(chanPoint)
|
2018-01-23 07:39:54 +03:00
|
|
|
if err == channeldb.ErrClosedChannelNotFound {
|
|
|
|
// This should never happen since the close summary
|
|
|
|
// should only be removed after the channel has been
|
|
|
|
// swept completely.
|
|
|
|
utxnLog.Warnf("Close summary not found for "+
|
|
|
|
"chan_point=%v, can't determine height hint"+
|
|
|
|
"to sweep commit txn", chanPoint)
|
|
|
|
continue
|
|
|
|
|
|
|
|
} else if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Use the close height from the channel summary as our height
|
|
|
|
// hint to drive our spend notifications, with our confirmation
|
|
|
|
// depth as a buffer for reorgs.
|
|
|
|
heightHint := closeSummary.CloseHeight - u.cfg.ConfDepth
|
|
|
|
err = u.registerPreschoolConf(kid, heightHint)
|
2017-05-05 01:51:57 +03:00
|
|
|
if err != nil {
|
2016-12-14 02:32:44 +03:00
|
|
|
return err
|
|
|
|
}
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
return nil
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// reloadClasses reinitializes any height-dependent state transitions for which
|
2018-01-17 07:46:55 +03:00
|
|
|
// the utxonursery has not received confirmation, and replays the graduation of
|
2018-10-23 13:08:03 +03:00
|
|
|
// all kindergarten and crib outputs for all heights up to the current block.
|
2017-10-07 02:44:05 +03:00
|
|
|
// This allows the nursery to reinitialize all state to continue sweeping
|
2018-10-23 13:08:03 +03:00
|
|
|
// outputs, even in the event that we missed blocks while offline. reloadClasses
|
|
|
|
// is called during the startup of the UTXO Nursery.
|
|
|
|
func (u *utxoNursery) reloadClasses(bestHeight uint32) error {
|
|
|
|
// Loading all active heights up to and including the current block.
|
|
|
|
activeHeights, err := u.cfg.Store.HeightsBelowOrEqual(
|
|
|
|
uint32(bestHeight))
|
2017-10-07 02:44:05 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
// Return early if nothing to sweep.
|
|
|
|
if len(activeHeights) == 0 {
|
|
|
|
return nil
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
utxnLog.Infof("(Re)-sweeping %d heights below height=%d",
|
|
|
|
len(activeHeights), bestHeight)
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// Attempt to re-register notifications for any outputs still at these
|
|
|
|
// heights.
|
|
|
|
for _, classHeight := range activeHeights {
|
2018-10-23 13:08:03 +03:00
|
|
|
utxnLog.Debugf("Attempting to sweep outputs at height=%v",
|
2017-10-07 02:44:05 +03:00
|
|
|
classHeight)
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
if err = u.graduateClass(classHeight); err != nil {
|
|
|
|
utxnLog.Errorf("Failed to sweep outputs at "+
|
2017-10-07 02:44:05 +03:00
|
|
|
"height=%v: %v", classHeight, err)
|
2016-12-14 02:32:44 +03:00
|
|
|
return err
|
|
|
|
}
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
utxnLog.Infof("UTXO Nursery is now fully synced")
|
2017-05-05 01:51:57 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
return nil
|
|
|
|
}
|
2017-05-05 01:51:57 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// incubator is tasked with driving all state transitions that are dependent on
|
|
|
|
// the current height of the blockchain. As new blocks arrive, the incubator
|
|
|
|
// will attempt spend outputs at the latest height. The asynchronous
|
|
|
|
// confirmation of these spends will either 1) move a crib output into the
|
|
|
|
// kindergarten bucket or 2) move a kindergarten output into the graduated
|
|
|
|
// bucket.
|
|
|
|
func (u *utxoNursery) incubator(newBlockChan *chainntnfs.BlockEpochEvent) {
|
|
|
|
defer u.wg.Done()
|
|
|
|
defer newBlockChan.Cancel()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case epoch, ok := <-newBlockChan.Epochs:
|
|
|
|
// If the epoch channel has been closed, then the
|
|
|
|
// ChainNotifier is exiting which means the daemon is
|
|
|
|
// as well. Therefore, we exit early also in order to
|
|
|
|
// ensure the daemon shuts down gracefully, yet
|
|
|
|
// swiftly.
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(roasbeef): if the BlockChainIO is rescanning
|
|
|
|
// will give stale data
|
|
|
|
|
|
|
|
// A new block has just been connected to the main
|
|
|
|
// chain, which means we might be able to graduate crib
|
|
|
|
// or kindergarten outputs at this height. This involves
|
|
|
|
// broadcasting any presigned htlc timeout txns, as well
|
|
|
|
// as signing and broadcasting a sweep txn that spends
|
|
|
|
// from all kindergarten outputs at this height.
|
|
|
|
height := uint32(epoch.Height)
|
2018-10-23 13:08:03 +03:00
|
|
|
|
|
|
|
// Update best known block height for late registrations
|
|
|
|
// to be scheduled properly.
|
|
|
|
atomic.StoreUint32(&u.bestHeight, height)
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
if err := u.graduateClass(height); err != nil {
|
|
|
|
utxnLog.Errorf("error while graduating "+
|
|
|
|
"class at height=%d: %v", height, err)
|
|
|
|
|
|
|
|
// TODO(conner): signal fatal error to daemon
|
|
|
|
}
|
|
|
|
|
|
|
|
case <-u.quit:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// graduateClass handles the steps involved in spending outputs whose CSV or
|
|
|
|
// CLTV delay expires at the nursery's current height. This method is called
|
|
|
|
// each time a new block arrives, or during startup to catch up on heights we
|
|
|
|
// may have missed while the nursery was offline.
|
|
|
|
func (u *utxoNursery) graduateClass(classHeight uint32) error {
|
|
|
|
// Record this height as the nursery's current best height.
|
|
|
|
u.mu.Lock()
|
|
|
|
defer u.mu.Unlock()
|
|
|
|
|
2018-01-17 07:46:55 +03:00
|
|
|
// Fetch all information about the crib and kindergarten outputs at
|
|
|
|
// this height.
|
2018-10-23 13:08:03 +03:00
|
|
|
kgtnOutputs, cribOutputs, err := u.cfg.Store.FetchClass(
|
2017-10-07 02:44:05 +03:00
|
|
|
classHeight)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
utxnLog.Infof("Attempting to graduate height=%v: num_kids=%v, "+
|
|
|
|
"num_babies=%v", classHeight, len(kgtnOutputs), len(cribOutputs))
|
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
// Offer the outputs to the sweeper and set up notifications that will
|
|
|
|
// transition the swept kindergarten outputs and cltvCrib into graduated
|
|
|
|
// outputs.
|
|
|
|
if len(kgtnOutputs) > 0 {
|
|
|
|
if err := u.sweepMatureOutputs(classHeight, kgtnOutputs); err != nil {
|
2018-01-17 07:51:38 +03:00
|
|
|
utxnLog.Errorf("Failed to sweep %d kindergarten "+
|
|
|
|
"outputs at height=%d: %v",
|
|
|
|
len(kgtnOutputs), classHeight, err)
|
2017-10-07 02:44:05 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
// Now, we broadcast all pre-signed htlc txns from the csv crib outputs
|
2018-10-23 13:08:03 +03:00
|
|
|
// at this height.
|
2017-10-07 02:44:05 +03:00
|
|
|
for i := range cribOutputs {
|
|
|
|
err := u.sweepCribOutput(classHeight, &cribOutputs[i])
|
|
|
|
if err != nil {
|
|
|
|
utxnLog.Errorf("Failed to sweep first-stage HTLC "+
|
|
|
|
"(CLTV-delayed) output %v",
|
|
|
|
cribOutputs[i].OutPoint())
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
return nil
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
// sweepMatureOutputs generates and broadcasts the transaction that transfers
|
|
|
|
// control of funds from a prior channel commitment transaction to the user's
|
|
|
|
// wallet. The outputs swept were previously time locked (either absolute or
|
|
|
|
// relative), but are not mature enough to sweep into the wallet.
|
2018-10-23 13:08:03 +03:00
|
|
|
func (u *utxoNursery) sweepMatureOutputs(classHeight uint32,
|
2018-01-17 07:51:38 +03:00
|
|
|
kgtnOutputs []kidOutput) error {
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
utxnLog.Infof("Sweeping %v CSV-delayed outputs with sweep tx for "+
|
|
|
|
"height %v", len(kgtnOutputs), classHeight)
|
2017-10-07 02:44:05 +03:00
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
for _, output := range kgtnOutputs {
|
|
|
|
// Create local copy to prevent pointer to loop variable to be
|
2019-05-05 01:35:37 +03:00
|
|
|
// passed in with disastrous consequences.
|
2018-10-23 13:08:03 +03:00
|
|
|
local := output
|
2017-10-07 02:44:05 +03:00
|
|
|
|
2018-12-19 14:49:01 +03:00
|
|
|
resultChan, err := u.cfg.SweepInput(&local)
|
2018-10-23 13:08:03 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
u.wg.Add(1)
|
2018-12-21 11:29:26 +03:00
|
|
|
go u.waitForSweepConf(classHeight, &local, resultChan)
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// waitForSweepConf watches for the confirmation of a sweep transaction
|
|
|
|
// containing a batch of kindergarten outputs. Once confirmation has been
|
|
|
|
// received, the nursery will mark those outputs as fully graduated, and proceed
|
|
|
|
// to mark any mature channels as fully closed in channeldb.
|
|
|
|
// NOTE(conner): this method MUST be called as a go routine.
|
|
|
|
func (u *utxoNursery) waitForSweepConf(classHeight uint32,
|
2018-10-23 13:08:03 +03:00
|
|
|
output *kidOutput, resultChan chan sweep.Result) {
|
2017-10-07 02:44:05 +03:00
|
|
|
|
|
|
|
defer u.wg.Done()
|
|
|
|
|
|
|
|
select {
|
2018-10-23 13:08:03 +03:00
|
|
|
case result, ok := <-resultChan:
|
2017-10-07 02:44:05 +03:00
|
|
|
if !ok {
|
2018-10-23 13:08:03 +03:00
|
|
|
utxnLog.Errorf("Notification chan closed, can't" +
|
|
|
|
" advance graduating output")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// In case of a remote spend, still graduate the output. There
|
|
|
|
// is no way to sweep it anymore.
|
|
|
|
if result.Err == sweep.ErrRemoteSpend {
|
|
|
|
utxnLog.Infof("Output %v was spend by remote party",
|
|
|
|
output.OutPoint())
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
if result.Err != nil {
|
|
|
|
utxnLog.Errorf("Failed to sweep %v at "+
|
|
|
|
"height=%d", output.OutPoint(),
|
|
|
|
classHeight)
|
2017-10-07 02:44:05 +03:00
|
|
|
return
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
case <-u.quit:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
u.mu.Lock()
|
|
|
|
defer u.mu.Unlock()
|
|
|
|
|
|
|
|
// TODO(conner): add retry logic?
|
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
// Mark the confirmed kindergarten output as graduated.
|
|
|
|
if err := u.cfg.Store.GraduateKinder(classHeight, output); err != nil {
|
|
|
|
utxnLog.Errorf("Unable to graduate kindergarten output %v: %v",
|
|
|
|
output.OutPoint(), err)
|
2017-10-07 02:44:05 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
utxnLog.Infof("Graduated kindergarten output from height=%d",
|
|
|
|
classHeight)
|
2017-10-07 02:44:05 +03:00
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
// Attempt to close the channel, only doing so if all of the channel's
|
2017-10-07 02:44:05 +03:00
|
|
|
// outputs have been graduated.
|
2018-10-23 13:08:03 +03:00
|
|
|
chanPoint := output.OriginChanPoint()
|
|
|
|
if err := u.closeAndRemoveIfMature(chanPoint); err != nil {
|
|
|
|
utxnLog.Errorf("Failed to close and remove channel %v",
|
|
|
|
*chanPoint)
|
|
|
|
return
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// sweepCribOutput broadcasts the crib output's htlc timeout txn, and sets up a
|
|
|
|
// notification that will advance it to the kindergarten bucket upon
|
|
|
|
// confirmation.
|
|
|
|
func (u *utxoNursery) sweepCribOutput(classHeight uint32, baby *babyOutput) error {
|
2018-01-17 07:51:38 +03:00
|
|
|
utxnLog.Infof("Publishing CLTV-delayed HTLC output using timeout tx "+
|
2017-10-07 02:44:05 +03:00
|
|
|
"(txid=%v): %v", baby.timeoutTx.TxHash(),
|
|
|
|
newLogClosure(func() string {
|
|
|
|
return spew.Sdump(baby.timeoutTx)
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
// We'll now broadcast the HTLC transaction, then wait for it to be
|
|
|
|
// confirmed before transitioning it to kindergarten.
|
2018-06-13 11:32:06 +03:00
|
|
|
err := u.cfg.PublishTransaction(baby.timeoutTx)
|
2019-03-19 06:56:44 +03:00
|
|
|
if err != nil && err != lnwallet.ErrDoubleSpend {
|
2017-10-07 02:44:05 +03:00
|
|
|
utxnLog.Errorf("Unable to broadcast baby tx: "+
|
2018-01-12 17:31:02 +03:00
|
|
|
"%v, %v", err, spew.Sdump(baby.timeoutTx))
|
2017-10-07 02:44:05 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return u.registerTimeoutConf(baby, classHeight)
|
|
|
|
}
|
|
|
|
|
|
|
|
// registerTimeoutConf is responsible for subscribing to confirmation
|
2018-01-17 07:51:38 +03:00
|
|
|
// notification for an htlc timeout transaction. If successful, a goroutine
|
|
|
|
// will be spawned that will transition the provided baby output into the
|
2017-10-07 02:44:05 +03:00
|
|
|
// kindergarten state within the nursery store.
|
|
|
|
func (u *utxoNursery) registerTimeoutConf(baby *babyOutput, heightHint uint32) error {
|
|
|
|
|
|
|
|
birthTxID := baby.timeoutTx.TxHash()
|
|
|
|
|
|
|
|
// Register for the confirmation of presigned htlc txn.
|
|
|
|
confChan, err := u.cfg.Notifier.RegisterConfirmationsNtfn(
|
2018-05-31 08:17:17 +03:00
|
|
|
&birthTxID, baby.timeoutTx.TxOut[0].PkScript, u.cfg.ConfDepth,
|
|
|
|
heightHint,
|
|
|
|
)
|
2017-10-07 02:44:05 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
utxnLog.Infof("Htlc output %v registered for promotion "+
|
|
|
|
"notification.", baby.OutPoint())
|
|
|
|
|
|
|
|
u.wg.Add(1)
|
|
|
|
go u.waitForTimeoutConf(baby, confChan)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// waitForTimeoutConf watches for the confirmation of an htlc timeout
|
|
|
|
// transaction, and attempts to move the htlc output from the crib bucket to the
|
|
|
|
// kindergarten bucket upon success.
|
|
|
|
func (u *utxoNursery) waitForTimeoutConf(baby *babyOutput,
|
|
|
|
confChan *chainntnfs.ConfirmationEvent) {
|
|
|
|
|
|
|
|
defer u.wg.Done()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case txConfirmation, ok := <-confChan.Confirmed:
|
|
|
|
if !ok {
|
|
|
|
utxnLog.Errorf("Notification chan "+
|
|
|
|
"closed, can't advance baby output %v",
|
|
|
|
baby.OutPoint())
|
|
|
|
return
|
2017-05-05 01:51:57 +03:00
|
|
|
}
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
baby.SetConfHeight(txConfirmation.BlockHeight)
|
|
|
|
|
|
|
|
case <-u.quit:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
u.mu.Lock()
|
|
|
|
defer u.mu.Unlock()
|
|
|
|
|
|
|
|
// TODO(conner): add retry logic?
|
|
|
|
|
|
|
|
err := u.cfg.Store.CribToKinder(baby)
|
|
|
|
if err != nil {
|
|
|
|
utxnLog.Errorf("Unable to move htlc output from "+
|
|
|
|
"crib to kindergarten bucket: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
utxnLog.Infof("Htlc output %v promoted to "+
|
|
|
|
"kindergarten", baby.OutPoint())
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
// registerPreschoolConf is responsible for subscribing to the confirmation of
|
|
|
|
// a commitment transaction, or an htlc success transaction for an incoming
|
|
|
|
// HTLC on our commitment transaction.. If successful, the provided preschool
|
|
|
|
// output will be moved persistently into the kindergarten state within the
|
|
|
|
// nursery store.
|
|
|
|
func (u *utxoNursery) registerPreschoolConf(kid *kidOutput, heightHint uint32) error {
|
2017-10-07 02:44:05 +03:00
|
|
|
txID := kid.OutPoint().Hash
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
// TODO(roasbeef): ensure we don't already have one waiting, need to
|
|
|
|
// de-duplicate
|
|
|
|
// * need to do above?
|
|
|
|
|
2018-05-31 08:17:17 +03:00
|
|
|
pkScript := kid.signDesc.Output.PkScript
|
|
|
|
confChan, err := u.cfg.Notifier.RegisterConfirmationsNtfn(
|
|
|
|
&txID, pkScript, u.cfg.ConfDepth, heightHint,
|
|
|
|
)
|
2017-10-07 02:44:05 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
var outputType string
|
|
|
|
if kid.isHtlc {
|
|
|
|
outputType = "HTLC"
|
|
|
|
} else {
|
|
|
|
outputType = "Commitment"
|
|
|
|
}
|
|
|
|
|
|
|
|
utxnLog.Infof("%v outpoint %v registered for "+
|
|
|
|
"confirmation notification.", outputType, kid.OutPoint())
|
2017-10-07 02:44:05 +03:00
|
|
|
|
|
|
|
u.wg.Add(1)
|
2018-01-17 07:51:38 +03:00
|
|
|
go u.waitForPreschoolConf(kid, confChan)
|
2017-10-07 02:44:05 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
// waitForPreschoolConf is intended to be run as a goroutine that will wait until
|
|
|
|
// a channel force close commitment transaction, or a second layer HTLC success
|
|
|
|
// transaction has been included in a confirmed block. Once the transaction has
|
|
|
|
// been confirmed (as reported by the Chain Notifier), waitForPreschoolConf
|
|
|
|
// will delete the output from the "preschool" database bucket and atomically
|
|
|
|
// add it to the "kindergarten" database bucket. This is the second step in
|
|
|
|
// the output incubation process.
|
|
|
|
func (u *utxoNursery) waitForPreschoolConf(kid *kidOutput,
|
2017-10-07 02:44:05 +03:00
|
|
|
confChan *chainntnfs.ConfirmationEvent) {
|
|
|
|
|
|
|
|
defer u.wg.Done()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case txConfirmation, ok := <-confChan.Confirmed:
|
|
|
|
if !ok {
|
|
|
|
utxnLog.Errorf("Notification chan "+
|
|
|
|
"closed, can't advance output %v",
|
|
|
|
kid.OutPoint())
|
|
|
|
return
|
2017-05-05 01:51:57 +03:00
|
|
|
}
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
kid.SetConfHeight(txConfirmation.BlockHeight)
|
|
|
|
|
|
|
|
case <-u.quit:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
u.mu.Lock()
|
|
|
|
defer u.mu.Unlock()
|
|
|
|
|
|
|
|
// TODO(conner): add retry logic?
|
|
|
|
|
2018-01-17 07:51:38 +03:00
|
|
|
var outputType string
|
|
|
|
if kid.isHtlc {
|
|
|
|
outputType = "HTLC"
|
|
|
|
} else {
|
|
|
|
outputType = "Commitment"
|
|
|
|
}
|
|
|
|
|
2018-10-23 13:08:03 +03:00
|
|
|
bestHeight := atomic.LoadUint32(&u.bestHeight)
|
|
|
|
err := u.cfg.Store.PreschoolToKinder(kid, bestHeight)
|
2017-10-07 02:44:05 +03:00
|
|
|
if err != nil {
|
2018-01-17 07:51:38 +03:00
|
|
|
utxnLog.Errorf("Unable to move %v output "+
|
2017-10-07 02:44:05 +03:00
|
|
|
"from preschool to kindergarten bucket: %v",
|
2018-01-17 07:51:38 +03:00
|
|
|
outputType, err)
|
2017-10-07 02:44:05 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// contractMaturityReport is a report that details the maturity progress of a
|
|
|
|
// particular force closed contract.
|
|
|
|
type contractMaturityReport struct {
|
|
|
|
// limboBalance is the total number of frozen coins within this
|
|
|
|
// contract.
|
|
|
|
limboBalance btcutil.Amount
|
|
|
|
|
|
|
|
// recoveredBalance is the total value that has been successfully swept
|
|
|
|
// back to the user's wallet.
|
|
|
|
recoveredBalance btcutil.Amount
|
|
|
|
|
|
|
|
// maturityHeight is the absolute block height that this output will
|
|
|
|
// mature at.
|
|
|
|
maturityHeight uint32
|
|
|
|
|
|
|
|
// htlcs records a maturity report for each htlc output in this channel.
|
|
|
|
htlcs []htlcMaturityReport
|
|
|
|
}
|
|
|
|
|
|
|
|
// htlcMaturityReport provides a summary of a single htlc output, and is
|
|
|
|
// embedded as party of the overarching contractMaturityReport
|
|
|
|
type htlcMaturityReport struct {
|
|
|
|
// outpoint is the final output that will be swept back to the wallet.
|
|
|
|
outpoint wire.OutPoint
|
|
|
|
|
|
|
|
// amount is the final value that will be swept in back to the wallet.
|
|
|
|
amount btcutil.Amount
|
|
|
|
|
|
|
|
// maturityHeight is the absolute block height that this output will
|
|
|
|
// mature at.
|
|
|
|
maturityHeight uint32
|
|
|
|
|
|
|
|
// stage indicates whether the htlc is in the CLTV-timeout stage (1) or
|
|
|
|
// the CSV-delay stage (2). A stage 1 htlc's maturity height will be set
|
2018-02-07 06:13:07 +03:00
|
|
|
// to its expiry height, while a stage 2 htlc's maturity height will be
|
|
|
|
// set to its confirmation height plus the maturity requirement.
|
2017-10-07 02:44:05 +03:00
|
|
|
stage uint32
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddLimboCommitment adds an incubating commitment output to maturity
|
|
|
|
// report's htlcs, and contributes its amount to the limbo balance.
|
|
|
|
func (c *contractMaturityReport) AddLimboCommitment(kid *kidOutput) {
|
|
|
|
c.limboBalance += kid.Amount()
|
|
|
|
|
|
|
|
// If the confirmation height is set, then this means the contract has
|
|
|
|
// been confirmed, and we know the final maturity height.
|
|
|
|
if kid.ConfHeight() != 0 {
|
|
|
|
c.maturityHeight = kid.BlocksToMaturity() + kid.ConfHeight()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddRecoveredCommitment adds a graduated commitment output to maturity
|
|
|
|
// report's htlcs, and contributes its amount to the recovered balance.
|
|
|
|
func (c *contractMaturityReport) AddRecoveredCommitment(kid *kidOutput) {
|
|
|
|
c.recoveredBalance += kid.Amount()
|
|
|
|
|
|
|
|
c.maturityHeight = kid.BlocksToMaturity() + kid.ConfHeight()
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:46:55 +03:00
|
|
|
// AddLimboStage1TimeoutHtlc adds an htlc crib output to the maturity report's
|
2017-10-07 02:44:05 +03:00
|
|
|
// htlcs, and contributes its amount to the limbo balance.
|
2018-01-17 07:46:55 +03:00
|
|
|
func (c *contractMaturityReport) AddLimboStage1TimeoutHtlc(baby *babyOutput) {
|
2017-10-07 02:44:05 +03:00
|
|
|
c.limboBalance += baby.Amount()
|
|
|
|
|
2018-01-17 07:46:55 +03:00
|
|
|
// TODO(roasbeef): bool to indicate stage 1 vs stage 2?
|
2017-10-07 02:44:05 +03:00
|
|
|
c.htlcs = append(c.htlcs, htlcMaturityReport{
|
|
|
|
outpoint: *baby.OutPoint(),
|
|
|
|
amount: baby.Amount(),
|
|
|
|
maturityHeight: baby.expiry,
|
|
|
|
stage: 1,
|
2016-12-14 02:32:44 +03:00
|
|
|
})
|
2016-09-12 22:37:51 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 07:46:55 +03:00
|
|
|
// AddLimboDirectHtlc adds a direct HTLC on the commitment transaction of the
|
|
|
|
// remote party to the maturity report. This a CLTV time-locked output that
|
2018-09-12 17:46:28 +03:00
|
|
|
// has or hasn't expired yet.
|
2018-01-17 07:46:55 +03:00
|
|
|
func (c *contractMaturityReport) AddLimboDirectHtlc(kid *kidOutput) {
|
|
|
|
c.limboBalance += kid.Amount()
|
|
|
|
|
|
|
|
htlcReport := htlcMaturityReport{
|
|
|
|
outpoint: *kid.OutPoint(),
|
|
|
|
amount: kid.Amount(),
|
|
|
|
maturityHeight: kid.absoluteMaturity,
|
|
|
|
stage: 2,
|
|
|
|
}
|
|
|
|
|
|
|
|
c.htlcs = append(c.htlcs, htlcReport)
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddLimboStage1SuccessHtlcHtlc adds an htlc crib output to the maturity
|
|
|
|
// report's set of HTLC's. We'll use this to report any incoming HTLC sweeps
|
|
|
|
// where the second level transaction hasn't yet confirmed.
|
|
|
|
func (c *contractMaturityReport) AddLimboStage1SuccessHtlc(kid *kidOutput) {
|
|
|
|
c.limboBalance += kid.Amount()
|
|
|
|
|
|
|
|
c.htlcs = append(c.htlcs, htlcMaturityReport{
|
2019-01-07 12:05:30 +03:00
|
|
|
outpoint: *kid.OutPoint(),
|
|
|
|
amount: kid.Amount(),
|
|
|
|
stage: 1,
|
2018-01-17 07:46:55 +03:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// AddLimboStage2Htlc adds an htlc kindergarten output to the maturity report's
|
|
|
|
// htlcs, and contributes its amount to the limbo balance.
|
|
|
|
func (c *contractMaturityReport) AddLimboStage2Htlc(kid *kidOutput) {
|
|
|
|
c.limboBalance += kid.Amount()
|
|
|
|
|
|
|
|
htlcReport := htlcMaturityReport{
|
2019-01-07 12:05:30 +03:00
|
|
|
outpoint: *kid.OutPoint(),
|
|
|
|
amount: kid.Amount(),
|
|
|
|
stage: 2,
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// If the confirmation height is set, then this means the first stage
|
|
|
|
// has been confirmed, and we know the final maturity height of the CSV
|
|
|
|
// delay.
|
|
|
|
if kid.ConfHeight() != 0 {
|
|
|
|
htlcReport.maturityHeight = kid.ConfHeight() + kid.BlocksToMaturity()
|
|
|
|
}
|
2016-09-12 22:37:51 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
c.htlcs = append(c.htlcs, htlcReport)
|
|
|
|
}
|
|
|
|
|
2018-04-18 05:02:04 +03:00
|
|
|
// AddRecoveredHtlc adds a graduate output to the maturity report's htlcs, and
|
2017-10-07 02:44:05 +03:00
|
|
|
// contributes its amount to the recovered balance.
|
|
|
|
func (c *contractMaturityReport) AddRecoveredHtlc(kid *kidOutput) {
|
|
|
|
c.recoveredBalance += kid.Amount()
|
|
|
|
|
|
|
|
c.htlcs = append(c.htlcs, htlcMaturityReport{
|
2019-01-07 12:05:30 +03:00
|
|
|
outpoint: *kid.OutPoint(),
|
|
|
|
amount: kid.Amount(),
|
|
|
|
maturityHeight: kid.ConfHeight() + kid.BlocksToMaturity(),
|
2016-12-14 02:32:44 +03:00
|
|
|
})
|
2017-10-07 02:44:05 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// closeAndRemoveIfMature removes a particular channel from the channel index
|
|
|
|
// if and only if all of its outputs have been marked graduated. If the channel
|
|
|
|
// still has ungraduated outputs, the method will succeed without altering the
|
|
|
|
// database state.
|
|
|
|
func (u *utxoNursery) closeAndRemoveIfMature(chanPoint *wire.OutPoint) error {
|
|
|
|
isMature, err := u.cfg.Store.IsMatureChannel(chanPoint)
|
|
|
|
if err == ErrContractNotFound {
|
|
|
|
return nil
|
|
|
|
} else if err != nil {
|
|
|
|
utxnLog.Errorf("Unable to determine maturity of "+
|
|
|
|
"channel=%s", chanPoint)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Nothing to do if we are still incubating.
|
|
|
|
if !isMature {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that the channel is fully closed, we remove the channel from the
|
|
|
|
// nursery store here. This preserves the invariant that we never remove
|
|
|
|
// a channel unless it is mature, as this is the only place the utxo
|
|
|
|
// nursery removes a channel.
|
|
|
|
if err := u.cfg.Store.RemoveChannel(chanPoint); err != nil {
|
|
|
|
utxnLog.Errorf("Unable to remove channel=%s from "+
|
|
|
|
"nursery store: %v", chanPoint, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
utxnLog.Infof("Removed channel %v from nursery store", chanPoint)
|
|
|
|
|
|
|
|
return nil
|
2016-09-12 22:37:51 +03:00
|
|
|
}
|
2016-11-21 22:27:50 +03:00
|
|
|
|
2016-11-29 03:53:15 +03:00
|
|
|
// newSweepPkScript creates a new public key script which should be used to
|
|
|
|
// sweep any time-locked, or contested channel funds into the wallet.
|
2017-10-07 02:44:05 +03:00
|
|
|
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
|
|
|
|
// (p2wkh) output.
|
2016-11-29 03:53:15 +03:00
|
|
|
func newSweepPkScript(wallet lnwallet.WalletController) ([]byte, error) {
|
|
|
|
sweepAddr, err := wallet.NewAddress(lnwallet.WitnessPubKey, false)
|
2016-11-21 22:27:50 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2016-11-29 03:53:15 +03:00
|
|
|
return txscript.PayToAddrScript(sweepAddr)
|
2016-11-21 22:27:50 +03:00
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2017-10-07 02:44:05 +03:00
|
|
|
// babyOutput represents a two-stage CSV locked output, and is used to track
|
|
|
|
// htlc outputs through incubation. The first stage requires broadcasting a
|
|
|
|
// presigned timeout txn that spends from the CLTV locked output on the
|
|
|
|
// commitment txn. A babyOutput is treated as a subset of CsvSpendableOutputs,
|
2018-01-17 07:46:55 +03:00
|
|
|
// with the additional constraint that a transaction must be broadcast before
|
|
|
|
// it can be spent. Each baby transaction embeds the kidOutput that can later
|
|
|
|
// be used to spend the CSV output contained in the timeout txn.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): re-rename to timeout tx
|
|
|
|
// * create CltvCsvSpendableOutput
|
2017-09-29 04:26:42 +03:00
|
|
|
type babyOutput struct {
|
2018-01-17 07:46:55 +03:00
|
|
|
// expiry is the absolute block height at which the secondLevelTx
|
|
|
|
// should be broadcast to the network.
|
|
|
|
//
|
|
|
|
// NOTE: This value will be zero if this is a baby output for a prior
|
|
|
|
// incoming HTLC.
|
2017-10-04 02:39:38 +03:00
|
|
|
expiry uint32
|
2017-09-29 04:26:42 +03:00
|
|
|
|
2017-10-04 02:39:38 +03:00
|
|
|
// timeoutTx is a fully-signed transaction that, upon confirmation,
|
|
|
|
// transitions the htlc into the delay+claim stage.
|
2017-09-29 04:26:42 +03:00
|
|
|
timeoutTx *wire.MsgTx
|
2017-10-04 02:39:38 +03:00
|
|
|
|
2018-01-17 07:46:55 +03:00
|
|
|
// kidOutput represents the CSV output to be swept from the
|
|
|
|
// secondLevelTx after it has been broadcast and confirmed.
|
2017-10-04 02:39:38 +03:00
|
|
|
kidOutput
|
2017-09-29 04:26:42 +03:00
|
|
|
}
|
|
|
|
|
2018-01-17 07:46:55 +03:00
|
|
|
// makeBabyOutput constructs a baby output that wraps a future kidOutput. The
|
2017-09-29 04:26:42 +03:00
|
|
|
// provided sign descriptors and witness types will be used once the output
|
|
|
|
// reaches the delay and claim stage.
|
2018-01-17 07:46:55 +03:00
|
|
|
func makeBabyOutput(chanPoint *wire.OutPoint,
|
2017-09-29 04:26:42 +03:00
|
|
|
htlcResolution *lnwallet.OutgoingHtlcResolution) babyOutput {
|
|
|
|
|
2018-01-17 07:46:55 +03:00
|
|
|
htlcOutpoint := htlcResolution.ClaimOutpoint
|
|
|
|
blocksToMaturity := htlcResolution.CsvDelay
|
2019-01-16 17:47:43 +03:00
|
|
|
witnessType := input.HtlcOfferedTimeoutSecondLevel
|
2018-01-17 07:46:55 +03:00
|
|
|
|
|
|
|
kid := makeKidOutput(
|
|
|
|
&htlcOutpoint, chanPoint, blocksToMaturity, witnessType,
|
|
|
|
&htlcResolution.SweepSignDesc, 0,
|
|
|
|
)
|
2017-09-29 04:26:42 +03:00
|
|
|
|
|
|
|
return babyOutput{
|
|
|
|
kidOutput: kid,
|
|
|
|
expiry: htlcResolution.Expiry,
|
|
|
|
timeoutTx: htlcResolution.SignedTimeoutTx,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Encode writes the baby output to the given io.Writer.
|
|
|
|
func (bo *babyOutput) Encode(w io.Writer) error {
|
|
|
|
var scratch [4]byte
|
|
|
|
byteOrder.PutUint32(scratch[:], bo.expiry)
|
|
|
|
if _, err := w.Write(scratch[:]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := bo.timeoutTx.Serialize(w); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bo.kidOutput.Encode(w)
|
|
|
|
}
|
|
|
|
|
2017-10-04 02:39:38 +03:00
|
|
|
// Decode reconstructs a baby output using the provided io.Reader.
|
2017-09-29 04:26:42 +03:00
|
|
|
func (bo *babyOutput) Decode(r io.Reader) error {
|
|
|
|
var scratch [4]byte
|
|
|
|
if _, err := r.Read(scratch[:]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
bo.expiry = byteOrder.Uint32(scratch[:])
|
|
|
|
|
|
|
|
bo.timeoutTx = new(wire.MsgTx)
|
|
|
|
if err := bo.timeoutTx.Deserialize(r); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bo.kidOutput.Decode(r)
|
|
|
|
}
|
|
|
|
|
|
|
|
// kidOutput represents an output that's waiting for a required blockheight
|
|
|
|
// before its funds will be available to be moved into the user's wallet. The
|
|
|
|
// struct includes a WitnessGenerator closure which will be used to generate
|
|
|
|
// the witness required to sweep the output once it's mature.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): rename to immatureOutput?
|
|
|
|
type kidOutput struct {
|
|
|
|
breachedOutput
|
|
|
|
|
|
|
|
originChanPoint wire.OutPoint
|
|
|
|
|
2018-01-17 07:44:50 +03:00
|
|
|
// isHtlc denotes if this kid output is an HTLC output or not. This
|
|
|
|
// value will be used to determine how to report this output within the
|
|
|
|
// nursery report.
|
|
|
|
isHtlc bool
|
|
|
|
|
|
|
|
// blocksToMaturity is the relative CSV delay required after initial
|
|
|
|
// confirmation of the commitment transaction before we can sweep this
|
|
|
|
// output.
|
|
|
|
//
|
|
|
|
// NOTE: This will be set for: commitment outputs, and incoming HTLC's.
|
|
|
|
// Otherwise, this will be zero.
|
2017-09-29 04:26:42 +03:00
|
|
|
blocksToMaturity uint32
|
2018-01-17 07:44:50 +03:00
|
|
|
|
|
|
|
// absoluteMaturity is the absolute height that this output will be
|
|
|
|
// mature at. In order to sweep the output after this height, the
|
|
|
|
// locktime of sweep transaction will need to be set to this value.
|
|
|
|
//
|
|
|
|
// NOTE: This will only be set for: outgoing HTLC's on the commitment
|
|
|
|
// transaction of the remote party.
|
|
|
|
absoluteMaturity uint32
|
2017-09-29 04:26:42 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func makeKidOutput(outpoint, originChanPoint *wire.OutPoint,
|
2019-01-16 17:47:43 +03:00
|
|
|
blocksToMaturity uint32, witnessType input.WitnessType,
|
|
|
|
signDescriptor *input.SignDescriptor,
|
2018-01-17 07:44:50 +03:00
|
|
|
absoluteMaturity uint32) kidOutput {
|
|
|
|
|
|
|
|
// This is an HTLC either if it's an incoming HTLC on our commitment
|
|
|
|
// transaction, or is an outgoing HTLC on the commitment transaction of
|
|
|
|
// the remote peer.
|
2019-01-16 17:47:43 +03:00
|
|
|
isHtlc := (witnessType == input.HtlcAcceptedSuccessSecondLevel ||
|
|
|
|
witnessType == input.HtlcOfferedRemoteTimeout)
|
2017-09-29 04:26:42 +03:00
|
|
|
|
2018-11-07 18:35:54 +03:00
|
|
|
// heightHint can be safely set to zero here, because after this
|
|
|
|
// function returns, nursery will set a proper confirmation height in
|
|
|
|
// waitForTimeoutConf or waitForPreschoolConf.
|
|
|
|
heightHint := uint32(0)
|
|
|
|
|
2017-09-29 04:26:42 +03:00
|
|
|
return kidOutput{
|
|
|
|
breachedOutput: makeBreachedOutput(
|
2018-11-07 18:35:54 +03:00
|
|
|
outpoint, witnessType, nil, signDescriptor, heightHint,
|
2017-09-29 04:26:42 +03:00
|
|
|
),
|
2018-01-17 07:44:50 +03:00
|
|
|
isHtlc: isHtlc,
|
2017-09-29 04:26:42 +03:00
|
|
|
originChanPoint: *originChanPoint,
|
|
|
|
blocksToMaturity: blocksToMaturity,
|
2018-01-17 07:44:50 +03:00
|
|
|
absoluteMaturity: absoluteMaturity,
|
2017-09-29 04:26:42 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kidOutput) OriginChanPoint() *wire.OutPoint {
|
|
|
|
return &k.originChanPoint
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kidOutput) BlocksToMaturity() uint32 {
|
|
|
|
return k.blocksToMaturity
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kidOutput) SetConfHeight(height uint32) {
|
|
|
|
k.confHeight = height
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kidOutput) ConfHeight() uint32 {
|
|
|
|
return k.confHeight
|
|
|
|
}
|
|
|
|
|
|
|
|
// Encode converts a KidOutput struct into a form suitable for on-disk database
|
|
|
|
// storage. Note that the signDescriptor struct field is included so that the
|
|
|
|
// output's witness can be generated by createSweepTx() when the output becomes
|
|
|
|
// spendable.
|
|
|
|
func (k *kidOutput) Encode(w io.Writer) error {
|
2016-12-14 02:32:44 +03:00
|
|
|
var scratch [8]byte
|
2017-09-29 04:26:42 +03:00
|
|
|
byteOrder.PutUint64(scratch[:], uint64(k.Amount()))
|
2016-12-14 02:32:44 +03:00
|
|
|
if _, err := w.Write(scratch[:]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-09-29 04:26:42 +03:00
|
|
|
if err := writeOutpoint(w, k.OutPoint()); err != nil {
|
2016-12-14 02:32:44 +03:00
|
|
|
return err
|
|
|
|
}
|
2017-09-29 04:26:42 +03:00
|
|
|
if err := writeOutpoint(w, k.OriginChanPoint()); err != nil {
|
2017-05-05 01:45:31 +03:00
|
|
|
return err
|
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2018-01-17 07:44:50 +03:00
|
|
|
if err := binary.Write(w, byteOrder, k.isHtlc); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-09-29 04:26:42 +03:00
|
|
|
byteOrder.PutUint32(scratch[:4], k.BlocksToMaturity())
|
2016-12-14 02:32:44 +03:00
|
|
|
if _, err := w.Write(scratch[:4]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-01-17 07:44:50 +03:00
|
|
|
byteOrder.PutUint32(scratch[:4], k.absoluteMaturity)
|
|
|
|
if _, err := w.Write(scratch[:4]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-09-29 04:26:42 +03:00
|
|
|
byteOrder.PutUint32(scratch[:4], k.ConfHeight())
|
2016-12-14 02:32:44 +03:00
|
|
|
if _, err := w.Write(scratch[:4]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-09-29 04:26:42 +03:00
|
|
|
byteOrder.PutUint16(scratch[:2], uint16(k.WitnessType()))
|
2016-12-14 02:32:44 +03:00
|
|
|
if _, err := w.Write(scratch[:2]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
return input.WriteSignDescriptor(w, k.SignDesc())
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
|
|
|
|
2017-09-29 04:26:42 +03:00
|
|
|
// Decode takes a byte array representation of a kidOutput and converts it to an
|
|
|
|
// struct. Note that the witnessFunc method isn't added during deserialization
|
|
|
|
// and must be added later based on the value of the witnessType field.
|
|
|
|
func (k *kidOutput) Decode(r io.Reader) error {
|
|
|
|
var scratch [8]byte
|
2016-12-14 02:32:44 +03:00
|
|
|
|
|
|
|
if _, err := r.Read(scratch[:]); err != nil {
|
2017-09-29 04:26:42 +03:00
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
2017-09-29 04:26:42 +03:00
|
|
|
k.amt = btcutil.Amount(byteOrder.Uint64(scratch[:]))
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2017-09-29 04:26:42 +03:00
|
|
|
if err := readOutpoint(io.LimitReader(r, 40), &k.outpoint); err != nil {
|
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
2017-05-07 14:43:55 +03:00
|
|
|
|
2017-09-29 04:26:42 +03:00
|
|
|
err := readOutpoint(io.LimitReader(r, 40), &k.originChanPoint)
|
2017-05-07 14:43:55 +03:00
|
|
|
if err != nil {
|
2017-09-29 04:26:42 +03:00
|
|
|
return err
|
2017-05-05 01:45:31 +03:00
|
|
|
}
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2018-01-17 07:44:50 +03:00
|
|
|
if err := binary.Read(r, byteOrder, &k.isHtlc); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-12-14 02:32:44 +03:00
|
|
|
if _, err := r.Read(scratch[:4]); err != nil {
|
2017-09-29 04:26:42 +03:00
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
2017-09-29 04:26:42 +03:00
|
|
|
k.blocksToMaturity = byteOrder.Uint32(scratch[:4])
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2018-01-17 07:44:50 +03:00
|
|
|
if _, err := r.Read(scratch[:4]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
k.absoluteMaturity = byteOrder.Uint32(scratch[:4])
|
|
|
|
|
2016-12-14 02:32:44 +03:00
|
|
|
if _, err := r.Read(scratch[:4]); err != nil {
|
2017-09-29 04:26:42 +03:00
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
2017-09-29 04:26:42 +03:00
|
|
|
k.confHeight = byteOrder.Uint32(scratch[:4])
|
2016-12-14 02:32:44 +03:00
|
|
|
|
|
|
|
if _, err := r.Read(scratch[:2]); err != nil {
|
2017-09-29 04:26:42 +03:00
|
|
|
return err
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
2019-01-16 17:47:43 +03:00
|
|
|
k.witnessType = input.WitnessType(byteOrder.Uint16(scratch[:2]))
|
2016-12-14 02:32:44 +03:00
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
return input.ReadSignDescriptor(r, &k.signDesc)
|
2016-12-14 02:32:44 +03:00
|
|
|
}
|
2017-07-26 06:39:59 +03:00
|
|
|
|
|
|
|
// TODO(bvu): copied from channeldb, remove repetition
|
|
|
|
func writeOutpoint(w io.Writer, o *wire.OutPoint) error {
|
|
|
|
// TODO(roasbeef): make all scratch buffers on the stack
|
|
|
|
scratch := make([]byte, 4)
|
|
|
|
|
|
|
|
// TODO(roasbeef): write raw 32 bytes instead of wasting the extra
|
|
|
|
// byte.
|
|
|
|
if err := wire.WriteVarBytes(w, 0, o.Hash[:]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
byteOrder.PutUint32(scratch, o.Index)
|
|
|
|
_, err := w.Write(scratch)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bvu): copied from channeldb, remove repetition
|
|
|
|
func readOutpoint(r io.Reader, o *wire.OutPoint) error {
|
|
|
|
scratch := make([]byte, 4)
|
|
|
|
|
|
|
|
txid, err := wire.ReadVarBytes(r, 0, 32, "prevout")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
copy(o.Hash[:], txid)
|
|
|
|
|
|
|
|
if _, err := r.Read(scratch); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
o.Index = byteOrder.Uint32(scratch)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-09-26 18:59:30 +03:00
|
|
|
// Compile-time constraint to ensure kidOutput implements the
|
|
|
|
// Input interface.
|
|
|
|
|
2019-01-16 17:47:43 +03:00
|
|
|
var _ input.Input = (*kidOutput)(nil)
|