github.com/decred/dcrlnd@v0.7.6/funding/manager_test.go (about)

     1  //go:build !rpctest
     2  // +build !rpctest
     3  
     4  package funding
     5  
     6  import (
     7  	"bytes"
     8  	"encoding/hex"
     9  	"errors"
    10  	"fmt"
    11  	"io/ioutil"
    12  	"net"
    13  	"os"
    14  	"path/filepath"
    15  	"runtime"
    16  	"strings"
    17  	"sync"
    18  	"testing"
    19  	"time"
    20  
    21  	"github.com/decred/dcrd/chaincfg/chainhash"
    22  	"github.com/decred/dcrd/chaincfg/v3"
    23  	"github.com/decred/dcrd/dcrec/secp256k1/v4"
    24  	"github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
    25  	"github.com/decred/dcrd/dcrutil/v4"
    26  	"github.com/decred/dcrd/wire"
    27  	"github.com/stretchr/testify/require"
    28  
    29  	"github.com/decred/dcrlnd/chainntnfs"
    30  	"github.com/decred/dcrlnd/chainreg"
    31  	"github.com/decred/dcrlnd/chainscan"
    32  	"github.com/decred/dcrlnd/chanacceptor"
    33  	"github.com/decred/dcrlnd/channeldb"
    34  	"github.com/decred/dcrlnd/channelnotifier"
    35  	"github.com/decred/dcrlnd/discovery"
    36  	"github.com/decred/dcrlnd/htlcswitch"
    37  	"github.com/decred/dcrlnd/input"
    38  	"github.com/decred/dcrlnd/keychain"
    39  	"github.com/decred/dcrlnd/lncfg"
    40  	"github.com/decred/dcrlnd/lnpeer"
    41  	"github.com/decred/dcrlnd/lnrpc"
    42  	"github.com/decred/dcrlnd/lntest/mock"
    43  	"github.com/decred/dcrlnd/lnwallet"
    44  	"github.com/decred/dcrlnd/lnwallet/chainfee"
    45  	"github.com/decred/dcrlnd/lnwire"
    46  )
    47  
    48  const (
    49  	// testPollNumTries is the number of times we attempt to query
    50  	// for a certain expected database state before we give up and
    51  	// consider the test failed. Since it sometimes can take a
    52  	// while to update the database, we poll a certain amount of
    53  	// times, until it gets into the state we expect, or we are out
    54  	// of tries.
    55  	testPollNumTries = 10
    56  
    57  	// testPollSleepMs is the number of milliseconds to sleep between
    58  	// each attempt to access the database to check its state.
    59  	testPollSleepMs = 500
    60  
    61  	// maxPending is the maximum number of channels we allow opening to the
    62  	// same peer in the max pending channels test.
    63  	maxPending = 4
    64  
    65  	// A dummy value to use for the funding broadcast height.
    66  	fundingBroadcastHeight = 123
    67  
    68  	// defaultMaxLocalCSVDelay is the maximum delay we accept on our
    69  	// commitment output.
    70  	defaultMaxLocalCSVDelay = 10000
    71  )
    72  
    73  var (
    74  	// Use hard-coded keys for Alice and Bob, the two FundingManagers that
    75  	// we will test the interaction between.
    76  	alicePrivKeyBytes = [32]byte{
    77  		0xb7, 0x94, 0x38, 0x5f, 0x2d, 0x1e, 0xf7, 0xab,
    78  		0x4d, 0x92, 0x73, 0xd1, 0x90, 0x63, 0x81, 0xb4,
    79  		0x4f, 0x2f, 0x6f, 0x25, 0x88, 0xa3, 0xef, 0xb9,
    80  		0x6a, 0x49, 0x18, 0x83, 0x31, 0x98, 0x47, 0x53,
    81  	}
    82  
    83  	alicePrivKey, alicePubKey = privKeyFromBytes(alicePrivKeyBytes[:])
    84  
    85  	aliceTCPAddr, _ = net.ResolveTCPAddr("tcp", "10.0.0.2:9001")
    86  
    87  	aliceAddr = &lnwire.NetAddress{
    88  		IdentityKey: alicePubKey,
    89  		Address:     aliceTCPAddr,
    90  	}
    91  
    92  	bobPrivKeyBytes = [32]byte{
    93  		0x81, 0xb6, 0x37, 0xd8, 0xfc, 0xd2, 0xc6, 0xda,
    94  		0x63, 0x59, 0xe6, 0x96, 0x31, 0x13, 0xa1, 0x17,
    95  		0xd, 0xe7, 0x95, 0xe4, 0xb7, 0x25, 0xb8, 0x4d,
    96  		0x1e, 0xb, 0x4c, 0xfd, 0x9e, 0xc5, 0x8c, 0xe9,
    97  	}
    98  
    99  	bobPrivKey, bobPubKey = privKeyFromBytes(bobPrivKeyBytes[:])
   100  
   101  	bobTCPAddr, _ = net.ResolveTCPAddr("tcp", "10.0.0.2:9000")
   102  
   103  	bobAddr = &lnwire.NetAddress{
   104  		IdentityKey: bobPubKey,
   105  		Address:     bobTCPAddr,
   106  	}
   107  
   108  	rBytes, _ = hex.DecodeString("63724406601629180062774974542967536251589935445068131219452686511677818569431")
   109  	sBytes, _ = hex.DecodeString("18801056069249825825291287104931333862866033135609736119018462340006816851118")
   110  	testSig   = ecdsa.NewSignature(
   111  		modNScalar(rBytes),
   112  		modNScalar(sBytes),
   113  	)
   114  
   115  	testKeyLoc = keychain.KeyLocator{Family: keychain.KeyFamilyNodeKey}
   116  
   117  	fundingNetParams = chainreg.DecredTestNetParams
   118  )
   119  
   120  type mockNotifier struct {
   121  	oneConfChannel chan *chainntnfs.TxConfirmation
   122  	sixConfChannel chan *chainntnfs.TxConfirmation
   123  	epochChan      chan *chainntnfs.BlockEpoch
   124  
   125  	useByTxConfChannels bool
   126  	byTxConfChannels    *sync.Map
   127  }
   128  
   129  func (m *mockNotifier) confirmTx(t *testing.T, tx *wire.MsgTx) {
   130  	txid := tx.TxHash()
   131  	v, ok := m.byTxConfChannels.Load(txid)
   132  	if !ok {
   133  		t.Fatalf("could not find confirm channel for txid %s", txid)
   134  	}
   135  
   136  	ch := v.(chan *chainntnfs.TxConfirmation)
   137  	ch <- &chainntnfs.TxConfirmation{
   138  		Tx: tx,
   139  	}
   140  }
   141  
   142  func (m *mockNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
   143  	pkScript []byte, numConfs, heightHint uint32) (*chainntnfs.ConfirmationEvent, error) {
   144  
   145  	_, err := chainscan.ParsePkScript(0, pkScript)
   146  	if err != nil {
   147  		return nil, err
   148  	}
   149  
   150  	if m.useByTxConfChannels {
   151  		ch := make(chan *chainntnfs.TxConfirmation, 1)
   152  		m.byTxConfChannels.Store(*txid, ch)
   153  		return &chainntnfs.ConfirmationEvent{
   154  			Confirmed: ch,
   155  		}, nil
   156  	}
   157  
   158  	if numConfs == 6 {
   159  		return &chainntnfs.ConfirmationEvent{
   160  			Confirmed: m.sixConfChannel,
   161  		}, nil
   162  	}
   163  	return &chainntnfs.ConfirmationEvent{
   164  		Confirmed: m.oneConfChannel,
   165  	}, nil
   166  }
   167  
   168  func (m *mockNotifier) RegisterBlockEpochNtfn(
   169  	bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
   170  	return &chainntnfs.BlockEpochEvent{
   171  		Epochs: m.epochChan,
   172  		Cancel: func() {},
   173  	}, nil
   174  }
   175  
   176  func (m *mockNotifier) Start() error {
   177  	return nil
   178  }
   179  
   180  func (m *mockNotifier) Started() bool {
   181  	return true
   182  }
   183  
   184  func (m *mockNotifier) Stop() error {
   185  	return nil
   186  }
   187  
   188  func (m *mockNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint, _ []byte,
   189  	heightHint uint32) (*chainntnfs.SpendEvent, error) {
   190  	return &chainntnfs.SpendEvent{
   191  		Spend:  make(chan *chainntnfs.SpendDetail),
   192  		Cancel: func() {},
   193  	}, nil
   194  }
   195  
   196  type mockChanEvent struct {
   197  	openEvent        chan wire.OutPoint
   198  	pendingOpenEvent chan channelnotifier.PendingOpenChannelEvent
   199  }
   200  
   201  func (m *mockChanEvent) NotifyOpenChannelEvent(outpoint wire.OutPoint) {
   202  	m.openEvent <- outpoint
   203  }
   204  
   205  func (m *mockChanEvent) NotifyPendingOpenChannelEvent(outpoint wire.OutPoint,
   206  	pendingChannel *channeldb.OpenChannel) {
   207  
   208  	m.pendingOpenEvent <- channelnotifier.PendingOpenChannelEvent{
   209  		ChannelPoint:   &outpoint,
   210  		PendingChannel: pendingChannel,
   211  	}
   212  }
   213  
   214  type newChannelMsg struct {
   215  	channel *channeldb.OpenChannel
   216  	err     chan error
   217  }
   218  
   219  type testNode struct {
   220  	privKey         *secp256k1.PrivateKey
   221  	addr            *lnwire.NetAddress
   222  	msgChan         chan lnwire.Message
   223  	announceChan    chan lnwire.Message
   224  	publTxChan      chan *wire.MsgTx
   225  	fundingMgr      *Manager
   226  	newChannels     chan *newChannelMsg
   227  	mockNotifier    *mockNotifier
   228  	mockChanEvent   *mockChanEvent
   229  	testDir         string
   230  	shutdownChannel chan struct{}
   231  	remoteFeatures  []lnwire.FeatureBit
   232  
   233  	remotePeer  *testNode
   234  	sendMessage func(lnwire.Message) error
   235  }
   236  
   237  var _ lnpeer.Peer = (*testNode)(nil)
   238  
   239  func (n *testNode) IdentityKey() *secp256k1.PublicKey {
   240  	return n.addr.IdentityKey
   241  }
   242  
   243  func (n *testNode) Address() net.Addr {
   244  	return n.addr.Address
   245  }
   246  
   247  func (n *testNode) Inbound() bool {
   248  	return false
   249  }
   250  
   251  func (n *testNode) PubKey() [33]byte {
   252  	return newSerializedKey(n.addr.IdentityKey)
   253  }
   254  
   255  func (n *testNode) SendMessage(_ bool, msg ...lnwire.Message) error {
   256  	return n.sendMessage(msg[0])
   257  }
   258  
   259  func (n *testNode) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
   260  	return n.SendMessage(sync, msgs...)
   261  }
   262  
   263  func (n *testNode) WipeChannel(_ *wire.OutPoint) {}
   264  
   265  func (n *testNode) QuitSignal() <-chan struct{} {
   266  	return n.shutdownChannel
   267  }
   268  
   269  func (n *testNode) LocalFeatures() *lnwire.FeatureVector {
   270  	return lnwire.NewFeatureVector(nil, nil)
   271  }
   272  
   273  func (n *testNode) RemoteFeatures() *lnwire.FeatureVector {
   274  	return lnwire.NewFeatureVector(
   275  		lnwire.NewRawFeatureVector(n.remoteFeatures...), nil,
   276  	)
   277  }
   278  
   279  func (n *testNode) AddNewChannel(channel *channeldb.OpenChannel,
   280  	quit <-chan struct{}) error {
   281  
   282  	errChan := make(chan error)
   283  	msg := &newChannelMsg{
   284  		channel: channel,
   285  		err:     errChan,
   286  	}
   287  
   288  	select {
   289  	case n.newChannels <- msg:
   290  	case <-quit:
   291  		return ErrFundingManagerShuttingDown
   292  	}
   293  
   294  	select {
   295  	case err := <-errChan:
   296  		return err
   297  	case <-quit:
   298  		return ErrFundingManagerShuttingDown
   299  	}
   300  }
   301  
   302  func createTestWallet(cdb *channeldb.ChannelStateDB, netParams *chaincfg.Params,
   303  	notifier chainntnfs.ChainNotifier, wc lnwallet.WalletController,
   304  	signer input.Signer, keyRing keychain.SecretKeyRing,
   305  	bio lnwallet.BlockChainIO,
   306  	estimator chainfee.Estimator) (*lnwallet.LightningWallet, error) {
   307  
   308  	wallet, err := lnwallet.NewLightningWallet(lnwallet.Config{
   309  		Database:           cdb,
   310  		Notifier:           notifier,
   311  		SecretKeyRing:      keyRing,
   312  		WalletController:   wc,
   313  		Signer:             signer,
   314  		ChainIO:            bio,
   315  		FeeEstimator:       estimator,
   316  		NetParams:          *netParams,
   317  		DefaultConstraints: chainreg.GenDefaultDcrConstraints(),
   318  	})
   319  	if err != nil {
   320  		return nil, err
   321  	}
   322  
   323  	if err := wallet.Startup(); err != nil {
   324  		return nil, err
   325  	}
   326  
   327  	return wallet, nil
   328  }
   329  
   330  func createTestFundingManager(t *testing.T, privKey *secp256k1.PrivateKey,
   331  	addr *lnwire.NetAddress, tempTestDir string,
   332  	options ...cfgOption) (*testNode, error) {
   333  
   334  	netParams := fundingNetParams.Params
   335  	estimator := chainfee.NewStaticEstimator(62500, 0)
   336  
   337  	chainNotifier := &mockNotifier{
   338  		oneConfChannel:   make(chan *chainntnfs.TxConfirmation, 1),
   339  		sixConfChannel:   make(chan *chainntnfs.TxConfirmation, 1),
   340  		epochChan:        make(chan *chainntnfs.BlockEpoch, 2),
   341  		byTxConfChannels: &sync.Map{},
   342  	}
   343  
   344  	sentMessages := make(chan lnwire.Message)
   345  	sentAnnouncements := make(chan lnwire.Message)
   346  	publTxChan := make(chan *wire.MsgTx, 1)
   347  	shutdownChan := make(chan struct{})
   348  
   349  	wc := &mock.WalletController{
   350  		RootKey: alicePrivKey,
   351  	}
   352  	signer := &mock.SingleSigner{
   353  		Privkey: alicePrivKey,
   354  	}
   355  	bio := &mock.ChainIO{
   356  		BestHeight: fundingBroadcastHeight,
   357  	}
   358  
   359  	// The mock channel event notifier will receive events for each pending
   360  	// open and open channel. Because some tests will create multiple
   361  	// channels in a row before advancing to the next step, these channels
   362  	// need to be buffered.
   363  	evt := &mockChanEvent{
   364  		openEvent: make(chan wire.OutPoint, maxPending),
   365  		pendingOpenEvent: make(
   366  			chan channelnotifier.PendingOpenChannelEvent, maxPending,
   367  		),
   368  	}
   369  
   370  	dbDir := filepath.Join(tempTestDir, "cdb")
   371  	fullDB, err := channeldb.Open(dbDir)
   372  	if err != nil {
   373  		return nil, err
   374  	}
   375  
   376  	cdb := fullDB.ChannelStateDB()
   377  
   378  	keyRing := &mock.SecretKeyRing{
   379  		RootKey: alicePrivKey,
   380  	}
   381  
   382  	lnw, err := createTestWallet(
   383  		cdb, netParams, chainNotifier, wc, signer, keyRing, bio,
   384  		estimator,
   385  	)
   386  	if err != nil {
   387  		t.Fatalf("unable to create test ln wallet: %v", err)
   388  	}
   389  
   390  	var chanIDSeed [32]byte
   391  
   392  	chainedAcceptor := chanacceptor.NewChainedAcceptor()
   393  
   394  	fundingCfg := Config{
   395  		IDKey:        privKey.PubKey(),
   396  		IDKeyLoc:     testKeyLoc,
   397  		Wallet:       lnw,
   398  		Notifier:     chainNotifier,
   399  		FeeEstimator: estimator,
   400  		SignMessage: func(_ keychain.KeyLocator,
   401  			_ []byte, _ bool) (*ecdsa.Signature, error) {
   402  
   403  			return testSig, nil
   404  		},
   405  		SendAnnouncement: func(msg lnwire.Message,
   406  			_ ...discovery.OptionalMsgField) chan error {
   407  
   408  			errChan := make(chan error, 1)
   409  			select {
   410  			case sentAnnouncements <- msg:
   411  				errChan <- nil
   412  			case <-shutdownChan:
   413  				errChan <- fmt.Errorf("shutting down")
   414  			}
   415  			return errChan
   416  		},
   417  		CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement, error) {
   418  			return lnwire.NodeAnnouncement{}, nil
   419  		},
   420  		TempChanIDSeed: chanIDSeed,
   421  		FindChannel: func(chanID lnwire.ChannelID) (
   422  			*channeldb.OpenChannel, error) {
   423  			dbChannels, err := cdb.FetchAllChannels()
   424  			if err != nil {
   425  				return nil, err
   426  			}
   427  
   428  			for _, channel := range dbChannels {
   429  				if chanID.IsChanPoint(&channel.FundingOutpoint) {
   430  					return channel, nil
   431  				}
   432  			}
   433  
   434  			return nil, fmt.Errorf("unable to find channel")
   435  		},
   436  		DefaultRoutingPolicy: htlcswitch.ForwardingPolicy{
   437  			MinHTLCOut:    5,
   438  			BaseFee:       100,
   439  			FeeRate:       1000,
   440  			TimeLockDelta: 10,
   441  		},
   442  		DefaultMinHtlcIn: 5,
   443  		NumRequiredConfs: func(chanAmt dcrutil.Amount,
   444  			pushAmt lnwire.MilliAtom) uint16 {
   445  			return 3
   446  		},
   447  		RequiredRemoteDelay: func(amt dcrutil.Amount) uint16 {
   448  			return 4
   449  		},
   450  		RequiredRemoteChanReserve: func(chanAmt,
   451  			dustLimit dcrutil.Amount) dcrutil.Amount {
   452  
   453  			reserve := chanAmt / 100
   454  			if reserve < dustLimit {
   455  				reserve = dustLimit
   456  			}
   457  
   458  			return reserve
   459  		},
   460  		RequiredRemoteMaxValue: func(chanAmt dcrutil.Amount) lnwire.MilliAtom {
   461  			reserve := lnwire.NewMAtomsFromAtoms(chanAmt / 100)
   462  			return lnwire.NewMAtomsFromAtoms(chanAmt) - reserve
   463  		},
   464  		RequiredRemoteMaxHTLCs: func(chanAmt dcrutil.Amount) uint16 {
   465  			return uint16(input.MaxHTLCNumber / 2)
   466  		},
   467  		WatchNewChannel: func(*channeldb.OpenChannel, *secp256k1.PublicKey) error {
   468  			return nil
   469  		},
   470  		ReportShortChanID: func(wire.OutPoint) error {
   471  			return nil
   472  		},
   473  		PublishTransaction: func(txn *wire.MsgTx, _ string) error {
   474  			publTxChan <- txn
   475  			return nil
   476  		},
   477  		UpdateLabel: func(chainhash.Hash, string) error {
   478  			return nil
   479  		},
   480  		ZombieSweeperInterval:         1 * time.Hour,
   481  		ReservationTimeout:            1 * time.Nanosecond,
   482  		MaxChanSize:                   MaxFundingAmount,
   483  		MaxLocalCSVDelay:              defaultMaxLocalCSVDelay,
   484  		MaxPendingChannels:            lncfg.DefaultMaxPendingChannels,
   485  		NotifyOpenChannelEvent:        evt.NotifyOpenChannelEvent,
   486  		OpenChannelPredicate:          chainedAcceptor,
   487  		NotifyPendingOpenChannelEvent: evt.NotifyPendingOpenChannelEvent,
   488  		RegisteredChains:              chainreg.NewChainRegistry(),
   489  	}
   490  
   491  	for _, op := range options {
   492  		op(&fundingCfg)
   493  	}
   494  
   495  	f, err := NewFundingManager(fundingCfg)
   496  	if err != nil {
   497  		t.Fatalf("failed creating fundingManager: %v", err)
   498  	}
   499  	if err = f.Start(); err != nil {
   500  		t.Fatalf("failed starting fundingManager: %v", err)
   501  	}
   502  
   503  	testNode := &testNode{
   504  		privKey:         privKey,
   505  		msgChan:         sentMessages,
   506  		newChannels:     make(chan *newChannelMsg),
   507  		announceChan:    sentAnnouncements,
   508  		publTxChan:      publTxChan,
   509  		fundingMgr:      f,
   510  		mockNotifier:    chainNotifier,
   511  		mockChanEvent:   evt,
   512  		testDir:         tempTestDir,
   513  		shutdownChannel: shutdownChan,
   514  		addr:            addr,
   515  	}
   516  
   517  	f.cfg.NotifyWhenOnline = func(peer [33]byte,
   518  		connectedChan chan<- lnpeer.Peer) {
   519  
   520  		connectedChan <- testNode.remotePeer
   521  	}
   522  
   523  	return testNode, nil
   524  }
   525  
   526  func recreateAliceFundingManager(t *testing.T, alice *testNode) {
   527  	// Stop the old fundingManager before creating a new one.
   528  	close(alice.shutdownChannel)
   529  	if err := alice.fundingMgr.Stop(); err != nil {
   530  		t.Fatalf("failed stop funding manager: %v", err)
   531  	}
   532  
   533  	aliceMsgChan := make(chan lnwire.Message)
   534  	aliceAnnounceChan := make(chan lnwire.Message)
   535  	shutdownChan := make(chan struct{})
   536  	publishChan := make(chan *wire.MsgTx, 10)
   537  
   538  	oldCfg := alice.fundingMgr.cfg
   539  
   540  	chainedAcceptor := chanacceptor.NewChainedAcceptor()
   541  
   542  	f, err := NewFundingManager(Config{
   543  		IDKey:        oldCfg.IDKey,
   544  		IDKeyLoc:     oldCfg.IDKeyLoc,
   545  		Wallet:       oldCfg.Wallet,
   546  		Notifier:     oldCfg.Notifier,
   547  		FeeEstimator: oldCfg.FeeEstimator,
   548  		SignMessage: func(_ keychain.KeyLocator,
   549  			_ []byte, _ bool) (*ecdsa.Signature, error) {
   550  
   551  			return testSig, nil
   552  		},
   553  		SendAnnouncement: func(msg lnwire.Message,
   554  			_ ...discovery.OptionalMsgField) chan error {
   555  
   556  			errChan := make(chan error, 1)
   557  			select {
   558  			case aliceAnnounceChan <- msg:
   559  				errChan <- nil
   560  			case <-shutdownChan:
   561  				errChan <- fmt.Errorf("shutting down")
   562  			}
   563  			return errChan
   564  		},
   565  		CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement, error) {
   566  			return lnwire.NodeAnnouncement{}, nil
   567  		},
   568  		NotifyWhenOnline: func(peer [33]byte,
   569  			connectedChan chan<- lnpeer.Peer) {
   570  
   571  			connectedChan <- alice.remotePeer
   572  		},
   573  		TempChanIDSeed: oldCfg.TempChanIDSeed,
   574  		FindChannel:    oldCfg.FindChannel,
   575  		DefaultRoutingPolicy: htlcswitch.ForwardingPolicy{
   576  			MinHTLCOut:    5,
   577  			BaseFee:       100,
   578  			FeeRate:       1000,
   579  			TimeLockDelta: 10,
   580  		},
   581  		DefaultMinHtlcIn:       5,
   582  		RequiredRemoteMaxValue: oldCfg.RequiredRemoteMaxValue,
   583  		PublishTransaction: func(txn *wire.MsgTx, _ string) error {
   584  			publishChan <- txn
   585  			return nil
   586  		},
   587  		UpdateLabel: func(chainhash.Hash, string) error {
   588  			return nil
   589  		},
   590  		ZombieSweeperInterval: oldCfg.ZombieSweeperInterval,
   591  		ReservationTimeout:    oldCfg.ReservationTimeout,
   592  		OpenChannelPredicate:  chainedAcceptor,
   593  	})
   594  	if err != nil {
   595  		t.Fatalf("failed recreating aliceFundingManager: %v", err)
   596  	}
   597  
   598  	alice.fundingMgr = f
   599  	alice.msgChan = aliceMsgChan
   600  	alice.announceChan = aliceAnnounceChan
   601  	alice.publTxChan = publishChan
   602  	alice.shutdownChannel = shutdownChan
   603  
   604  	if err = f.Start(); err != nil {
   605  		t.Fatalf("failed starting fundingManager: %v", err)
   606  	}
   607  }
   608  
   609  type cfgOption func(*Config)
   610  
   611  func setupFundingManagers(t *testing.T,
   612  	options ...cfgOption) (*testNode, *testNode) {
   613  
   614  	aliceTestDir, err := ioutil.TempDir("", "alicelnwallet")
   615  	if err != nil {
   616  		t.Fatalf("unable to create temp directory: %v", err)
   617  	}
   618  
   619  	alice, err := createTestFundingManager(
   620  		t, alicePrivKey, aliceAddr, aliceTestDir, options...,
   621  	)
   622  	if err != nil {
   623  		t.Fatalf("failed creating fundingManager: %v", err)
   624  	}
   625  
   626  	bobTestDir, err := ioutil.TempDir("", "boblnwallet")
   627  	if err != nil {
   628  		t.Fatalf("unable to create temp directory: %v", err)
   629  	}
   630  
   631  	bob, err := createTestFundingManager(
   632  		t, bobPrivKey, bobAddr, bobTestDir, options...,
   633  	)
   634  	if err != nil {
   635  		t.Fatalf("failed creating fundingManager: %v", err)
   636  	}
   637  
   638  	// With the funding manager's created, we'll now attempt to mimic a
   639  	// connection pipe between them. In order to intercept the messages
   640  	// within it, we'll redirect all messages back to the msgChan of the
   641  	// sender. Since the fundingManager now has a reference to peers itself,
   642  	// alice.sendMessage will be triggered when Bob's funding manager
   643  	// attempts to send a message to Alice and vice versa.
   644  	alice.remotePeer = bob
   645  	alice.sendMessage = func(msg lnwire.Message) error {
   646  		select {
   647  		case alice.remotePeer.msgChan <- msg:
   648  		case <-alice.shutdownChannel:
   649  			return errors.New("shutting down")
   650  		}
   651  		return nil
   652  	}
   653  
   654  	bob.remotePeer = alice
   655  	bob.sendMessage = func(msg lnwire.Message) error {
   656  		select {
   657  		case bob.remotePeer.msgChan <- msg:
   658  		case <-bob.shutdownChannel:
   659  			return errors.New("shutting down")
   660  		}
   661  		return nil
   662  	}
   663  
   664  	return alice, bob
   665  }
   666  
   667  func tearDownFundingManagers(t *testing.T, a, b *testNode) {
   668  	close(a.shutdownChannel)
   669  	close(b.shutdownChannel)
   670  
   671  	if err := a.fundingMgr.Stop(); err != nil {
   672  		t.Fatalf("failed stop funding manager: %v", err)
   673  	}
   674  	if err := b.fundingMgr.Stop(); err != nil {
   675  		t.Fatalf("failed stop funding manager: %v", err)
   676  	}
   677  	os.RemoveAll(a.testDir)
   678  	os.RemoveAll(b.testDir)
   679  }
   680  
   681  // openChannel takes the funding process to the point where the funding
   682  // transaction is confirmed on-chain. Returns the funding out point.
   683  func openChannel(t *testing.T, alice, bob *testNode, localFundingAmt,
   684  	pushAmt dcrutil.Amount, numConfs uint32,
   685  	updateChan chan *lnrpc.OpenStatusUpdate, announceChan bool) (
   686  	*wire.OutPoint, *wire.MsgTx) {
   687  
   688  	publ := fundChannel(
   689  		t, alice, bob, localFundingAmt, pushAmt, false, numConfs,
   690  		updateChan, announceChan,
   691  	)
   692  	fundingOutPoint := &wire.OutPoint{
   693  		Hash:  publ.TxHash(),
   694  		Index: 0,
   695  	}
   696  	return fundingOutPoint, publ
   697  }
   698  
   699  // fundChannel takes the funding process to the point where the funding
   700  // transaction is confirmed on-chain. Returns the funding tx.
   701  func fundChannel(t *testing.T, alice, bob *testNode, localFundingAmt,
   702  	pushAmt dcrutil.Amount, subtractFees bool, numConfs uint32,
   703  	updateChan chan *lnrpc.OpenStatusUpdate, announceChan bool) *wire.MsgTx {
   704  
   705  	// Create a funding request and start the workflow.
   706  	errChan := make(chan error, 1)
   707  	initReq := &InitFundingMsg{
   708  		Peer:            bob,
   709  		TargetPubkey:    bob.privKey.PubKey(),
   710  		ChainHash:       fundingNetParams.GenesisHash,
   711  		SubtractFees:    subtractFees,
   712  		LocalFundingAmt: localFundingAmt,
   713  		PushAmt:         lnwire.NewMAtomsFromAtoms(pushAmt),
   714  		FundingFeePerKB: 1000,
   715  		Private:         !announceChan,
   716  		Updates:         updateChan,
   717  		Err:             errChan,
   718  	}
   719  
   720  	alice.fundingMgr.InitFundingWorkflow(initReq)
   721  
   722  	// Alice should have sent the OpenChannel message to Bob.
   723  	var aliceMsg lnwire.Message
   724  	select {
   725  	case aliceMsg = <-alice.msgChan:
   726  	case err := <-initReq.Err:
   727  		t.Fatalf("error init funding workflow: %v", err)
   728  	case <-time.After(time.Second * 5):
   729  		t.Fatalf("alice did not send OpenChannel message")
   730  	}
   731  
   732  	openChannelReq, ok := aliceMsg.(*lnwire.OpenChannel)
   733  	if !ok {
   734  		errorMsg, gotError := aliceMsg.(*lnwire.Error)
   735  		if gotError {
   736  			t.Fatalf("expected OpenChannel to be sent "+
   737  				"from bob, instead got error: %v",
   738  				errorMsg.Error())
   739  		}
   740  		t.Fatalf("expected OpenChannel to be sent from "+
   741  			"alice, instead got %T", aliceMsg)
   742  	}
   743  
   744  	// Let Bob handle the init message.
   745  	bob.fundingMgr.ProcessFundingMsg(openChannelReq, alice)
   746  
   747  	// Bob should answer with an AcceptChannel message.
   748  	acceptChannelResponse := assertFundingMsgSent(
   749  		t, bob.msgChan, "AcceptChannel",
   750  	).(*lnwire.AcceptChannel)
   751  
   752  	// They now should both have pending reservations for this channel
   753  	// active.
   754  	assertNumPendingReservations(t, alice, bobPubKey, 1)
   755  	assertNumPendingReservations(t, bob, alicePubKey, 1)
   756  
   757  	// Forward the response to Alice.
   758  	alice.fundingMgr.ProcessFundingMsg(acceptChannelResponse, bob)
   759  
   760  	// Alice responds with a FundingCreated message.
   761  	fundingCreated := assertFundingMsgSent(
   762  		t, alice.msgChan, "FundingCreated",
   763  	).(*lnwire.FundingCreated)
   764  
   765  	// Give the message to Bob.
   766  	bob.fundingMgr.ProcessFundingMsg(fundingCreated, alice)
   767  
   768  	// Finally, Bob should send the FundingSigned message.
   769  	fundingSigned := assertFundingMsgSent(
   770  		t, bob.msgChan, "FundingSigned",
   771  	).(*lnwire.FundingSigned)
   772  
   773  	// Forward the signature to Alice.
   774  	alice.fundingMgr.ProcessFundingMsg(fundingSigned, bob)
   775  
   776  	// After Alice processes the singleFundingSignComplete message, she will
   777  	// broadcast the funding transaction to the network. We expect to get a
   778  	// channel update saying the channel is pending.
   779  	var pendingUpdate *lnrpc.OpenStatusUpdate
   780  	select {
   781  	case pendingUpdate = <-updateChan:
   782  	case <-time.After(time.Second * 5):
   783  		t.Fatalf("alice did not send OpenStatusUpdate_ChanPending")
   784  	}
   785  
   786  	_, ok = pendingUpdate.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
   787  	if !ok {
   788  		t.Fatal("OpenStatusUpdate was not OpenStatusUpdate_ChanPending")
   789  	}
   790  
   791  	// Get and return the transaction Alice published to the network.
   792  	var publ *wire.MsgTx
   793  	select {
   794  	case publ = <-alice.publTxChan:
   795  	case <-time.After(time.Second * 5):
   796  		t.Fatalf("alice did not publish funding tx")
   797  	}
   798  
   799  	// Make sure the notification about the pending channel was sent out.
   800  	select {
   801  	case <-alice.mockChanEvent.pendingOpenEvent:
   802  	case <-time.After(time.Second * 5):
   803  		t.Fatalf("alice did not send pending channel event")
   804  	}
   805  	select {
   806  	case <-bob.mockChanEvent.pendingOpenEvent:
   807  	case <-time.After(time.Second * 5):
   808  		t.Fatalf("bob did not send pending channel event")
   809  	}
   810  
   811  	// Finally, make sure neither have active reservation for the channel
   812  	// now pending open in the database.
   813  	assertNumPendingReservations(t, alice, bobPubKey, 0)
   814  	assertNumPendingReservations(t, bob, alicePubKey, 0)
   815  
   816  	return publ
   817  }
   818  
   819  func assertErrorNotSent(t *testing.T, msgChan chan lnwire.Message) {
   820  	t.Helper()
   821  
   822  	select {
   823  	case <-msgChan:
   824  		t.Fatalf("error sent unexpectedly")
   825  	case <-time.After(100 * time.Millisecond):
   826  		// Expected, return.
   827  	}
   828  }
   829  
   830  func assertErrorSent(t *testing.T, msgChan chan lnwire.Message) {
   831  	t.Helper()
   832  
   833  	var msg lnwire.Message
   834  	select {
   835  	case msg = <-msgChan:
   836  	case <-time.After(time.Second * 5):
   837  		t.Fatalf("node did not send Error message")
   838  	}
   839  	_, ok := msg.(*lnwire.Error)
   840  	if !ok {
   841  		t.Fatalf("expected Error to be sent from "+
   842  			"node, instead got %T", msg)
   843  	}
   844  }
   845  
   846  func assertFundingMsgSent(t *testing.T, msgChan chan lnwire.Message,
   847  	msgType string) lnwire.Message {
   848  	t.Helper()
   849  
   850  	var msg lnwire.Message
   851  	select {
   852  	case msg = <-msgChan:
   853  	case <-time.After(time.Second * 5):
   854  		t.Fatalf("peer did not send %s message", msgType)
   855  	}
   856  
   857  	var (
   858  		sentMsg lnwire.Message
   859  		ok      bool
   860  	)
   861  	switch msgType {
   862  	case "AcceptChannel":
   863  		sentMsg, ok = msg.(*lnwire.AcceptChannel)
   864  	case "FundingCreated":
   865  		sentMsg, ok = msg.(*lnwire.FundingCreated)
   866  	case "FundingSigned":
   867  		sentMsg, ok = msg.(*lnwire.FundingSigned)
   868  	case "FundingLocked":
   869  		sentMsg, ok = msg.(*lnwire.FundingLocked)
   870  	case "Error":
   871  		sentMsg, ok = msg.(*lnwire.Error)
   872  	default:
   873  		t.Fatalf("unknown message type: %s", msgType)
   874  	}
   875  
   876  	if !ok {
   877  		errorMsg, gotError := msg.(*lnwire.Error)
   878  		if gotError {
   879  			t.Fatalf("expected %s to be sent, instead got error: %v",
   880  				msgType, errorMsg.Error())
   881  		}
   882  
   883  		_, _, line, _ := runtime.Caller(1)
   884  		t.Fatalf("expected %s to be sent, instead got %T at %v",
   885  			msgType, msg, line)
   886  	}
   887  
   888  	return sentMsg
   889  }
   890  
   891  func assertNumPendingReservations(t *testing.T, node *testNode,
   892  	peerPubKey *secp256k1.PublicKey, expectedNum int) {
   893  	t.Helper()
   894  
   895  	serializedPubKey := newSerializedKey(peerPubKey)
   896  	actualNum := len(node.fundingMgr.activeReservations[serializedPubKey])
   897  	if actualNum == expectedNum {
   898  		// Success, return.
   899  		return
   900  	}
   901  
   902  	t.Fatalf("Expected node to have %d pending reservations, had %v",
   903  		expectedNum, actualNum)
   904  }
   905  
   906  func assertNumPendingChannelsBecomes(t *testing.T, node *testNode, expectedNum int) {
   907  	t.Helper()
   908  
   909  	var numPendingChans int
   910  	for i := 0; i < testPollNumTries; i++ {
   911  		// If this is not the first try, sleep before retrying.
   912  		if i > 0 {
   913  			time.Sleep(testPollSleepMs * time.Millisecond)
   914  		}
   915  		pendingChannels, err := node.fundingMgr.
   916  			cfg.Wallet.Cfg.Database.FetchPendingChannels()
   917  		if err != nil {
   918  			t.Fatalf("unable to fetch pending channels: %v", err)
   919  		}
   920  
   921  		numPendingChans = len(pendingChannels)
   922  		if numPendingChans == expectedNum {
   923  			// Success, return.
   924  			return
   925  		}
   926  	}
   927  
   928  	t.Fatalf("Expected node to have %d pending channels, had %v",
   929  		expectedNum, numPendingChans)
   930  }
   931  
   932  func assertNumPendingChannelsRemains(t *testing.T, node *testNode, expectedNum int) {
   933  	t.Helper()
   934  
   935  	var numPendingChans int
   936  	for i := 0; i < 5; i++ {
   937  		// If this is not the first try, sleep before retrying.
   938  		if i > 0 {
   939  			time.Sleep(200 * time.Millisecond)
   940  		}
   941  		pendingChannels, err := node.fundingMgr.
   942  			cfg.Wallet.Cfg.Database.FetchPendingChannels()
   943  		if err != nil {
   944  			t.Fatalf("unable to fetch pending channels: %v", err)
   945  		}
   946  
   947  		numPendingChans = len(pendingChannels)
   948  		if numPendingChans != expectedNum {
   949  
   950  			t.Fatalf("Expected node to have %d pending channels, had %v",
   951  				expectedNum, numPendingChans)
   952  		}
   953  	}
   954  }
   955  
   956  func assertDatabaseState(t *testing.T, node *testNode,
   957  	fundingOutPoint *wire.OutPoint, expectedState channelOpeningState) {
   958  	t.Helper()
   959  
   960  	var state channelOpeningState
   961  	var err error
   962  	for i := 0; i < testPollNumTries; i++ {
   963  		// If this is not the first try, sleep before retrying.
   964  		if i > 0 {
   965  			time.Sleep(testPollSleepMs * time.Millisecond)
   966  		}
   967  		state, _, err = node.fundingMgr.getChannelOpeningState(
   968  			fundingOutPoint)
   969  		if err != nil && err != channeldb.ErrChannelNotFound {
   970  			t.Fatalf("unable to get channel state: %v", err)
   971  		}
   972  
   973  		// If we found the channel, check if it had the expected state.
   974  		if err != channeldb.ErrChannelNotFound && state == expectedState {
   975  			// Got expected state, return with success.
   976  			return
   977  		}
   978  	}
   979  
   980  	// 10 tries without success.
   981  	if err != nil {
   982  		t.Fatalf("error getting channelOpeningState: %v", err)
   983  	} else {
   984  		t.Fatalf("expected state to be %v, was %v", expectedState,
   985  			state)
   986  	}
   987  }
   988  
   989  func assertMarkedOpen(t *testing.T, alice, bob *testNode,
   990  	fundingOutPoint *wire.OutPoint) {
   991  	t.Helper()
   992  
   993  	// Make sure the notification about the pending channel was sent out.
   994  	select {
   995  	case <-alice.mockChanEvent.openEvent:
   996  	case <-time.After(time.Second * 5):
   997  		t.Fatalf("alice did not send open channel event")
   998  	}
   999  	select {
  1000  	case <-bob.mockChanEvent.openEvent:
  1001  	case <-time.After(time.Second * 5):
  1002  		t.Fatalf("bob did not send open channel event")
  1003  	}
  1004  
  1005  	assertDatabaseState(t, alice, fundingOutPoint, markedOpen)
  1006  	assertDatabaseState(t, bob, fundingOutPoint, markedOpen)
  1007  }
  1008  
  1009  func assertFundingLockedSent(t *testing.T, alice, bob *testNode,
  1010  	fundingOutPoint *wire.OutPoint) {
  1011  	t.Helper()
  1012  
  1013  	assertDatabaseState(t, alice, fundingOutPoint, fundingLockedSent)
  1014  	assertDatabaseState(t, bob, fundingOutPoint, fundingLockedSent)
  1015  }
  1016  
  1017  func assertAddedToRouterGraph(t *testing.T, alice, bob *testNode,
  1018  	fundingOutPoint *wire.OutPoint) {
  1019  	t.Helper()
  1020  
  1021  	assertDatabaseState(t, alice, fundingOutPoint, addedToRouterGraph)
  1022  	assertDatabaseState(t, bob, fundingOutPoint, addedToRouterGraph)
  1023  }
  1024  
  1025  // assertChannelAnnouncements checks that alice and bob both sends the expected
  1026  // announcements (ChannelAnnouncement, ChannelUpdate) after the funding tx has
  1027  // confirmed. The last arguments can be set if we expect the nodes to advertise
  1028  // custom min_htlc values as part of their ChannelUpdate. We expect Alice to
  1029  // advertise the value required by Bob and vice versa. If they are not set the
  1030  // advertised value will be checked against the other node's default min_htlc
  1031  // value.
  1032  func assertChannelAnnouncements(t *testing.T, alice, bob *testNode,
  1033  	capacity dcrutil.Amount, customMinHtlc []lnwire.MilliAtom,
  1034  	customMaxHtlc []lnwire.MilliAtom) {
  1035  	t.Helper()
  1036  
  1037  	// After the FundingLocked message is sent, Alice and Bob will each
  1038  	// send the following messages to their gossiper:
  1039  	//	1) ChannelAnnouncement
  1040  	//	2) ChannelUpdate
  1041  	// The ChannelAnnouncement is kept locally, while the ChannelUpdate
  1042  	// is sent directly to the other peer, so the edge policies are
  1043  	// known to both peers.
  1044  	nodes := []*testNode{alice, bob}
  1045  	for j, node := range nodes {
  1046  		announcements := make([]lnwire.Message, 2)
  1047  		for i := 0; i < len(announcements); i++ {
  1048  			select {
  1049  			case announcements[i] = <-node.announceChan:
  1050  			case <-time.After(time.Second * 5):
  1051  				t.Fatalf("node did not send announcement: %v", i)
  1052  			}
  1053  		}
  1054  
  1055  		gotChannelAnnouncement := false
  1056  		gotChannelUpdate := false
  1057  		for _, msg := range announcements {
  1058  			switch m := msg.(type) {
  1059  			case *lnwire.ChannelAnnouncement:
  1060  				gotChannelAnnouncement = true
  1061  			case *lnwire.ChannelUpdate:
  1062  
  1063  				// The channel update sent by the node should
  1064  				// advertise the MinHTLC value required by the
  1065  				// _other_ node.
  1066  				other := (j + 1) % 2
  1067  				minHtlc := nodes[other].fundingMgr.cfg.
  1068  					DefaultMinHtlcIn
  1069  
  1070  				// We might expect a custom MinHTLC value.
  1071  				if len(customMinHtlc) > 0 {
  1072  					if len(customMinHtlc) != 2 {
  1073  						t.Fatalf("only 0 or 2 custom " +
  1074  							"min htlc values " +
  1075  							"currently supported")
  1076  					}
  1077  
  1078  					minHtlc = customMinHtlc[j]
  1079  				}
  1080  
  1081  				if m.HtlcMinimumMAtoms != minHtlc {
  1082  					t.Fatalf("expected ChannelUpdate to "+
  1083  						"advertise min HTLC %v, had %v",
  1084  						minHtlc, m.HtlcMinimumMAtoms)
  1085  				}
  1086  
  1087  				maxHtlc := alice.fundingMgr.cfg.RequiredRemoteMaxValue(
  1088  					capacity,
  1089  				)
  1090  				// We might expect a custom MaxHltc value.
  1091  				if len(customMaxHtlc) > 0 {
  1092  					if len(customMaxHtlc) != 2 {
  1093  						t.Fatalf("only 0 or 2 custom " +
  1094  							"min htlc values " +
  1095  							"currently supported")
  1096  					}
  1097  
  1098  					maxHtlc = customMaxHtlc[j]
  1099  				}
  1100  				if m.MessageFlags != 1 {
  1101  					t.Fatalf("expected message flags to "+
  1102  						"be 1, was %v", m.MessageFlags)
  1103  				}
  1104  
  1105  				if maxHtlc != m.HtlcMaximumMAtoms {
  1106  					t.Fatalf("expected ChannelUpdate to "+
  1107  						"advertise max HTLC %v, had %v",
  1108  						maxHtlc,
  1109  						m.HtlcMaximumMAtoms)
  1110  				}
  1111  
  1112  				gotChannelUpdate = true
  1113  			}
  1114  		}
  1115  
  1116  		if !gotChannelAnnouncement {
  1117  			t.Fatalf("did not get ChannelAnnouncement from node %d",
  1118  				j)
  1119  		}
  1120  		if !gotChannelUpdate {
  1121  			t.Fatalf("did not get ChannelUpdate from node %d", j)
  1122  		}
  1123  
  1124  		// Make sure no other message is sent.
  1125  		select {
  1126  		case <-node.announceChan:
  1127  			t.Fatalf("received unexpected announcement")
  1128  		case <-time.After(300 * time.Millisecond):
  1129  			// Expected
  1130  		}
  1131  	}
  1132  }
  1133  
  1134  func assertAnnouncementSignatures(t *testing.T, alice, bob *testNode) {
  1135  	t.Helper()
  1136  
  1137  	// After the FundingLocked message is sent and six confirmations have
  1138  	// been reached, the channel will be announced to the greater network
  1139  	// by having the nodes exchange announcement signatures.
  1140  	// Two distinct messages will be sent:
  1141  	//	1) AnnouncementSignatures
  1142  	//	2) NodeAnnouncement
  1143  	// These may arrive in no particular order.
  1144  	// Note that sending the NodeAnnouncement at this point is an
  1145  	// implementation detail, and not something required by the LN spec.
  1146  	for j, node := range []*testNode{alice, bob} {
  1147  		announcements := make([]lnwire.Message, 2)
  1148  		for i := 0; i < len(announcements); i++ {
  1149  			select {
  1150  			case announcements[i] = <-node.announceChan:
  1151  			case <-time.After(time.Second * 5):
  1152  				t.Fatalf("node did not send announcement %v", i)
  1153  			}
  1154  		}
  1155  
  1156  		gotAnnounceSignatures := false
  1157  		gotNodeAnnouncement := false
  1158  		for _, msg := range announcements {
  1159  			switch msg.(type) {
  1160  			case *lnwire.AnnounceSignatures:
  1161  				gotAnnounceSignatures = true
  1162  			case *lnwire.NodeAnnouncement:
  1163  				gotNodeAnnouncement = true
  1164  			}
  1165  		}
  1166  
  1167  		if !gotAnnounceSignatures {
  1168  			t.Fatalf("did not get AnnounceSignatures from node %d",
  1169  				j)
  1170  		}
  1171  		if !gotNodeAnnouncement {
  1172  			t.Fatalf("did not get NodeAnnouncement from node %d", j)
  1173  		}
  1174  	}
  1175  }
  1176  
  1177  func waitForOpenUpdate(t *testing.T, updateChan chan *lnrpc.OpenStatusUpdate) {
  1178  	var openUpdate *lnrpc.OpenStatusUpdate
  1179  	select {
  1180  	case openUpdate = <-updateChan:
  1181  	case <-time.After(time.Second * 5):
  1182  		t.Fatalf("alice did not send OpenStatusUpdate")
  1183  	}
  1184  
  1185  	_, ok := openUpdate.Update.(*lnrpc.OpenStatusUpdate_ChanOpen)
  1186  	if !ok {
  1187  		t.Fatal("OpenStatusUpdate was not OpenStatusUpdate_ChanOpen")
  1188  	}
  1189  }
  1190  
  1191  func assertNoChannelState(t *testing.T, alice, bob *testNode,
  1192  	fundingOutPoint *wire.OutPoint) {
  1193  	t.Helper()
  1194  
  1195  	assertErrChannelNotFound(t, alice, fundingOutPoint)
  1196  	assertErrChannelNotFound(t, bob, fundingOutPoint)
  1197  }
  1198  
  1199  func assertErrChannelNotFound(t *testing.T, node *testNode,
  1200  	fundingOutPoint *wire.OutPoint) {
  1201  	t.Helper()
  1202  
  1203  	var state channelOpeningState
  1204  	var err error
  1205  	for i := 0; i < testPollNumTries; i++ {
  1206  		// If this is not the first try, sleep before retrying.
  1207  		if i > 0 {
  1208  			time.Sleep(testPollSleepMs * time.Millisecond)
  1209  		}
  1210  		state, _, err = node.fundingMgr.getChannelOpeningState(
  1211  			fundingOutPoint)
  1212  		if err == channeldb.ErrChannelNotFound {
  1213  			// Got expected state, return with success.
  1214  			return
  1215  		} else if err != nil {
  1216  			t.Fatalf("unable to get channel state: %v", err)
  1217  		}
  1218  	}
  1219  
  1220  	// 10 tries without success.
  1221  	t.Fatalf("expected to not find state, found state %v", state)
  1222  }
  1223  
  1224  func assertHandleFundingLocked(t *testing.T, alice, bob *testNode) {
  1225  	t.Helper()
  1226  
  1227  	// They should both send the new channel state to their peer.
  1228  	select {
  1229  	case c := <-alice.newChannels:
  1230  		close(c.err)
  1231  	case <-time.After(time.Second * 15):
  1232  		t.Fatalf("alice did not send new channel to peer")
  1233  	}
  1234  
  1235  	select {
  1236  	case c := <-bob.newChannels:
  1237  		close(c.err)
  1238  	case <-time.After(time.Second * 15):
  1239  		t.Fatalf("bob did not send new channel to peer")
  1240  	}
  1241  }
  1242  
  1243  func TestFundingManagerNormalWorkflow(t *testing.T) {
  1244  	t.Parallel()
  1245  
  1246  	alice, bob := setupFundingManagers(t)
  1247  	defer tearDownFundingManagers(t, alice, bob)
  1248  
  1249  	// We will consume the channel updates as we go, so no buffering is needed.
  1250  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  1251  
  1252  	// Run through the process of opening the channel, up until the funding
  1253  	// transaction is broadcasted.
  1254  	localAmt := dcrutil.Amount(500000)
  1255  	pushAmt := dcrutil.Amount(0)
  1256  	capacity := localAmt + pushAmt
  1257  	fundingOutPoint, fundingTx := openChannel(
  1258  		t, alice, bob, localAmt, pushAmt, 1, updateChan, true,
  1259  	)
  1260  
  1261  	// Check that neither Alice nor Bob sent an error message.
  1262  	assertErrorNotSent(t, alice.msgChan)
  1263  	assertErrorNotSent(t, bob.msgChan)
  1264  
  1265  	// Notify that transaction was mined.
  1266  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  1267  		Tx: fundingTx,
  1268  	}
  1269  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  1270  		Tx: fundingTx,
  1271  	}
  1272  
  1273  	// The funding transaction was mined, so assert that both funding
  1274  	// managers now have the state of this channel 'markedOpen' in their
  1275  	// internal state machine.
  1276  	assertMarkedOpen(t, alice, bob, fundingOutPoint)
  1277  
  1278  	// After the funding transaction is mined, Alice will send
  1279  	// fundingLocked to Bob.
  1280  	fundingLockedAlice := assertFundingMsgSent(
  1281  		t, alice.msgChan, "FundingLocked",
  1282  	).(*lnwire.FundingLocked)
  1283  
  1284  	// And similarly Bob will send funding locked to Alice.
  1285  	fundingLockedBob := assertFundingMsgSent(
  1286  		t, bob.msgChan, "FundingLocked",
  1287  	).(*lnwire.FundingLocked)
  1288  
  1289  	// Check that the state machine is updated accordingly
  1290  	assertFundingLockedSent(t, alice, bob, fundingOutPoint)
  1291  
  1292  	// Make sure both fundingManagers send the expected channel
  1293  	// announcements.
  1294  	assertChannelAnnouncements(t, alice, bob, capacity, nil, nil)
  1295  
  1296  	// Check that the state machine is updated accordingly
  1297  	assertAddedToRouterGraph(t, alice, bob, fundingOutPoint)
  1298  
  1299  	// The funding transaction is now confirmed, wait for the
  1300  	// OpenStatusUpdate_ChanOpen update
  1301  	waitForOpenUpdate(t, updateChan)
  1302  
  1303  	// Exchange the fundingLocked messages.
  1304  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  1305  	bob.fundingMgr.ProcessFundingMsg(fundingLockedAlice, alice)
  1306  
  1307  	// Check that they notify the breach arbiter and peer about the new
  1308  	// channel.
  1309  	assertHandleFundingLocked(t, alice, bob)
  1310  
  1311  	// Notify that six confirmations has been reached on funding transaction.
  1312  	alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  1313  		Tx: fundingTx,
  1314  	}
  1315  	bob.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  1316  		Tx: fundingTx,
  1317  	}
  1318  
  1319  	// Make sure the fundingManagers exchange announcement signatures.
  1320  	assertAnnouncementSignatures(t, alice, bob)
  1321  
  1322  	// The internal state-machine should now have deleted the channelStates
  1323  	// from the database, as the channel is announced.
  1324  	assertNoChannelState(t, alice, bob, fundingOutPoint)
  1325  }
  1326  
  1327  // TestFundingManagerRejectCSV tests checking of local CSV values against our
  1328  // local CSV limit for incoming and outgoing channels.
  1329  func TestFundingManagerRejectCSV(t *testing.T) {
  1330  	t.Run("csv too high", func(t *testing.T) {
  1331  		testLocalCSVLimit(t, 400, 500)
  1332  	})
  1333  	t.Run("csv within limit", func(t *testing.T) {
  1334  		testLocalCSVLimit(t, 600, 500)
  1335  	})
  1336  }
  1337  
  1338  // testLocalCSVLimit creates two funding managers, alice and bob, where alice
  1339  // has a limit on her maximum local CSV and bob sets his required CSV for alice.
  1340  // We test an incoming and outgoing channel, ensuring that alice accepts csvs
  1341  // below her maximum, and rejects those above it.
  1342  func testLocalCSVLimit(t *testing.T, aliceMaxCSV, bobRequiredCSV uint16) {
  1343  	t.Parallel()
  1344  
  1345  	alice, bob := setupFundingManagers(t)
  1346  	defer tearDownFundingManagers(t, alice, bob)
  1347  
  1348  	// Set a maximum local delay in alice's config to aliceMaxCSV and overwrite
  1349  	// bob's required remote delay function to return bobRequiredCSV.
  1350  	alice.fundingMgr.cfg.MaxLocalCSVDelay = aliceMaxCSV
  1351  	bob.fundingMgr.cfg.RequiredRemoteDelay = func(_ dcrutil.Amount) uint16 {
  1352  		return bobRequiredCSV
  1353  	}
  1354  
  1355  	// For convenience, we bump our max pending channels to 2 so that we
  1356  	// can test incoming and outgoing channels without needing to step
  1357  	// through the full funding process.
  1358  	alice.fundingMgr.cfg.MaxPendingChannels = 2
  1359  	bob.fundingMgr.cfg.MaxPendingChannels = 2
  1360  
  1361  	// If our maximum is less than the value bob sets, we expect this test
  1362  	// to fail.
  1363  	expectFail := aliceMaxCSV < bobRequiredCSV
  1364  
  1365  	// First, we will initiate an outgoing channel from Alice -> Bob.
  1366  	errChan := make(chan error, 1)
  1367  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  1368  	initReq := &InitFundingMsg{
  1369  		Peer:            bob,
  1370  		TargetPubkey:    bob.privKey.PubKey(),
  1371  		ChainHash:       fundingNetParams.GenesisHash,
  1372  		LocalFundingAmt: 200000,
  1373  		FundingFeePerKB: 1000,
  1374  		Updates:         updateChan,
  1375  		Err:             errChan,
  1376  	}
  1377  
  1378  	// Alice should have sent the OpenChannel message to Bob.
  1379  	alice.fundingMgr.InitFundingWorkflow(initReq)
  1380  	var aliceMsg lnwire.Message
  1381  	select {
  1382  	case aliceMsg = <-alice.msgChan:
  1383  
  1384  	case err := <-initReq.Err:
  1385  		t.Fatalf("error init funding workflow: %v", err)
  1386  
  1387  	case <-time.After(time.Second * 5):
  1388  		t.Fatalf("alice did not send OpenChannel message")
  1389  	}
  1390  
  1391  	openChannelReq, ok := aliceMsg.(*lnwire.OpenChannel)
  1392  	require.True(t, ok)
  1393  
  1394  	// Let Bob handle the init message.
  1395  	bob.fundingMgr.ProcessFundingMsg(openChannelReq, alice)
  1396  
  1397  	// Bob should answer with an AcceptChannel message.
  1398  	acceptChannelResponse := assertFundingMsgSent(
  1399  		t, bob.msgChan, "AcceptChannel",
  1400  	).(*lnwire.AcceptChannel)
  1401  
  1402  	// They now should both have pending reservations for this channel
  1403  	// active.
  1404  	assertNumPendingReservations(t, alice, bobPubKey, 1)
  1405  	assertNumPendingReservations(t, bob, alicePubKey, 1)
  1406  
  1407  	// Forward the response to Alice.
  1408  	alice.fundingMgr.ProcessFundingMsg(acceptChannelResponse, bob)
  1409  
  1410  	// At this point, Alice has received an AcceptChannel message from
  1411  	// bob with the CSV value that he has set for her, and has to evaluate
  1412  	// whether she wants to accept this channel. If we get an error, we
  1413  	// assert that we expected the channel to fail, otherwise we assert that
  1414  	// she proceeded with the channel open as usual.
  1415  	select {
  1416  	case err := <-errChan:
  1417  		require.Error(t, err)
  1418  		require.True(t, expectFail)
  1419  
  1420  	case msg := <-alice.msgChan:
  1421  		_, ok := msg.(*lnwire.FundingCreated)
  1422  		require.True(t, ok)
  1423  		require.False(t, expectFail)
  1424  
  1425  	case <-time.After(time.Second):
  1426  		t.Fatal("funding flow was not failed")
  1427  	}
  1428  
  1429  	// We do not need to complete the rest of the funding flow (it is
  1430  	// covered in other tests). So now we test that Alice will appropriately
  1431  	// handle incoming channels, opening a channel from Bob->Alice.
  1432  	errChan = make(chan error, 1)
  1433  	updateChan = make(chan *lnrpc.OpenStatusUpdate)
  1434  	initReq = &InitFundingMsg{
  1435  		Peer:            alice,
  1436  		TargetPubkey:    alice.privKey.PubKey(),
  1437  		ChainHash:       fundingNetParams.GenesisHash,
  1438  		LocalFundingAmt: 200000,
  1439  		FundingFeePerKB: 1000,
  1440  		Updates:         updateChan,
  1441  		Err:             errChan,
  1442  	}
  1443  
  1444  	bob.fundingMgr.InitFundingWorkflow(initReq)
  1445  
  1446  	// Bob should have sent the OpenChannel message to Alice.
  1447  	var bobMsg lnwire.Message
  1448  	select {
  1449  	case bobMsg = <-bob.msgChan:
  1450  
  1451  	case err := <-initReq.Err:
  1452  		t.Fatalf("bob OpenChannel message failed: %v", err)
  1453  
  1454  	case <-time.After(time.Second * 5):
  1455  		t.Fatalf("bob did not send OpenChannel message")
  1456  	}
  1457  
  1458  	openChannelReq, ok = bobMsg.(*lnwire.OpenChannel)
  1459  	require.True(t, ok)
  1460  
  1461  	// Let Alice handle the init message.
  1462  	alice.fundingMgr.ProcessFundingMsg(openChannelReq, bob)
  1463  
  1464  	// We expect a error message from Alice if we're expecting the channel
  1465  	// to fail, otherwise we expect her to proceed with the channel as
  1466  	// usual.
  1467  	select {
  1468  	case msg := <-alice.msgChan:
  1469  		var ok bool
  1470  		if expectFail {
  1471  			_, ok = msg.(*lnwire.Error)
  1472  		} else {
  1473  			_, ok = msg.(*lnwire.AcceptChannel)
  1474  		}
  1475  		require.True(t, ok)
  1476  
  1477  	case <-time.After(time.Second * 5):
  1478  		t.Fatal("funding flow was not failed")
  1479  	}
  1480  }
  1481  
  1482  func TestFundingManagerRestartBehavior(t *testing.T) {
  1483  	t.Parallel()
  1484  
  1485  	alice, bob := setupFundingManagers(t)
  1486  	defer tearDownFundingManagers(t, alice, bob)
  1487  
  1488  	// Run through the process of opening the channel, up until the funding
  1489  	// transaction is broadcasted.
  1490  	localAmt := dcrutil.Amount(500000)
  1491  	pushAmt := dcrutil.Amount(0)
  1492  	capacity := localAmt + pushAmt
  1493  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  1494  	fundingOutPoint, fundingTx := openChannel(
  1495  		t, alice, bob, localAmt, pushAmt, 1, updateChan, true,
  1496  	)
  1497  
  1498  	// After the funding transaction gets mined, both nodes will send the
  1499  	// fundingLocked message to the other peer. If the funding node fails
  1500  	// before this message has been successfully sent, it should retry
  1501  	// sending it on restart. We mimic this behavior by letting the
  1502  	// SendToPeer method return an error, as if the message was not
  1503  	// successfully sent. We then recreate the fundingManager and make sure
  1504  	// it continues the process as expected. We'll save the current
  1505  	// implementation of sendMessage to restore the original behavior later
  1506  	// on.
  1507  	workingSendMessage := bob.sendMessage
  1508  	bob.sendMessage = func(msg lnwire.Message) error {
  1509  		return fmt.Errorf("intentional error in SendToPeer")
  1510  	}
  1511  	alice.fundingMgr.cfg.NotifyWhenOnline = func(peer [33]byte,
  1512  		con chan<- lnpeer.Peer) {
  1513  		// Intentionally empty.
  1514  	}
  1515  
  1516  	// Notify that transaction was mined
  1517  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  1518  		Tx: fundingTx,
  1519  	}
  1520  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  1521  		Tx: fundingTx,
  1522  	}
  1523  
  1524  	// The funding transaction was mined, so assert that both funding
  1525  	// managers now have the state of this channel 'markedOpen' in their
  1526  	// internal state machine.
  1527  	assertMarkedOpen(t, alice, bob, fundingOutPoint)
  1528  
  1529  	// After the funding transaction was mined, Bob should have successfully
  1530  	// sent the fundingLocked message, while Alice failed sending it. In
  1531  	// Alice's case this means that there should be no messages for Bob, and
  1532  	// the channel should still be in state 'markedOpen'
  1533  	select {
  1534  	case msg := <-alice.msgChan:
  1535  		t.Fatalf("did not expect any message from Alice: %v", msg)
  1536  	default:
  1537  		// Expected.
  1538  	}
  1539  
  1540  	// Bob will send funding locked to Alice.
  1541  	fundingLockedBob := assertFundingMsgSent(
  1542  		t, bob.msgChan, "FundingLocked",
  1543  	).(*lnwire.FundingLocked)
  1544  
  1545  	// Alice should still be markedOpen
  1546  	assertDatabaseState(t, alice, fundingOutPoint, markedOpen)
  1547  
  1548  	// While Bob successfully sent fundingLocked.
  1549  	assertDatabaseState(t, bob, fundingOutPoint, fundingLockedSent)
  1550  
  1551  	// We now recreate Alice's fundingManager with the correct sendMessage
  1552  	// implementation, and expect it to retry sending the fundingLocked
  1553  	// message. We'll explicitly shut down Alice's funding manager to
  1554  	// prevent a race when overriding the sendMessage implementation.
  1555  	if err := alice.fundingMgr.Stop(); err != nil {
  1556  		t.Fatalf("failed stop funding manager: %v", err)
  1557  	}
  1558  	bob.sendMessage = workingSendMessage
  1559  	recreateAliceFundingManager(t, alice)
  1560  
  1561  	// Intentionally make the channel announcements fail
  1562  	alice.fundingMgr.cfg.SendAnnouncement = func(msg lnwire.Message,
  1563  		_ ...discovery.OptionalMsgField) chan error {
  1564  
  1565  		errChan := make(chan error, 1)
  1566  		errChan <- fmt.Errorf("intentional error in SendAnnouncement")
  1567  		return errChan
  1568  	}
  1569  
  1570  	fundingLockedAlice := assertFundingMsgSent(
  1571  		t, alice.msgChan, "FundingLocked",
  1572  	).(*lnwire.FundingLocked)
  1573  
  1574  	// The state should now be fundingLockedSent
  1575  	assertDatabaseState(t, alice, fundingOutPoint, fundingLockedSent)
  1576  
  1577  	// Check that the channel announcements were never sent
  1578  	select {
  1579  	case ann := <-alice.announceChan:
  1580  		t.Fatalf("unexpectedly got channel announcement message: %v",
  1581  			ann)
  1582  	default:
  1583  		// Expected
  1584  	}
  1585  
  1586  	// Exchange the fundingLocked messages.
  1587  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  1588  	bob.fundingMgr.ProcessFundingMsg(fundingLockedAlice, alice)
  1589  
  1590  	// Check that they notify the breach arbiter and peer about the new
  1591  	// channel.
  1592  	assertHandleFundingLocked(t, alice, bob)
  1593  
  1594  	// Next up, we check that Alice rebroadcasts the announcement
  1595  	// messages on restart. Bob should as expected send announcements.
  1596  	recreateAliceFundingManager(t, alice)
  1597  	time.Sleep(300 * time.Millisecond)
  1598  
  1599  	// Make sure both fundingManagers send the expected channel
  1600  	// announcements.
  1601  	assertChannelAnnouncements(t, alice, bob, capacity, nil, nil)
  1602  
  1603  	// Check that the state machine is updated accordingly
  1604  	assertAddedToRouterGraph(t, alice, bob, fundingOutPoint)
  1605  
  1606  	// Next, we check that Alice sends the announcement signatures
  1607  	// on restart after six confirmations. Bob should as expected send
  1608  	// them as well.
  1609  	recreateAliceFundingManager(t, alice)
  1610  	time.Sleep(300 * time.Millisecond)
  1611  
  1612  	// Notify that six confirmations has been reached on funding transaction.
  1613  	alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  1614  		Tx: fundingTx,
  1615  	}
  1616  	bob.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  1617  		Tx: fundingTx,
  1618  	}
  1619  
  1620  	// Make sure the fundingManagers exchange announcement signatures.
  1621  	assertAnnouncementSignatures(t, alice, bob)
  1622  
  1623  	// The internal state-machine should now have deleted the channelStates
  1624  	// from the database, as the channel is announced.
  1625  	assertNoChannelState(t, alice, bob, fundingOutPoint)
  1626  }
  1627  
  1628  // TestFundingManagerOfflinePeer checks that the fundingManager waits for the
  1629  // server to notify when the peer comes online, in case sending the
  1630  // fundingLocked message fails the first time.
  1631  func TestFundingManagerOfflinePeer(t *testing.T) {
  1632  	t.Parallel()
  1633  
  1634  	alice, bob := setupFundingManagers(t)
  1635  	defer tearDownFundingManagers(t, alice, bob)
  1636  
  1637  	// Run through the process of opening the channel, up until the funding
  1638  	// transaction is broadcasted.
  1639  	localAmt := dcrutil.Amount(500000)
  1640  	pushAmt := dcrutil.Amount(0)
  1641  	capacity := localAmt + pushAmt
  1642  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  1643  	fundingOutPoint, fundingTx := openChannel(
  1644  		t, alice, bob, localAmt, pushAmt, 1, updateChan, true,
  1645  	)
  1646  
  1647  	// After the funding transaction gets mined, both nodes will send the
  1648  	// fundingLocked message to the other peer. If the funding node fails
  1649  	// to send the fundingLocked message to the peer, it should wait for
  1650  	// the server to notify it that the peer is back online, and try again.
  1651  	// We'll save the current implementation of sendMessage to restore the
  1652  	// original behavior later on.
  1653  	workingSendMessage := bob.sendMessage
  1654  	bob.sendMessage = func(msg lnwire.Message) error {
  1655  		return fmt.Errorf("intentional error in SendToPeer")
  1656  	}
  1657  	peerChan := make(chan [33]byte, 1)
  1658  	conChan := make(chan chan<- lnpeer.Peer, 1)
  1659  	alice.fundingMgr.cfg.NotifyWhenOnline = func(peer [33]byte,
  1660  		connected chan<- lnpeer.Peer) {
  1661  
  1662  		peerChan <- peer
  1663  		conChan <- connected
  1664  	}
  1665  
  1666  	// Notify that transaction was mined
  1667  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  1668  		Tx: fundingTx,
  1669  	}
  1670  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  1671  		Tx: fundingTx,
  1672  	}
  1673  
  1674  	// The funding transaction was mined, so assert that both funding
  1675  	// managers now have the state of this channel 'markedOpen' in their
  1676  	// internal state machine.
  1677  	assertMarkedOpen(t, alice, bob, fundingOutPoint)
  1678  
  1679  	// After the funding transaction was mined, Bob should have successfully
  1680  	// sent the fundingLocked message, while Alice failed sending it. In
  1681  	// Alice's case this means that there should be no messages for Bob, and
  1682  	// the channel should still be in state 'markedOpen'
  1683  	select {
  1684  	case msg := <-alice.msgChan:
  1685  		t.Fatalf("did not expect any message from Alice: %v", msg)
  1686  	default:
  1687  		// Expected.
  1688  	}
  1689  
  1690  	// Bob will send funding locked to Alice
  1691  	fundingLockedBob := assertFundingMsgSent(
  1692  		t, bob.msgChan, "FundingLocked",
  1693  	).(*lnwire.FundingLocked)
  1694  
  1695  	// Alice should still be markedOpen
  1696  	assertDatabaseState(t, alice, fundingOutPoint, markedOpen)
  1697  
  1698  	// While Bob successfully sent fundingLocked.
  1699  	assertDatabaseState(t, bob, fundingOutPoint, fundingLockedSent)
  1700  
  1701  	// Alice should be waiting for the server to notify when Bob comes back
  1702  	// online.
  1703  	var peer [33]byte
  1704  	var con chan<- lnpeer.Peer
  1705  	select {
  1706  	case peer = <-peerChan:
  1707  		// Expected
  1708  	case <-time.After(time.Second * 3):
  1709  		t.Fatalf("alice did not register peer with server")
  1710  	}
  1711  
  1712  	select {
  1713  	case con = <-conChan:
  1714  		// Expected
  1715  	case <-time.After(time.Second * 3):
  1716  		t.Fatalf("alice did not register connectedChan with server")
  1717  	}
  1718  
  1719  	if !bytes.Equal(peer[:], bobPubKey.SerializeCompressed()) {
  1720  		t.Fatalf("expected to receive Bob's pubkey (%v), instead got %v",
  1721  			bobPubKey, peer)
  1722  	}
  1723  
  1724  	// Restore the correct sendMessage implementation, and notify that Bob
  1725  	// is back online.
  1726  	bob.sendMessage = workingSendMessage
  1727  	con <- bob
  1728  
  1729  	// This should make Alice send the fundingLocked.
  1730  	fundingLockedAlice := assertFundingMsgSent(
  1731  		t, alice.msgChan, "FundingLocked",
  1732  	).(*lnwire.FundingLocked)
  1733  
  1734  	// The state should now be fundingLockedSent
  1735  	assertDatabaseState(t, alice, fundingOutPoint, fundingLockedSent)
  1736  
  1737  	// Make sure both fundingManagers send the expected channel
  1738  	// announcements.
  1739  	assertChannelAnnouncements(t, alice, bob, capacity, nil, nil)
  1740  
  1741  	// Check that the state machine is updated accordingly
  1742  	assertAddedToRouterGraph(t, alice, bob, fundingOutPoint)
  1743  
  1744  	// The funding transaction is now confirmed, wait for the
  1745  	// OpenStatusUpdate_ChanOpen update
  1746  	waitForOpenUpdate(t, updateChan)
  1747  
  1748  	// Exchange the fundingLocked messages.
  1749  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  1750  	bob.fundingMgr.ProcessFundingMsg(fundingLockedAlice, alice)
  1751  
  1752  	// Check that they notify the breach arbiter and peer about the new
  1753  	// channel.
  1754  	assertHandleFundingLocked(t, alice, bob)
  1755  
  1756  	// Notify that six confirmations has been reached on funding transaction.
  1757  	alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  1758  		Tx: fundingTx,
  1759  	}
  1760  	bob.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  1761  		Tx: fundingTx,
  1762  	}
  1763  
  1764  	// Make sure both fundingManagers send the expected announcement
  1765  	// signatures.
  1766  	assertAnnouncementSignatures(t, alice, bob)
  1767  
  1768  	// The internal state-machine should now have deleted the channelStates
  1769  	// from the database, as the channel is announced.
  1770  	assertNoChannelState(t, alice, bob, fundingOutPoint)
  1771  }
  1772  
  1773  // TestFundingManagerPeerTimeoutAfterInitFunding checks that the zombie sweeper
  1774  // will properly clean up a zombie reservation that times out after the
  1775  // InitFundingMsg has been handled.
  1776  func TestFundingManagerPeerTimeoutAfterInitFunding(t *testing.T) {
  1777  	t.Parallel()
  1778  
  1779  	alice, bob := setupFundingManagers(t)
  1780  	defer tearDownFundingManagers(t, alice, bob)
  1781  
  1782  	// We will consume the channel updates as we go, so no buffering is needed.
  1783  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  1784  
  1785  	// Create a funding request and start the workflow.
  1786  	errChan := make(chan error, 1)
  1787  	initReq := &InitFundingMsg{
  1788  		Peer:            bob,
  1789  		TargetPubkey:    bob.privKey.PubKey(),
  1790  		ChainHash:       fundingNetParams.GenesisHash,
  1791  		LocalFundingAmt: 500000,
  1792  		PushAmt:         lnwire.NewMAtomsFromAtoms(0),
  1793  		Private:         false,
  1794  		Updates:         updateChan,
  1795  		Err:             errChan,
  1796  	}
  1797  
  1798  	alice.fundingMgr.InitFundingWorkflow(initReq)
  1799  
  1800  	// Alice should have sent the OpenChannel message to Bob.
  1801  	var aliceMsg lnwire.Message
  1802  	select {
  1803  	case aliceMsg = <-alice.msgChan:
  1804  	case err := <-initReq.Err:
  1805  		t.Fatalf("error init funding workflow: %v", err)
  1806  	case <-time.After(time.Second * 5):
  1807  		t.Fatalf("alice did not send OpenChannel message")
  1808  	}
  1809  
  1810  	_, ok := aliceMsg.(*lnwire.OpenChannel)
  1811  	if !ok {
  1812  		errorMsg, gotError := aliceMsg.(*lnwire.Error)
  1813  		if gotError {
  1814  			t.Fatalf("expected OpenChannel to be sent "+
  1815  				"from bob, instead got error: %v",
  1816  				errorMsg.Error())
  1817  		}
  1818  		t.Fatalf("expected OpenChannel to be sent from "+
  1819  			"alice, instead got %T", aliceMsg)
  1820  	}
  1821  
  1822  	// Alice should have a new pending reservation.
  1823  	assertNumPendingReservations(t, alice, bobPubKey, 1)
  1824  
  1825  	// Make sure Alice's reservation times out and then run her zombie sweeper.
  1826  	time.Sleep(1 * time.Millisecond)
  1827  	go alice.fundingMgr.pruneZombieReservations()
  1828  
  1829  	// Alice should have sent an Error message to Bob.
  1830  	assertErrorSent(t, alice.msgChan)
  1831  
  1832  	// Alice's zombie reservation should have been pruned.
  1833  	assertNumPendingReservations(t, alice, bobPubKey, 0)
  1834  }
  1835  
  1836  // TestFundingManagerPeerTimeoutAfterFundingOpen checks that the zombie sweeper
  1837  // will properly clean up a zombie reservation that times out after the
  1838  // fundingOpenMsg has been handled.
  1839  func TestFundingManagerPeerTimeoutAfterFundingOpen(t *testing.T) {
  1840  	t.Parallel()
  1841  
  1842  	alice, bob := setupFundingManagers(t)
  1843  	defer tearDownFundingManagers(t, alice, bob)
  1844  
  1845  	// We will consume the channel updates as we go, so no buffering is needed.
  1846  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  1847  
  1848  	// Create a funding request and start the workflow.
  1849  	errChan := make(chan error, 1)
  1850  	initReq := &InitFundingMsg{
  1851  		Peer:            bob,
  1852  		TargetPubkey:    bob.privKey.PubKey(),
  1853  		ChainHash:       fundingNetParams.GenesisHash,
  1854  		LocalFundingAmt: 500000,
  1855  		PushAmt:         lnwire.NewMAtomsFromAtoms(0),
  1856  		Private:         false,
  1857  		Updates:         updateChan,
  1858  		Err:             errChan,
  1859  	}
  1860  
  1861  	alice.fundingMgr.InitFundingWorkflow(initReq)
  1862  
  1863  	// Alice should have sent the OpenChannel message to Bob.
  1864  	var aliceMsg lnwire.Message
  1865  	select {
  1866  	case aliceMsg = <-alice.msgChan:
  1867  	case err := <-initReq.Err:
  1868  		t.Fatalf("error init funding workflow: %v", err)
  1869  	case <-time.After(time.Second * 5):
  1870  		t.Fatalf("alice did not send OpenChannel message")
  1871  	}
  1872  
  1873  	openChannelReq, ok := aliceMsg.(*lnwire.OpenChannel)
  1874  	if !ok {
  1875  		errorMsg, gotError := aliceMsg.(*lnwire.Error)
  1876  		if gotError {
  1877  			t.Fatalf("expected OpenChannel to be sent "+
  1878  				"from bob, instead got error: %v",
  1879  				errorMsg.Error())
  1880  		}
  1881  		t.Fatalf("expected OpenChannel to be sent from "+
  1882  			"alice, instead got %T", aliceMsg)
  1883  	}
  1884  
  1885  	// Alice should have a new pending reservation.
  1886  	assertNumPendingReservations(t, alice, bobPubKey, 1)
  1887  
  1888  	// Let Bob handle the init message.
  1889  	bob.fundingMgr.ProcessFundingMsg(openChannelReq, alice)
  1890  
  1891  	// Bob should answer with an AcceptChannel.
  1892  	assertFundingMsgSent(t, bob.msgChan, "AcceptChannel")
  1893  
  1894  	// Bob should have a new pending reservation.
  1895  	assertNumPendingReservations(t, bob, alicePubKey, 1)
  1896  
  1897  	// Make sure Bob's reservation times out and then run his zombie sweeper.
  1898  	time.Sleep(1 * time.Millisecond)
  1899  	go bob.fundingMgr.pruneZombieReservations()
  1900  
  1901  	// Bob should have sent an Error message to Alice.
  1902  	assertErrorSent(t, bob.msgChan)
  1903  
  1904  	// Bob's zombie reservation should have been pruned.
  1905  	assertNumPendingReservations(t, bob, alicePubKey, 0)
  1906  }
  1907  
  1908  // TestFundingManagerPeerTimeoutAfterFundingAccept checks that the zombie sweeper
  1909  // will properly clean up a zombie reservation that times out after the
  1910  // fundingAcceptMsg has been handled.
  1911  func TestFundingManagerPeerTimeoutAfterFundingAccept(t *testing.T) {
  1912  	t.Parallel()
  1913  
  1914  	alice, bob := setupFundingManagers(t)
  1915  	defer tearDownFundingManagers(t, alice, bob)
  1916  
  1917  	// We will consume the channel updates as we go, so no buffering is needed.
  1918  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  1919  
  1920  	// Create a funding request and start the workflow.
  1921  	errChan := make(chan error, 1)
  1922  	initReq := &InitFundingMsg{
  1923  		Peer:            bob,
  1924  		TargetPubkey:    bob.privKey.PubKey(),
  1925  		ChainHash:       fundingNetParams.GenesisHash,
  1926  		LocalFundingAmt: 500000,
  1927  		PushAmt:         lnwire.NewMAtomsFromAtoms(0),
  1928  		Private:         false,
  1929  		Updates:         updateChan,
  1930  		Err:             errChan,
  1931  	}
  1932  
  1933  	alice.fundingMgr.InitFundingWorkflow(initReq)
  1934  
  1935  	// Alice should have sent the OpenChannel message to Bob.
  1936  	var aliceMsg lnwire.Message
  1937  	select {
  1938  	case aliceMsg = <-alice.msgChan:
  1939  	case err := <-initReq.Err:
  1940  		t.Fatalf("error init funding workflow: %v", err)
  1941  	case <-time.After(time.Second * 5):
  1942  		t.Fatalf("alice did not send OpenChannel message")
  1943  	}
  1944  
  1945  	openChannelReq, ok := aliceMsg.(*lnwire.OpenChannel)
  1946  	if !ok {
  1947  		errorMsg, gotError := aliceMsg.(*lnwire.Error)
  1948  		if gotError {
  1949  			t.Fatalf("expected OpenChannel to be sent "+
  1950  				"from bob, instead got error: %v",
  1951  				errorMsg.Error())
  1952  		}
  1953  		t.Fatalf("expected OpenChannel to be sent from "+
  1954  			"alice, instead got %T", aliceMsg)
  1955  	}
  1956  
  1957  	// Alice should have a new pending reservation.
  1958  	assertNumPendingReservations(t, alice, bobPubKey, 1)
  1959  
  1960  	// Let Bob handle the init message.
  1961  	bob.fundingMgr.ProcessFundingMsg(openChannelReq, alice)
  1962  
  1963  	// Bob should answer with an AcceptChannel.
  1964  	acceptChannelResponse := assertFundingMsgSent(
  1965  		t, bob.msgChan, "AcceptChannel",
  1966  	).(*lnwire.AcceptChannel)
  1967  
  1968  	// Bob should have a new pending reservation.
  1969  	assertNumPendingReservations(t, bob, alicePubKey, 1)
  1970  
  1971  	// Forward the response to Alice.
  1972  	alice.fundingMgr.ProcessFundingMsg(acceptChannelResponse, bob)
  1973  
  1974  	// Alice responds with a FundingCreated messages.
  1975  	assertFundingMsgSent(t, alice.msgChan, "FundingCreated")
  1976  
  1977  	// Make sure Alice's reservation times out and then run her zombie sweeper.
  1978  	time.Sleep(1 * time.Millisecond)
  1979  	go alice.fundingMgr.pruneZombieReservations()
  1980  
  1981  	// Alice should have sent an Error message to Bob.
  1982  	assertErrorSent(t, alice.msgChan)
  1983  
  1984  	// Alice's zombie reservation should have been pruned.
  1985  	assertNumPendingReservations(t, alice, bobPubKey, 0)
  1986  }
  1987  
  1988  func TestFundingManagerFundingTimeout(t *testing.T) {
  1989  	t.Parallel()
  1990  
  1991  	alice, bob := setupFundingManagers(t)
  1992  	defer tearDownFundingManagers(t, alice, bob)
  1993  
  1994  	// We will consume the channel updates as we go, so no buffering is needed.
  1995  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  1996  
  1997  	// Run through the process of opening the channel, up until the funding
  1998  	// transaction is broadcasted.
  1999  	_, _ = openChannel(t, alice, bob, 500000, 0, 1, updateChan, true)
  2000  
  2001  	// Bob will at this point be waiting for the funding transaction to be
  2002  	// confirmed, so the channel should be considered pending.
  2003  	pendingChannels, err := bob.fundingMgr.cfg.Wallet.Cfg.Database.FetchPendingChannels()
  2004  	if err != nil {
  2005  		t.Fatalf("unable to fetch pending channels: %v", err)
  2006  	}
  2007  	if len(pendingChannels) != 1 {
  2008  		t.Fatalf("Expected Bob to have 1 pending channel, had  %v",
  2009  			len(pendingChannels))
  2010  	}
  2011  
  2012  	// We expect Bob to forget the channel after 4032 blocks (2 weeks), so
  2013  	// mine 4032-1, and check that it is still pending.
  2014  	bob.mockNotifier.epochChan <- &chainntnfs.BlockEpoch{
  2015  		Height: fundingBroadcastHeight + maxWaitNumBlocksFundingConf - 1,
  2016  	}
  2017  
  2018  	// Bob should still be waiting for the channel to open.
  2019  	assertNumPendingChannelsRemains(t, bob, 1)
  2020  
  2021  	bob.mockNotifier.epochChan <- &chainntnfs.BlockEpoch{
  2022  		Height: fundingBroadcastHeight + maxWaitNumBlocksFundingConf,
  2023  	}
  2024  
  2025  	// Bob should have sent an Error message to Alice.
  2026  	assertErrorSent(t, bob.msgChan)
  2027  
  2028  	// Should not be pending anymore.
  2029  	assertNumPendingChannelsBecomes(t, bob, 0)
  2030  }
  2031  
  2032  // TestFundingManagerFundingNotTimeoutInitiator checks that if the user was
  2033  // the channel initiator, that it does not timeout when the lnd restarts.
  2034  func TestFundingManagerFundingNotTimeoutInitiator(t *testing.T) {
  2035  	t.Parallel()
  2036  
  2037  	alice, bob := setupFundingManagers(t)
  2038  	defer tearDownFundingManagers(t, alice, bob)
  2039  
  2040  	// We will consume the channel updates as we go, so no buffering is needed.
  2041  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  2042  
  2043  	// Run through the process of opening the channel, up until the funding
  2044  	// transaction is broadcasted.
  2045  	_, _ = openChannel(t, alice, bob, 500000, 0, 1, updateChan, true)
  2046  
  2047  	// Alice will at this point be waiting for the funding transaction to be
  2048  	// confirmed, so the channel should be considered pending.
  2049  	pendingChannels, err := alice.fundingMgr.cfg.Wallet.Cfg.Database.FetchPendingChannels()
  2050  	if err != nil {
  2051  		t.Fatalf("unable to fetch pending channels: %v", err)
  2052  	}
  2053  	if len(pendingChannels) != 1 {
  2054  		t.Fatalf("Expected Alice to have 1 pending channel, had  %v",
  2055  			len(pendingChannels))
  2056  	}
  2057  
  2058  	recreateAliceFundingManager(t, alice)
  2059  
  2060  	// We should receive the rebroadcasted funding txn.
  2061  	select {
  2062  	case <-alice.publTxChan:
  2063  	case <-time.After(time.Second * 5):
  2064  		t.Fatalf("alice did not publish funding tx")
  2065  	}
  2066  
  2067  	// Increase the height to 1 minus the maxWaitNumBlocksFundingConf height.
  2068  	alice.mockNotifier.epochChan <- &chainntnfs.BlockEpoch{
  2069  		Height: fundingBroadcastHeight + maxWaitNumBlocksFundingConf - 1,
  2070  	}
  2071  
  2072  	bob.mockNotifier.epochChan <- &chainntnfs.BlockEpoch{
  2073  		Height: fundingBroadcastHeight + maxWaitNumBlocksFundingConf - 1,
  2074  	}
  2075  
  2076  	// Assert both and Alice and Bob still have 1 pending channels.
  2077  	assertNumPendingChannelsRemains(t, alice, 1)
  2078  
  2079  	assertNumPendingChannelsRemains(t, bob, 1)
  2080  
  2081  	// Increase both Alice and Bob to maxWaitNumBlocksFundingConf height.
  2082  	alice.mockNotifier.epochChan <- &chainntnfs.BlockEpoch{
  2083  		Height: fundingBroadcastHeight + maxWaitNumBlocksFundingConf,
  2084  	}
  2085  
  2086  	bob.mockNotifier.epochChan <- &chainntnfs.BlockEpoch{
  2087  		Height: fundingBroadcastHeight + maxWaitNumBlocksFundingConf,
  2088  	}
  2089  
  2090  	// Since Alice was the initiator, the channel should not have timed out.
  2091  	assertNumPendingChannelsRemains(t, alice, 1)
  2092  
  2093  	// Bob should have sent an Error message to Alice.
  2094  	assertErrorSent(t, bob.msgChan)
  2095  
  2096  	// Since Bob was not the initiator, the channel should timeout.
  2097  	assertNumPendingChannelsBecomes(t, bob, 0)
  2098  }
  2099  
  2100  // TestFundingManagerReceiveFundingLockedTwice checks that the fundingManager
  2101  // continues to operate as expected in case we receive a duplicate fundingLocked
  2102  // message.
  2103  func TestFundingManagerReceiveFundingLockedTwice(t *testing.T) {
  2104  	t.Parallel()
  2105  
  2106  	alice, bob := setupFundingManagers(t)
  2107  	defer tearDownFundingManagers(t, alice, bob)
  2108  
  2109  	// We will consume the channel updates as we go, so no buffering is needed.
  2110  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  2111  
  2112  	// Run through the process of opening the channel, up until the funding
  2113  	// transaction is broadcasted.
  2114  	localAmt := dcrutil.Amount(500000)
  2115  	pushAmt := dcrutil.Amount(0)
  2116  	capacity := localAmt + pushAmt
  2117  	fundingOutPoint, fundingTx := openChannel(
  2118  		t, alice, bob, localAmt, pushAmt, 1, updateChan, true,
  2119  	)
  2120  
  2121  	// Notify that transaction was mined
  2122  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2123  		Tx: fundingTx,
  2124  	}
  2125  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2126  		Tx: fundingTx,
  2127  	}
  2128  
  2129  	// The funding transaction was mined, so assert that both funding
  2130  	// managers now have the state of this channel 'markedOpen' in their
  2131  	// internal state machine.
  2132  	assertMarkedOpen(t, alice, bob, fundingOutPoint)
  2133  
  2134  	// After the funding transaction is mined, Alice will send
  2135  	// fundingLocked to Bob.
  2136  	fundingLockedAlice := assertFundingMsgSent(
  2137  		t, alice.msgChan, "FundingLocked",
  2138  	).(*lnwire.FundingLocked)
  2139  
  2140  	// And similarly Bob will send funding locked to Alice.
  2141  	fundingLockedBob := assertFundingMsgSent(
  2142  		t, bob.msgChan, "FundingLocked",
  2143  	).(*lnwire.FundingLocked)
  2144  
  2145  	// Check that the state machine is updated accordingly
  2146  	assertFundingLockedSent(t, alice, bob, fundingOutPoint)
  2147  
  2148  	// Make sure both fundingManagers send the expected channel
  2149  	// announcements.
  2150  	assertChannelAnnouncements(t, alice, bob, capacity, nil, nil)
  2151  
  2152  	// Check that the state machine is updated accordingly
  2153  	assertAddedToRouterGraph(t, alice, bob, fundingOutPoint)
  2154  
  2155  	// The funding transaction is now confirmed, wait for the
  2156  	// OpenStatusUpdate_ChanOpen update
  2157  	waitForOpenUpdate(t, updateChan)
  2158  
  2159  	// Send the fundingLocked message twice to Alice, and once to Bob.
  2160  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  2161  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  2162  	bob.fundingMgr.ProcessFundingMsg(fundingLockedAlice, alice)
  2163  
  2164  	// Check that they notify the breach arbiter and peer about the new
  2165  	// channel.
  2166  	assertHandleFundingLocked(t, alice, bob)
  2167  
  2168  	// Alice should not send the channel state the second time, as the
  2169  	// second funding locked should just be ignored.
  2170  	select {
  2171  	case <-alice.newChannels:
  2172  		t.Fatalf("alice sent new channel to peer a second time")
  2173  	case <-time.After(time.Millisecond * 300):
  2174  		// Expected
  2175  	}
  2176  
  2177  	// Another fundingLocked should also be ignored, since Alice should
  2178  	// have updated her database at this point.
  2179  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  2180  	select {
  2181  	case <-alice.newChannels:
  2182  		t.Fatalf("alice sent new channel to peer a second time")
  2183  	case <-time.After(time.Millisecond * 300):
  2184  		// Expected
  2185  	}
  2186  
  2187  	// Notify that six confirmations has been reached on funding transaction.
  2188  	alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2189  		Tx: fundingTx,
  2190  	}
  2191  	bob.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2192  		Tx: fundingTx,
  2193  	}
  2194  
  2195  	// Make sure the fundingManagers exchange announcement signatures.
  2196  	assertAnnouncementSignatures(t, alice, bob)
  2197  
  2198  	// The internal state-machine should now have deleted the channelStates
  2199  	// from the database, as the channel is announced.
  2200  	assertNoChannelState(t, alice, bob, fundingOutPoint)
  2201  }
  2202  
  2203  // TestFundingManagerRestartAfterChanAnn checks that the fundingManager properly
  2204  // handles receiving a fundingLocked after the its own fundingLocked and channel
  2205  // announcement is sent and gets restarted.
  2206  func TestFundingManagerRestartAfterChanAnn(t *testing.T) {
  2207  	t.Parallel()
  2208  
  2209  	alice, bob := setupFundingManagers(t)
  2210  	defer tearDownFundingManagers(t, alice, bob)
  2211  
  2212  	// We will consume the channel updates as we go, so no buffering is needed.
  2213  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  2214  
  2215  	// Run through the process of opening the channel, up until the funding
  2216  	// transaction is broadcasted.
  2217  	localAmt := dcrutil.Amount(500000)
  2218  	pushAmt := dcrutil.Amount(0)
  2219  	capacity := localAmt + pushAmt
  2220  	fundingOutPoint, fundingTx := openChannel(
  2221  		t, alice, bob, localAmt, pushAmt, 1, updateChan, true,
  2222  	)
  2223  
  2224  	// Notify that transaction was mined
  2225  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2226  		Tx: fundingTx,
  2227  	}
  2228  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2229  		Tx: fundingTx,
  2230  	}
  2231  
  2232  	// The funding transaction was mined, so assert that both funding
  2233  	// managers now have the state of this channel 'markedOpen' in their
  2234  	// internal state machine.
  2235  	assertMarkedOpen(t, alice, bob, fundingOutPoint)
  2236  
  2237  	// After the funding transaction is mined, Alice will send
  2238  	// fundingLocked to Bob.
  2239  	fundingLockedAlice := assertFundingMsgSent(
  2240  		t, alice.msgChan, "FundingLocked",
  2241  	).(*lnwire.FundingLocked)
  2242  
  2243  	// And similarly Bob will send funding locked to Alice.
  2244  	fundingLockedBob := assertFundingMsgSent(
  2245  		t, bob.msgChan, "FundingLocked",
  2246  	).(*lnwire.FundingLocked)
  2247  
  2248  	// Check that the state machine is updated accordingly
  2249  	assertFundingLockedSent(t, alice, bob, fundingOutPoint)
  2250  
  2251  	// Make sure both fundingManagers send the expected channel
  2252  	// announcements.
  2253  	assertChannelAnnouncements(t, alice, bob, capacity, nil, nil)
  2254  
  2255  	// Check that the state machine is updated accordingly
  2256  	assertAddedToRouterGraph(t, alice, bob, fundingOutPoint)
  2257  
  2258  	// The funding transaction is now confirmed, wait for the
  2259  	// OpenStatusUpdate_ChanOpen update
  2260  	waitForOpenUpdate(t, updateChan)
  2261  
  2262  	// At this point we restart Alice's fundingManager, before she receives
  2263  	// the fundingLocked message. After restart, she will receive it, and
  2264  	// we expect her to be able to handle it correctly.
  2265  	recreateAliceFundingManager(t, alice)
  2266  
  2267  	// Exchange the fundingLocked messages.
  2268  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  2269  	bob.fundingMgr.ProcessFundingMsg(fundingLockedAlice, alice)
  2270  
  2271  	// Check that they notify the breach arbiter and peer about the new
  2272  	// channel.
  2273  	assertHandleFundingLocked(t, alice, bob)
  2274  
  2275  	// Notify that six confirmations has been reached on funding transaction.
  2276  	alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2277  		Tx: fundingTx,
  2278  	}
  2279  	bob.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2280  		Tx: fundingTx,
  2281  	}
  2282  
  2283  	// Make sure both fundingManagers send the expected channel announcements.
  2284  	assertAnnouncementSignatures(t, alice, bob)
  2285  
  2286  	// The internal state-machine should now have deleted the channelStates
  2287  	// from the database, as the channel is announced.
  2288  	assertNoChannelState(t, alice, bob, fundingOutPoint)
  2289  }
  2290  
  2291  // TestFundingManagerRestartAfterReceivingFundingLocked checks that the
  2292  // fundingManager continues to operate as expected after it has received
  2293  // fundingLocked and then gets restarted.
  2294  func TestFundingManagerRestartAfterReceivingFundingLocked(t *testing.T) {
  2295  	t.Parallel()
  2296  
  2297  	alice, bob := setupFundingManagers(t)
  2298  	defer tearDownFundingManagers(t, alice, bob)
  2299  
  2300  	// We will consume the channel updates as we go, so no buffering is needed.
  2301  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  2302  
  2303  	// Run through the process of opening the channel, up until the funding
  2304  	// transaction is broadcasted.
  2305  	localAmt := dcrutil.Amount(500000)
  2306  	pushAmt := dcrutil.Amount(0)
  2307  	capacity := localAmt + pushAmt
  2308  	fundingOutPoint, fundingTx := openChannel(
  2309  		t, alice, bob, localAmt, pushAmt, 1, updateChan, true,
  2310  	)
  2311  
  2312  	// Notify that transaction was mined
  2313  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2314  		Tx: fundingTx,
  2315  	}
  2316  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2317  		Tx: fundingTx,
  2318  	}
  2319  
  2320  	// The funding transaction was mined, so assert that both funding
  2321  	// managers now have the state of this channel 'markedOpen' in their
  2322  	// internal state machine.
  2323  	assertMarkedOpen(t, alice, bob, fundingOutPoint)
  2324  
  2325  	// After the funding transaction is mined, Alice will send
  2326  	// fundingLocked to Bob.
  2327  	fundingLockedAlice := assertFundingMsgSent(
  2328  		t, alice.msgChan, "FundingLocked",
  2329  	).(*lnwire.FundingLocked)
  2330  
  2331  	// And similarly Bob will send funding locked to Alice.
  2332  	fundingLockedBob := assertFundingMsgSent(
  2333  		t, bob.msgChan, "FundingLocked",
  2334  	).(*lnwire.FundingLocked)
  2335  
  2336  	// Check that the state machine is updated accordingly
  2337  	assertFundingLockedSent(t, alice, bob, fundingOutPoint)
  2338  
  2339  	// Let Alice immediately get the fundingLocked message.
  2340  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  2341  
  2342  	// Also let Bob get the fundingLocked message.
  2343  	bob.fundingMgr.ProcessFundingMsg(fundingLockedAlice, alice)
  2344  
  2345  	// Check that they notify the breach arbiter and peer about the new
  2346  	// channel.
  2347  	assertHandleFundingLocked(t, alice, bob)
  2348  
  2349  	// At this point we restart Alice's fundingManager.
  2350  	recreateAliceFundingManager(t, alice)
  2351  
  2352  	// Make sure both fundingManagers send the expected channel
  2353  	// announcements.
  2354  	assertChannelAnnouncements(t, alice, bob, capacity, nil, nil)
  2355  
  2356  	// Check that the state machine is updated accordingly
  2357  	assertAddedToRouterGraph(t, alice, bob, fundingOutPoint)
  2358  
  2359  	// Notify that six confirmations has been reached on funding transaction.
  2360  	alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2361  		Tx: fundingTx,
  2362  	}
  2363  	bob.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2364  		Tx: fundingTx,
  2365  	}
  2366  
  2367  	// Make sure both fundingManagers send the expected channel announcements.
  2368  	assertAnnouncementSignatures(t, alice, bob)
  2369  
  2370  	// The internal state-machine should now have deleted the channelStates
  2371  	// from the database, as the channel is announced.
  2372  	assertNoChannelState(t, alice, bob, fundingOutPoint)
  2373  }
  2374  
  2375  // TestFundingManagerPrivateChannel tests that if we open a private channel
  2376  // (a channel not supposed to be announced to the rest of the network),
  2377  // the announcementSignatures nor the nodeAnnouncement messages are sent.
  2378  func TestFundingManagerPrivateChannel(t *testing.T) {
  2379  	t.Parallel()
  2380  
  2381  	alice, bob := setupFundingManagers(t)
  2382  	defer tearDownFundingManagers(t, alice, bob)
  2383  
  2384  	// We will consume the channel updates as we go, so no buffering is needed.
  2385  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  2386  
  2387  	// Run through the process of opening the channel, up until the funding
  2388  	// transaction is broadcasted.
  2389  	localAmt := dcrutil.Amount(500000)
  2390  	pushAmt := dcrutil.Amount(0)
  2391  	capacity := localAmt + pushAmt
  2392  	fundingOutPoint, fundingTx := openChannel(
  2393  		t, alice, bob, localAmt, pushAmt, 1, updateChan, false,
  2394  	)
  2395  
  2396  	// Notify that transaction was mined
  2397  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2398  		Tx: fundingTx,
  2399  	}
  2400  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2401  		Tx: fundingTx,
  2402  	}
  2403  
  2404  	// The funding transaction was mined, so assert that both funding
  2405  	// managers now have the state of this channel 'markedOpen' in their
  2406  	// internal state machine.
  2407  	assertMarkedOpen(t, alice, bob, fundingOutPoint)
  2408  
  2409  	// After the funding transaction is mined, Alice will send
  2410  	// fundingLocked to Bob.
  2411  	fundingLockedAlice := assertFundingMsgSent(
  2412  		t, alice.msgChan, "FundingLocked",
  2413  	).(*lnwire.FundingLocked)
  2414  
  2415  	// And similarly Bob will send funding locked to Alice.
  2416  	fundingLockedBob := assertFundingMsgSent(
  2417  		t, bob.msgChan, "FundingLocked",
  2418  	).(*lnwire.FundingLocked)
  2419  
  2420  	// Check that the state machine is updated accordingly
  2421  	assertFundingLockedSent(t, alice, bob, fundingOutPoint)
  2422  
  2423  	// Make sure both fundingManagers send the expected channel
  2424  	// announcements.
  2425  	assertChannelAnnouncements(t, alice, bob, capacity, nil, nil)
  2426  
  2427  	// The funding transaction is now confirmed, wait for the
  2428  	// OpenStatusUpdate_ChanOpen update
  2429  	waitForOpenUpdate(t, updateChan)
  2430  
  2431  	// Exchange the fundingLocked messages.
  2432  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  2433  	bob.fundingMgr.ProcessFundingMsg(fundingLockedAlice, alice)
  2434  
  2435  	// Check that they notify the breach arbiter and peer about the new
  2436  	// channel.
  2437  	assertHandleFundingLocked(t, alice, bob)
  2438  
  2439  	// Notify that six confirmations has been reached on funding transaction.
  2440  	alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2441  		Tx: fundingTx,
  2442  	}
  2443  	bob.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2444  		Tx: fundingTx,
  2445  	}
  2446  
  2447  	// Since this is a private channel, we shouldn't receive the
  2448  	// announcement signatures.
  2449  	select {
  2450  	case ann := <-alice.announceChan:
  2451  		t.Fatalf("unexpectedly got channel announcement message: %v", ann)
  2452  	case <-time.After(300 * time.Millisecond):
  2453  		// Expected
  2454  	}
  2455  
  2456  	select {
  2457  	case ann := <-bob.announceChan:
  2458  		t.Fatalf("unexpectedly got channel announcement message: %v", ann)
  2459  	case <-time.After(300 * time.Millisecond):
  2460  		// Expected
  2461  	}
  2462  
  2463  	// We should however receive each side's node announcement.
  2464  	select {
  2465  	case msg := <-alice.msgChan:
  2466  		if _, ok := msg.(*lnwire.NodeAnnouncement); !ok {
  2467  			t.Fatalf("expected to receive node announcement")
  2468  		}
  2469  	case <-time.After(time.Second):
  2470  		t.Fatalf("expected to receive node announcement")
  2471  	}
  2472  
  2473  	select {
  2474  	case msg := <-bob.msgChan:
  2475  		if _, ok := msg.(*lnwire.NodeAnnouncement); !ok {
  2476  			t.Fatalf("expected to receive node announcement")
  2477  		}
  2478  	case <-time.After(time.Second):
  2479  		t.Fatalf("expected to receive node announcement")
  2480  	}
  2481  
  2482  	// The internal state-machine should now have deleted the channelStates
  2483  	// from the database, as the channel is announced.
  2484  	assertNoChannelState(t, alice, bob, fundingOutPoint)
  2485  }
  2486  
  2487  // TestFundingManagerPrivateRestart tests that the privacy guarantees granted
  2488  // by the private channel persist even on restart. This means that the
  2489  // announcement signatures nor the node announcement messages are sent upon
  2490  // restart.
  2491  func TestFundingManagerPrivateRestart(t *testing.T) {
  2492  	t.Parallel()
  2493  
  2494  	alice, bob := setupFundingManagers(t)
  2495  	defer tearDownFundingManagers(t, alice, bob)
  2496  
  2497  	// We will consume the channel updates as we go, so no buffering is needed.
  2498  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  2499  
  2500  	// Run through the process of opening the channel, up until the funding
  2501  	// transaction is broadcasted.
  2502  	localAmt := dcrutil.Amount(500000)
  2503  	pushAmt := dcrutil.Amount(0)
  2504  	capacity := localAmt + pushAmt
  2505  	fundingOutPoint, fundingTx := openChannel(
  2506  		t, alice, bob, localAmt, pushAmt, 1, updateChan, false,
  2507  	)
  2508  
  2509  	// Notify that transaction was mined
  2510  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2511  		Tx: fundingTx,
  2512  	}
  2513  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2514  		Tx: fundingTx,
  2515  	}
  2516  
  2517  	// The funding transaction was mined, so assert that both funding
  2518  	// managers now have the state of this channel 'markedOpen' in their
  2519  	// internal state machine.
  2520  	assertMarkedOpen(t, alice, bob, fundingOutPoint)
  2521  
  2522  	// After the funding transaction is mined, Alice will send
  2523  	// fundingLocked to Bob.
  2524  	fundingLockedAlice := assertFundingMsgSent(
  2525  		t, alice.msgChan, "FundingLocked",
  2526  	).(*lnwire.FundingLocked)
  2527  
  2528  	// And similarly Bob will send funding locked to Alice.
  2529  	fundingLockedBob := assertFundingMsgSent(
  2530  		t, bob.msgChan, "FundingLocked",
  2531  	).(*lnwire.FundingLocked)
  2532  
  2533  	// Check that the state machine is updated accordingly
  2534  	assertFundingLockedSent(t, alice, bob, fundingOutPoint)
  2535  
  2536  	// Make sure both fundingManagers send the expected channel
  2537  	// announcements.
  2538  	assertChannelAnnouncements(t, alice, bob, capacity, nil, nil)
  2539  
  2540  	// Note: We don't check for the addedToRouterGraph state because in
  2541  	// the private channel mode, the state is quickly changed from
  2542  	// addedToRouterGraph to deleted from the database since the public
  2543  	// announcement phase is skipped.
  2544  
  2545  	// The funding transaction is now confirmed, wait for the
  2546  	// OpenStatusUpdate_ChanOpen update
  2547  	waitForOpenUpdate(t, updateChan)
  2548  
  2549  	// Exchange the fundingLocked messages.
  2550  	alice.fundingMgr.ProcessFundingMsg(fundingLockedBob, bob)
  2551  	bob.fundingMgr.ProcessFundingMsg(fundingLockedAlice, alice)
  2552  
  2553  	// Check that they notify the breach arbiter and peer about the new
  2554  	// channel.
  2555  	assertHandleFundingLocked(t, alice, bob)
  2556  
  2557  	// Notify that six confirmations has been reached on funding transaction.
  2558  	alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2559  		Tx: fundingTx,
  2560  	}
  2561  	bob.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
  2562  		Tx: fundingTx,
  2563  	}
  2564  
  2565  	// Since this is a private channel, we shouldn't receive the public
  2566  	// channel announcement messages.
  2567  	select {
  2568  	case ann := <-alice.announceChan:
  2569  		t.Fatalf("unexpectedly got channel announcement message: %v", ann)
  2570  	case <-time.After(300 * time.Millisecond):
  2571  	}
  2572  
  2573  	select {
  2574  	case ann := <-bob.announceChan:
  2575  		t.Fatalf("unexpectedly got channel announcement message: %v", ann)
  2576  	case <-time.After(300 * time.Millisecond):
  2577  	}
  2578  
  2579  	// We should however receive each side's node announcement.
  2580  	select {
  2581  	case msg := <-alice.msgChan:
  2582  		if _, ok := msg.(*lnwire.NodeAnnouncement); !ok {
  2583  			t.Fatalf("expected to receive node announcement")
  2584  		}
  2585  	case <-time.After(time.Second):
  2586  		t.Fatalf("expected to receive node announcement")
  2587  	}
  2588  
  2589  	select {
  2590  	case msg := <-bob.msgChan:
  2591  		if _, ok := msg.(*lnwire.NodeAnnouncement); !ok {
  2592  			t.Fatalf("expected to receive node announcement")
  2593  		}
  2594  	case <-time.After(time.Second):
  2595  		t.Fatalf("expected to receive node announcement")
  2596  	}
  2597  
  2598  	// Restart Alice's fundingManager so we can prove that the public
  2599  	// channel announcements are not sent upon restart and that the private
  2600  	// setting persists upon restart.
  2601  	recreateAliceFundingManager(t, alice)
  2602  
  2603  	select {
  2604  	case ann := <-alice.announceChan:
  2605  		t.Fatalf("unexpectedly got channel announcement message: %v", ann)
  2606  	case <-time.After(300 * time.Millisecond):
  2607  		// Expected
  2608  	}
  2609  
  2610  	select {
  2611  	case ann := <-bob.announceChan:
  2612  		t.Fatalf("unexpectedly got channel announcement message: %v", ann)
  2613  	case <-time.After(300 * time.Millisecond):
  2614  		// Expected
  2615  	}
  2616  
  2617  	// The internal state-machine should now have deleted the channelStates
  2618  	// from the database, as the channel is announced.
  2619  	assertNoChannelState(t, alice, bob, fundingOutPoint)
  2620  }
  2621  
  2622  // TestFundingManagerCustomChannelParameters checks that custom requirements we
  2623  // specify during the channel funding flow is preserved correcly on both sides.
  2624  func TestFundingManagerCustomChannelParameters(t *testing.T) {
  2625  	t.Parallel()
  2626  
  2627  	alice, bob := setupFundingManagers(t)
  2628  	defer tearDownFundingManagers(t, alice, bob)
  2629  
  2630  	// This is the custom parameters we'll use.
  2631  	const csvDelay = 67
  2632  	const minHtlcIn = 1234
  2633  	const maxValueInFlight = 50000
  2634  	const fundingAmt = 5000000
  2635  
  2636  	// We will consume the channel updates as we go, so no buffering is
  2637  	// needed.
  2638  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  2639  
  2640  	localAmt := dcrutil.Amount(5000000)
  2641  	pushAmt := dcrutil.Amount(0)
  2642  	capacity := localAmt + pushAmt
  2643  
  2644  	// Create a funding request with the custom parameters and start the
  2645  	// workflow.
  2646  	errChan := make(chan error, 1)
  2647  	initReq := &InitFundingMsg{
  2648  		Peer:             bob,
  2649  		TargetPubkey:     bob.privKey.PubKey(),
  2650  		ChainHash:        fundingNetParams.GenesisHash,
  2651  		LocalFundingAmt:  localAmt,
  2652  		PushAmt:          lnwire.NewMAtomsFromAtoms(pushAmt),
  2653  		Private:          false,
  2654  		MaxValueInFlight: maxValueInFlight,
  2655  		MinHtlcIn:        minHtlcIn,
  2656  		RemoteCsvDelay:   csvDelay,
  2657  		Updates:          updateChan,
  2658  		Err:              errChan,
  2659  	}
  2660  
  2661  	alice.fundingMgr.InitFundingWorkflow(initReq)
  2662  
  2663  	// Alice should have sent the OpenChannel message to Bob.
  2664  	var aliceMsg lnwire.Message
  2665  	select {
  2666  	case aliceMsg = <-alice.msgChan:
  2667  	case err := <-initReq.Err:
  2668  		t.Fatalf("error init funding workflow: %v", err)
  2669  	case <-time.After(time.Second * 5):
  2670  		t.Fatalf("alice did not send OpenChannel message")
  2671  	}
  2672  
  2673  	openChannelReq, ok := aliceMsg.(*lnwire.OpenChannel)
  2674  	if !ok {
  2675  		errorMsg, gotError := aliceMsg.(*lnwire.Error)
  2676  		if gotError {
  2677  			t.Fatalf("expected OpenChannel to be sent "+
  2678  				"from bob, instead got error: %v",
  2679  				errorMsg.Error())
  2680  		}
  2681  		t.Fatalf("expected OpenChannel to be sent from "+
  2682  			"alice, instead got %T", aliceMsg)
  2683  	}
  2684  
  2685  	// Check that the custom CSV delay is sent as part of OpenChannel.
  2686  	if openChannelReq.CsvDelay != csvDelay {
  2687  		t.Fatalf("expected OpenChannel to have CSV delay %v, got %v",
  2688  			csvDelay, openChannelReq.CsvDelay)
  2689  	}
  2690  
  2691  	// Check that the custom minHTLC value is sent.
  2692  	if openChannelReq.HtlcMinimum != minHtlcIn {
  2693  		t.Fatalf("expected OpenChannel to have minHtlc %v, got %v",
  2694  			minHtlcIn, openChannelReq.HtlcMinimum)
  2695  	}
  2696  
  2697  	// Check that the max value in flight is sent as part of OpenChannel.
  2698  	if openChannelReq.MaxValueInFlight != maxValueInFlight {
  2699  		t.Fatalf("expected OpenChannel to have MaxValueInFlight %v, got %v",
  2700  			maxValueInFlight, openChannelReq.MaxValueInFlight)
  2701  	}
  2702  
  2703  	chanID := openChannelReq.PendingChannelID
  2704  
  2705  	// Let Bob handle the init message.
  2706  	bob.fundingMgr.ProcessFundingMsg(openChannelReq, alice)
  2707  
  2708  	// Bob should answer with an AcceptChannel message.
  2709  	acceptChannelResponse := assertFundingMsgSent(
  2710  		t, bob.msgChan, "AcceptChannel",
  2711  	).(*lnwire.AcceptChannel)
  2712  
  2713  	// Bob should require the default delay of 4.
  2714  	if acceptChannelResponse.CsvDelay != 4 {
  2715  		t.Fatalf("expected AcceptChannel to have CSV delay %v, got %v",
  2716  			4, acceptChannelResponse.CsvDelay)
  2717  	}
  2718  
  2719  	// And the default MinHTLC value of 5.
  2720  	if acceptChannelResponse.HtlcMinimum != 5 {
  2721  		t.Fatalf("expected AcceptChannel to have minHtlc %v, got %v",
  2722  			5, acceptChannelResponse.HtlcMinimum)
  2723  	}
  2724  
  2725  	reserve := lnwire.NewMAtomsFromAtoms(fundingAmt / 100)
  2726  	maxValueAcceptChannel := lnwire.NewMAtomsFromAtoms(fundingAmt) - reserve
  2727  
  2728  	if acceptChannelResponse.MaxValueInFlight != maxValueAcceptChannel {
  2729  		t.Fatalf("expected AcceptChannel to have MaxValueInFlight %v, got %v",
  2730  			maxValueAcceptChannel, acceptChannelResponse.MaxValueInFlight)
  2731  	}
  2732  
  2733  	// Forward the response to Alice.
  2734  	alice.fundingMgr.ProcessFundingMsg(acceptChannelResponse, bob)
  2735  
  2736  	// Alice responds with a FundingCreated message.
  2737  	fundingCreated := assertFundingMsgSent(
  2738  		t, alice.msgChan, "FundingCreated",
  2739  	).(*lnwire.FundingCreated)
  2740  
  2741  	// Helper method for checking the CSV delay stored for a reservation.
  2742  	assertDelay := func(resCtx *reservationWithCtx,
  2743  		ourDelay, theirDelay uint16) error {
  2744  
  2745  		ourCsvDelay := resCtx.reservation.OurContribution().CsvDelay
  2746  		if ourCsvDelay != ourDelay {
  2747  			return fmt.Errorf("expected our CSV delay to be %v, "+
  2748  				"was %v", ourDelay, ourCsvDelay)
  2749  		}
  2750  
  2751  		theirCsvDelay := resCtx.reservation.TheirContribution().CsvDelay
  2752  		if theirCsvDelay != theirDelay {
  2753  			return fmt.Errorf("expected their CSV delay to be %v, "+
  2754  				"was %v", theirDelay, theirCsvDelay)
  2755  		}
  2756  		return nil
  2757  	}
  2758  
  2759  	// Helper method for checking the MinHtlc value stored for a
  2760  	// reservation.
  2761  	assertMinHtlc := func(resCtx *reservationWithCtx,
  2762  		expOurMinHtlc, expTheirMinHtlc lnwire.MilliAtom) error {
  2763  
  2764  		ourMinHtlc := resCtx.reservation.OurContribution().MinHTLC
  2765  		if ourMinHtlc != expOurMinHtlc {
  2766  			return fmt.Errorf("expected our minHtlc to be %v, "+
  2767  				"was %v", expOurMinHtlc, ourMinHtlc)
  2768  		}
  2769  
  2770  		theirMinHtlc := resCtx.reservation.TheirContribution().MinHTLC
  2771  		if theirMinHtlc != expTheirMinHtlc {
  2772  			return fmt.Errorf("expected their minHtlc to be %v, "+
  2773  				"was %v", expTheirMinHtlc, theirMinHtlc)
  2774  		}
  2775  		return nil
  2776  	}
  2777  
  2778  	// Helper method for checking the MaxValueInFlight stored for a
  2779  	// reservation.
  2780  	assertMaxHtlc := func(resCtx *reservationWithCtx,
  2781  		expOurMaxValue, expTheirMaxValue lnwire.MilliAtom) error {
  2782  
  2783  		ourMaxValue :=
  2784  			resCtx.reservation.OurContribution().MaxPendingAmount
  2785  		if ourMaxValue != expOurMaxValue {
  2786  			return fmt.Errorf("expected our maxValue to be %v, "+
  2787  				"was %v", expOurMaxValue, ourMaxValue)
  2788  		}
  2789  
  2790  		theirMaxValue :=
  2791  			resCtx.reservation.TheirContribution().MaxPendingAmount
  2792  		if theirMaxValue != expTheirMaxValue {
  2793  			return fmt.Errorf("expected their MaxPendingAmount to be %v, "+
  2794  				"was %v", expTheirMaxValue, theirMaxValue)
  2795  		}
  2796  		return nil
  2797  	}
  2798  
  2799  	// Check that the custom channel parameters were properly set in the
  2800  	// channel reservation.
  2801  	resCtx, err := alice.fundingMgr.getReservationCtx(bobPubKey, chanID)
  2802  	if err != nil {
  2803  		t.Fatalf("unable to find ctx: %v", err)
  2804  	}
  2805  
  2806  	// Alice's CSV delay should be 4 since Bob sent the default value, and
  2807  	// Bob's should be 67 since Alice sent the custom value.
  2808  	if err := assertDelay(resCtx, 4, csvDelay); err != nil {
  2809  		t.Fatal(err)
  2810  	}
  2811  
  2812  	// The minimum HTLC value Alice can offer should be 5, and the minimum
  2813  	// Bob can offer should be 1234.
  2814  	if err := assertMinHtlc(resCtx, 5, minHtlcIn); err != nil {
  2815  		t.Fatal(err)
  2816  	}
  2817  
  2818  	// The max value in flight Alice can have should be maxValueAcceptChannel,
  2819  	// which is the default value and the maxium Bob can offer should be
  2820  	// maxValueInFlight.
  2821  	if err := assertMaxHtlc(resCtx,
  2822  		maxValueAcceptChannel, maxValueInFlight); err != nil {
  2823  		t.Fatal(err)
  2824  	}
  2825  
  2826  	// Also make sure the parameters are properly set on Bob's end.
  2827  	resCtx, err = bob.fundingMgr.getReservationCtx(alicePubKey, chanID)
  2828  	if err != nil {
  2829  		t.Fatalf("unable to find ctx: %v", err)
  2830  	}
  2831  
  2832  	if err := assertDelay(resCtx, csvDelay, 4); err != nil {
  2833  		t.Fatal(err)
  2834  	}
  2835  
  2836  	if err := assertMinHtlc(resCtx, minHtlcIn, 5); err != nil {
  2837  		t.Fatal(err)
  2838  	}
  2839  
  2840  	if err := assertMaxHtlc(resCtx,
  2841  		maxValueInFlight, maxValueAcceptChannel); err != nil {
  2842  		t.Fatal(err)
  2843  	}
  2844  	// Give the message to Bob.
  2845  	bob.fundingMgr.ProcessFundingMsg(fundingCreated, alice)
  2846  
  2847  	// Finally, Bob should send the FundingSigned message.
  2848  	fundingSigned := assertFundingMsgSent(
  2849  		t, bob.msgChan, "FundingSigned",
  2850  	).(*lnwire.FundingSigned)
  2851  
  2852  	// Forward the signature to Alice.
  2853  	alice.fundingMgr.ProcessFundingMsg(fundingSigned, bob)
  2854  
  2855  	// After Alice processes the singleFundingSignComplete message, she will
  2856  	// broadcast the funding transaction to the network. We expect to get a
  2857  	// channel update saying the channel is pending.
  2858  	var pendingUpdate *lnrpc.OpenStatusUpdate
  2859  	select {
  2860  	case pendingUpdate = <-updateChan:
  2861  	case <-time.After(time.Second * 5):
  2862  		t.Fatalf("alice did not send OpenStatusUpdate_ChanPending")
  2863  	}
  2864  
  2865  	_, ok = pendingUpdate.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
  2866  	if !ok {
  2867  		t.Fatal("OpenStatusUpdate was not OpenStatusUpdate_ChanPending")
  2868  	}
  2869  
  2870  	// Wait for Alice to published the funding tx to the network.
  2871  	var fundingTx *wire.MsgTx
  2872  	select {
  2873  	case fundingTx = <-alice.publTxChan:
  2874  	case <-time.After(time.Second * 5):
  2875  		t.Fatalf("alice did not publish funding tx")
  2876  	}
  2877  
  2878  	// Notify that transaction was mined.
  2879  	alice.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2880  		Tx: fundingTx,
  2881  	}
  2882  	bob.mockNotifier.oneConfChannel <- &chainntnfs.TxConfirmation{
  2883  		Tx: fundingTx,
  2884  	}
  2885  
  2886  	// After the funding transaction is mined, Alice will send
  2887  	// fundingLocked to Bob.
  2888  	_ = assertFundingMsgSent(
  2889  		t, alice.msgChan, "FundingLocked",
  2890  	).(*lnwire.FundingLocked)
  2891  
  2892  	// And similarly Bob will send funding locked to Alice.
  2893  	_ = assertFundingMsgSent(
  2894  		t, bob.msgChan, "FundingLocked",
  2895  	).(*lnwire.FundingLocked)
  2896  
  2897  	// Make sure both fundingManagers send the expected channel
  2898  	// announcements.
  2899  	// Alice should advertise the default MinHTLC value of
  2900  	// 5, while bob should advertise the value minHtlc, since Alice
  2901  	// required him to use it.
  2902  	minHtlcArr := []lnwire.MilliAtom{5, minHtlcIn}
  2903  
  2904  	// For maxHltc Alice should advertise the default MaxHtlc value of
  2905  	// maxValueAcceptChannel, while bob should advertise the value
  2906  	// maxValueInFlight since Alice required him to use it.
  2907  	maxHtlcArr := []lnwire.MilliAtom{maxValueAcceptChannel, maxValueInFlight}
  2908  
  2909  	assertChannelAnnouncements(t, alice, bob, capacity, minHtlcArr, maxHtlcArr)
  2910  
  2911  	// The funding transaction is now confirmed, wait for the
  2912  	// OpenStatusUpdate_ChanOpen update
  2913  	waitForOpenUpdate(t, updateChan)
  2914  }
  2915  
  2916  // TestFundingManagerMaxPendingChannels checks that trying to open another
  2917  // channel with the same peer when MaxPending channels are pending fails.
  2918  func TestFundingManagerMaxPendingChannels(t *testing.T) {
  2919  	t.Parallel()
  2920  
  2921  	alice, bob := setupFundingManagers(
  2922  		t, func(cfg *Config) {
  2923  			cfg.MaxPendingChannels = maxPending
  2924  		},
  2925  	)
  2926  	defer tearDownFundingManagers(t, alice, bob)
  2927  
  2928  	// We confirm multiple txs concurrently, so use different confirmation
  2929  	// channels per tx to ensure there's no mix up in the readers.
  2930  	alice.mockNotifier.useByTxConfChannels = true
  2931  	bob.mockNotifier.useByTxConfChannels = true
  2932  
  2933  	// Create InitFundingMsg structs for maxPending+1 channels.
  2934  	var initReqs []*InitFundingMsg
  2935  	for i := 0; i < maxPending+1; i++ {
  2936  		updateChan := make(chan *lnrpc.OpenStatusUpdate)
  2937  		errChan := make(chan error, 1)
  2938  		initReq := &InitFundingMsg{
  2939  			Peer:            bob,
  2940  			TargetPubkey:    bob.privKey.PubKey(),
  2941  			ChainHash:       fundingNetParams.GenesisHash,
  2942  			LocalFundingAmt: 5000000,
  2943  			PushAmt:         lnwire.NewMAtomsFromAtoms(0),
  2944  			Private:         false,
  2945  			Updates:         updateChan,
  2946  			Err:             errChan,
  2947  		}
  2948  		initReqs = append(initReqs, initReq)
  2949  	}
  2950  
  2951  	// Kick of maxPending+1 funding workflows.
  2952  	var accepts []*lnwire.AcceptChannel
  2953  	var lastOpen *lnwire.OpenChannel
  2954  	for i, initReq := range initReqs {
  2955  		alice.fundingMgr.InitFundingWorkflow(initReq)
  2956  
  2957  		// Alice should have sent the OpenChannel message to Bob.
  2958  		var aliceMsg lnwire.Message
  2959  		select {
  2960  		case aliceMsg = <-alice.msgChan:
  2961  		case err := <-initReq.Err:
  2962  			t.Fatalf("error init funding workflow: %v", err)
  2963  		case <-time.After(time.Second * 5):
  2964  			t.Fatalf("alice did not send OpenChannel message")
  2965  		}
  2966  
  2967  		openChannelReq, ok := aliceMsg.(*lnwire.OpenChannel)
  2968  		if !ok {
  2969  			errorMsg, gotError := aliceMsg.(*lnwire.Error)
  2970  			if gotError {
  2971  				t.Fatalf("expected OpenChannel to be sent "+
  2972  					"from bob, instead got error: %v",
  2973  					errorMsg.Error())
  2974  			}
  2975  			t.Fatalf("expected OpenChannel to be sent from "+
  2976  				"alice, instead got %T", aliceMsg)
  2977  		}
  2978  
  2979  		// Let Bob handle the init message.
  2980  		bob.fundingMgr.ProcessFundingMsg(openChannelReq, alice)
  2981  
  2982  		// Bob should answer with an AcceptChannel message for the
  2983  		// first maxPending channels.
  2984  		if i < maxPending {
  2985  			acceptChannelResponse := assertFundingMsgSent(
  2986  				t, bob.msgChan, "AcceptChannel",
  2987  			).(*lnwire.AcceptChannel)
  2988  			accepts = append(accepts, acceptChannelResponse)
  2989  			continue
  2990  		}
  2991  
  2992  		// For the last channel, Bob should answer with an error.
  2993  		lastOpen = openChannelReq
  2994  		_ = assertFundingMsgSent(
  2995  			t, bob.msgChan, "Error",
  2996  		).(*lnwire.Error)
  2997  
  2998  	}
  2999  
  3000  	// Forward the responses to Alice.
  3001  	var signs []*lnwire.FundingSigned
  3002  	for _, accept := range accepts {
  3003  		alice.fundingMgr.ProcessFundingMsg(accept, bob)
  3004  
  3005  		// Alice responds with a FundingCreated message.
  3006  		fundingCreated := assertFundingMsgSent(
  3007  			t, alice.msgChan, "FundingCreated",
  3008  		).(*lnwire.FundingCreated)
  3009  
  3010  		// Give the message to Bob.
  3011  		bob.fundingMgr.ProcessFundingMsg(fundingCreated, alice)
  3012  
  3013  		// Finally, Bob should send the FundingSigned message.
  3014  		fundingSigned := assertFundingMsgSent(
  3015  			t, bob.msgChan, "FundingSigned",
  3016  		).(*lnwire.FundingSigned)
  3017  
  3018  		signs = append(signs, fundingSigned)
  3019  	}
  3020  
  3021  	// Sending another init request from Alice should still make Bob
  3022  	// respond with an error.
  3023  	bob.fundingMgr.ProcessFundingMsg(lastOpen, alice)
  3024  	_ = assertFundingMsgSent(
  3025  		t, bob.msgChan, "Error",
  3026  	).(*lnwire.Error)
  3027  
  3028  	// Give the FundingSigned messages to Alice.
  3029  	var txs []*wire.MsgTx
  3030  	for i, sign := range signs {
  3031  		alice.fundingMgr.ProcessFundingMsg(sign, bob)
  3032  
  3033  		// Alice should send a status update for each channel, and
  3034  		// publish a funding tx to the network.
  3035  		var pendingUpdate *lnrpc.OpenStatusUpdate
  3036  		select {
  3037  		case pendingUpdate = <-initReqs[i].Updates:
  3038  		case <-time.After(time.Second * 5):
  3039  			t.Fatalf("alice did not send OpenStatusUpdate_ChanPending")
  3040  		}
  3041  
  3042  		_, ok := pendingUpdate.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
  3043  		if !ok {
  3044  			t.Fatal("OpenStatusUpdate was not OpenStatusUpdate_ChanPending")
  3045  		}
  3046  
  3047  		select {
  3048  		case tx := <-alice.publTxChan:
  3049  			txs = append(txs, tx)
  3050  		case <-time.After(time.Second * 5):
  3051  			t.Fatalf("alice did not publish funding tx")
  3052  		}
  3053  	}
  3054  
  3055  	// Sending another init request from Alice should still make Bob
  3056  	// respond with an error, since the funding transactions are not
  3057  	// confirmed yet,
  3058  	bob.fundingMgr.ProcessFundingMsg(lastOpen, alice)
  3059  	_ = assertFundingMsgSent(
  3060  		t, bob.msgChan, "Error",
  3061  	).(*lnwire.Error)
  3062  
  3063  	// Notify that the transactions were mined.
  3064  	for i := 0; i < maxPending; i++ {
  3065  		alice.mockNotifier.confirmTx(t, txs[i])
  3066  		bob.mockNotifier.confirmTx(t, txs[i])
  3067  
  3068  		// Expect both to be sending FundingLocked.
  3069  		_ = assertFundingMsgSent(
  3070  			t, alice.msgChan, "FundingLocked",
  3071  		).(*lnwire.FundingLocked)
  3072  
  3073  		_ = assertFundingMsgSent(
  3074  			t, bob.msgChan, "FundingLocked",
  3075  		).(*lnwire.FundingLocked)
  3076  
  3077  	}
  3078  
  3079  	// Now opening another channel should work.
  3080  	bob.fundingMgr.ProcessFundingMsg(lastOpen, alice)
  3081  
  3082  	// Bob should answer with an AcceptChannel message.
  3083  	_ = assertFundingMsgSent(
  3084  		t, bob.msgChan, "AcceptChannel",
  3085  	).(*lnwire.AcceptChannel)
  3086  }
  3087  
  3088  // TestFundingManagerRejectPush checks behaviour of 'rejectpush'
  3089  // option, namely that non-zero incoming push amounts are disabled.
  3090  func TestFundingManagerRejectPush(t *testing.T) {
  3091  	t.Parallel()
  3092  
  3093  	// Enable 'rejectpush' option and initialize funding managers.
  3094  	alice, bob := setupFundingManagers(
  3095  		t, func(cfg *Config) {
  3096  			cfg.RejectPush = true
  3097  		},
  3098  	)
  3099  	defer tearDownFundingManagers(t, alice, bob)
  3100  
  3101  	// Create a funding request and start the workflow.
  3102  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  3103  	errChan := make(chan error, 1)
  3104  	initReq := &InitFundingMsg{
  3105  		Peer:            bob,
  3106  		TargetPubkey:    bob.privKey.PubKey(),
  3107  		ChainHash:       fundingNetParams.GenesisHash,
  3108  		LocalFundingAmt: 500000,
  3109  		PushAmt:         lnwire.NewMAtomsFromAtoms(10),
  3110  		Private:         true,
  3111  		Updates:         updateChan,
  3112  		Err:             errChan,
  3113  	}
  3114  
  3115  	alice.fundingMgr.InitFundingWorkflow(initReq)
  3116  
  3117  	// Alice should have sent the OpenChannel message to Bob.
  3118  	var aliceMsg lnwire.Message
  3119  	select {
  3120  	case aliceMsg = <-alice.msgChan:
  3121  	case err := <-initReq.Err:
  3122  		t.Fatalf("error init funding workflow: %v", err)
  3123  	case <-time.After(time.Second * 5):
  3124  		t.Fatalf("alice did not send OpenChannel message")
  3125  	}
  3126  
  3127  	openChannelReq, ok := aliceMsg.(*lnwire.OpenChannel)
  3128  	if !ok {
  3129  		errorMsg, gotError := aliceMsg.(*lnwire.Error)
  3130  		if gotError {
  3131  			t.Fatalf("expected OpenChannel to be sent "+
  3132  				"from bob, instead got error: %v",
  3133  				errorMsg.Error())
  3134  		}
  3135  		t.Fatalf("expected OpenChannel to be sent from "+
  3136  			"alice, instead got %T", aliceMsg)
  3137  	}
  3138  
  3139  	// Let Bob handle the init message.
  3140  	bob.fundingMgr.ProcessFundingMsg(openChannelReq, alice)
  3141  
  3142  	// Assert Bob responded with an ErrNonZeroPushAmount error.
  3143  	err := assertFundingMsgSent(t, bob.msgChan, "Error").(*lnwire.Error)
  3144  	if !strings.Contains(err.Error(), "non-zero push amounts are disabled") {
  3145  		t.Fatalf("expected ErrNonZeroPushAmount error, got \"%v\"",
  3146  			err.Error())
  3147  	}
  3148  }
  3149  
  3150  // TestFundingManagerMaxConfs ensures that we don't accept a funding proposal
  3151  // that proposes a MinAcceptDepth greater than the maximum number of
  3152  // confirmations we're willing to accept.
  3153  func TestFundingManagerMaxConfs(t *testing.T) {
  3154  	t.Parallel()
  3155  
  3156  	alice, bob := setupFundingManagers(t)
  3157  	defer tearDownFundingManagers(t, alice, bob)
  3158  
  3159  	// Create a funding request and start the workflow.
  3160  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  3161  	errChan := make(chan error, 1)
  3162  	initReq := &InitFundingMsg{
  3163  		Peer:            bob,
  3164  		TargetPubkey:    bob.privKey.PubKey(),
  3165  		ChainHash:       fundingNetParams.GenesisHash,
  3166  		LocalFundingAmt: 500000,
  3167  		PushAmt:         lnwire.NewMAtomsFromAtoms(10),
  3168  		Private:         false,
  3169  		Updates:         updateChan,
  3170  		Err:             errChan,
  3171  	}
  3172  
  3173  	alice.fundingMgr.InitFundingWorkflow(initReq)
  3174  
  3175  	// Alice should have sent the OpenChannel message to Bob.
  3176  	var aliceMsg lnwire.Message
  3177  	select {
  3178  	case aliceMsg = <-alice.msgChan:
  3179  	case err := <-initReq.Err:
  3180  		t.Fatalf("error init funding workflow: %v", err)
  3181  	case <-time.After(time.Second * 5):
  3182  		t.Fatalf("alice did not send OpenChannel message")
  3183  	}
  3184  
  3185  	openChannelReq, ok := aliceMsg.(*lnwire.OpenChannel)
  3186  	if !ok {
  3187  		errorMsg, gotError := aliceMsg.(*lnwire.Error)
  3188  		if gotError {
  3189  			t.Fatalf("expected OpenChannel to be sent "+
  3190  				"from bob, instead got error: %v",
  3191  				errorMsg.Error())
  3192  		}
  3193  		t.Fatalf("expected OpenChannel to be sent from "+
  3194  			"alice, instead got %T", aliceMsg)
  3195  	}
  3196  
  3197  	// Let Bob handle the init message.
  3198  	bob.fundingMgr.ProcessFundingMsg(openChannelReq, alice)
  3199  
  3200  	// Bob should answer with an AcceptChannel message.
  3201  	acceptChannelResponse := assertFundingMsgSent(
  3202  		t, bob.msgChan, "AcceptChannel",
  3203  	).(*lnwire.AcceptChannel)
  3204  
  3205  	// Modify the AcceptChannel message Bob is proposing to including a
  3206  	// MinAcceptDepth Alice won't be willing to accept.
  3207  	acceptChannelResponse.MinAcceptDepth = chainntnfs.MaxNumConfs + 1
  3208  
  3209  	alice.fundingMgr.ProcessFundingMsg(acceptChannelResponse, bob)
  3210  
  3211  	// Alice should respond back with an error indicating MinAcceptDepth is
  3212  	// too large.
  3213  	err := assertFundingMsgSent(t, alice.msgChan, "Error").(*lnwire.Error)
  3214  	if !strings.Contains(err.Error(), "minimum depth") {
  3215  		t.Fatalf("expected ErrNumConfsTooLarge, got \"%v\"",
  3216  			err.Error())
  3217  	}
  3218  }
  3219  
  3220  // TestFundingManagerFundAll tests that we can initiate a funding request to
  3221  // use the funds remaining in the wallet. This should produce a funding tx with
  3222  // no change output.
  3223  func TestFundingManagerFundAll(t *testing.T) {
  3224  	t.Parallel()
  3225  
  3226  	// We set up our mock wallet to control a list of UTXOs that sum to
  3227  	// less than the max channel size.
  3228  	allCoins := []*lnwallet.Utxo{
  3229  		{
  3230  			AddressType: lnwallet.PubKeyHash,
  3231  			Value: dcrutil.Amount(
  3232  				0.05 * dcrutil.AtomsPerCoin,
  3233  			),
  3234  			PkScript: mock.CoinPkScript,
  3235  			OutPoint: wire.OutPoint{
  3236  				Hash:  chainhash.Hash{},
  3237  				Index: 0,
  3238  			},
  3239  		},
  3240  		{
  3241  			AddressType: lnwallet.PubKeyHash,
  3242  			Value: dcrutil.Amount(
  3243  				0.06 * dcrutil.AtomsPerCoin,
  3244  			),
  3245  			PkScript: mock.CoinPkScript,
  3246  			OutPoint: wire.OutPoint{
  3247  				Hash:  chainhash.Hash{},
  3248  				Index: 1,
  3249  			},
  3250  		},
  3251  	}
  3252  
  3253  	tests := []struct {
  3254  		spendAmt dcrutil.Amount
  3255  		change   bool
  3256  	}{
  3257  		{
  3258  			// We will spend all the funds in the wallet, and
  3259  			// expects no change output.
  3260  			spendAmt: dcrutil.Amount(
  3261  				0.11 * dcrutil.AtomsPerCoin,
  3262  			),
  3263  			change: false,
  3264  		},
  3265  		{
  3266  			// We spend a little less than the funds in the wallet,
  3267  			// so a change output should be created.
  3268  			spendAmt: dcrutil.Amount(
  3269  				0.10 * dcrutil.AtomsPerCoin,
  3270  			),
  3271  			change: true,
  3272  		},
  3273  	}
  3274  
  3275  	for _, test := range tests {
  3276  		alice, bob := setupFundingManagers(t)
  3277  		defer tearDownFundingManagers(t, alice, bob)
  3278  
  3279  		alice.fundingMgr.cfg.Wallet.WalletController.(*mock.WalletController).Utxos = allCoins
  3280  
  3281  		// We will consume the channel updates as we go, so no
  3282  		// buffering is needed.
  3283  		updateChan := make(chan *lnrpc.OpenStatusUpdate)
  3284  
  3285  		// Initiate a fund channel, and inspect the funding tx.
  3286  		pushAmt := dcrutil.Amount(0)
  3287  		fundingTx := fundChannel(
  3288  			t, alice, bob, test.spendAmt, pushAmt, true, 1,
  3289  			updateChan, true,
  3290  		)
  3291  
  3292  		// Check whether the expected change output is present.
  3293  		if test.change && len(fundingTx.TxOut) != 2 {
  3294  			t.Fatalf("expected 2 outputs, had %v",
  3295  				len(fundingTx.TxOut))
  3296  		}
  3297  
  3298  		if !test.change && len(fundingTx.TxOut) != 1 {
  3299  			t.Fatalf("expected 1 output, had %v",
  3300  				len(fundingTx.TxOut))
  3301  		}
  3302  
  3303  		// Inputs should be all funds in the wallet.
  3304  		if len(fundingTx.TxIn) != len(allCoins) {
  3305  			t.Fatalf("Had %d inputs, expected %d",
  3306  				len(fundingTx.TxIn), len(allCoins))
  3307  		}
  3308  
  3309  		for i, txIn := range fundingTx.TxIn {
  3310  			if txIn.PreviousOutPoint != allCoins[i].OutPoint {
  3311  				t.Fatalf("expected outpoint to be %v, was %v",
  3312  					allCoins[i].OutPoint,
  3313  					txIn.PreviousOutPoint)
  3314  			}
  3315  		}
  3316  	}
  3317  }
  3318  
  3319  // TestGetUpfrontShutdown tests different combinations of inputs for getting a
  3320  // shutdown script. It varies whether the peer has the feature set, whether
  3321  // the user has provided a script and our local configuration to test that
  3322  // GetUpfrontShutdownScript returns the expected outcome.
  3323  func TestGetUpfrontShutdownScript(t *testing.T) {
  3324  	upfrontScript := []byte("upfront script")
  3325  	generatedScript := []byte("generated script")
  3326  
  3327  	getScript := func() (lnwire.DeliveryAddress, error) {
  3328  		return generatedScript, nil
  3329  	}
  3330  
  3331  	tests := []struct {
  3332  		name           string
  3333  		getScript      func() (lnwire.DeliveryAddress, error)
  3334  		upfrontScript  lnwire.DeliveryAddress
  3335  		peerEnabled    bool
  3336  		localEnabled   bool
  3337  		expectedScript lnwire.DeliveryAddress
  3338  		expectedErr    error
  3339  	}{
  3340  		{
  3341  			name:      "peer disabled, no shutdown",
  3342  			getScript: getScript,
  3343  		},
  3344  		{
  3345  			name:          "peer disabled, upfront provided",
  3346  			upfrontScript: upfrontScript,
  3347  			expectedErr:   errUpfrontShutdownScriptNotSupported,
  3348  		},
  3349  		{
  3350  			name:           "peer enabled, upfront provided",
  3351  			upfrontScript:  upfrontScript,
  3352  			peerEnabled:    true,
  3353  			expectedScript: upfrontScript,
  3354  		},
  3355  		{
  3356  			name:        "peer enabled, local disabled",
  3357  			peerEnabled: true,
  3358  		},
  3359  		{
  3360  			name:           "local enabled, no upfront script",
  3361  			getScript:      getScript,
  3362  			peerEnabled:    true,
  3363  			localEnabled:   true,
  3364  			expectedScript: generatedScript,
  3365  		},
  3366  		{
  3367  			name:           "local enabled, upfront script",
  3368  			peerEnabled:    true,
  3369  			upfrontScript:  upfrontScript,
  3370  			localEnabled:   true,
  3371  			expectedScript: upfrontScript,
  3372  		},
  3373  	}
  3374  
  3375  	for _, test := range tests {
  3376  		test := test
  3377  
  3378  		t.Run(test.name, func(t *testing.T) {
  3379  			var mockPeer testNode
  3380  
  3381  			// If the remote peer in the test should support upfront shutdown,
  3382  			// add the feature bit.
  3383  			if test.peerEnabled {
  3384  				mockPeer.remoteFeatures = []lnwire.FeatureBit{
  3385  					lnwire.UpfrontShutdownScriptOptional,
  3386  				}
  3387  			}
  3388  
  3389  			addr, err := getUpfrontShutdownScript(
  3390  				test.localEnabled, &mockPeer, test.upfrontScript,
  3391  				test.getScript,
  3392  			)
  3393  			if err != test.expectedErr {
  3394  				t.Fatalf("got: %v, expected error: %v", err, test.expectedErr)
  3395  			}
  3396  
  3397  			if !bytes.Equal(addr, test.expectedScript) {
  3398  				t.Fatalf("expected address: %x, got: %x",
  3399  					test.expectedScript, addr)
  3400  			}
  3401  
  3402  		})
  3403  	}
  3404  }
  3405  
  3406  func expectOpenChannelMsg(t *testing.T, msgChan chan lnwire.Message) *lnwire.OpenChannel {
  3407  	t.Helper()
  3408  
  3409  	var msg lnwire.Message
  3410  	select {
  3411  	case msg = <-msgChan:
  3412  	case <-time.After(time.Second * 5):
  3413  		t.Fatalf("node did not send OpenChannel message")
  3414  	}
  3415  
  3416  	openChannelReq, ok := msg.(*lnwire.OpenChannel)
  3417  	if !ok {
  3418  		errorMsg, gotError := msg.(*lnwire.Error)
  3419  		if gotError {
  3420  			t.Fatalf("expected OpenChannel to be sent "+
  3421  				"from bob, instead got error: %v",
  3422  				errorMsg.Error())
  3423  		}
  3424  		t.Fatalf("expected OpenChannel to be sent, instead got %T",
  3425  			msg)
  3426  	}
  3427  
  3428  	return openChannelReq
  3429  }
  3430  
  3431  func TestMaxChannelSizeConfig(t *testing.T) {
  3432  	t.Parallel()
  3433  
  3434  	// Create a set of funding managers that will reject wumbo
  3435  	// channels but set --maxchansize explicitly lower than soft-limit.
  3436  	// Verify that wumbo rejecting funding managers will respect
  3437  	// --maxchansize below 1073741823 atoms (MaxFundingAmount) limit.
  3438  	alice, bob := setupFundingManagers(t, func(cfg *Config) {
  3439  		cfg.NoWumboChans = true
  3440  		cfg.MaxChanSize = MaxFundingAmount - 1
  3441  	})
  3442  
  3443  	// Attempt to create a channel above the limit
  3444  	// imposed by --maxchansize, which should be rejected.
  3445  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  3446  	errChan := make(chan error, 1)
  3447  	initReq := &InitFundingMsg{
  3448  		Peer:            bob,
  3449  		TargetPubkey:    bob.privKey.PubKey(),
  3450  		ChainHash:       fundingNetParams.GenesisHash,
  3451  		LocalFundingAmt: MaxDecredFundingAmount,
  3452  		PushAmt:         lnwire.NewMAtomsFromAtoms(0),
  3453  		Private:         false,
  3454  		Updates:         updateChan,
  3455  		Err:             errChan,
  3456  	}
  3457  
  3458  	// After processing the funding open message, bob should respond with
  3459  	// an error rejecting the channel that exceeds size limit.
  3460  	alice.fundingMgr.InitFundingWorkflow(initReq)
  3461  	openChanMsg := expectOpenChannelMsg(t, alice.msgChan)
  3462  	bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
  3463  	assertErrorSent(t, bob.msgChan)
  3464  
  3465  	// Create a set of funding managers that will reject wumbo
  3466  	// channels but set --maxchansize explicitly higher than soft-limit
  3467  	// A --maxchansize greater than this limit should have no effect.
  3468  	tearDownFundingManagers(t, alice, bob)
  3469  	alice, bob = setupFundingManagers(t, func(cfg *Config) {
  3470  		cfg.NoWumboChans = true
  3471  		cfg.MaxChanSize = MaxFundingAmount + 1
  3472  	})
  3473  
  3474  	// Reset the Peer to the newly created one.
  3475  	initReq.Peer = bob
  3476  
  3477  	// We expect Bob to respond with an Accept channel message.
  3478  	alice.fundingMgr.InitFundingWorkflow(initReq)
  3479  	openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
  3480  	bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
  3481  	assertFundingMsgSent(t, bob.msgChan, "AcceptChannel")
  3482  
  3483  	// Verify that wumbo accepting funding managers will respect --maxchansize
  3484  	// Create the funding managers, this time allowing
  3485  	// wumbo channels but setting --maxchansize explicitly.
  3486  	tearDownFundingManagers(t, alice, bob)
  3487  	alice, bob = setupFundingManagers(t, func(cfg *Config) {
  3488  		cfg.NoWumboChans = false
  3489  		cfg.MaxChanSize = dcrutil.Amount(11e8)
  3490  	})
  3491  
  3492  	// Reset the Peer to the newly created one.
  3493  	initReq.Peer = bob
  3494  
  3495  	// Attempt to create a channel above the limit
  3496  	// imposed by --maxchansize, which should be rejected.
  3497  	initReq.LocalFundingAmt = dcrutil.Amount(11e8) + 1
  3498  
  3499  	// After processing the funding open message, bob should respond with
  3500  	// an error rejecting the channel that exceeds size limit.
  3501  	alice.fundingMgr.InitFundingWorkflow(initReq)
  3502  	openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
  3503  	bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
  3504  	assertErrorSent(t, bob.msgChan)
  3505  }
  3506  
  3507  // TestWumboChannelConfig tests that the funding manager will respect the wumbo
  3508  // channel config param when creating or accepting new channels.
  3509  func TestWumboChannelConfig(t *testing.T) {
  3510  	t.Parallel()
  3511  
  3512  	// First we'll create a set of funding managers that will reject wumbo
  3513  	// channels.
  3514  	alice, bob := setupFundingManagers(t, func(cfg *Config) {
  3515  		cfg.NoWumboChans = true
  3516  	})
  3517  
  3518  	// If we attempt to initiate a new funding open request to Alice,
  3519  	// that's below the wumbo channel mark, we should be able to start the
  3520  	// funding process w/o issue.
  3521  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  3522  	errChan := make(chan error, 1)
  3523  	initReq := &InitFundingMsg{
  3524  		Peer:            bob,
  3525  		TargetPubkey:    bob.privKey.PubKey(),
  3526  		ChainHash:       fundingNetParams.GenesisHash,
  3527  		LocalFundingAmt: MaxDecredFundingAmount,
  3528  		PushAmt:         lnwire.NewMAtomsFromAtoms(0),
  3529  		Private:         false,
  3530  		Updates:         updateChan,
  3531  		Err:             errChan,
  3532  	}
  3533  
  3534  	// We expect Bob to respond with an Accept channel message.
  3535  	alice.fundingMgr.InitFundingWorkflow(initReq)
  3536  	openChanMsg := expectOpenChannelMsg(t, alice.msgChan)
  3537  	bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
  3538  	assertFundingMsgSent(t, bob.msgChan, "AcceptChannel")
  3539  
  3540  	// We'll now attempt to create a channel above the wumbo mark, which
  3541  	// should be rejected.
  3542  	initReq.LocalFundingAmt = dcrutil.AtomsPerCoin
  3543  
  3544  	// After processing the funding open message, bob should respond with
  3545  	// an error rejecting the channel.
  3546  	alice.fundingMgr.InitFundingWorkflow(initReq)
  3547  	openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
  3548  	bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
  3549  	assertErrorSent(t, bob.msgChan)
  3550  
  3551  	// Next, we'll re-create the funding managers, but this time allowing
  3552  	// wumbo channels explicitly.
  3553  	tearDownFundingManagers(t, alice, bob)
  3554  	alice, bob = setupFundingManagers(t, func(cfg *Config) {
  3555  		cfg.NoWumboChans = false
  3556  		cfg.MaxChanSize = MaxDecredFundingAmountWumbo
  3557  	})
  3558  
  3559  	// Reset the Peer to the newly created one.
  3560  	initReq.Peer = bob
  3561  
  3562  	// We should now be able to initiate a wumbo channel funding w/o any
  3563  	// issues.
  3564  	alice.fundingMgr.InitFundingWorkflow(initReq)
  3565  	openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
  3566  	bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
  3567  	assertFundingMsgSent(t, bob.msgChan, "AcceptChannel")
  3568  }
  3569  
  3570  // TestFundingManagerUpfrontShutdown asserts that we'll properly fail out if
  3571  // an invalid upfront shutdown script is sent in the open_channel message.
  3572  // Since both the open_channel and accept_message logic validate the script
  3573  // using the same validation function, it suffices to just check the
  3574  // open_channel case.
  3575  func TestFundingManagerUpfrontShutdown(t *testing.T) {
  3576  	t.Parallel()
  3577  
  3578  	tests := []struct {
  3579  		name      string
  3580  		pkscript  []byte
  3581  		expectErr bool
  3582  	}{
  3583  		{
  3584  			name: "p2pk script",
  3585  			pkscript: []byte("\x21\x02\xd3\x00\x50\x2f\x61\x15" +
  3586  				"\x0d\x58\x0a\x42\xa0\x99\x63\xe3\x47\xa2" +
  3587  				"\xad\x3c\xe5\x1f\x11\x96\x0d\x35\x8d\xf8" +
  3588  				"\xf3\x94\xf9\x67\x2a\x67\xac"),
  3589  			expectErr: true,
  3590  		},
  3591  		{
  3592  			name: "op return script",
  3593  			pkscript: []byte("\x6a\x24\xaa\x21\xa9\xed\x18\xa9" +
  3594  				"\x93\x58\x94\xbd\x48\x9b\xeb\x87\x66\x13" +
  3595  				"\x60\xbc\x80\x92\xab\xf6\xdd\xe9\x1e\x82" +
  3596  				"\x0c\x7d\x91\x89\x9d\x0a\x02\x34\x14\x3f"),
  3597  			expectErr: true,
  3598  		},
  3599  		{
  3600  			name: "standard (non-p2sh) 2-of-3 multisig",
  3601  			pkscript: []byte("\x51\x41\x04\xcc\x71\xeb\x30\xd6" +
  3602  				"\x53\xc0\xc3\x16\x39\x90\xc4\x7b\x97\x6f" +
  3603  				"\x3f\xb3\xf3\x7c\xcc\xdc\xbe\xdb\x16\x9a" +
  3604  				"\x1d\xfe\xf5\x8b\xbf\xbf\xaf\xf7\xd8\xa4" +
  3605  				"\x73\xe7\xe2\xe6\xd3\x17\xb8\x7b\xaf\xe8" +
  3606  				"\xbd\xe9\x7e\x3c\xf8\xf0\x65\xde\xc0\x22" +
  3607  				"\xb5\x1d\x11\xfc\xdd\x0d\x34\x8a\xc4\x41" +
  3608  				"\x04\x61\xcb\xdc\xc5\x40\x9f\xb4\xb4\xd4" +
  3609  				"\x2b\x51\xd3\x33\x81\x35\x4d\x80\xe5\x50" +
  3610  				"\x07\x8c\xb5\x32\xa3\x4b\xfa\x2f\xcf\xde" +
  3611  				"\xb7\xd7\x65\x19\xae\xcc\x62\x77\x0f\x5b" +
  3612  				"\x0e\x4e\xf8\x55\x19\x46\xd8\xa5\x40\x91" +
  3613  				"\x1a\xbe\x3e\x78\x54\xa2\x6f\x39\xf5\x8b" +
  3614  				"\x25\xc1\x53\x42\xaf\x52\xae"),
  3615  			expectErr: true,
  3616  		},
  3617  		{
  3618  			name:      "nonstandard script",
  3619  			pkscript:  []byte("\x99"),
  3620  			expectErr: true,
  3621  		},
  3622  		{
  3623  			name: "p2sh script",
  3624  			pkscript: []byte("\xa9\x14\xfe\x44\x10\x65\xb6\x53" +
  3625  				"\x22\x31\xde\x2f\xac\x56\x31\x52\x20\x5e" +
  3626  				"\xc4\xf5\x9c\x74\x87"),
  3627  			expectErr: false,
  3628  		},
  3629  		{
  3630  			name: "p2pkh script",
  3631  			pkscript: []byte("\x76\xa9\x14\x64\x1a\xd5\x05\x1e" +
  3632  				"\xdd\x97\x02\x9a\x00\x3f\xe9\xef\xb2\x93" +
  3633  				"\x59\xfc\xee\x40\x9d\x88\xac"),
  3634  			expectErr: false,
  3635  		},
  3636  	}
  3637  
  3638  	for _, test := range tests {
  3639  		test := test
  3640  
  3641  		t.Run(test.name, func(t *testing.T) {
  3642  			testUpfrontFailure(t, test.pkscript, test.expectErr)
  3643  		})
  3644  	}
  3645  }
  3646  
  3647  func testUpfrontFailure(t *testing.T, pkscript []byte, expectErr bool) {
  3648  	alice, bob := setupFundingManagers(t)
  3649  	defer tearDownFundingManagers(t, alice, bob)
  3650  
  3651  	errChan := make(chan error, 1)
  3652  	updateChan := make(chan *lnrpc.OpenStatusUpdate)
  3653  
  3654  	fundingAmt := dcrutil.Amount(500000)
  3655  	pushAmt := lnwire.NewMAtomsFromAtoms(dcrutil.Amount(0))
  3656  
  3657  	initReq := &InitFundingMsg{
  3658  		Peer:            alice,
  3659  		TargetPubkey:    alice.privKey.PubKey(),
  3660  		ChainHash:       fundingNetParams.GenesisHash,
  3661  		SubtractFees:    false,
  3662  		LocalFundingAmt: fundingAmt,
  3663  		PushAmt:         pushAmt,
  3664  		FundingFeePerKB: 1000,
  3665  		Private:         false,
  3666  		Updates:         updateChan,
  3667  		Err:             errChan,
  3668  	}
  3669  	bob.fundingMgr.InitFundingWorkflow(initReq)
  3670  
  3671  	// Bob should send an open_channel message to Alice.
  3672  	var bobMsg lnwire.Message
  3673  	select {
  3674  	case bobMsg = <-bob.msgChan:
  3675  	case err := <-initReq.Err:
  3676  		t.Fatalf("received unexpected error: %v", err)
  3677  	case <-time.After(time.Second * 5):
  3678  		t.Fatalf("timed out waiting for bob's message")
  3679  	}
  3680  
  3681  	bobOpenChan, ok := bobMsg.(*lnwire.OpenChannel)
  3682  	require.True(t, ok, "did not receive OpenChannel")
  3683  
  3684  	// Set the UpfrontShutdownScript in OpenChannel.
  3685  	bobOpenChan.UpfrontShutdownScript = lnwire.DeliveryAddress(pkscript)
  3686  
  3687  	// Send the OpenChannel message to Alice now. If we expected an error,
  3688  	// check that we received it.
  3689  	alice.fundingMgr.ProcessFundingMsg(bobOpenChan, bob)
  3690  
  3691  	var aliceMsg lnwire.Message
  3692  	select {
  3693  	case aliceMsg = <-alice.msgChan:
  3694  	case <-time.After(time.Second * 5):
  3695  		t.Fatalf("timed out waiting for alice's message")
  3696  	}
  3697  
  3698  	if expectErr {
  3699  		// Assert that Error was received.
  3700  		_, ok = aliceMsg.(*lnwire.Error)
  3701  		require.True(t, ok, "did not receive Error")
  3702  	} else {
  3703  		// Assert that AcceptChannel was received.
  3704  		_, ok = aliceMsg.(*lnwire.AcceptChannel)
  3705  		require.True(t, ok, "did not receive AcceptChannel")
  3706  	}
  3707  }