github.com/decred/dcrlnd@v0.7.6/contractcourt/breacharbiter.go (about)

     1  package contractcourt
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/binary"
     6  	"errors"
     7  	"fmt"
     8  	"io"
     9  	"sync"
    10  	"time"
    11  
    12  	"github.com/davecgh/go-spew/spew"
    13  	"github.com/decred/dcrd/blockchain/standalone/v2"
    14  	"github.com/decred/dcrd/chaincfg/chainhash"
    15  	"github.com/decred/dcrd/chaincfg/v3"
    16  	"github.com/decred/dcrd/dcrutil/v4"
    17  	"github.com/decred/dcrd/wire"
    18  
    19  	"github.com/decred/dcrlnd/chainntnfs"
    20  	"github.com/decred/dcrlnd/channeldb"
    21  	"github.com/decred/dcrlnd/input"
    22  	"github.com/decred/dcrlnd/kvdb"
    23  	"github.com/decred/dcrlnd/labels"
    24  	"github.com/decred/dcrlnd/lnwallet"
    25  	"github.com/decred/dcrlnd/lnwallet/chainfee"
    26  )
    27  
    28  const (
    29  	// justiceTxConfTarget is the number of blocks we'll use as a
    30  	// confirmation target when creating the justice transaction. We'll
    31  	// choose an aggressive target, since we want to be sure it confirms
    32  	// quickly.
    33  	justiceTxConfTarget = 2
    34  
    35  	// blocksPassedSplitPublish is the number of blocks without
    36  	// confirmation of the justice tx we'll wait before starting to publish
    37  	// smaller variants of the justice tx. We do this to mitigate an attack
    38  	// the channel peer can do by pinning the HTLC outputs of the
    39  	// commitment with low-fee HTLC transactions.
    40  	blocksPassedSplitPublish = 4
    41  )
    42  
    43  var (
    44  	// retributionBucket stores retribution state on disk between detecting
    45  	// a contract breach, broadcasting a justice transaction that sweeps the
    46  	// channel, and finally witnessing the justice transaction confirm on
    47  	// the blockchain. It is critical that such state is persisted on disk,
    48  	// so that if our node restarts at any point during the retribution
    49  	// procedure, we can recover and continue from the persisted state.
    50  	retributionBucket = []byte("retribution")
    51  
    52  	// justiceTxnBucket holds the finalized justice transactions for all
    53  	// breached contracts. Entries are added to the justice txn bucket just
    54  	// before broadcasting the sweep txn.
    55  	justiceTxnBucket = []byte("justice-txn")
    56  
    57  	// errBrarShuttingDown is an error returned if the breacharbiter has
    58  	// been signalled to exit.
    59  	errBrarShuttingDown = errors.New("breacharbiter shutting down")
    60  )
    61  
    62  // ContractBreachEvent is an event the BreachArbiter will receive in case a
    63  // contract breach is observed on-chain. It contains the necessary information
    64  // to handle the breach, and a ProcessACK closure we will use to ACK the event
    65  // when we have safely stored all the necessary information.
    66  type ContractBreachEvent struct {
    67  	// ChanPoint is the channel point of the breached channel.
    68  	ChanPoint wire.OutPoint
    69  
    70  	// ProcessACK is an closure that should be called with a nil error iff
    71  	// the breach retribution info is safely stored in the retribution
    72  	// store. In case storing the information to the store fails, a non-nil
    73  	// error should be used. When this closure returns, it means that the
    74  	// contract court has marked the channel pending close in the DB, and
    75  	// it is safe for the BreachArbiter to carry on its duty.
    76  	ProcessACK func(error)
    77  
    78  	// BreachRetribution is the information needed to act on this contract
    79  	// breach.
    80  	BreachRetribution *lnwallet.BreachRetribution
    81  }
    82  
    83  // ChannelCloseType is an enum which signals the type of channel closure the
    84  // peer should execute.
    85  type ChannelCloseType uint8
    86  
    87  const (
    88  	// CloseRegular indicates a regular cooperative channel closure
    89  	// should be attempted.
    90  	CloseRegular ChannelCloseType = iota
    91  
    92  	// CloseBreach indicates that a channel breach has been detected, and
    93  	// the link should immediately be marked as unavailable.
    94  	CloseBreach
    95  )
    96  
    97  // RetributionStorer provides an interface for managing a persistent map from
    98  // wire.OutPoint -> retributionInfo. Upon learning of a breach, a BreachArbiter
    99  // should record the retributionInfo for the breached channel, which serves a
   100  // checkpoint in the event that retribution needs to be resumed after failure.
   101  // A RetributionStore provides an interface for managing the persisted set, as
   102  // well as mapping user defined functions over the entire on-disk contents.
   103  //
   104  // Calls to RetributionStore may occur concurrently. A concrete instance of
   105  // RetributionStore should use appropriate synchronization primitives, or
   106  // be otherwise safe for concurrent access.
   107  type RetributionStorer interface {
   108  	// Add persists the retributionInfo to disk, using the information's
   109  	// chanPoint as the key. This method should overwrite any existing
   110  	// entries found under the same key, and an error should be raised if
   111  	// the addition fails.
   112  	Add(retInfo *retributionInfo) error
   113  
   114  	// IsBreached queries the retribution store to see if the breach arbiter
   115  	// is aware of any breaches for the provided channel point.
   116  	IsBreached(chanPoint *wire.OutPoint) (bool, error)
   117  
   118  	// Remove deletes the retributionInfo from disk, if any exists, under
   119  	// the given key. An error should be re raised if the removal fails.
   120  	Remove(key *wire.OutPoint) error
   121  
   122  	// ForAll iterates over the existing on-disk contents and applies a
   123  	// chosen, read-only callback to each. This method should ensure that it
   124  	// immediately propagate any errors generated by the callback.
   125  	ForAll(cb func(*retributionInfo) error, reset func()) error
   126  }
   127  
   128  // BreachConfig bundles the required subsystems used by the breach arbiter. An
   129  // instance of BreachConfig is passed to newBreachArbiter during instantiation.
   130  type BreachConfig struct {
   131  	// CloseLink allows the breach arbiter to shutdown any channel links for
   132  	// which it detects a breach, ensuring now further activity will
   133  	// continue across the link. The method accepts link's channel point and
   134  	// a close type to be included in the channel close summary.
   135  	CloseLink func(*wire.OutPoint, ChannelCloseType)
   136  
   137  	// DB provides access to the user's channels, allowing the breach
   138  	// arbiter to determine the current state of a user's channels, and how
   139  	// it should respond to channel closure.
   140  	DB *channeldb.ChannelStateDB
   141  
   142  	// Estimator is used by the breach arbiter to determine an appropriate
   143  	// fee level when generating, signing, and broadcasting sweep
   144  	// transactions.
   145  	Estimator chainfee.Estimator
   146  
   147  	// GenSweepScript generates the receiving scripts for swept outputs.
   148  	GenSweepScript func() ([]byte, error)
   149  
   150  	// Notifier provides a publish/subscribe interface for event driven
   151  	// notifications regarding the confirmation of txids.
   152  	Notifier chainntnfs.ChainNotifier
   153  
   154  	// PublishTransaction facilitates the process of broadcasting a
   155  	// transaction to the network.
   156  	PublishTransaction func(*wire.MsgTx, string) error
   157  
   158  	// ContractBreaches is a channel where the BreachArbiter will receive
   159  	// notifications in the event of a contract breach being observed. A
   160  	// ContractBreachEvent must be ACKed by the BreachArbiter, such that
   161  	// the sending subsystem knows that the event is properly handed off.
   162  	ContractBreaches <-chan *ContractBreachEvent
   163  
   164  	// Signer is used by the breach arbiter to generate sweep transactions,
   165  	// which move coins from previously open channels back to the user's
   166  	// wallet.
   167  	Signer input.Signer
   168  
   169  	// Store is a persistent resource that maintains information regarding
   170  	// breached channels. This is used in conjunction with DB to recover
   171  	// from crashes, restarts, or other failures.
   172  	Store RetributionStorer
   173  
   174  	// NetParams is a reference to the network parameters for the chain this
   175  	// breach arbiter runs on.
   176  	NetParams *chaincfg.Params
   177  }
   178  
   179  // BreachArbiter is a special subsystem which is responsible for watching and
   180  // acting on the detection of any attempted uncooperative channel breaches by
   181  // channel counterparties. This file essentially acts as deterrence code for
   182  // those attempting to launch attacks against the daemon. In practice it's
   183  // expected that the logic in this file never gets executed, but it is
   184  // important to have it in place just in case we encounter cheating channel
   185  // counterparties.
   186  // TODO(roasbeef): closures in config for subsystem pointers to decouple?
   187  type BreachArbiter struct {
   188  	started sync.Once
   189  	stopped sync.Once
   190  
   191  	cfg *BreachConfig
   192  
   193  	subscriptions map[wire.OutPoint]chan struct{}
   194  
   195  	quit chan struct{}
   196  	wg   sync.WaitGroup
   197  	sync.Mutex
   198  }
   199  
   200  // NewBreachArbiter creates a new instance of a BreachArbiter initialized with
   201  // its dependent objects.
   202  func NewBreachArbiter(cfg *BreachConfig) *BreachArbiter {
   203  	return &BreachArbiter{
   204  		cfg:           cfg,
   205  		subscriptions: make(map[wire.OutPoint]chan struct{}),
   206  		quit:          make(chan struct{}),
   207  	}
   208  }
   209  
   210  // Start is an idempotent method that officially starts the BreachArbiter along
   211  // with all other goroutines it needs to perform its functions.
   212  func (b *BreachArbiter) Start() error {
   213  	var err error
   214  	b.started.Do(func() {
   215  		err = b.start()
   216  	})
   217  	return err
   218  }
   219  
   220  func (b *BreachArbiter) start() error {
   221  	brarLog.Tracef("Starting breach arbiter")
   222  
   223  	// Load all retributions currently persisted in the retribution store.
   224  	var breachRetInfos map[wire.OutPoint]retributionInfo
   225  	if err := b.cfg.Store.ForAll(func(ret *retributionInfo) error {
   226  		breachRetInfos[ret.chanPoint] = *ret
   227  		return nil
   228  	}, func() {
   229  		breachRetInfos = make(map[wire.OutPoint]retributionInfo)
   230  	}); err != nil {
   231  		brarLog.Errorf("Unable to create retribution info: %v", err)
   232  		return err
   233  	}
   234  
   235  	// Load all currently closed channels from disk, we will use the
   236  	// channels that have been marked fully closed to filter the retribution
   237  	// information loaded from disk. This is necessary in the event that the
   238  	// channel was marked fully closed, but was not removed from the
   239  	// retribution store.
   240  	closedChans, err := b.cfg.DB.FetchClosedChannels(false)
   241  	if err != nil {
   242  		brarLog.Errorf("Unable to fetch closing channels: %v", err)
   243  		return err
   244  	}
   245  
   246  	brarLog.Debugf("Found %v closing channels, %v retribution records",
   247  		len(closedChans), len(breachRetInfos))
   248  
   249  	// Using the set of non-pending, closed channels, reconcile any
   250  	// discrepancies between the channeldb and the retribution store by
   251  	// removing any retribution information for which we have already
   252  	// finished our responsibilities. If the removal is successful, we also
   253  	// remove the entry from our in-memory map, to avoid any further action
   254  	// for this channel.
   255  	// TODO(halseth): no need continue on IsPending once closed channels
   256  	// actually means close transaction is confirmed.
   257  	for _, chanSummary := range closedChans {
   258  		brarLog.Debugf("Working on close channel: %v, is_pending: %v",
   259  			chanSummary.ChanPoint, chanSummary.IsPending)
   260  
   261  		if chanSummary.IsPending {
   262  			continue
   263  		}
   264  
   265  		chanPoint := &chanSummary.ChanPoint
   266  		if _, ok := breachRetInfos[*chanPoint]; ok {
   267  			if err := b.cfg.Store.Remove(chanPoint); err != nil {
   268  				brarLog.Errorf("Unable to remove closed "+
   269  					"chanid=%v from breach arbiter: %v",
   270  					chanPoint, err)
   271  				return err
   272  			}
   273  			delete(breachRetInfos, *chanPoint)
   274  
   275  			brarLog.Debugf("Skipped closed channel: %v",
   276  				chanSummary.ChanPoint)
   277  		}
   278  	}
   279  
   280  	// Spawn the exactRetribution tasks to monitor and resolve any breaches
   281  	// that were loaded from the retribution store.
   282  	for chanPoint := range breachRetInfos {
   283  		retInfo := breachRetInfos[chanPoint]
   284  
   285  		brarLog.Debugf("Handling breach handoff on startup "+
   286  			"for ChannelPoint(%v)", chanPoint)
   287  
   288  		// Register for a notification when the breach transaction is
   289  		// confirmed on chain.
   290  		breachTXID := retInfo.commitHash
   291  		breachScript := retInfo.breachedOutputs[0].signDesc.Output.PkScript
   292  		confChan, err := b.cfg.Notifier.RegisterConfirmationsNtfn(
   293  			&breachTXID, breachScript, 1, retInfo.breachHeight,
   294  		)
   295  		if err != nil {
   296  			brarLog.Errorf("Unable to register for conf updates "+
   297  				"for txid: %v, err: %v", breachTXID, err)
   298  			return err
   299  		}
   300  
   301  		// Launch a new goroutine which to finalize the channel
   302  		// retribution after the breach transaction confirms.
   303  		b.wg.Add(1)
   304  		go b.exactRetribution(confChan, &retInfo)
   305  	}
   306  
   307  	// Start watching the remaining active channels!
   308  	b.wg.Add(1)
   309  	go b.contractObserver()
   310  
   311  	return nil
   312  }
   313  
   314  // Stop is an idempotent method that signals the BreachArbiter to execute a
   315  // graceful shutdown. This function will block until all goroutines spawned by
   316  // the BreachArbiter have gracefully exited.
   317  func (b *BreachArbiter) Stop() error {
   318  	b.stopped.Do(func() {
   319  		brarLog.Infof("Breach arbiter shutting down")
   320  
   321  		close(b.quit)
   322  		b.wg.Wait()
   323  	})
   324  	return nil
   325  }
   326  
   327  // IsBreached queries the breach arbiter's retribution store to see if it is
   328  // aware of any channel breaches for a particular channel point.
   329  func (b *BreachArbiter) IsBreached(chanPoint *wire.OutPoint) (bool, error) {
   330  	return b.cfg.Store.IsBreached(chanPoint)
   331  }
   332  
   333  // SubscribeBreachComplete is used by outside subsystems to be notified of a
   334  // successful breach resolution.
   335  func (b *BreachArbiter) SubscribeBreachComplete(chanPoint *wire.OutPoint,
   336  	c chan struct{}) (bool, error) {
   337  
   338  	breached, err := b.cfg.Store.IsBreached(chanPoint)
   339  	if err != nil {
   340  		// If an error occurs, no subscription will be registered.
   341  		return false, err
   342  	}
   343  
   344  	if !breached {
   345  		// If chanPoint no longer exists in the Store, then the breach
   346  		// was cleaned up successfully. Any subscription that occurs
   347  		// happens after the breach information was persisted to the
   348  		// underlying store.
   349  		return true, nil
   350  	}
   351  
   352  	// Otherwise since the channel point is not resolved, add a
   353  	// subscription. There can only be one subscription per channel point.
   354  	b.Lock()
   355  	defer b.Unlock()
   356  	b.subscriptions[*chanPoint] = c
   357  
   358  	return false, nil
   359  }
   360  
   361  // notifyBreachComplete is used by the BreachArbiter to notify outside
   362  // subsystems that the breach resolution process is complete.
   363  func (b *BreachArbiter) notifyBreachComplete(chanPoint *wire.OutPoint) {
   364  	b.Lock()
   365  	defer b.Unlock()
   366  	if c, ok := b.subscriptions[*chanPoint]; ok {
   367  		close(c)
   368  	}
   369  
   370  	// Remove the subscription.
   371  	delete(b.subscriptions, *chanPoint)
   372  }
   373  
   374  // contractObserver is the primary goroutine for the BreachArbiter. This
   375  // goroutine is responsible for handling breach events coming from the
   376  // contractcourt on the ContractBreaches channel. If a channel breach is
   377  // detected, then the contractObserver will execute the retribution logic
   378  // required to sweep ALL outputs from a contested channel into the daemon's
   379  // wallet.
   380  //
   381  // NOTE: This MUST be run as a goroutine.
   382  func (b *BreachArbiter) contractObserver() {
   383  	defer b.wg.Done()
   384  
   385  	brarLog.Infof("Starting contract observer, watching for breaches.")
   386  
   387  	for {
   388  		select {
   389  		case breachEvent := <-b.cfg.ContractBreaches:
   390  			// We have been notified about a contract breach!
   391  			// Handle the handoff, making sure we ACK the event
   392  			// after we have safely added it to the retribution
   393  			// store.
   394  			b.wg.Add(1)
   395  			go b.handleBreachHandoff(breachEvent)
   396  
   397  		case <-b.quit:
   398  			return
   399  		}
   400  	}
   401  }
   402  
   403  // spend is used to wrap the index of the retributionInfo output that gets
   404  // spent together with the spend details.
   405  type spend struct {
   406  	index  int
   407  	detail *chainntnfs.SpendDetail
   408  }
   409  
   410  // waitForSpendEvent waits for any of the breached outputs to get spent, and
   411  // returns the spend details for those outputs. The spendNtfns map is a cache
   412  // used to store registered spend subscriptions, in case we must call this
   413  // method multiple times.
   414  func (b *BreachArbiter) waitForSpendEvent(breachInfo *retributionInfo,
   415  	spendNtfns map[wire.OutPoint]*chainntnfs.SpendEvent) ([]spend, error) {
   416  
   417  	inputs := breachInfo.breachedOutputs
   418  
   419  	// We create a channel the first goroutine that gets a spend event can
   420  	// signal. We make it buffered in case multiple spend events come in at
   421  	// the same time.
   422  	anySpend := make(chan struct{}, len(inputs))
   423  
   424  	// The allSpends channel will be used to pass spend events from all the
   425  	// goroutines that detects a spend before they are signalled to exit.
   426  	allSpends := make(chan spend, len(inputs))
   427  
   428  	// exit will be used to signal the goroutines that they can exit.
   429  	exit := make(chan struct{})
   430  	var wg sync.WaitGroup
   431  
   432  	// We'll now launch a goroutine for each of the HTLC outputs, that will
   433  	// signal the moment they detect a spend event.
   434  	for i := range inputs {
   435  		breachedOutput := &inputs[i]
   436  
   437  		brarLog.Infof("Checking spend from %v(%v) for ChannelPoint(%v)",
   438  			breachedOutput.witnessType, breachedOutput.outpoint,
   439  			breachInfo.chanPoint)
   440  
   441  		// If we have already registered for a notification for this
   442  		// output, we'll reuse it.
   443  		spendNtfn, ok := spendNtfns[breachedOutput.outpoint]
   444  		if !ok {
   445  			var err error
   446  			spendNtfn, err = b.cfg.Notifier.RegisterSpendNtfn(
   447  				&breachedOutput.outpoint,
   448  				breachedOutput.signDesc.Output.PkScript,
   449  				breachInfo.breachHeight,
   450  			)
   451  			if err != nil {
   452  				brarLog.Errorf("Unable to check for spentness "+
   453  					"of outpoint=%v: %v",
   454  					breachedOutput.outpoint, err)
   455  
   456  				// Registration may have failed if we've been
   457  				// instructed to shutdown. If so, return here
   458  				// to avoid entering an infinite loop.
   459  				select {
   460  				case <-b.quit:
   461  					return nil, errBrarShuttingDown
   462  				default:
   463  					continue
   464  				}
   465  			}
   466  			spendNtfns[breachedOutput.outpoint] = spendNtfn
   467  		}
   468  
   469  		// Launch a goroutine waiting for a spend event.
   470  		b.wg.Add(1)
   471  		wg.Add(1)
   472  		go func(index int, spendEv *chainntnfs.SpendEvent) {
   473  			defer b.wg.Done()
   474  			defer wg.Done()
   475  
   476  			select {
   477  			// The output has been taken to the second level!
   478  			case sp, ok := <-spendEv.Spend:
   479  				if !ok {
   480  					return
   481  				}
   482  
   483  				brarLog.Infof("Detected spend on %s(%v) by "+
   484  					"txid(%v) for ChannelPoint(%v)",
   485  					inputs[index].witnessType,
   486  					inputs[index].outpoint,
   487  					sp.SpenderTxHash,
   488  					breachInfo.chanPoint)
   489  
   490  				// First we send the spend event on the
   491  				// allSpends channel, such that it can be
   492  				// handled after all go routines have exited.
   493  				allSpends <- spend{index, sp}
   494  
   495  				// Finally we'll signal the anySpend channel
   496  				// that a spend was detected, such that the
   497  				// other goroutines can be shut down.
   498  				anySpend <- struct{}{}
   499  			case <-exit:
   500  				return
   501  			case <-b.quit:
   502  				return
   503  			}
   504  		}(i, spendNtfn)
   505  	}
   506  
   507  	// We'll wait for any of the outputs to be spent, or that we are
   508  	// signalled to exit.
   509  	select {
   510  	// A goroutine have signalled that a spend occurred.
   511  	case <-anySpend:
   512  		// The notifier may still be in the process of dispatching the
   513  		// spend notifications, therefore wait for a few milliseconds
   514  		// before signalling the close event to give a chance for all
   515  		// goroutines to receive them (in case the notifier is slow in
   516  		// dispatching the sequential spend notifications).
   517  		//
   518  		// Note: this is not done in upstream lnd because the resulting
   519  		// transactions are invalid if they are double-spent. This was
   520  		// determined by a flake in the testRevokedCloseRetributionRemoteHodl
   521  		// integration test that happens on SPV.
   522  		select {
   523  		case <-time.After(10 * time.Millisecond):
   524  		case <-b.quit:
   525  			return nil, errBrarShuttingDown
   526  		}
   527  
   528  		// Signal for the remaining goroutines to exit.
   529  		close(exit)
   530  		wg.Wait()
   531  
   532  		// At this point all goroutines that can send on the allSpends
   533  		// channel have exited. We can therefore safely close the
   534  		// channel before ranging over its content.
   535  		close(allSpends)
   536  
   537  		// Gather all detected spends and return them.
   538  		var spends []spend
   539  		for s := range allSpends {
   540  			breachedOutput := &inputs[s.index]
   541  			delete(spendNtfns, breachedOutput.outpoint)
   542  
   543  			spends = append(spends, s)
   544  		}
   545  
   546  		return spends, nil
   547  
   548  	case <-b.quit:
   549  		return nil, errBrarShuttingDown
   550  	}
   551  }
   552  
   553  // convertToSecondLevelRevoke takes a breached output, and a transaction that
   554  // spends it to the second level, and mutates the breach output into one that
   555  // is able to properly sweep that second level output. We'll use this function
   556  // when we go to sweep a breached commitment transaction, but the cheating
   557  // party has already attempted to take it to the second level
   558  func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo,
   559  	spendDetails *chainntnfs.SpendDetail) {
   560  
   561  	// In this case, we'll modify the witness type of this output to
   562  	// actually prepare for a second level revoke.
   563  	bo.witnessType = input.HtlcSecondLevelRevoke
   564  
   565  	// We'll also redirect the outpoint to this second level output, so the
   566  	// spending transaction updates it inputs accordingly.
   567  	spendingTx := spendDetails.SpendingTx
   568  	oldOp := bo.outpoint
   569  	bo.outpoint = wire.OutPoint{
   570  		Hash:  spendingTx.TxHash(),
   571  		Index: 0,
   572  	}
   573  
   574  	// Next, we need to update the amount so we can do fee estimation
   575  	// properly, and also so we can generate a valid signature as we need
   576  	// to know the new input value (the second level transactions shaves
   577  	// off some funds to fees).
   578  	newAmt := spendingTx.TxOut[0].Value
   579  	bo.amt = dcrutil.Amount(newAmt)
   580  	bo.signDesc.Output.Value = newAmt
   581  	bo.signDesc.Output.PkScript = spendingTx.TxOut[0].PkScript
   582  
   583  	// Finally, we'll need to adjust the witness program in the
   584  	// SignDescriptor.
   585  	bo.signDesc.WitnessScript = bo.secondLevelWitnessScript
   586  
   587  	brarLog.Warnf("HTLC(%v) for ChannelPoint(%v) has been spent to the "+
   588  		"second-level, adjusting -> %v", oldOp, breachInfo.chanPoint,
   589  		bo.outpoint)
   590  }
   591  
   592  // updateBreachInfo mutates the passed breachInfo by removing or converting any
   593  // outputs among the spends. It also counts the total and revoked funds swept
   594  // by our justice spends.
   595  func updateBreachInfo(breachInfo *retributionInfo, spends []spend) (
   596  	dcrutil.Amount, dcrutil.Amount) {
   597  
   598  	inputs := breachInfo.breachedOutputs
   599  	doneOutputs := make(map[int]struct{})
   600  
   601  	var totalFunds, revokedFunds dcrutil.Amount
   602  	for _, s := range spends {
   603  		breachedOutput := &inputs[s.index]
   604  		txIn := s.detail.SpendingTx.TxIn[s.detail.SpenderInputIndex]
   605  
   606  		switch breachedOutput.witnessType {
   607  		case input.HtlcAcceptedRevoke:
   608  			fallthrough
   609  		case input.HtlcOfferedRevoke:
   610  			// If the HTLC output was spent using the revocation
   611  			// key, it is our own spend, and we can forget the
   612  			// output. Otherwise it has been taken to the second
   613  			// level.
   614  			signDesc := &breachedOutput.signDesc
   615  			ok, err := input.IsHtlcSpendRevoke(txIn, signDesc)
   616  			if err != nil {
   617  				brarLog.Errorf("Unable to determine if "+
   618  					"revoke spend: %v", err)
   619  				break
   620  			}
   621  
   622  			if ok {
   623  				brarLog.Debugf("HTLC spend was our own " +
   624  					"revocation spend")
   625  				break
   626  			}
   627  
   628  			brarLog.Infof("Spend on second-level "+
   629  				"%s(%v) for ChannelPoint(%v) "+
   630  				"transitions to second-level output",
   631  				breachedOutput.witnessType,
   632  				breachedOutput.outpoint, breachInfo.chanPoint)
   633  
   634  			// In this case we'll morph our initial revoke
   635  			// spend to instead point to the second level
   636  			// output, and update the sign descriptor in the
   637  			// process.
   638  			convertToSecondLevelRevoke(
   639  				breachedOutput, breachInfo, s.detail,
   640  			)
   641  
   642  			continue
   643  		}
   644  
   645  		// Now that we have determined the spend is done by us, we
   646  		// count the total and revoked funds swept depending on the
   647  		// input type.
   648  		switch breachedOutput.witnessType {
   649  
   650  		// If the output being revoked is the remote commitment
   651  		// output or an offered HTLC output, it's amount
   652  		// contributes to the value of funds being revoked from
   653  		// the counter party.
   654  		case input.CommitmentRevoke, input.HtlcSecondLevelRevoke,
   655  			input.HtlcOfferedRevoke:
   656  
   657  			revokedFunds += breachedOutput.Amount()
   658  		}
   659  
   660  		totalFunds += breachedOutput.Amount()
   661  		brarLog.Infof("Spend on %s(%v) for ChannelPoint(%v) "+
   662  			"transitions output to terminal state, "+
   663  			"removing input from justice transaction",
   664  			breachedOutput.witnessType,
   665  			breachedOutput.outpoint, breachInfo.chanPoint)
   666  
   667  		doneOutputs[s.index] = struct{}{}
   668  	}
   669  
   670  	// Filter the inputs for which we can no longer proceed.
   671  	var nextIndex int
   672  	for i := range inputs {
   673  		if _, ok := doneOutputs[i]; ok {
   674  			continue
   675  		}
   676  
   677  		inputs[nextIndex] = inputs[i]
   678  		nextIndex++
   679  	}
   680  
   681  	// Update our remaining set of outputs before continuing with
   682  	// another attempt at publication.
   683  	breachInfo.breachedOutputs = inputs[:nextIndex]
   684  	return totalFunds, revokedFunds
   685  }
   686  
   687  // exactRetribution is a goroutine which is executed once a contract breach has
   688  // been detected by a breachObserver. This function is responsible for
   689  // punishing a counterparty for violating the channel contract by sweeping ALL
   690  // the lingering funds within the channel into the daemon's wallet.
   691  //
   692  // NOTE: This MUST be run as a goroutine.
   693  func (b *BreachArbiter) exactRetribution(confChan *chainntnfs.ConfirmationEvent,
   694  	breachInfo *retributionInfo) {
   695  
   696  	defer b.wg.Done()
   697  
   698  	// TODO(roasbeef): state needs to be checkpointed here
   699  	select {
   700  	case _, ok := <-confChan.Confirmed:
   701  		// If the second value is !ok, then the channel has been closed
   702  		// signifying a daemon shutdown, so we exit.
   703  		if !ok {
   704  			return
   705  		}
   706  
   707  		// Otherwise, if this is a real confirmation notification, then
   708  		// we fall through to complete our duty.
   709  	case <-b.quit:
   710  		return
   711  	}
   712  
   713  	brarLog.Debugf("Breach transaction %v has been confirmed, sweeping "+
   714  		"revoked funds", breachInfo.commitHash)
   715  
   716  	// We may have to wait for some of the HTLC outputs to be spent to the
   717  	// second level before broadcasting the justice tx. We'll store the
   718  	// SpendEvents between each attempt to not re-register uneccessarily.
   719  	spendNtfns := make(map[wire.OutPoint]*chainntnfs.SpendEvent)
   720  
   721  	// Compute both the total value of funds being swept and the
   722  	// amount of funds that were revoked from the counter party.
   723  	var totalFunds, revokedFunds dcrutil.Amount
   724  
   725  justiceTxBroadcast:
   726  	// With the breach transaction confirmed, we now create the
   727  	// justice tx which will claim ALL the funds within the
   728  	// channel.
   729  	justiceTxs, err := b.createJusticeTx(breachInfo.breachedOutputs)
   730  	if err != nil {
   731  		brarLog.Errorf("Unable to create justice tx: %v", err)
   732  		return
   733  	}
   734  	finalTx := justiceTxs.spendAll
   735  
   736  	brarLog.Debugf("Broadcasting justice tx: %v", newLogClosure(func() string {
   737  		finalTx.CachedTxHash()
   738  		return spew.Sdump(finalTx)
   739  	}))
   740  
   741  	// We'll now attempt to broadcast the transaction which finalized the
   742  	// channel's retribution against the cheating counter party.
   743  	label := labels.MakeLabel(labels.LabelTypeJusticeTransaction, nil)
   744  	err = b.cfg.PublishTransaction(finalTx, label)
   745  	if err != nil {
   746  		brarLog.Errorf("Unable to broadcast justice tx: %v", err)
   747  	}
   748  
   749  	// Regardless of publication succeeded or not, we now wait for any of
   750  	// the inputs to be spent. If any input got spent by the remote, we
   751  	// must recreate our justice transaction.
   752  	var (
   753  		spendChan = make(chan []spend, 1)
   754  		errChan   = make(chan error, 1)
   755  		wg        sync.WaitGroup
   756  	)
   757  
   758  	wg.Add(1)
   759  	go func() {
   760  		defer wg.Done()
   761  
   762  		spends, err := b.waitForSpendEvent(breachInfo, spendNtfns)
   763  		if err != nil {
   764  			errChan <- err
   765  			return
   766  		}
   767  		spendChan <- spends
   768  	}()
   769  
   770  	// We'll also register for block notifications, such that in case our
   771  	// justice tx doesn't confirm within a reasonable timeframe, we can
   772  	// start to more aggressively sweep the time sensitive outputs.
   773  	newBlockChan, err := b.cfg.Notifier.RegisterBlockEpochNtfn(nil)
   774  	if err != nil {
   775  		brarLog.Errorf("Unable to register for block notifications: %v",
   776  			err)
   777  		return
   778  	}
   779  	defer newBlockChan.Cancel()
   780  
   781  	// Drain the initial block epoch notification to avoid prematurely
   782  	// attempting the variant with multiple justice txs.
   783  	select {
   784  	case <-newBlockChan.Epochs:
   785  	case <-b.quit:
   786  	case <-time.After(time.Second):
   787  		// This case should not happen, but prevents a buggy notifier
   788  		// from blocking.
   789  		brarLog.Warnf("Buggy ChainNotifier did not send initial epoch")
   790  	}
   791  
   792  Loop:
   793  	for {
   794  
   795  		select {
   796  		case spends := <-spendChan:
   797  			// Update the breach info with the new spends.
   798  			t, r := updateBreachInfo(breachInfo, spends)
   799  			totalFunds += t
   800  			revokedFunds += r
   801  
   802  			brarLog.Infof("%v spends from breach tx for "+
   803  				"ChannelPoint(%v) has been detected, %v "+
   804  				"revoked funds (%v total) have been claimed",
   805  				len(spends), breachInfo.chanPoint,
   806  				revokedFunds, totalFunds)
   807  
   808  			if len(breachInfo.breachedOutputs) == 0 {
   809  				brarLog.Infof("Justice for ChannelPoint(%v) "+
   810  					"has been served, %v revoked funds "+
   811  					"(%v total) have been claimed. No "+
   812  					"more outputs to sweep, marking fully "+
   813  					"resolved", breachInfo.chanPoint,
   814  					revokedFunds, totalFunds)
   815  
   816  				err = b.cleanupBreach(&breachInfo.chanPoint)
   817  				if err != nil {
   818  					brarLog.Errorf("Failed to cleanup "+
   819  						"breached ChannelPoint(%v): %v",
   820  						breachInfo.chanPoint, err)
   821  				}
   822  
   823  				// TODO(roasbeef): add peer to blacklist?
   824  
   825  				// TODO(roasbeef): close other active channels
   826  				// with offending peer
   827  				break Loop
   828  			}
   829  
   830  			brarLog.Infof("Attempting another justice tx "+
   831  				"with %d inputs",
   832  				len(breachInfo.breachedOutputs))
   833  
   834  			wg.Wait()
   835  			goto justiceTxBroadcast
   836  
   837  		// On every new block, we check whether we should republish the
   838  		// transactions.
   839  		case epoch, ok := <-newBlockChan.Epochs:
   840  			if !ok {
   841  				return
   842  			}
   843  
   844  			// If less than four blocks have passed since the
   845  			// breach confirmed, we'll continue waiting. It was
   846  			// published with a 2-block fee estimate, so it's not
   847  			// unexpected that four blocks without confirmation can
   848  			// pass.
   849  			splitHeight := breachInfo.breachHeight +
   850  				blocksPassedSplitPublish
   851  			if uint32(epoch.Height) < splitHeight {
   852  				continue Loop
   853  			}
   854  
   855  			brarLog.Warnf("Block height %v arrived without "+
   856  				"justice tx confirming (breached at "+
   857  				"height %v), splitting justice tx.",
   858  				epoch.Height, breachInfo.breachHeight)
   859  
   860  			// Otherwise we'll attempt to publish the two separate
   861  			// justice transactions that sweeps the commitment
   862  			// outputs and the HTLC outputs separately. This is to
   863  			// mitigate the case where our "spend all" justice TX
   864  			// doesn't propagate because the HTLC outputs have been
   865  			// pinned by low fee HTLC txs.
   866  			label := labels.MakeLabel(
   867  				labels.LabelTypeJusticeTransaction, nil,
   868  			)
   869  			if justiceTxs.spendCommitOuts != nil {
   870  				tx := justiceTxs.spendCommitOuts
   871  
   872  				brarLog.Debugf("Broadcasting justice tx "+
   873  					"spending commitment outs: %v",
   874  					newLogClosure(func() string {
   875  						tx.CachedTxHash()
   876  						return spew.Sdump(tx)
   877  					}))
   878  
   879  				err = b.cfg.PublishTransaction(tx, label)
   880  				if err != nil {
   881  					brarLog.Warnf("Unable to broadcast "+
   882  						"commit out spending justice "+
   883  						"tx: %v", err)
   884  				}
   885  			}
   886  
   887  			if justiceTxs.spendHTLCs != nil {
   888  				tx := justiceTxs.spendHTLCs
   889  
   890  				brarLog.Debugf("Broadcasting justice tx "+
   891  					"spending HTLC outs: %v",
   892  					newLogClosure(func() string {
   893  						tx.CachedTxHash()
   894  						return spew.Sdump(tx)
   895  					}))
   896  
   897  				err = b.cfg.PublishTransaction(tx, label)
   898  				if err != nil {
   899  					brarLog.Warnf("Unable to broadcast "+
   900  						"HTLC out spending justice "+
   901  						"tx: %v", err)
   902  				}
   903  			}
   904  
   905  		case err := <-errChan:
   906  			if err != errBrarShuttingDown {
   907  				brarLog.Errorf("error waiting for "+
   908  					"spend event: %v", err)
   909  			}
   910  			break Loop
   911  
   912  		case <-b.quit:
   913  			break Loop
   914  		}
   915  	}
   916  
   917  	// Wait for our go routine to exit.
   918  	wg.Wait()
   919  }
   920  
   921  // cleanupBreach marks the given channel point as fully resolved and removes the
   922  // retribution for that the channel from the retribution store.
   923  func (b *BreachArbiter) cleanupBreach(chanPoint *wire.OutPoint) error {
   924  	// With the channel closed, mark it in the database as such.
   925  	err := b.cfg.DB.MarkChanFullyClosed(chanPoint)
   926  	if err != nil {
   927  		return fmt.Errorf("unable to mark chan as closed: %v", err)
   928  	}
   929  
   930  	// Justice has been carried out; we can safely delete the retribution
   931  	// info from the database.
   932  	err = b.cfg.Store.Remove(chanPoint)
   933  	if err != nil {
   934  		return fmt.Errorf("unable to remove retribution from db: %v",
   935  			err)
   936  	}
   937  
   938  	// This is after the Remove call so that the chan passed in via
   939  	// SubscribeBreachComplete is always notified, no matter when it is
   940  	// called. Otherwise, if notifyBreachComplete was before Remove, a
   941  	// very rare edge case could occur in which SubscribeBreachComplete
   942  	// is called after notifyBreachComplete and before Remove, meaning the
   943  	// caller would never be notified.
   944  	b.notifyBreachComplete(chanPoint)
   945  
   946  	return nil
   947  }
   948  
   949  // handleBreachHandoff handles a new breach event, by writing it to disk, then
   950  // notifies the BreachArbiter contract observer goroutine that a channel's
   951  // contract has been breached by the prior counterparty. Once notified the
   952  // BreachArbiter will attempt to sweep ALL funds within the channel using the
   953  // information provided within the BreachRetribution generated due to the
   954  // breach of channel contract. The funds will be swept only after the breaching
   955  // transaction receives a necessary number of confirmations.
   956  //
   957  // NOTE: This MUST be run as a goroutine.
   958  func (b *BreachArbiter) handleBreachHandoff(breachEvent *ContractBreachEvent) {
   959  	defer b.wg.Done()
   960  
   961  	chanPoint := breachEvent.ChanPoint
   962  	brarLog.Debugf("Handling breach handoff for ChannelPoint(%v)",
   963  		chanPoint)
   964  
   965  	// A read from this channel indicates that a channel breach has been
   966  	// detected! So we notify the main coordination goroutine with the
   967  	// information needed to bring the counterparty to justice.
   968  	breachInfo := breachEvent.BreachRetribution
   969  	brarLog.Warnf("REVOKED STATE #%v FOR ChannelPoint(%v) "+
   970  		"broadcast, REMOTE PEER IS DOING SOMETHING "+
   971  		"SKETCHY!!!", breachInfo.RevokedStateNum,
   972  		chanPoint)
   973  
   974  	// Immediately notify the HTLC switch that this link has been
   975  	// breached in order to ensure any incoming or outgoing
   976  	// multi-hop HTLCs aren't sent over this link, nor any other
   977  	// links associated with this peer.
   978  	b.cfg.CloseLink(&chanPoint, CloseBreach)
   979  
   980  	// TODO(roasbeef): need to handle case of remote broadcast
   981  	// mid-local initiated state-transition, possible
   982  	// false-positive?
   983  
   984  	// Acquire the mutex to ensure consistency between the call to
   985  	// IsBreached and Add below.
   986  	b.Lock()
   987  
   988  	// We first check if this breach info is already added to the
   989  	// retribution store.
   990  	breached, err := b.cfg.Store.IsBreached(&chanPoint)
   991  	if err != nil {
   992  		b.Unlock()
   993  		brarLog.Errorf("Unable to check breach info in DB: %v", err)
   994  
   995  		// Notify about the failed lookup and return.
   996  		breachEvent.ProcessACK(err)
   997  		return
   998  	}
   999  
  1000  	// If this channel is already marked as breached in the retribution
  1001  	// store, we already have handled the handoff for this breach. In this
  1002  	// case we can safely ACK the handoff, and return.
  1003  	if breached {
  1004  		b.Unlock()
  1005  		breachEvent.ProcessACK(nil)
  1006  		return
  1007  	}
  1008  
  1009  	// Using the breach information provided by the wallet and the
  1010  	// channel snapshot, construct the retribution information that
  1011  	// will be persisted to disk.
  1012  	retInfo := newRetributionInfo(&chanPoint, breachInfo)
  1013  
  1014  	// Persist the pending retribution state to disk.
  1015  	err = b.cfg.Store.Add(retInfo)
  1016  	b.Unlock()
  1017  	if err != nil {
  1018  		brarLog.Errorf("Unable to persist retribution "+
  1019  			"info to db: %v", err)
  1020  	}
  1021  
  1022  	// Now that the breach has been persisted, try to send an
  1023  	// acknowledgment back to the close observer with the error. If
  1024  	// the ack is successful, the close observer will mark the
  1025  	// channel as pending-closed in the channeldb.
  1026  	breachEvent.ProcessACK(err)
  1027  
  1028  	// Bail if we failed to persist retribution info.
  1029  	if err != nil {
  1030  		return
  1031  	}
  1032  
  1033  	// Now that a new channel contract has been added to the retribution
  1034  	// store, we first register for a notification to be dispatched once
  1035  	// the breach transaction (the revoked commitment transaction) has been
  1036  	// confirmed in the chain to ensure we're not dealing with a moving
  1037  	// target.
  1038  	breachTXID := &retInfo.commitHash
  1039  	breachScript := retInfo.breachedOutputs[0].signDesc.Output.PkScript
  1040  	cfChan, err := b.cfg.Notifier.RegisterConfirmationsNtfn(
  1041  		breachTXID, breachScript, 1, retInfo.breachHeight,
  1042  	)
  1043  	if err != nil {
  1044  		brarLog.Errorf("Unable to register for conf updates for "+
  1045  			"txid: %v, err: %v", breachTXID, err)
  1046  		return
  1047  	}
  1048  
  1049  	brarLog.Warnf("A channel has been breached with txid: %v. Waiting "+
  1050  		"for confirmation, then justice will be served!", breachTXID)
  1051  
  1052  	// With the retribution state persisted, channel close persisted, and
  1053  	// notification registered, we launch a new goroutine which will
  1054  	// finalize the channel retribution after the breach transaction has
  1055  	// been confirmed.
  1056  	b.wg.Add(1)
  1057  	go b.exactRetribution(cfChan, retInfo)
  1058  }
  1059  
  1060  // breachedOutput contains all the information needed to sweep a breached
  1061  // output. A breached output is an output that we are now entitled to due to a
  1062  // revoked commitment transaction being broadcast.
  1063  type breachedOutput struct {
  1064  	amt         dcrutil.Amount
  1065  	outpoint    wire.OutPoint
  1066  	witnessType input.StandardWitnessType
  1067  	signDesc    input.SignDescriptor
  1068  	confHeight  uint32
  1069  
  1070  	secondLevelWitnessScript []byte
  1071  
  1072  	witnessFunc input.WitnessGenerator
  1073  }
  1074  
  1075  // makeBreachedOutput assembles a new breachedOutput that can be used by the
  1076  // breach arbiter to construct a justice or sweep transaction.
  1077  func makeBreachedOutput(outpoint *wire.OutPoint,
  1078  	witnessType input.StandardWitnessType,
  1079  	secondLevelScript []byte,
  1080  	signDescriptor *input.SignDescriptor,
  1081  	confHeight uint32) breachedOutput {
  1082  
  1083  	amount := signDescriptor.Output.Value
  1084  
  1085  	return breachedOutput{
  1086  		amt:                      dcrutil.Amount(amount),
  1087  		outpoint:                 *outpoint,
  1088  		secondLevelWitnessScript: secondLevelScript,
  1089  		witnessType:              witnessType,
  1090  		signDesc:                 *signDescriptor,
  1091  		confHeight:               confHeight,
  1092  	}
  1093  }
  1094  
  1095  // Amount returns the number of satoshis contained in the breached output.
  1096  func (bo *breachedOutput) Amount() dcrutil.Amount {
  1097  	return bo.amt
  1098  }
  1099  
  1100  // OutPoint returns the breached output's identifier that is to be included as a
  1101  // transaction input.
  1102  func (bo *breachedOutput) OutPoint() *wire.OutPoint {
  1103  	return &bo.outpoint
  1104  }
  1105  
  1106  // RequiredTxOut returns a non-nil TxOut if input commits to a certain
  1107  // transaction output. This is used in the SINGLE|ANYONECANPAY case to make
  1108  // sure any presigned input is still valid by including the output.
  1109  func (bo *breachedOutput) RequiredTxOut() *wire.TxOut {
  1110  	return nil
  1111  }
  1112  
  1113  // RequiredLockTime returns whether this input commits to a tx locktime that
  1114  // must be used in the transaction including it.
  1115  func (bo *breachedOutput) RequiredLockTime() (uint32, bool) {
  1116  	return 0, false
  1117  }
  1118  
  1119  // WitnessType returns the type of witness that must be generated to spend the
  1120  // breached output.
  1121  func (bo *breachedOutput) WitnessType() input.WitnessType {
  1122  	return bo.witnessType
  1123  }
  1124  
  1125  // SignDesc returns the breached output's SignDescriptor, which is used during
  1126  // signing to compute the witness.
  1127  func (bo *breachedOutput) SignDesc() *input.SignDescriptor {
  1128  	return &bo.signDesc
  1129  }
  1130  
  1131  // CraftInputScript computes a valid witness that allows us to spend from the
  1132  // breached output. It does so by first generating and memoizing the witness
  1133  // generation function, which parameterized primarily by the witness type and
  1134  // sign descriptor. The method then returns the witness computed by invoking
  1135  // this function on the first and subsequent calls.
  1136  func (bo *breachedOutput) CraftInputScript(signer input.Signer, txn *wire.MsgTx,
  1137  	txinIdx int) (*input.Script, error) {
  1138  
  1139  	// First, we ensure that the witness generation function has been
  1140  	// initialized for this breached output.
  1141  	bo.witnessFunc = bo.witnessType.WitnessGenerator(signer, bo.SignDesc())
  1142  
  1143  	// Now that we have ensured that the witness generation function has
  1144  	// been initialized, we can proceed to execute it and generate the
  1145  	// witness for this particular breached output.
  1146  	return bo.witnessFunc(txn, txinIdx)
  1147  }
  1148  
  1149  // BlocksToMaturity returns the relative timelock, as a number of blocks, that
  1150  // must be built on top of the confirmation height before the output can be
  1151  // spent.
  1152  func (bo *breachedOutput) BlocksToMaturity() uint32 {
  1153  	// If the output is a to_remote output we can claim, and it's of the
  1154  	// confirmed type, we must wait one block before claiming it.
  1155  	if bo.witnessType == input.CommitmentToRemoteConfirmed {
  1156  		return 1
  1157  	}
  1158  
  1159  	// All other breached outputs have no CSV delay.
  1160  	return 0
  1161  }
  1162  
  1163  // HeightHint returns the minimum height at which a confirmed spending tx can
  1164  // occur.
  1165  func (bo *breachedOutput) HeightHint() uint32 {
  1166  	return bo.confHeight
  1167  }
  1168  
  1169  // UnconfParent returns information about a possibly unconfirmed parent tx.
  1170  func (bo *breachedOutput) UnconfParent() *input.TxInfo {
  1171  	return nil
  1172  }
  1173  
  1174  // Add compile-time constraint ensuring breachedOutput implements the Input
  1175  // interface.
  1176  var _ input.Input = (*breachedOutput)(nil)
  1177  
  1178  // retributionInfo encapsulates all the data needed to sweep all the contested
  1179  // funds within a channel whose contract has been breached by the prior
  1180  // counterparty. This struct is used to create the justice transaction which
  1181  // spends all outputs of the commitment transaction into an output controlled
  1182  // by the wallet.
  1183  type retributionInfo struct {
  1184  	commitHash   chainhash.Hash
  1185  	chanPoint    wire.OutPoint
  1186  	chainHash    chainhash.Hash
  1187  	breachHeight uint32
  1188  
  1189  	breachedOutputs []breachedOutput
  1190  }
  1191  
  1192  // newRetributionInfo constructs a retributionInfo containing all the
  1193  // information required by the breach arbiter to recover funds from breached
  1194  // channels.  The information is primarily populated using the BreachRetribution
  1195  // delivered by the wallet when it detects a channel breach.
  1196  func newRetributionInfo(chanPoint *wire.OutPoint,
  1197  	breachInfo *lnwallet.BreachRetribution) *retributionInfo {
  1198  
  1199  	// Determine the number of second layer HTLCs we will attempt to sweep.
  1200  	nHtlcs := len(breachInfo.HtlcRetributions)
  1201  
  1202  	// Initialize a slice to hold the outputs we will attempt to sweep. The
  1203  	// maximum capacity of the slice is set to 2+nHtlcs to handle the case
  1204  	// where the local, remote, and all HTLCs are not dust outputs.  All
  1205  	// HTLC outputs provided by the wallet are guaranteed to be non-dust,
  1206  	// though the commitment outputs are conditionally added depending on
  1207  	// the nil-ness of their sign descriptors.
  1208  	breachedOutputs := make([]breachedOutput, 0, nHtlcs+2)
  1209  
  1210  	// First, record the breach information for the local channel point if
  1211  	// it is not considered dust, which is signaled by a non-nil sign
  1212  	// descriptor. Here we use CommitmentNoDelay (or
  1213  	// CommitmentNoDelayTweakless for newer commitments) since this output
  1214  	// belongs to us and has no time-based constraints on spending.
  1215  	if breachInfo.LocalOutputSignDesc != nil {
  1216  		witnessType := input.CommitmentNoDelay
  1217  		if breachInfo.LocalOutputSignDesc.SingleTweak == nil {
  1218  			witnessType = input.CommitSpendNoDelayTweakless
  1219  		}
  1220  
  1221  		// If the local delay is non-zero, it means this output is of
  1222  		// the confirmed to_remote type.
  1223  		if breachInfo.LocalDelay != 0 {
  1224  			witnessType = input.CommitmentToRemoteConfirmed
  1225  		}
  1226  
  1227  		localOutput := makeBreachedOutput(
  1228  			&breachInfo.LocalOutpoint,
  1229  			witnessType,
  1230  			// No second level script as this is a commitment
  1231  			// output.
  1232  			nil,
  1233  			breachInfo.LocalOutputSignDesc,
  1234  			breachInfo.BreachHeight,
  1235  		)
  1236  
  1237  		breachedOutputs = append(breachedOutputs, localOutput)
  1238  	}
  1239  
  1240  	// Second, record the same information regarding the remote outpoint,
  1241  	// again if it is not dust, which belongs to the party who tried to
  1242  	// steal our money! Here we set witnessType of the breachedOutput to
  1243  	// CommitmentRevoke, since we will be using a revoke key, withdrawing
  1244  	// the funds from the commitment transaction immediately.
  1245  	if breachInfo.RemoteOutputSignDesc != nil {
  1246  		remoteOutput := makeBreachedOutput(
  1247  			&breachInfo.RemoteOutpoint,
  1248  			input.CommitmentRevoke,
  1249  			// No second level script as this is a commitment
  1250  			// output.
  1251  			nil,
  1252  			breachInfo.RemoteOutputSignDesc,
  1253  			breachInfo.BreachHeight,
  1254  		)
  1255  
  1256  		breachedOutputs = append(breachedOutputs, remoteOutput)
  1257  	}
  1258  
  1259  	// Lastly, for each of the breached HTLC outputs, record each as a
  1260  	// breached output with the appropriate witness type based on its
  1261  	// directionality. All HTLC outputs provided by the wallet are assumed
  1262  	// to be non-dust.
  1263  	for i, breachedHtlc := range breachInfo.HtlcRetributions {
  1264  		// Using the breachedHtlc's incoming flag, determine the
  1265  		// appropriate witness type that needs to be generated in order
  1266  		// to sweep the HTLC output.
  1267  		var htlcWitnessType input.StandardWitnessType
  1268  		if breachedHtlc.IsIncoming {
  1269  			htlcWitnessType = input.HtlcAcceptedRevoke
  1270  		} else {
  1271  			htlcWitnessType = input.HtlcOfferedRevoke
  1272  		}
  1273  
  1274  		htlcOutput := makeBreachedOutput(
  1275  			&breachInfo.HtlcRetributions[i].OutPoint,
  1276  			htlcWitnessType,
  1277  			breachInfo.HtlcRetributions[i].SecondLevelWitnessScript,
  1278  			&breachInfo.HtlcRetributions[i].SignDesc,
  1279  			breachInfo.BreachHeight)
  1280  
  1281  		breachedOutputs = append(breachedOutputs, htlcOutput)
  1282  	}
  1283  
  1284  	return &retributionInfo{
  1285  		commitHash:      breachInfo.BreachTransaction.TxHash(),
  1286  		chainHash:       breachInfo.ChainHash,
  1287  		chanPoint:       *chanPoint,
  1288  		breachedOutputs: breachedOutputs,
  1289  		breachHeight:    breachInfo.BreachHeight,
  1290  	}
  1291  }
  1292  
  1293  // justiceTxVariants is a struct that holds transactions which exacts "justice"
  1294  // by sweeping ALL the funds within the channel which we are now entitled to
  1295  // due to a breach of the channel's contract by the counterparty. There are
  1296  // three variants of the justice transaction:
  1297  //
  1298  // 1. The "normal" justice tx that spends all breached outputs
  1299  // 2. A tx that spends only the breached to_local output and to_remote output
  1300  // (can be nil if none of these exist)
  1301  // 3. A tx that spends all the breached HTLC outputs, and second-level HTLC
  1302  // outputs (can be nil if no HTLC outputs exist).
  1303  //
  1304  // The reason we create these three variants, is that in certain cases (like
  1305  // with the anchor output HTLC malleability), the channel counter party can pin
  1306  // the HTLC outputs with low fee children, hindering our normal justice tx that
  1307  // attempts to spend these outputs from propagating. In this case we want to
  1308  // spend the to_local output separately, before the CSV lock expires.
  1309  type justiceTxVariants struct {
  1310  	spendAll        *wire.MsgTx
  1311  	spendCommitOuts *wire.MsgTx
  1312  	spendHTLCs      *wire.MsgTx
  1313  }
  1314  
  1315  // createJusticeTx creates transactions which exacts "justice" by sweeping ALL
  1316  // the funds within the channel which we are now entitled to due to a breach of
  1317  // the channel's contract by the counterparty. This function returns a *fully*
  1318  // signed transaction with the witness for each input fully in place.
  1319  func (b *BreachArbiter) createJusticeTx(
  1320  	breachedOutputs []breachedOutput) (*justiceTxVariants, error) {
  1321  
  1322  	var (
  1323  		allInputs    []input.Input
  1324  		commitInputs []input.Input
  1325  		htlcInputs   []input.Input
  1326  	)
  1327  
  1328  	for i := range breachedOutputs {
  1329  		// Grab locally scoped reference to breached output.
  1330  		inp := &breachedOutputs[i]
  1331  		allInputs = append(allInputs, inp)
  1332  
  1333  		// Check if the input is from an HTLC or a commitment output.
  1334  		if inp.WitnessType() == input.HtlcAcceptedRevoke ||
  1335  			inp.WitnessType() == input.HtlcOfferedRevoke ||
  1336  			inp.WitnessType() == input.HtlcSecondLevelRevoke {
  1337  
  1338  			htlcInputs = append(htlcInputs, inp)
  1339  		} else {
  1340  			commitInputs = append(commitInputs, inp)
  1341  		}
  1342  	}
  1343  
  1344  	var (
  1345  		txs = &justiceTxVariants{}
  1346  		err error
  1347  	)
  1348  
  1349  	// For each group of inputs, create a tx that spends them.
  1350  	txs.spendAll, err = b.createSweepTx(allInputs)
  1351  	if err != nil {
  1352  		return nil, err
  1353  	}
  1354  
  1355  	txs.spendCommitOuts, err = b.createSweepTx(commitInputs)
  1356  	if err != nil {
  1357  		return nil, err
  1358  	}
  1359  
  1360  	txs.spendHTLCs, err = b.createSweepTx(htlcInputs)
  1361  	if err != nil {
  1362  		return nil, err
  1363  	}
  1364  
  1365  	return txs, nil
  1366  }
  1367  
  1368  // createSweepTx creates a tx that sweeps the passed inputs back to our wallet.
  1369  func (b *BreachArbiter) createSweepTx(inputs []input.Input) (*wire.MsgTx,
  1370  	error) {
  1371  	if len(inputs) == 0 {
  1372  		return nil, nil
  1373  	}
  1374  
  1375  	// We will assemble the breached outputs into a slice of spendable
  1376  	// outputs, while simultaneously computing the estimated size of the
  1377  	// transaction.
  1378  	//
  1379  	// Allocate enough space to potentially hold each of the breached
  1380  	// outputs in the retribution info.
  1381  	spendableOutputs := make([]input.Input, 0, len(inputs))
  1382  
  1383  	// The justice transaction we construct will be a transaction
  1384  	// that pays to a p2pkh output. Components such as the version,
  1385  	// nLockTime, and output are already included in the TxSizeEstimator.
  1386  	var sizeEstimate input.TxSizeEstimator
  1387  	sizeEstimate.AddP2PKHOutput()
  1388  
  1389  	// Next, we iterate over the breached outputs contained in the
  1390  	// retribution info.  For each, we switch over the witness type such
  1391  	// that we contribute the appropriate weight for each input and
  1392  	// witness, finally adding to our list of spendable outputs.
  1393  	for i := range inputs {
  1394  		// Grab locally scoped reference to breached output.
  1395  		inp := inputs[i]
  1396  
  1397  		// First, determine the appropriate estimated sig script size
  1398  		// for the give witness type of this breached output. If the
  1399  		// witness weight cannot be estimated, we will omit it from the
  1400  		// transaction.
  1401  		sigScriptSize, _, err := inp.WitnessType().SizeUpperBound()
  1402  		if err != nil {
  1403  			brarLog.Warnf("could not determine witness size"+
  1404  				"for breached output in retribution info: %v",
  1405  				err)
  1406  			continue
  1407  		}
  1408  		sizeEstimate.AddCustomInput(sigScriptSize)
  1409  
  1410  		// Finally, append this input to our list of spendable outputs.
  1411  		spendableOutputs = append(spendableOutputs, inp)
  1412  	}
  1413  
  1414  	txSize := sizeEstimate.Size()
  1415  	return b.sweepSpendableOutputsTxn(txSize, spendableOutputs...)
  1416  }
  1417  
  1418  // sweepSpendableOutputsTxn creates a signed transaction from a sequence of
  1419  // spendable outputs by sweeping the funds into a single p2wkh output.
  1420  func (b *BreachArbiter) sweepSpendableOutputsTxn(txSize int64,
  1421  	inputs ...input.Input) (*wire.MsgTx, error) {
  1422  
  1423  	// First, we obtain a new public key script from the wallet which we'll
  1424  	// sweep the funds to.
  1425  	// TODO(roasbeef): possibly create many outputs to minimize change in
  1426  	// the future?
  1427  	pkScript, err := b.cfg.GenSweepScript()
  1428  	if err != nil {
  1429  		return nil, err
  1430  	}
  1431  
  1432  	// Compute the total amount contained in the inputs.
  1433  	var totalAmt dcrutil.Amount
  1434  	for _, input := range inputs {
  1435  		totalAmt += dcrutil.Amount(input.SignDesc().Output.Value)
  1436  	}
  1437  
  1438  	// We'll actually attempt to target inclusion within the next two
  1439  	// blocks as we'd like to sweep these funds back into our wallet ASAP.
  1440  	feePerKB, err := b.cfg.Estimator.EstimateFeePerKB(justiceTxConfTarget)
  1441  	if err != nil {
  1442  		return nil, err
  1443  	}
  1444  	txFee := feePerKB.FeeForSize(txSize)
  1445  
  1446  	// TODO(roasbeef): already start to siphon their funds into fees
  1447  	sweepAmt := int64(totalAmt - txFee)
  1448  
  1449  	// With the fee calculated, we can now create the transaction using the
  1450  	// information gathered above and the provided retribution information.
  1451  	txn := wire.NewMsgTx()
  1452  
  1453  	// We begin by adding the output to which our funds will be deposited.
  1454  	txn.AddTxOut(&wire.TxOut{
  1455  		PkScript: pkScript,
  1456  		Value:    sweepAmt,
  1457  	})
  1458  
  1459  	// Next, we add all of the spendable outputs as inputs to the
  1460  	// transaction.
  1461  	for _, input := range inputs {
  1462  		txn.AddTxIn(&wire.TxIn{
  1463  			ValueIn:          input.SignDesc().Output.Value,
  1464  			PreviousOutPoint: *input.OutPoint(),
  1465  			Sequence:         input.BlocksToMaturity(),
  1466  		})
  1467  	}
  1468  
  1469  	// Before signing the transaction, check to ensure that it meets some
  1470  	// basic validity requirements.
  1471  	if err := standalone.CheckTransactionSanity(txn, uint64(b.cfg.NetParams.MaxTxSize)); err != nil {
  1472  		brarLog.Debugf("Sweep tx does not pass sanity check: %v. "+
  1473  			"Tx=%s", logClosure(func() string {
  1474  			return spew.Sdump(txn)
  1475  		}))
  1476  		return nil, err
  1477  	}
  1478  
  1479  	// Create a closure that encapsulates the process of initializing a
  1480  	// particular output's witness generation function, computing the
  1481  	// witness, and attaching it to the transaction. This function accepts
  1482  	// an integer index representing the intended txin index, and the
  1483  	// breached output from which it will spend.
  1484  	addWitness := func(idx int, so input.Input) error {
  1485  		// First, we construct a valid witness for this outpoint and
  1486  		// transaction using the SpendableOutput's witness generation
  1487  		// function.
  1488  		inputScript, err := so.CraftInputScript(
  1489  			b.cfg.Signer, txn, idx,
  1490  		)
  1491  		if err != nil {
  1492  			return err
  1493  		}
  1494  
  1495  		// Then, we add the witness to the transaction at the
  1496  		// appropriate txin index.
  1497  		txn.TxIn[idx].SignatureScript, err = input.WitnessStackToSigScript(inputScript.Witness)
  1498  
  1499  		return err
  1500  	}
  1501  
  1502  	// Finally, generate a witness for each output and attach it to the
  1503  	// transaction.
  1504  	for i, input := range inputs {
  1505  		if err := addWitness(i, input); err != nil {
  1506  			return nil, err
  1507  		}
  1508  	}
  1509  
  1510  	return txn, nil
  1511  }
  1512  
  1513  // RetributionStore handles persistence of retribution states to disk and is
  1514  // backed by a bboltdb bucket. The primary responsibility of the retribution
  1515  // store is to ensure that we can recover from a restart in the middle of a
  1516  // breached contract retribution.
  1517  type RetributionStore struct {
  1518  	db kvdb.Backend
  1519  }
  1520  
  1521  // NewRetributionStore creates a new instance of a RetributionStore.
  1522  func NewRetributionStore(db kvdb.Backend) *RetributionStore {
  1523  	return &RetributionStore{
  1524  		db: db,
  1525  	}
  1526  }
  1527  
  1528  // Add adds a retribution state to the RetributionStore, which is then persisted
  1529  // to disk.
  1530  func (rs *RetributionStore) Add(ret *retributionInfo) error {
  1531  	return kvdb.Update(rs.db, func(tx kvdb.RwTx) error {
  1532  		// If this is our first contract breach, the retributionBucket
  1533  		// won't exist, in which case, we just create a new bucket.
  1534  		retBucket, err := tx.CreateTopLevelBucket(retributionBucket)
  1535  		if err != nil {
  1536  			return err
  1537  		}
  1538  
  1539  		var outBuf bytes.Buffer
  1540  		if err := writeOutpoint(&outBuf, &ret.chanPoint); err != nil {
  1541  			return err
  1542  		}
  1543  
  1544  		var retBuf bytes.Buffer
  1545  		if err := ret.Encode(&retBuf); err != nil {
  1546  			return err
  1547  		}
  1548  
  1549  		return retBucket.Put(outBuf.Bytes(), retBuf.Bytes())
  1550  	}, func() {})
  1551  }
  1552  
  1553  // IsBreached queries the retribution store to discern if this channel was
  1554  // previously breached. This is used when connecting to a peer to determine if
  1555  // it is safe to add a link to the htlcswitch, as we should never add a channel
  1556  // that has already been breached.
  1557  func (rs *RetributionStore) IsBreached(chanPoint *wire.OutPoint) (bool, error) {
  1558  	var found bool
  1559  	err := kvdb.View(rs.db, func(tx kvdb.RTx) error {
  1560  		retBucket := tx.ReadBucket(retributionBucket)
  1561  		if retBucket == nil {
  1562  			return nil
  1563  		}
  1564  
  1565  		var chanBuf bytes.Buffer
  1566  		if err := writeOutpoint(&chanBuf, chanPoint); err != nil {
  1567  			return err
  1568  		}
  1569  
  1570  		retInfo := retBucket.Get(chanBuf.Bytes())
  1571  		if retInfo != nil {
  1572  			found = true
  1573  		}
  1574  
  1575  		return nil
  1576  	}, func() {
  1577  		found = false
  1578  	})
  1579  
  1580  	return found, err
  1581  }
  1582  
  1583  // Remove removes a retribution state and finalized justice transaction by
  1584  // channel point  from the retribution store.
  1585  func (rs *RetributionStore) Remove(chanPoint *wire.OutPoint) error {
  1586  	return kvdb.Update(rs.db, func(tx kvdb.RwTx) error {
  1587  		retBucket := tx.ReadWriteBucket(retributionBucket)
  1588  
  1589  		// We return an error if the bucket is not already created,
  1590  		// since normal operation of the breach arbiter should never try
  1591  		// to remove a finalized retribution state that is not already
  1592  		// stored in the db.
  1593  		if retBucket == nil {
  1594  			return errors.New("unable to remove retribution " +
  1595  				"because the retribution bucket doesn't exist")
  1596  		}
  1597  
  1598  		// Serialize the channel point we are intending to remove.
  1599  		var chanBuf bytes.Buffer
  1600  		if err := writeOutpoint(&chanBuf, chanPoint); err != nil {
  1601  			return err
  1602  		}
  1603  		chanBytes := chanBuf.Bytes()
  1604  
  1605  		// Remove the persisted retribution info and finalized justice
  1606  		// transaction.
  1607  		if err := retBucket.Delete(chanBytes); err != nil {
  1608  			return err
  1609  		}
  1610  
  1611  		// If we have not finalized this channel breach, we can exit
  1612  		// early.
  1613  		justiceBkt := tx.ReadWriteBucket(justiceTxnBucket)
  1614  		if justiceBkt == nil {
  1615  			return nil
  1616  		}
  1617  
  1618  		return justiceBkt.Delete(chanBytes)
  1619  	}, func() {})
  1620  }
  1621  
  1622  // ForAll iterates through all stored retributions and executes the passed
  1623  // callback function on each retribution.
  1624  func (rs *RetributionStore) ForAll(cb func(*retributionInfo) error,
  1625  	reset func()) error {
  1626  
  1627  	return kvdb.View(rs.db, func(tx kvdb.RTx) error {
  1628  		// If the bucket does not exist, then there are no pending
  1629  		// retributions.
  1630  		retBucket := tx.ReadBucket(retributionBucket)
  1631  		if retBucket == nil {
  1632  			return nil
  1633  		}
  1634  
  1635  		// Otherwise, we fetch each serialized retribution info,
  1636  		// deserialize it, and execute the passed in callback function
  1637  		// on it.
  1638  		return retBucket.ForEach(func(_, retBytes []byte) error {
  1639  			ret := &retributionInfo{}
  1640  			err := ret.Decode(bytes.NewBuffer(retBytes))
  1641  			if err != nil {
  1642  				return err
  1643  			}
  1644  
  1645  			return cb(ret)
  1646  		})
  1647  	}, reset)
  1648  }
  1649  
  1650  // Encode serializes the retribution into the passed byte stream.
  1651  func (ret *retributionInfo) Encode(w io.Writer) error {
  1652  	var scratch [4]byte
  1653  
  1654  	if _, err := w.Write(ret.commitHash[:]); err != nil {
  1655  		return err
  1656  	}
  1657  
  1658  	if err := writeOutpoint(w, &ret.chanPoint); err != nil {
  1659  		return err
  1660  	}
  1661  
  1662  	if _, err := w.Write(ret.chainHash[:]); err != nil {
  1663  		return err
  1664  	}
  1665  
  1666  	binary.BigEndian.PutUint32(scratch[:], ret.breachHeight)
  1667  	if _, err := w.Write(scratch[:]); err != nil {
  1668  		return err
  1669  	}
  1670  
  1671  	nOutputs := len(ret.breachedOutputs)
  1672  	if err := wire.WriteVarInt(w, 0, uint64(nOutputs)); err != nil {
  1673  		return err
  1674  	}
  1675  
  1676  	for _, output := range ret.breachedOutputs {
  1677  		if err := output.Encode(w); err != nil {
  1678  			return err
  1679  		}
  1680  	}
  1681  
  1682  	return nil
  1683  }
  1684  
  1685  // Dencode deserializes a retribution from the passed byte stream.
  1686  func (ret *retributionInfo) Decode(r io.Reader) error {
  1687  	var scratch [32]byte
  1688  
  1689  	if _, err := io.ReadFull(r, scratch[:]); err != nil {
  1690  		return err
  1691  	}
  1692  	hash, err := chainhash.NewHash(scratch[:])
  1693  	if err != nil {
  1694  		return err
  1695  	}
  1696  	ret.commitHash = *hash
  1697  
  1698  	if err := readOutpoint(r, &ret.chanPoint); err != nil {
  1699  		return err
  1700  	}
  1701  
  1702  	if _, err := io.ReadFull(r, scratch[:]); err != nil {
  1703  		return err
  1704  	}
  1705  	chainHash, err := chainhash.NewHash(scratch[:])
  1706  	if err != nil {
  1707  		return err
  1708  	}
  1709  	ret.chainHash = *chainHash
  1710  
  1711  	if _, err := io.ReadFull(r, scratch[:4]); err != nil {
  1712  		return err
  1713  	}
  1714  	ret.breachHeight = binary.BigEndian.Uint32(scratch[:4])
  1715  
  1716  	nOutputsU64, err := wire.ReadVarInt(r, 0)
  1717  	if err != nil {
  1718  		return err
  1719  	}
  1720  	nOutputs := int(nOutputsU64)
  1721  
  1722  	ret.breachedOutputs = make([]breachedOutput, nOutputs)
  1723  	for i := range ret.breachedOutputs {
  1724  		if err := ret.breachedOutputs[i].Decode(r); err != nil {
  1725  			return err
  1726  		}
  1727  	}
  1728  
  1729  	return nil
  1730  }
  1731  
  1732  // Encode serializes a breachedOutput into the passed byte stream.
  1733  func (bo *breachedOutput) Encode(w io.Writer) error {
  1734  	var scratch [8]byte
  1735  
  1736  	binary.BigEndian.PutUint64(scratch[:8], uint64(bo.amt))
  1737  	if _, err := w.Write(scratch[:8]); err != nil {
  1738  		return err
  1739  	}
  1740  
  1741  	if err := writeOutpoint(w, &bo.outpoint); err != nil {
  1742  		return err
  1743  	}
  1744  
  1745  	err := input.WriteSignDescriptor(w, &bo.signDesc)
  1746  	if err != nil {
  1747  		return err
  1748  	}
  1749  
  1750  	err = wire.WriteVarBytes(w, 0, bo.secondLevelWitnessScript)
  1751  	if err != nil {
  1752  		return err
  1753  	}
  1754  
  1755  	binary.BigEndian.PutUint16(scratch[:2], uint16(bo.witnessType))
  1756  	if _, err := w.Write(scratch[:2]); err != nil {
  1757  		return err
  1758  	}
  1759  
  1760  	return nil
  1761  }
  1762  
  1763  // Decode deserializes a breachedOutput from the passed byte stream.
  1764  func (bo *breachedOutput) Decode(r io.Reader) error {
  1765  	var scratch [8]byte
  1766  
  1767  	if _, err := io.ReadFull(r, scratch[:8]); err != nil {
  1768  		return err
  1769  	}
  1770  	bo.amt = dcrutil.Amount(binary.BigEndian.Uint64(scratch[:8]))
  1771  
  1772  	if err := readOutpoint(r, &bo.outpoint); err != nil {
  1773  		return err
  1774  	}
  1775  
  1776  	if err := input.ReadSignDescriptor(r, &bo.signDesc); err != nil {
  1777  		return err
  1778  	}
  1779  
  1780  	wScript, err := wire.ReadVarBytes(r, 0, 1000, "witness script")
  1781  	if err != nil {
  1782  		return err
  1783  	}
  1784  	bo.secondLevelWitnessScript = wScript
  1785  
  1786  	if _, err := io.ReadFull(r, scratch[:2]); err != nil {
  1787  		return err
  1788  	}
  1789  	bo.witnessType = input.StandardWitnessType(
  1790  		binary.BigEndian.Uint16(scratch[:2]),
  1791  	)
  1792  
  1793  	return nil
  1794  }