funding: code style cleanup for the funding package

This commit is contained in:
Slyghtning 2023-01-11 15:39:03 +10:30
parent b1645ec46d
commit b47cf7e871
4 changed files with 240 additions and 134 deletions

View File

@ -134,7 +134,8 @@ type Wallet interface {
PsbtFundingFinalize([32]byte, *psbt.Packet, *wire.MsgTx) error PsbtFundingFinalize([32]byte, *psbt.Packet, *wire.MsgTx) error
// PublishTransaction performs cursory validation (dust checks, etc), // PublishTransaction performs cursory validation (dust checks, etc),
// then finally broadcasts the passed transaction to the Bitcoin network. // then finally broadcasts the passed transaction to the Bitcoin
// network.
PublishTransaction(*wire.MsgTx, string) error PublishTransaction(*wire.MsgTx, string) error
// CancelFundingIntent allows a caller to cancel a previously registered // CancelFundingIntent allows a caller to cancel a previously registered

View File

@ -34,7 +34,10 @@ func negotiateCommitmentType(channelType *lnwire.ChannelType, local,
if channelType != nil { if channelType != nil {
// If the peer does know explicit negotiation, let's attempt // If the peer does know explicit negotiation, let's attempt
// that now. // that now.
if hasFeatures(local, remote, lnwire.ExplicitChannelTypeOptional) { if hasFeatures(
local, remote, lnwire.ExplicitChannelTypeOptional,
) {
chanType, err := explicitNegotiateCommitmentType( chanType, err := explicitNegotiateCommitmentType(
*channelType, local, remote, *channelType, local, remote,
) )
@ -233,7 +236,8 @@ func explicitNegotiateCommitmentType(channelType lnwire.ChannelType, local,
// implicitly by choosing the latest type supported by the local and remote // implicitly by choosing the latest type supported by the local and remote
// features. // features.
func implicitNegotiateCommitmentType(local, func implicitNegotiateCommitmentType(local,
remote *lnwire.FeatureVector) (*lnwire.ChannelType, lnwallet.CommitmentType) { remote *lnwire.FeatureVector) (*lnwire.ChannelType,
lnwallet.CommitmentType) {
// If both peers are signalling support for anchor commitments with // If both peers are signalling support for anchor commitments with
// zero-fee HTLC transactions, we'll use this type. // zero-fee HTLC transactions, we'll use this type.

View File

@ -71,12 +71,12 @@ const (
// to use for its commitment transaction. // to use for its commitment transaction.
MaxBtcRemoteDelay uint16 = 2016 MaxBtcRemoteDelay uint16 = 2016
// MinLtcRemoteDelay is the minimum Litecoin CSV delay we will require the // MinLtcRemoteDelay is the minimum Litecoin CSV delay we will require
// remote to use for its commitment transaction. // the remote to use for its commitment transaction.
MinLtcRemoteDelay uint16 = 576 MinLtcRemoteDelay uint16 = 576
// MaxLtcRemoteDelay is the maximum Litecoin CSV delay we will require the // MaxLtcRemoteDelay is the maximum Litecoin CSV delay we will require
// remote to use for its commitment transaction. // the remote to use for its commitment transaction.
MaxLtcRemoteDelay uint16 = 8064 MaxLtcRemoteDelay uint16 = 8064
// MinChanFundingSize is the smallest channel that we'll allow to be // MinChanFundingSize is the smallest channel that we'll allow to be
@ -98,7 +98,8 @@ const (
// MaxLtcFundingAmount is a soft-limit of the maximum channel size // MaxLtcFundingAmount is a soft-limit of the maximum channel size
// currently accepted on the Litecoin chain within the Lightning // currently accepted on the Litecoin chain within the Lightning
// Protocol. // Protocol.
MaxLtcFundingAmount = MaxBtcFundingAmount * chainreg.BtcToLtcConversionRate MaxLtcFundingAmount = MaxBtcFundingAmount *
chainreg.BtcToLtcConversionRate
// TODO(roasbeef): tune. // TODO(roasbeef): tune.
msgBufferSize = 50 msgBufferSize = 50
@ -122,10 +123,11 @@ var (
ErrConfirmationTimeout = errors.New("timeout waiting for funding " + ErrConfirmationTimeout = errors.New("timeout waiting for funding " +
"confirmation") "confirmation")
// errUpfrontShutdownScriptNotSupported is returned if an upfront shutdown // errUpfrontShutdownScriptNotSupported is returned if an upfront
// script is set for a peer that does not support the feature bit. // shutdown script is set for a peer that does not support the feature
errUpfrontShutdownScriptNotSupported = errors.New("peer does not support" + // bit.
"option upfront shutdown script") errUpfrontShutdownScriptNotSupported = errors.New("peer does not " +
"support option upfront shutdown script")
zeroID [32]byte zeroID [32]byte
) )
@ -169,7 +171,8 @@ type reservationWithCtx struct {
err chan error err chan error
} }
// isLocked checks the reservation's timestamp to determine whether it is locked. // isLocked checks the reservation's timestamp to determine whether it is
// locked.
func (r *reservationWithCtx) isLocked() bool { func (r *reservationWithCtx) isLocked() bool {
r.updateMtx.RLock() r.updateMtx.RLock()
defer r.updateMtx.RUnlock() defer r.updateMtx.RUnlock()
@ -411,7 +414,8 @@ type Config struct {
// channel capacity and dust limit, will return an appropriate amount // channel capacity and dust limit, will return an appropriate amount
// for the remote peer's required channel reserve that is to be adhered // for the remote peer's required channel reserve that is to be adhered
// to at all times. // to at all times.
RequiredRemoteChanReserve func(capacity, dustLimit btcutil.Amount) btcutil.Amount RequiredRemoteChanReserve func(capacity,
dustLimit btcutil.Amount) btcutil.Amount
// RequiredRemoteMaxValue is a function closure that, given the channel // RequiredRemoteMaxValue is a function closure that, given the channel
// capacity, returns the amount of MilliSatoshis that our remote peer // capacity, returns the amount of MilliSatoshis that our remote peer
@ -471,13 +475,14 @@ type Config struct {
NotifyOpenChannelEvent func(wire.OutPoint) NotifyOpenChannelEvent func(wire.OutPoint)
// OpenChannelPredicate is a predicate on the lnwire.OpenChannel message // OpenChannelPredicate is a predicate on the lnwire.OpenChannel message
// and on the requesting node's public key that returns a bool which tells // and on the requesting node's public key that returns a bool which
// the funding manager whether or not to accept the channel. // tells the funding manager whether or not to accept the channel.
OpenChannelPredicate chanacceptor.ChannelAcceptor OpenChannelPredicate chanacceptor.ChannelAcceptor
// NotifyPendingOpenChannelEvent informs the ChannelNotifier when channels // NotifyPendingOpenChannelEvent informs the ChannelNotifier when
// enter a pending state. // channels enter a pending state.
NotifyPendingOpenChannelEvent func(wire.OutPoint, *channeldb.OpenChannel) NotifyPendingOpenChannelEvent func(wire.OutPoint,
*channeldb.OpenChannel)
// EnableUpfrontShutdown specifies whether the upfront shutdown script // EnableUpfrontShutdown specifies whether the upfront shutdown script
// is enabled. // is enabled.
@ -667,7 +672,8 @@ func (f *Manager) start() error {
// channel that we initiated. No error will be returned // channel that we initiated. No error will be returned
// if the transaction already has been broadcast. // if the transaction already has been broadcast.
chanType := channel.ChanType chanType := channel.ChanType
if chanType.IsSingleFunder() && chanType.HasFundingTx() && if chanType.IsSingleFunder() &&
chanType.HasFundingTx() &&
channel.IsInitiator { channel.IsInitiator {
f.rebroadcastFundingTx(channel) f.rebroadcastFundingTx(channel)
@ -809,7 +815,9 @@ func (f *Manager) failFundingFlow(peer lnpeer.Peer, tempChanID [32]byte,
log.Debugf("Failing funding flow for pending_id=%x: %v", log.Debugf("Failing funding flow for pending_id=%x: %v",
tempChanID, fundingErr) tempChanID, fundingErr)
ctx, err := f.cancelReservationCtx(peer.IdentityKey(), tempChanID, false) ctx, err := f.cancelReservationCtx(
peer.IdentityKey(), tempChanID, false,
)
if err != nil { if err != nil {
log.Errorf("unable to cancel reservation: %v", err) log.Errorf("unable to cancel reservation: %v", err)
} }
@ -1357,8 +1365,8 @@ func (f *Manager) handleFundingOpen(peer lnpeer.Peer,
return return
} }
// Send the OpenChannel request to the ChannelAcceptor to determine whether // Send the OpenChannel request to the ChannelAcceptor to determine
// this node will accept the channel. // whether this node will accept the channel.
chanReq := &chanacceptor.ChannelAcceptRequest{ chanReq := &chanacceptor.ChannelAcceptRequest{
Node: peer.IdentityKey(), Node: peer.IdentityKey(),
OpenChanMsg: msg, OpenChanMsg: msg,
@ -1418,8 +1426,8 @@ func (f *Manager) handleFundingOpen(peer lnpeer.Peer,
) )
if wasExplicit { if wasExplicit {
// Only echo back a channel type in AcceptChannel if we // Only echo back a channel type in AcceptChannel if we actually
// actually used explicit negotiation above. // used explicit negotiation above.
chanTypeFeatureBits = msg.ChannelType chanTypeFeatureBits = msg.ChannelType
// Check if the channel type includes the zero-conf or // Check if the channel type includes the zero-conf or
@ -1548,10 +1556,10 @@ func (f *Manager) handleFundingOpen(peer lnpeer.Peer,
return return
} }
// Check whether the peer supports upfront shutdown, and get a new wallet // Check whether the peer supports upfront shutdown, and get a new
// address if our node is configured to set shutdown addresses by default. // wallet address if our node is configured to set shutdown addresses by
// We use the upfront shutdown script provided by our channel acceptor // default. We use the upfront shutdown script provided by our channel
// (if any) in lieu of user input. // acceptor (if any) in lieu of user input.
shutdown, err := getUpfrontShutdownScript( shutdown, err := getUpfrontShutdownScript(
f.cfg.EnableUpfrontShutdown, peer, acceptorResp.UpfrontShutdown, f.cfg.EnableUpfrontShutdown, peer, acceptorResp.UpfrontShutdown,
f.selectShutdownScript, f.selectShutdownScript,
@ -1579,17 +1587,21 @@ func (f *Manager) handleFundingOpen(peer lnpeer.Peer,
// validate the proposed LeaseExpiry against what was registered // validate the proposed LeaseExpiry against what was registered
// in our shim. // in our shim.
if reservation.LeaseExpiry() != 0 { if reservation.LeaseExpiry() != 0 {
if uint32(*msg.LeaseExpiry) != reservation.LeaseExpiry() { if uint32(*msg.LeaseExpiry) !=
reservation.LeaseExpiry() {
err := errors.New("lease expiry mismatch") err := errors.New("lease expiry mismatch")
f.failFundingFlow(peer, msg.PendingChannelID, err) f.failFundingFlow(
peer, msg.PendingChannelID, err,
)
return return
} }
} }
} }
log.Infof("Requiring %v confirmations for pendingChan(%x): "+ log.Infof("Requiring %v confirmations for pendingChan(%x): "+
"amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x", numConfsReq, "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
msg.PendingChannelID, amt, msg.PushAmount, numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
commitType, msg.UpfrontShutdownScript) commitType, msg.UpfrontShutdownScript)
// Generate our required constraints for the remote party, using the // Generate our required constraints for the remote party, using the
@ -1771,7 +1783,8 @@ func (f *Manager) handleFundingAccept(peer lnpeer.Peer,
// We'll want to quickly check that the ChannelType echoed by // We'll want to quickly check that the ChannelType echoed by
// the channel request recipient matches what we proposed. // the channel request recipient matches what we proposed.
if msg.ChannelType == nil { if msg.ChannelType == nil {
err := errors.New("explicit channel type not echoed back") err := errors.New("explicit channel type not echoed " +
"back")
f.failFundingFlow(peer, msg.PendingChannelID, err) f.failFundingFlow(peer, msg.PendingChannelID, err)
return return
} }
@ -1787,13 +1800,20 @@ func (f *Manager) handleFundingAccept(peer lnpeer.Peer,
// be set. // be set.
if resCtx.reservation.LeaseExpiry() != 0 { if resCtx.reservation.LeaseExpiry() != 0 {
if msg.LeaseExpiry == nil { if msg.LeaseExpiry == nil {
err := errors.New("lease expiry not echoed back") err := errors.New("lease expiry not echoed " +
f.failFundingFlow(peer, msg.PendingChannelID, err) "back")
f.failFundingFlow(
peer, msg.PendingChannelID, err,
)
return return
} }
if uint32(*msg.LeaseExpiry) != resCtx.reservation.LeaseExpiry() { if uint32(*msg.LeaseExpiry) !=
resCtx.reservation.LeaseExpiry() {
err := errors.New("lease expiry mismatch") err := errors.New("lease expiry mismatch")
f.failFundingFlow(peer, msg.PendingChannelID, err) f.failFundingFlow(
peer, msg.PendingChannelID, err,
)
return return
} }
} }
@ -1957,7 +1977,8 @@ func (f *Manager) handleFundingAccept(peer lnpeer.Peer,
} }
log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+ log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
"csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth, msg.CsvDelay) "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
msg.CsvDelay)
log.Debugf("Remote party accepted commitment constraints: %v", log.Debugf("Remote party accepted commitment constraints: %v",
spew.Sdump(remoteContribution.ChannelConfig.ChannelConstraints)) spew.Sdump(remoteContribution.ChannelConfig.ChannelConstraints))
@ -2804,16 +2825,16 @@ func (f *Manager) handleFundingConfirmation(
&fundingPoint, markedOpen, &confChannel.shortChanID, &fundingPoint, markedOpen, &confChannel.shortChanID,
) )
if err != nil { if err != nil {
return fmt.Errorf("error setting channel state to markedOpen: %v", return fmt.Errorf("error setting channel state to "+
err) "markedOpen: %v", err)
} }
// Now that the channel has been fully confirmed and we successfully // Now that the channel has been fully confirmed and we successfully
// saved the opening state, we'll mark it as open within the database. // saved the opening state, we'll mark it as open within the database.
err = completeChan.MarkAsOpen(confChannel.shortChanID) err = completeChan.MarkAsOpen(confChannel.shortChanID)
if err != nil { if err != nil {
return fmt.Errorf("error setting channel pending flag to false: "+ return fmt.Errorf("error setting channel pending flag to "+
"%v", err) "false: %v", err)
} }
// Update the confirmed funding transaction label. // Update the confirmed funding transaction label.
@ -3151,8 +3172,8 @@ func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
fundingScript, err := makeFundingScript(completeChan) fundingScript, err := makeFundingScript(completeChan)
if err != nil { if err != nil {
return fmt.Errorf("unable to create funding script for "+ return fmt.Errorf("unable to create funding script "+
"ChannelPoint(%v): %v", "for ChannelPoint(%v): %v",
completeChan.FundingOutpoint, err) completeChan.FundingOutpoint, err)
} }
@ -3236,7 +3257,8 @@ func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
*shortChanID, chanID, *shortChanID, chanID,
) )
if err != nil { if err != nil {
return fmt.Errorf("channel announcement failed: %v", err) return fmt.Errorf("channel announcement failed: %w",
err)
} }
log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+ log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+

View File

@ -162,7 +162,9 @@ type mockNotifier struct {
} }
func (m *mockNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash, func (m *mockNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
_ []byte, numConfs, heightHint uint32, opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) { _ []byte, numConfs, heightHint uint32,
opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent,
error) {
if numConfs == 6 { if numConfs == 6 {
return &chainntnfs.ConfirmationEvent{ return &chainntnfs.ConfirmationEvent{
@ -387,7 +389,8 @@ func createTestFundingManager(t *testing.T, privKey *btcec.PrivateKey,
evt := &mockChanEvent{ evt := &mockChanEvent{
openEvent: make(chan wire.OutPoint, maxPending), openEvent: make(chan wire.OutPoint, maxPending),
pendingOpenEvent: make( pendingOpenEvent: make(
chan channelnotifier.PendingOpenChannelEvent, maxPending, chan channelnotifier.PendingOpenChannelEvent,
maxPending,
), ),
} }
@ -436,7 +439,9 @@ func createTestFundingManager(t *testing.T, privKey *btcec.PrivateKey,
} }
return errChan return errChan
}, },
CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement, error) { CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
error) {
return lnwire.NodeAnnouncement{}, nil return lnwire.NodeAnnouncement{}, nil
}, },
TempChanIDSeed: chanIDSeed, TempChanIDSeed: chanIDSeed,
@ -450,7 +455,10 @@ func createTestFundingManager(t *testing.T, privKey *btcec.PrivateKey,
} }
for _, channel := range nodeChans { for _, channel := range nodeChans {
if chanID.IsChanPoint(&channel.FundingOutpoint) { if chanID.IsChanPoint(
&channel.FundingOutpoint,
) {
return channel, nil return channel, nil
} }
} }
@ -488,7 +496,9 @@ func createTestFundingManager(t *testing.T, privKey *btcec.PrivateKey,
RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 { RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
return uint16(input.MaxHTLCNumber / 2) return uint16(input.MaxHTLCNumber / 2)
}, },
WatchNewChannel: func(*channeldb.OpenChannel, *btcec.PublicKey) error { WatchNewChannel: func(*channeldb.OpenChannel,
*btcec.PublicKey) error {
return nil return nil
}, },
ReportShortChanID: func(wire.OutPoint) error { ReportShortChanID: func(wire.OutPoint) error {
@ -592,7 +602,9 @@ func recreateAliceFundingManager(t *testing.T, alice *testNode) {
} }
return errChan return errChan
}, },
CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement, error) { CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
error) {
return lnwire.NodeAnnouncement{}, nil return lnwire.NodeAnnouncement{}, nil
}, },
NotifyWhenOnline: func(peer [33]byte, NotifyWhenOnline: func(peer [33]byte,
@ -870,6 +882,7 @@ func assertErrorSent(t *testing.T, msgChan chan lnwire.Message) {
func assertFundingMsgSent(t *testing.T, msgChan chan lnwire.Message, func assertFundingMsgSent(t *testing.T, msgChan chan lnwire.Message,
msgType string) lnwire.Message { msgType string) lnwire.Message {
t.Helper() t.Helper()
var msg lnwire.Message var msg lnwire.Message
@ -901,8 +914,8 @@ func assertFundingMsgSent(t *testing.T, msgChan chan lnwire.Message,
if !ok { if !ok {
errorMsg, gotError := msg.(*lnwire.Error) errorMsg, gotError := msg.(*lnwire.Error)
if gotError { if gotError {
t.Fatalf("expected %s to be sent, instead got error: %v", t.Fatalf("expected %s to be sent, instead got "+
msgType, errorMsg.Error()) "error: %v", msgType, errorMsg.Error())
} }
_, _, line, _ := runtime.Caller(1) _, _, line, _ := runtime.Caller(1)
@ -915,6 +928,7 @@ func assertFundingMsgSent(t *testing.T, msgChan chan lnwire.Message,
func assertNumPendingReservations(t *testing.T, node *testNode, func assertNumPendingReservations(t *testing.T, node *testNode,
peerPubKey *btcec.PublicKey, expectedNum int) { peerPubKey *btcec.PublicKey, expectedNum int) {
t.Helper() t.Helper()
serializedPubKey := newSerializedKey(peerPubKey) serializedPubKey := newSerializedKey(peerPubKey)
@ -928,7 +942,9 @@ func assertNumPendingReservations(t *testing.T, node *testNode,
expectedNum, actualNum) expectedNum, actualNum)
} }
func assertNumPendingChannelsBecomes(t *testing.T, node *testNode, expectedNum int) { func assertNumPendingChannelsBecomes(t *testing.T, node *testNode,
expectedNum int) {
t.Helper() t.Helper()
var numPendingChans int var numPendingChans int
@ -954,7 +970,9 @@ func assertNumPendingChannelsBecomes(t *testing.T, node *testNode, expectedNum i
expectedNum, numPendingChans) expectedNum, numPendingChans)
} }
func assertNumPendingChannelsRemains(t *testing.T, node *testNode, expectedNum int) { func assertNumPendingChannelsRemains(t *testing.T, node *testNode,
expectedNum int) {
t.Helper() t.Helper()
var numPendingChans int var numPendingChans int
@ -980,6 +998,7 @@ func assertNumPendingChannelsRemains(t *testing.T, node *testNode, expectedNum i
func assertDatabaseState(t *testing.T, node *testNode, func assertDatabaseState(t *testing.T, node *testNode,
fundingOutPoint *wire.OutPoint, expectedState channelOpeningState) { fundingOutPoint *wire.OutPoint, expectedState channelOpeningState) {
t.Helper() t.Helper()
var state channelOpeningState var state channelOpeningState
@ -996,7 +1015,9 @@ func assertDatabaseState(t *testing.T, node *testNode,
} }
// If we found the channel, check if it had the expected state. // If we found the channel, check if it had the expected state.
if err != channeldb.ErrChannelNotFound && state == expectedState { if !errors.Is(err, channeldb.ErrChannelNotFound) &&
state == expectedState {
// Got expected state, return with success. // Got expected state, return with success.
return return
} }
@ -1013,6 +1034,7 @@ func assertDatabaseState(t *testing.T, node *testNode,
func assertMarkedOpen(t *testing.T, alice, bob *testNode, func assertMarkedOpen(t *testing.T, alice, bob *testNode,
fundingOutPoint *wire.OutPoint) { fundingOutPoint *wire.OutPoint) {
t.Helper() t.Helper()
// Make sure the notification about the pending channel was sent out. // Make sure the notification about the pending channel was sent out.
@ -1033,6 +1055,7 @@ func assertMarkedOpen(t *testing.T, alice, bob *testNode,
func assertFundingLockedSent(t *testing.T, alice, bob *testNode, func assertFundingLockedSent(t *testing.T, alice, bob *testNode,
fundingOutPoint *wire.OutPoint) { fundingOutPoint *wire.OutPoint) {
t.Helper() t.Helper()
assertDatabaseState(t, alice, fundingOutPoint, fundingLockedSent) assertDatabaseState(t, alice, fundingOutPoint, fundingLockedSent)
@ -1041,6 +1064,7 @@ func assertFundingLockedSent(t *testing.T, alice, bob *testNode,
func assertAddedToRouterGraph(t *testing.T, alice, bob *testNode, func assertAddedToRouterGraph(t *testing.T, alice, bob *testNode,
fundingOutPoint *wire.OutPoint) { fundingOutPoint *wire.OutPoint) {
t.Helper() t.Helper()
assertDatabaseState(t, alice, fundingOutPoint, addedToRouterGraph) assertDatabaseState(t, alice, fundingOutPoint, addedToRouterGraph)
@ -1061,13 +1085,13 @@ func assertChannelAnnouncements(t *testing.T, alice, bob *testNode,
t.Helper() t.Helper()
// After the FundingLocked message is sent, Alice and Bob will each // After the FundingLocked message is sent, Alice and Bob will each send
// send the following messages to their gossiper: // the following messages to their gossiper:
// 1) ChannelAnnouncement // 1) ChannelAnnouncement
// 2) ChannelUpdate // 2) ChannelUpdate
// The ChannelAnnouncement is kept locally, while the ChannelUpdate // The ChannelAnnouncement is kept locally, while the ChannelUpdate is
// is sent directly to the other peer, so the edge policies are // sent directly to the other peer, so the edge policies are known to
// known to both peers. // both peers.
nodes := []*testNode{alice, bob} nodes := []*testNode{alice, bob}
for j, node := range nodes { for j, node := range nodes {
announcements := make([]lnwire.Message, 2) announcements := make([]lnwire.Message, 2)
@ -1075,7 +1099,7 @@ func assertChannelAnnouncements(t *testing.T, alice, bob *testNode,
select { select {
case announcements[i] = <-node.announceChan: case announcements[i] = <-node.announceChan:
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("node did not send announcement: %v", i) t.Fatalf("node didn't send announcement: %v", i)
} }
} }
@ -1316,7 +1340,8 @@ func assertInitialFwdingPolicyNotFound(t *testing.T, node *testNode,
// Got expected result, return with success. // Got expected result, return with success.
return return
} else if err != nil { } else if err != nil {
t.Fatalf("unable to get forwarding policy from db: %v", err) t.Fatalf("unable to get forwarding policy from db: %v",
err)
} }
} }
@ -1352,7 +1377,8 @@ func TestFundingManagerNormalWorkflow(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Run through the process of opening the channel, up until the funding // Run through the process of opening the channel, up until the funding
@ -1414,7 +1440,8 @@ func TestFundingManagerNormalWorkflow(t *testing.T) {
// OpenStatusUpdate_ChanOpen update // OpenStatusUpdate_ChanOpen update
waitForOpenUpdate(t, updateChan) waitForOpenUpdate(t, updateChan)
// Notify that six confirmations has been reached on funding transaction. // Notify that six confirmations has been reached on funding
// transaction.
alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{ alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
Tx: fundingTx, Tx: fundingTx,
} }
@ -1457,8 +1484,9 @@ func testLocalCSVLimit(t *testing.T, aliceMaxCSV, bobRequiredCSV uint16) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// Set a maximum local delay in alice's config to aliceMaxCSV and overwrite // Set a maximum local delay in alice's config to aliceMaxCSV and
// bob's required remote delay function to return bobRequiredCSV. // overwrite bob's required remote delay function to return
// bobRequiredCSV.
alice.fundingMgr.cfg.MaxLocalCSVDelay = aliceMaxCSV alice.fundingMgr.cfg.MaxLocalCSVDelay = aliceMaxCSV
bob.fundingMgr.cfg.RequiredRemoteDelay = func(_ btcutil.Amount) uint16 { bob.fundingMgr.cfg.RequiredRemoteDelay = func(_ btcutil.Amount) uint16 {
return bobRequiredCSV return bobRequiredCSV
@ -1723,7 +1751,8 @@ func TestFundingManagerRestartBehavior(t *testing.T) {
recreateAliceFundingManager(t, alice) recreateAliceFundingManager(t, alice)
time.Sleep(300 * time.Millisecond) time.Sleep(300 * time.Millisecond)
// Notify that six confirmations has been reached on funding transaction. // Notify that six confirmations has been reached on funding
// transaction.
alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{ alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
Tx: fundingTx, Tx: fundingTx,
} }
@ -1837,8 +1866,8 @@ func TestFundingManagerOfflinePeer(t *testing.T) {
} }
if !bytes.Equal(peer[:], bobPubKey.SerializeCompressed()) { if !bytes.Equal(peer[:], bobPubKey.SerializeCompressed()) {
t.Fatalf("expected to receive Bob's pubkey (%v), instead got %v", t.Fatalf("expected to receive Bob's pubkey (%v), instead "+
bobPubKey, peer) "got %v", bobPubKey, peer)
} }
// Before sending on the con chan, update Alice's NotifyWhenOnline // Before sending on the con chan, update Alice's NotifyWhenOnline
@ -1882,7 +1911,8 @@ func TestFundingManagerOfflinePeer(t *testing.T) {
// OpenStatusUpdate_ChanOpen update // OpenStatusUpdate_ChanOpen update
waitForOpenUpdate(t, updateChan) waitForOpenUpdate(t, updateChan)
// Notify that six confirmations has been reached on funding transaction. // Notify that six confirmations has been reached on funding
// transaction.
alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{ alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
Tx: fundingTx, Tx: fundingTx,
} }
@ -1914,7 +1944,8 @@ func TestFundingManagerPeerTimeoutAfterInitFunding(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
@ -1957,7 +1988,8 @@ func TestFundingManagerPeerTimeoutAfterInitFunding(t *testing.T) {
// Alice should have a new pending reservation. // Alice should have a new pending reservation.
assertNumPendingReservations(t, alice, bobPubKey, 1) assertNumPendingReservations(t, alice, bobPubKey, 1)
// Make sure Alice's reservation times out and then run her zombie sweeper. // Make sure Alice's reservation times out and then run her zombie
// sweeper.
time.Sleep(1 * time.Millisecond) time.Sleep(1 * time.Millisecond)
go alice.fundingMgr.pruneZombieReservations() go alice.fundingMgr.pruneZombieReservations()
@ -1979,7 +2011,8 @@ func TestFundingManagerPeerTimeoutAfterFundingOpen(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
@ -2031,7 +2064,8 @@ func TestFundingManagerPeerTimeoutAfterFundingOpen(t *testing.T) {
// Bob should have a new pending reservation. // Bob should have a new pending reservation.
assertNumPendingReservations(t, bob, alicePubKey, 1) assertNumPendingReservations(t, bob, alicePubKey, 1)
// Make sure Bob's reservation times out and then run his zombie sweeper. // Make sure Bob's reservation times out and then run his zombie
// sweeper.
time.Sleep(1 * time.Millisecond) time.Sleep(1 * time.Millisecond)
go bob.fundingMgr.pruneZombieReservations() go bob.fundingMgr.pruneZombieReservations()
@ -2042,8 +2076,8 @@ func TestFundingManagerPeerTimeoutAfterFundingOpen(t *testing.T) {
assertNumPendingReservations(t, bob, alicePubKey, 0) assertNumPendingReservations(t, bob, alicePubKey, 0)
} }
// TestFundingManagerPeerTimeoutAfterFundingAccept checks that the zombie sweeper // TestFundingManagerPeerTimeoutAfterFundingAccept checks that the zombie
// will properly clean up a zombie reservation that times out after the // sweeper will properly clean up a zombie reservation that times out after the
// fundingAcceptMsg has been handled. // fundingAcceptMsg has been handled.
func TestFundingManagerPeerTimeoutAfterFundingAccept(t *testing.T) { func TestFundingManagerPeerTimeoutAfterFundingAccept(t *testing.T) {
t.Parallel() t.Parallel()
@ -2053,7 +2087,8 @@ func TestFundingManagerPeerTimeoutAfterFundingAccept(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
@ -2113,7 +2148,8 @@ func TestFundingManagerPeerTimeoutAfterFundingAccept(t *testing.T) {
// Alice responds with a FundingCreated messages. // Alice responds with a FundingCreated messages.
assertFundingMsgSent(t, alice.msgChan, "FundingCreated") assertFundingMsgSent(t, alice.msgChan, "FundingCreated")
// Make sure Alice's reservation times out and then run her zombie sweeper. // Make sure Alice's reservation times out and then run her zombie
// sweeper.
time.Sleep(1 * time.Millisecond) time.Sleep(1 * time.Millisecond)
go alice.fundingMgr.pruneZombieReservations() go alice.fundingMgr.pruneZombieReservations()
@ -2132,7 +2168,8 @@ func TestFundingManagerFundingTimeout(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Run through the process of opening the channel, up until the funding // Run through the process of opening the channel, up until the funding
@ -2178,7 +2215,8 @@ func TestFundingManagerFundingNotTimeoutInitiator(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Run through the process of opening the channel, up until the funding // Run through the process of opening the channel, up until the funding
@ -2203,7 +2241,8 @@ func TestFundingManagerFundingNotTimeoutInitiator(t *testing.T) {
t.Fatalf("alice did not publish funding tx") t.Fatalf("alice did not publish funding tx")
} }
// Increase the height to 1 minus the maxWaitNumBlocksFundingConf height. // Increase the height to 1 minus the maxWaitNumBlocksFundingConf
// height.
alice.mockNotifier.epochChan <- &chainntnfs.BlockEpoch{ alice.mockNotifier.epochChan <- &chainntnfs.BlockEpoch{
Height: fundingBroadcastHeight + maxWaitNumBlocksFundingConf - 1, Height: fundingBroadcastHeight + maxWaitNumBlocksFundingConf - 1,
} }
@ -2247,7 +2286,8 @@ func TestFundingManagerReceiveFundingLockedTwice(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Run through the process of opening the channel, up until the funding // Run through the process of opening the channel, up until the funding
@ -2325,7 +2365,8 @@ func TestFundingManagerReceiveFundingLockedTwice(t *testing.T) {
// OpenStatusUpdate_ChanOpen update // OpenStatusUpdate_ChanOpen update
waitForOpenUpdate(t, updateChan) waitForOpenUpdate(t, updateChan)
// Notify that six confirmations has been reached on funding transaction. // Notify that six confirmations has been reached on funding
// transaction.
alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{ alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
Tx: fundingTx, Tx: fundingTx,
} }
@ -2356,7 +2397,8 @@ func TestFundingManagerRestartAfterChanAnn(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Run through the process of opening the channel, up until the funding // Run through the process of opening the channel, up until the funding
@ -2419,7 +2461,8 @@ func TestFundingManagerRestartAfterChanAnn(t *testing.T) {
// we expect her to be able to handle it correctly. // we expect her to be able to handle it correctly.
recreateAliceFundingManager(t, alice) recreateAliceFundingManager(t, alice)
// Notify that six confirmations has been reached on funding transaction. // Notify that six confirmations has been reached on funding
// transaction.
alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{ alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
Tx: fundingTx, Tx: fundingTx,
} }
@ -2427,7 +2470,8 @@ func TestFundingManagerRestartAfterChanAnn(t *testing.T) {
Tx: fundingTx, Tx: fundingTx,
} }
// Make sure both fundingManagers send the expected channel announcements. // Make sure both fundingManagers send the expected channel
// announcements.
assertAnnouncementSignatures(t, alice, bob) assertAnnouncementSignatures(t, alice, bob)
// The internal state-machine should now have deleted the channelStates // The internal state-machine should now have deleted the channelStates
@ -2450,7 +2494,8 @@ func TestFundingManagerRestartAfterReceivingFundingLocked(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Run through the process of opening the channel, up until the funding // Run through the process of opening the channel, up until the funding
@ -2509,7 +2554,8 @@ func TestFundingManagerRestartAfterReceivingFundingLocked(t *testing.T) {
// Check that the state machine is updated accordingly // Check that the state machine is updated accordingly
assertAddedToRouterGraph(t, alice, bob, fundingOutPoint) assertAddedToRouterGraph(t, alice, bob, fundingOutPoint)
// Notify that six confirmations has been reached on funding transaction. // Notify that six confirmations has been reached on funding
// transaction.
alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{ alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
Tx: fundingTx, Tx: fundingTx,
} }
@ -2517,7 +2563,8 @@ func TestFundingManagerRestartAfterReceivingFundingLocked(t *testing.T) {
Tx: fundingTx, Tx: fundingTx,
} }
// Make sure both fundingManagers send the expected channel announcements. // Make sure both fundingManagers send the expected channel
// announcements.
assertAnnouncementSignatures(t, alice, bob) assertAnnouncementSignatures(t, alice, bob)
// The internal state-machine should now have deleted the channelStates // The internal state-machine should now have deleted the channelStates
@ -2540,7 +2587,8 @@ func TestFundingManagerPrivateChannel(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Run through the process of opening the channel, up until the funding // Run through the process of opening the channel, up until the funding
@ -2595,7 +2643,8 @@ func TestFundingManagerPrivateChannel(t *testing.T) {
// OpenStatusUpdate_ChanOpen update // OpenStatusUpdate_ChanOpen update
waitForOpenUpdate(t, updateChan) waitForOpenUpdate(t, updateChan)
// Notify that six confirmations has been reached on funding transaction. // Notify that six confirmations has been reached on funding
// transaction.
alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{ alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
Tx: fundingTx, Tx: fundingTx,
} }
@ -2607,14 +2656,16 @@ func TestFundingManagerPrivateChannel(t *testing.T) {
// announcement signatures. // announcement signatures.
select { select {
case ann := <-alice.announceChan: case ann := <-alice.announceChan:
t.Fatalf("unexpectedly got channel announcement message: %v", ann) t.Fatalf("unexpectedly got channel announcement message: %v",
ann)
case <-time.After(300 * time.Millisecond): case <-time.After(300 * time.Millisecond):
// Expected // Expected
} }
select { select {
case ann := <-bob.announceChan: case ann := <-bob.announceChan:
t.Fatalf("unexpectedly got channel announcement message: %v", ann) t.Fatalf("unexpectedly got channel announcement message: %v",
ann)
case <-time.After(300 * time.Millisecond): case <-time.After(300 * time.Millisecond):
// Expected // Expected
} }
@ -2659,7 +2710,8 @@ func TestFundingManagerPrivateRestart(t *testing.T) {
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
}) })
// We will consume the channel updates as we go, so no buffering is needed. // We will consume the channel updates as we go, so no buffering is
// needed.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
// Run through the process of opening the channel, up until the funding // Run through the process of opening the channel, up until the funding
@ -2719,7 +2771,8 @@ func TestFundingManagerPrivateRestart(t *testing.T) {
// OpenStatusUpdate_ChanOpen update // OpenStatusUpdate_ChanOpen update
waitForOpenUpdate(t, updateChan) waitForOpenUpdate(t, updateChan)
// Notify that six confirmations has been reached on funding transaction. // Notify that six confirmations has been reached on funding
// transaction.
alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{ alice.mockNotifier.sixConfChannel <- &chainntnfs.TxConfirmation{
Tx: fundingTx, Tx: fundingTx,
} }
@ -2731,13 +2784,15 @@ func TestFundingManagerPrivateRestart(t *testing.T) {
// channel announcement messages. // channel announcement messages.
select { select {
case ann := <-alice.announceChan: case ann := <-alice.announceChan:
t.Fatalf("unexpectedly got channel announcement message: %v", ann) t.Fatalf("unexpectedly got channel announcement message: %v",
ann)
case <-time.After(300 * time.Millisecond): case <-time.After(300 * time.Millisecond):
} }
select { select {
case ann := <-bob.announceChan: case ann := <-bob.announceChan:
t.Fatalf("unexpectedly got channel announcement message: %v", ann) t.Fatalf("unexpectedly got channel announcement message: %v",
ann)
case <-time.After(300 * time.Millisecond): case <-time.After(300 * time.Millisecond):
} }
@ -2767,14 +2822,16 @@ func TestFundingManagerPrivateRestart(t *testing.T) {
select { select {
case ann := <-alice.announceChan: case ann := <-alice.announceChan:
t.Fatalf("unexpectedly got channel announcement message: %v", ann) t.Fatalf("unexpectedly got channel announcement message: %v",
ann)
case <-time.After(300 * time.Millisecond): case <-time.After(300 * time.Millisecond):
// Expected // Expected
} }
select { select {
case ann := <-bob.announceChan: case ann := <-bob.announceChan:
t.Fatalf("unexpectedly got channel announcement message: %v", ann) t.Fatalf("unexpectedly got channel announcement message: %v",
ann)
case <-time.After(300 * time.Millisecond): case <-time.After(300 * time.Millisecond):
// Expected // Expected
} }
@ -2878,8 +2935,9 @@ func TestFundingManagerCustomChannelParameters(t *testing.T) {
// Check that the max value in flight is sent as part of OpenChannel. // Check that the max value in flight is sent as part of OpenChannel.
if openChannelReq.MaxValueInFlight != maxValueInFlight { if openChannelReq.MaxValueInFlight != maxValueInFlight {
t.Fatalf("expected OpenChannel to have MaxValueInFlight %v, got %v", t.Fatalf("expected OpenChannel to have MaxValueInFlight %v, "+
maxValueInFlight, openChannelReq.MaxValueInFlight) "got %v", maxValueInFlight,
openChannelReq.MaxValueInFlight)
} }
// Check that the custom remoteChanReserve value is sent. // Check that the custom remoteChanReserve value is sent.
@ -2914,8 +2972,9 @@ func TestFundingManagerCustomChannelParameters(t *testing.T) {
maxValueAcceptChannel := lnwire.NewMSatFromSatoshis(fundingAmt) - reserve maxValueAcceptChannel := lnwire.NewMSatFromSatoshis(fundingAmt) - reserve
if acceptChannelResponse.MaxValueInFlight != maxValueAcceptChannel { if acceptChannelResponse.MaxValueInFlight != maxValueAcceptChannel {
t.Fatalf("expected AcceptChannel to have MaxValueInFlight %v, got %v", t.Fatalf("expected AcceptChannel to have MaxValueInFlight %v, "+
maxValueAcceptChannel, acceptChannelResponse.MaxValueInFlight) "got %v", maxValueAcceptChannel,
acceptChannelResponse.MaxValueInFlight)
} }
// Forward the response to Alice. // Forward the response to Alice.
@ -2978,8 +3037,9 @@ func TestFundingManagerCustomChannelParameters(t *testing.T) {
theirMaxValue := theirMaxValue :=
resCtx.reservation.TheirContribution().MaxPendingAmount resCtx.reservation.TheirContribution().MaxPendingAmount
if theirMaxValue != expTheirMaxValue { if theirMaxValue != expTheirMaxValue {
return fmt.Errorf("expected their MaxPendingAmount to be %v, "+ return fmt.Errorf("expected their MaxPendingAmount to "+
"was %v", expTheirMaxValue, theirMaxValue) "be %v, was %v", expTheirMaxValue,
theirMaxValue)
} }
return nil return nil
} }
@ -3018,9 +3078,9 @@ func TestFundingManagerCustomChannelParameters(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
// The max value in flight Alice can have should be maxValueAcceptChannel, // The max value in flight Alice can have should be
// which is the default value and the maximum Bob can offer should be // maxValueAcceptChannel, which is the default value and the maximum Bob
// maxValueInFlight. // can offer should be maxValueInFlight.
if err := assertMaxHtlc(resCtx, if err := assertMaxHtlc(resCtx,
maxValueAcceptChannel, maxValueInFlight); err != nil { maxValueAcceptChannel, maxValueInFlight); err != nil {
t.Fatal(err) t.Fatal(err)
@ -3081,7 +3141,8 @@ func TestFundingManagerCustomChannelParameters(t *testing.T) {
} }
// After the funding is sigend and before the channel announcement // After the funding is sigend and before the channel announcement
// we expect Alice and Bob to store their respective fees in the database. // we expect Alice and Bob to store their respective fees in the
// database.
forwardingPolicy, err := alice.fundingMgr.getInitialFwdingPolicy( forwardingPolicy, err := alice.fundingMgr.getInitialFwdingPolicy(
fundingSigned.ChanID, fundingSigned.ChanID,
) )
@ -3139,16 +3200,25 @@ func TestFundingManagerCustomChannelParameters(t *testing.T) {
// For maxHltc Alice should advertise the default MaxHtlc value of // For maxHltc Alice should advertise the default MaxHtlc value of
// maxValueAcceptChannel, while bob should advertise the value // maxValueAcceptChannel, while bob should advertise the value
// maxValueInFlight since Alice required him to use it. // maxValueInFlight since Alice required him to use it.
maxHtlcArr := []lnwire.MilliSatoshi{maxValueAcceptChannel, maxValueInFlight} maxHtlcArr := []lnwire.MilliSatoshi{
maxValueAcceptChannel, maxValueInFlight,
}
// Alice should have custom fees set whereas Bob should see his // Alice should have custom fees set whereas Bob should see his
// configured default fees announced. // configured default fees announced.
defaultBaseFee := bob.fundingMgr.cfg.DefaultRoutingPolicy.BaseFee defaultBaseFee := bob.fundingMgr.cfg.DefaultRoutingPolicy.BaseFee
defaultFeerate := bob.fundingMgr.cfg.DefaultRoutingPolicy.FeeRate defaultFeerate := bob.fundingMgr.cfg.DefaultRoutingPolicy.FeeRate
baseFees := []lnwire.MilliSatoshi{lnwire.MilliSatoshi(baseFee), defaultBaseFee} baseFees := []lnwire.MilliSatoshi{
feeRates := []lnwire.MilliSatoshi{lnwire.MilliSatoshi(feeRate), defaultFeerate} lnwire.MilliSatoshi(baseFee), defaultBaseFee,
}
feeRates := []lnwire.MilliSatoshi{
lnwire.MilliSatoshi(feeRate), defaultFeerate,
}
assertChannelAnnouncements(t, alice, bob, capacity, minHtlcArr, maxHtlcArr, baseFees, feeRates) assertChannelAnnouncements(
t, alice, bob, capacity, minHtlcArr, maxHtlcArr, baseFees,
feeRates,
)
// The funding transaction is now confirmed, wait for the // The funding transaction is now confirmed, wait for the
// OpenStatusUpdate_ChanOpen update // OpenStatusUpdate_ChanOpen update
@ -3383,12 +3453,14 @@ func TestFundingManagerMaxPendingChannels(t *testing.T) {
select { select {
case pendingUpdate = <-initReqs[i].Updates: case pendingUpdate = <-initReqs[i].Updates:
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenStatusUpdate_ChanPending") t.Fatalf("alice did not send " +
"OpenStatusUpdate_ChanPending")
} }
_, ok := pendingUpdate.Update.(*lnrpc.OpenStatusUpdate_ChanPending) _, ok := pendingUpdate.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
if !ok { if !ok {
t.Fatal("OpenStatusUpdate was not OpenStatusUpdate_ChanPending") t.Fatal("OpenStatusUpdate was not " +
"OpenStatusUpdate_ChanPending")
} }
select { select {
@ -3495,10 +3567,10 @@ func TestFundingManagerRejectPush(t *testing.T) {
// Assert Bob responded with an ErrNonZeroPushAmount error. // Assert Bob responded with an ErrNonZeroPushAmount error.
err := assertFundingMsgSent(t, bob.msgChan, "Error").(*lnwire.Error) err := assertFundingMsgSent(t, bob.msgChan, "Error").(*lnwire.Error)
if !strings.Contains(err.Error(), "non-zero push amounts are disabled") { require.ErrorContains(
t.Fatalf("expected ErrNonZeroPushAmount error, got \"%v\"", t, err, "non-zero push amounts are disabled",
err.Error()) "expected ErrNonZeroPushAmount error, got \"%v\"", err.Error(),
} )
} }
// TestFundingManagerMaxConfs ensures that we don't accept a funding proposal // TestFundingManagerMaxConfs ensures that we don't accept a funding proposal
@ -3736,8 +3808,8 @@ func TestGetUpfrontShutdownScript(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
var mockPeer testNode var mockPeer testNode
// If the remote peer in the test should support upfront shutdown, // If the remote peer in the test should support
// add the feature bit. // upfront shutdown, add the feature bit.
if test.peerEnabled { if test.peerEnabled {
mockPeer.remoteFeatures = []lnwire.FeatureBit{ mockPeer.remoteFeatures = []lnwire.FeatureBit{
lnwire.UpfrontShutdownScriptOptional, lnwire.UpfrontShutdownScriptOptional,
@ -3749,7 +3821,8 @@ func TestGetUpfrontShutdownScript(t *testing.T) {
test.getScript, test.getScript,
) )
if err != test.expectedErr { if err != test.expectedErr {
t.Fatalf("got: %v, expected error: %v", err, test.expectedErr) t.Fatalf("got: %v, expected error: %v", err,
test.expectedErr)
} }
if !bytes.Equal(addr, test.expectedScript) { if !bytes.Equal(addr, test.expectedScript) {
@ -3760,7 +3833,9 @@ func TestGetUpfrontShutdownScript(t *testing.T) {
} }
} }
func expectOpenChannelMsg(t *testing.T, msgChan chan lnwire.Message) *lnwire.OpenChannel { func expectOpenChannelMsg(t *testing.T,
msgChan chan lnwire.Message) *lnwire.OpenChannel {
var msg lnwire.Message var msg lnwire.Message
select { select {
case msg = <-msgChan: case msg = <-msgChan:
@ -3788,8 +3863,8 @@ func TestMaxChannelSizeConfig(t *testing.T) {
// Create a set of funding managers that will reject wumbo // Create a set of funding managers that will reject wumbo
// channels but set --maxchansize explicitly lower than soft-limit. // channels but set --maxchansize explicitly lower than soft-limit.
// Verify that wumbo rejecting funding managers will respect --maxchansize // Verify that wumbo rejecting funding managers will respect
// below 16777215 satoshi (MaxBtcFundingAmount) limit. // --maxchansize below 16777215 satoshi (MaxBtcFundingAmount) limit.
alice, bob := setupFundingManagers(t, func(cfg *Config) { alice, bob := setupFundingManagers(t, func(cfg *Config) {
cfg.NoWumboChans = true cfg.NoWumboChans = true
cfg.MaxChanSize = MaxBtcFundingAmount - 1 cfg.MaxChanSize = MaxBtcFundingAmount - 1
@ -3835,9 +3910,9 @@ func TestMaxChannelSizeConfig(t *testing.T) {
bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice) bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
assertFundingMsgSent(t, bob.msgChan, "AcceptChannel") assertFundingMsgSent(t, bob.msgChan, "AcceptChannel")
// Verify that wumbo accepting funding managers will respect --maxchansize // Verify that wumbo accepting funding managers will respect
// Create the funding managers, this time allowing // --maxchansize. Create the funding managers, this time allowing wumbo
// wumbo channels but setting --maxchansize explicitly. // channels but setting --maxchansize explicitly.
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
alice, bob = setupFundingManagers(t, func(cfg *Config) { alice, bob = setupFundingManagers(t, func(cfg *Config) {
cfg.NoWumboChans = false cfg.NoWumboChans = false
@ -3896,8 +3971,8 @@ func TestWumboChannelConfig(t *testing.T) {
// should be rejected. // should be rejected.
initReq.LocalFundingAmt = btcutil.SatoshiPerBitcoin initReq.LocalFundingAmt = btcutil.SatoshiPerBitcoin
// After processing the funding open message, bob should respond with // After processing the funding open message, bob should respond with an
// an error rejecting the channel. // error rejecting the channel.
alice.fundingMgr.InitFundingWorkflow(initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
openChanMsg = expectOpenChannelMsg(t, alice.msgChan) openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice) bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
@ -4153,7 +4228,9 @@ func TestFundingManagerZeroConf(t *testing.T) {
// We'll now assert that both sides send ChannelAnnouncement and // We'll now assert that both sides send ChannelAnnouncement and
// ChannelUpdate messages. // ChannelUpdate messages.
assertChannelAnnouncements(t, alice, bob, fundingAmt, nil, nil, nil, nil) assertChannelAnnouncements(
t, alice, bob, fundingAmt, nil, nil, nil, nil,
)
// We'll now wait for the OpenStatusUpdate_ChanOpen update. // We'll now wait for the OpenStatusUpdate_ChanOpen update.
waitForOpenUpdate(t, updateChan) waitForOpenUpdate(t, updateChan)
@ -4179,7 +4256,9 @@ func TestFundingManagerZeroConf(t *testing.T) {
Tx: fundingTx, Tx: fundingTx,
} }
assertChannelAnnouncements(t, alice, bob, fundingAmt, nil, nil, nil, nil) assertChannelAnnouncements(
t, alice, bob, fundingAmt, nil, nil, nil, nil,
)
// Both Alice and Bob should send on reportScidChan. // Both Alice and Bob should send on reportScidChan.
select { select {