diff --git a/chainntnfs/height_hint_cache.go b/chainntnfs/height_hint_cache.go index b2859ac37..53ee0469a 100644 --- a/chainntnfs/height_hint_cache.go +++ b/chainntnfs/height_hint_cache.go @@ -35,7 +35,7 @@ var ( ErrConfirmHintNotFound = errors.New("confirm hint not found") ) -// CacheConfig contains the HeightHintCache configuration +// CacheConfig contains the HeightHintCache configuration. type CacheConfig struct { // QueryDisable prevents reliance on the Height Hint Cache. This is // necessary to recover from an edge case when the height recorded in diff --git a/chainreg/chainregistry.go b/chainreg/chainregistry.go index 48cc5df37..252412863 100644 --- a/chainreg/chainregistry.go +++ b/chainreg/chainregistry.go @@ -901,7 +901,7 @@ var ( // the network seed. // // TODO(roasbeef): extend and collapse these and chainparams.go into - // struct like chaincfg.Params + // struct like chaincfg.Params. ChainDNSSeeds = map[chainhash.Hash][][2]string{ BitcoinMainnetGenesis: { { @@ -935,7 +935,7 @@ var ( } ) -// ChainRegistry keeps track of the current chains +// ChainRegistry keeps track of the current chains. type ChainRegistry struct { sync.RWMutex diff --git a/chanfitness/chanevent_test.go b/chanfitness/chanevent_test.go index 111c8e4e4..43046db25 100644 --- a/chanfitness/chanevent_test.go +++ b/chanfitness/chanevent_test.go @@ -402,7 +402,6 @@ func TestGetOnlinePeriod(t *testing.T) { require.Equal(t, test.expectedOnline, online) }) - } } diff --git a/chanfitness/chaneventstore_test.go b/chanfitness/chaneventstore_test.go index 0c9921119..9674f0db3 100644 --- a/chanfitness/chaneventstore_test.go +++ b/chanfitness/chaneventstore_test.go @@ -155,7 +155,6 @@ func TestMonitorChannelEvents(t *testing.T) { testEventStore(t, gen, peer1, 1) }) - } // testEventStore creates a new test contexts, generates a set of events for it diff --git a/channeldb/channel.go b/channeldb/channel.go index 746208bc5..2750d190f 100644 --- a/channeldb/channel.go +++ b/channeldb/channel.go @@ -49,7 +49,7 @@ var ( // outpointBucket stores all of our channel outpoints and a tlv // stream containing channel data. // - // outpoint -> tlv stream + // outpoint -> tlv stream. // outpointBucket = []byte("outpoint-bucket") diff --git a/channeldb/channel_test.go b/channeldb/channel_test.go index 1d794ee47..0963ebfc7 100644 --- a/channeldb/channel_test.go +++ b/channeldb/channel_test.go @@ -658,6 +658,7 @@ func TestChannelStateTransition(t *testing.T) { if !reflect.DeepEqual( dbUnsignedAckedUpdates[0], unsignedAckedUpdates[0], ) { + t.Fatalf("unexpected update: expected %v, got %v", spew.Sdump(unsignedAckedUpdates[0]), spew.Sdump(dbUnsignedAckedUpdates)) diff --git a/channeldb/db_test.go b/channeldb/db_test.go index 98c0ea228..9a76ae65a 100644 --- a/channeldb/db_test.go +++ b/channeldb/db_test.go @@ -759,5 +759,4 @@ func TestFetchHistoricalChannel(t *testing.T) { if err != ErrChannelNotFound { t.Fatalf("expected chan not found, got: %v", err) } - } diff --git a/channeldb/duplicate_payments.go b/channeldb/duplicate_payments.go index 7dad7df70..1338f70f0 100644 --- a/channeldb/duplicate_payments.go +++ b/channeldb/duplicate_payments.go @@ -150,7 +150,6 @@ func fetchDuplicatePayment(bucket kvdb.RBucket) (*MPPayment, error) { creationInfo, err := deserializeDuplicatePaymentCreationInfo(r) if err != nil { return nil, err - } // Get failure reason if available. diff --git a/channeldb/graph.go b/channeldb/graph.go index fc8bcfe2d..aa71b9839 100644 --- a/channeldb/graph.go +++ b/channeldb/graph.go @@ -520,7 +520,6 @@ func (c *ChannelGraph) FetchNodeFeatures( // Fallback that uses the database. targetNode, err := c.FetchLightningNode(node) switch err { - // If the node exists and has features, return them directly. case nil: return targetNode.Features, nil @@ -592,7 +591,6 @@ func (c *ChannelGraph) ForEachNodeCached(cb func(node route.Vertex, channels[e.ChannelID] = directedChannel return nil - }) if err != nil { return err @@ -2429,7 +2427,6 @@ func makeZombiePubkeys(info *ChannelEdgeInfo, e1, e2 *ChannelEdgePolicy) ([33]byte, [33]byte) { switch { - // If we don't have either edge policy, we'll return both pubkeys so // that the channel can be resurrected by either party. case e1 == nil && e2 == nil: diff --git a/channeldb/graph_cache.go b/channeldb/graph_cache.go index 3dc404525..e59c21e2d 100644 --- a/channeldb/graph_cache.go +++ b/channeldb/graph_cache.go @@ -467,7 +467,6 @@ func (c *GraphCache) ForEachChannel(node route.Vertex, if err := cb(channel); err != nil { return err } - } return nil diff --git a/channeldb/graph_test.go b/channeldb/graph_test.go index 0897416d1..dad94e096 100644 --- a/channeldb/graph_test.go +++ b/channeldb/graph_test.go @@ -1279,6 +1279,7 @@ func TestGraphCacheTraversal(t *testing.T) { if !bytes.Equal( inPolicyNodeKey[:], node.PubKeyBytes[:], ) { + return fmt.Errorf("wrong outgoing edge") } @@ -3784,7 +3785,6 @@ func TestGraphCacheForEachNodeChannel(t *testing.T) { var numChans int err = graph.ForEachNodeChannel(nil, node1.PubKeyBytes, func(channel *DirectedChannel) error { - numChans++ return nil }) diff --git a/channeldb/invoice_test.go b/channeldb/invoice_test.go index b4535f79b..c235899ce 100644 --- a/channeldb/invoice_test.go +++ b/channeldb/invoice_test.go @@ -1010,7 +1010,6 @@ func TestScanInvoices(t *testing.T) { invoices = make(map[lntypes.Hash]*Invoice) callCount = 0 resetCount++ - } scanFunc := func(paymentHash lntypes.Hash, invoice *Invoice) error { @@ -1661,7 +1660,6 @@ func TestHTLCSet(t *testing.T) { ampData = &InvoiceHtlcAMPData{ Record: *record.NewAMP([32]byte{0}, *h.setID, 0), } - } // Add the HTLC to the invoice's set of HTLCs. @@ -2045,7 +2043,7 @@ func TestUnexpectedInvoicePreimage(t *testing.T) { getUpdateInvoice(invoice.Terms.Value), ) - //Assert that we get ErrUnexpectedInvoicePreimage. + // Assert that we get ErrUnexpectedInvoicePreimage. require.Error(t, ErrUnexpectedInvoicePreimage, err) } diff --git a/channeldb/invoices.go b/channeldb/invoices.go index 0d01f5d76..8dffd6ed9 100644 --- a/channeldb/invoices.go +++ b/channeldb/invoices.go @@ -422,7 +422,7 @@ func (c ContractState) String() string { return "Unknown" } -// IsFinal returns a boolean indicating whether an invoice state is final +// IsFinal returns a boolean indicating whether an invoice state is final. func (c ContractState) IsFinal() bool { return c == ContractSettled || c == ContractCanceled } @@ -1156,7 +1156,6 @@ func fetchInvoiceNumByRef(invoiceIndex, payAddrIndex, setIDIndex kvdb.RBucket, invoiceNumByHash := getInvoiceNumByHash() invoiceNumByAddr := getInvoiceNumByAddr() switch { - // If payment address and payment hash both reference an existing // invoice, ensure they reference the _same_ invoice. case invoiceNumByAddr != nil && invoiceNumByHash != nil: @@ -2814,7 +2813,6 @@ func (d *DB) updateInvoice(hash *lntypes.Hash, refSetID *SetID, invoices, if setID != nil && update.State != nil { preimage, ok := update.State.HTLCPreimages[key] switch { - // If we don't already have a preimage for this HTLC, we // can set it now. case ok && htlc.AMP.Preimage == nil: @@ -2890,7 +2888,6 @@ func (d *DB) updateInvoice(hash *lntypes.Hash, refSetID *SetID, invoices, if !invoiceIsAMP { invoice.AmtPaid = amtPaid } else { - invoice.AmtPaid += amtPaid } @@ -2941,7 +2938,6 @@ func updateInvoiceState(invoice *Invoice, hash *lntypes.Hash, } switch invoice.State { - // Once a contract is accepted, we can only transition to settled or // canceled. Forbid transitioning back into this state. Otherwise this // state is identical to ContractOpen, so we fallthrough to apply the @@ -2979,7 +2975,6 @@ func updateInvoiceState(invoice *Invoice, hash *lntypes.Hash, } switch { - // If an invoice-level preimage was supplied, but the InvoiceRef // doesn't specify a hash (e.g. AMP invoices) we fail. case update.Preimage != nil && hash == nil: @@ -3063,7 +3058,6 @@ func updateHtlc(resolveTime time.Time, htlc *InvoiceHTLC, // the invoice level. For AMP HTLCs, verify that the // per-HTLC preimage-hash pair is valid. switch { - // Non-AMP HTLCs can be settle immediately since we // already know the preimage is valid due to checks at // the invoice level. @@ -3112,7 +3106,6 @@ func updateHtlc(resolveTime time.Time, htlc *InvoiceHTLC, } switch invState { - case ContractCanceled: if htlc.State == HtlcStateAccepted { htlc.State = HtlcStateCanceled @@ -3369,7 +3362,6 @@ func (d *DB) DeleteInvoice(invoicesToDelete []InvoiceDeleteRef) error { if err != nil { return err } - } // In addition to deleting the main invoice state, if diff --git a/channeldb/migration21/legacy/legacy_decoding.go b/channeldb/migration21/legacy/legacy_decoding.go index 20c83bcdd..ea44e1835 100644 --- a/channeldb/migration21/legacy/legacy_decoding.go +++ b/channeldb/migration21/legacy/legacy_decoding.go @@ -257,7 +257,8 @@ func readChanConfig(b io.Reader, c *common.ChannelConfig) error { // nolint: dup ) } -func DeserializeCloseChannelSummary(r io.Reader) (*common.ChannelCloseSummary, error) { // nolint: dupl +func DeserializeCloseChannelSummary( + r io.Reader) (*common.ChannelCloseSummary, error) { // nolint: dupl c := &common.ChannelCloseSummary{} diff --git a/channeldb/migration21/migration_test.go b/channeldb/migration21/migration_test.go index 9e58989c7..1998bbc7d 100644 --- a/channeldb/migration21/migration_test.go +++ b/channeldb/migration21/migration_test.go @@ -175,7 +175,6 @@ var ( // migrate three areas: open channel commit diffs, open channel unacked updates, // and network results in the switch. func TestMigrateDatabaseWireMessages(t *testing.T) { - var pub [33]byte copy(pub[:], key[:]) @@ -344,6 +343,7 @@ func TestMigrateDatabaseWireMessages(t *testing.T) { if !reflect.DeepEqual( newUpdates, testCommitDiff.LogUpdates, ) { + return fmt.Errorf("updates mismatch: expected "+ "%v, got %v", spew.Sdump(testCommitDiff.LogUpdates), @@ -365,6 +365,7 @@ func TestMigrateDatabaseWireMessages(t *testing.T) { if !reflect.DeepEqual( newUpdates, testCommitDiff.LogUpdates, ) { + return fmt.Errorf("updates mismatch: expected "+ "%v, got %v", spew.Sdump(testCommitDiff.LogUpdates), @@ -402,6 +403,7 @@ func TestMigrateDatabaseWireMessages(t *testing.T) { if !reflect.DeepEqual( newChanCloseSummary, testChanCloseSummary, ) { + return fmt.Errorf("summary mismatch: expected "+ "%v, got %v", spew.Sdump(testChanCloseSummary), diff --git a/channeldb/migration23/migration.go b/channeldb/migration23/migration.go index 7e48791ec..f3043e257 100644 --- a/channeldb/migration23/migration.go +++ b/channeldb/migration23/migration.go @@ -140,7 +140,6 @@ func migrateHtlcsBucket(htlcs kvdb.RwBucket) error { if err := htlcs.Put(newKey, settleInfo); err != nil { return err } - } failInfo := attempt.Get(oldFailInfoKey) diff --git a/channeldb/migtest/raw_db.go b/channeldb/migtest/raw_db.go index f6d6455ac..f89f60654 100644 --- a/channeldb/migtest/raw_db.go +++ b/channeldb/migtest/raw_db.go @@ -72,7 +72,6 @@ func restoreDB(bucket kvdb.RwBucket, data map[string]interface{}) error { key := []byte(k) switch value := v.(type) { - // Key contains value. case string: err := bucket.Put(key, []byte(value)) @@ -114,7 +113,6 @@ func verifyDB(bucket kvdb.RBucket, data map[string]interface{}) error { key := []byte(k) switch value := v.(type) { - // Key contains value. case string: expectedValue := []byte(value) diff --git a/channeldb/options_test.go b/channeldb/options_test.go index f6a873b9b..e60c1cfcf 100644 --- a/channeldb/options_test.go +++ b/channeldb/options_test.go @@ -10,7 +10,6 @@ import ( // TestDefaultOptions tests the default options are created as intended. func TestDefaultOptions(t *testing.T) { - opts := channeldb.DefaultOptions() require.True(t, opts.NoFreelistSync) diff --git a/channeldb/paginate.go b/channeldb/paginate.go index 48001f489..496c236e0 100644 --- a/channeldb/paginate.go +++ b/channeldb/paginate.go @@ -69,7 +69,6 @@ func (p paginator) cursorStart() ([]byte, []byte) { // handle a few offset cases. if p.reversed { switch { - // This indicates the default case, where no offset was // specified. In that case we just start from the last // entry. diff --git a/channeldb/payment_control.go b/channeldb/payment_control.go index 8e8384134..4ea0a9545 100644 --- a/channeldb/payment_control.go +++ b/channeldb/payment_control.go @@ -324,7 +324,6 @@ func (p *PaymentControl) RegisterAttempt(paymentHash lntypes.Hash, hMpp := h.Route.FinalHop().MPP switch { - // We tried to register a non-MPP attempt for a MPP // payment. case mpp == nil && hMpp != nil: diff --git a/channeldb/payment_control_test.go b/channeldb/payment_control_test.go index ef4e87c31..b67be2e00 100644 --- a/channeldb/payment_control_test.go +++ b/channeldb/payment_control_test.go @@ -1254,7 +1254,6 @@ func createTestPayments(t *testing.T, p *PaymentControl, payments []*payment) { require.NoError(t, err, "unable to send htlc message") switch payments[i].status { - // Fail the attempt and the payment overall. case StatusFailed: htlcFailure := HTLCFailUnreadable diff --git a/channeldb/payments.go b/channeldb/payments.go index cf21c0f74..80fe928ab 100644 --- a/channeldb/payments.go +++ b/channeldb/payments.go @@ -357,7 +357,6 @@ func fetchPayment(bucket kvdb.RBucket) (*MPPayment, error) { var paymentStatus PaymentStatus switch { - // If any of the the HTLCs did succeed and there are no HTLCs in // flight, the payment succeeded. case !inflight && settled: @@ -1093,7 +1092,6 @@ func deserializeHTLCAttemptInfo(r io.Reader) (*HTLCAttemptInfo, error) { _, err = io.ReadFull(r, hash[:]) switch { - // Older payment attempts wouldn't have the hash set, in which case we // can just return. case err == io.EOF, err == io.ErrUnexpectedEOF: diff --git a/channeldb/payments_test.go b/channeldb/payments_test.go index 370a1d9c5..0ed3bf03f 100644 --- a/channeldb/payments_test.go +++ b/channeldb/payments_test.go @@ -487,6 +487,7 @@ func TestQueryPayments(t *testing.T) { } if tt.firstIndex != querySlice.FirstIndexOffset || tt.lastIndex != querySlice.LastIndexOffset { + t.Errorf("First or last index does not match "+ "expected index. Want (%d, %d), got (%d, %d).", tt.firstIndex, tt.lastIndex, diff --git a/chanrestore.go b/chanrestore.go index 909c2e397..0126240c6 100644 --- a/chanrestore.go +++ b/chanrestore.go @@ -133,7 +133,6 @@ func (c *chanDBRestorer) openChannelShell(backup chanbackup.Single) ( var chanType channeldb.ChannelType switch backup.Version { - case chanbackup.DefaultSingleVersion: chanType = channeldb.SingleFunderBit diff --git a/cmd/lncli/cmd_open_channel.go b/cmd/lncli/cmd_open_channel.go index e2d507c13..8c14320e2 100644 --- a/cmd/lncli/cmd_open_channel.go +++ b/cmd/lncli/cmd_open_channel.go @@ -63,7 +63,7 @@ Signed base64 encoded PSBT or hex encoded raw wire TX (or path to text file): ` channelTypeAnchors = "anchors" ) -// TODO(roasbeef): change default number of confirmations +// TODO(roasbeef): change default number of confirmations. var openChannelCommand = cli.Command{ Name: "openchannel", Category: "Channels", @@ -289,6 +289,7 @@ func openChannel(ctx *cli.Context) error { _, err := client.ConnectPeer(ctxc, req) if err != nil && !strings.Contains(err.Error(), "already connected") { + return err } } diff --git a/cmd/lncli/cmd_payments.go b/cmd/lncli/cmd_payments.go index 6758321f9..b31e92d12 100644 --- a/cmd/lncli/cmd_payments.go +++ b/cmd/lncli/cmd_payments.go @@ -201,7 +201,6 @@ var sendPaymentCommand = cli.Command{ // default. func retrieveFeeLimit(ctx *cli.Context, amt int64) (int64, error) { switch { - case ctx.IsSet("fee_limit") && ctx.IsSet("fee_limit_percent"): return 0, fmt.Errorf("either fee_limit or fee_limit_percent " + "can be set, but not both") @@ -404,6 +403,7 @@ func sendPayment(ctx *cli.Context) error { func sendPaymentRequest(ctx *cli.Context, req *routerrpc.SendPaymentRequest) error { + ctxc := getContext() conn := getClientConn(ctx, false) @@ -702,6 +702,7 @@ func formatMsat(amt int64) string { // formatPayment formats the payment state as an ascii table. func formatPayment(ctxc context.Context, payment *lnrpc.Payment, aliases *aliasCache) string { + t := table.NewWriter() // Build table header. @@ -1521,7 +1522,7 @@ func deletePayments(ctx *cli.Context) error { return nil } -// ESC is the ASCII code for escape character +// ESC is the ASCII code for escape character. const ESC = 27 // clearCode defines a terminal escape code to clear the currently line and move diff --git a/cmd/lncli/cmd_walletunlocker.go b/cmd/lncli/cmd_walletunlocker.go index ad549af2b..5500e458e 100644 --- a/cmd/lncli/cmd_walletunlocker.go +++ b/cmd/lncli/cmd_walletunlocker.go @@ -149,7 +149,6 @@ func create(ctx *cli.Context) error { warningLoop: for { - fmt.Println() fmt.Printf("WARNING: You are attempting to restore from a " + "static channel backup (SCB) file.\nThis action will CLOSE " + diff --git a/config_builder.go b/config_builder.go index ed1b57711..0e8ddfa8d 100644 --- a/config_builder.go +++ b/config_builder.go @@ -952,7 +952,6 @@ func waitForWalletPassword(cfg *Config, // for creation or unlocking, as a new wallet db will be created if // none exists when creating the chain control. select { - // The wallet is being created for the first time, we'll check to see // if the user provided any entropy for seed creation. If so, then // we'll create the wallet early to load the seed. diff --git a/contractcourt/anchor_resolver.go b/contractcourt/anchor_resolver.go index fe2adc8b1..e44d07d61 100644 --- a/contractcourt/anchor_resolver.go +++ b/contractcourt/anchor_resolver.go @@ -125,7 +125,6 @@ func (c *anchorResolver) Resolve() (ContractResolver, error) { select { case sweepRes := <-resultChan: switch sweepRes.Err { - // Anchor was swept successfully. case nil: sweepTxID := sweepRes.Tx.TxHash() diff --git a/contractcourt/breacharbiter.go b/contractcourt/breacharbiter.go index 954bdb718..6f160141b 100644 --- a/contractcourt/breacharbiter.go +++ b/contractcourt/breacharbiter.go @@ -532,7 +532,7 @@ func (b *BreachArbiter) waitForSpendEvent(breachInfo *retributionInfo, // spends it to the second level, and mutates the breach output into one that // is able to properly sweep that second level output. We'll use this function // when we go to sweep a breached commitment transaction, but the cheating -// party has already attempted to take it to the second level +// party has already attempted to take it to the second level. func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo, spendDetails *chainntnfs.SpendDetail) { @@ -625,7 +625,6 @@ func updateBreachInfo(breachInfo *retributionInfo, spends []spend) ( // count the total and revoked funds swept depending on the // input type. switch breachedOutput.witnessType { - // If the output being revoked is the remote commitment // output or an offered HTLC output, it's amount // contributes to the value of funds being revoked from @@ -758,7 +757,6 @@ justiceTxBroadcast: Loop: for { - select { case spends := <-spendChan: // Update the breach info with the new spends. @@ -1333,6 +1331,7 @@ func (b *BreachArbiter) createJusticeTx( // createSweepTx creates a tx that sweeps the passed inputs back to our wallet. func (b *BreachArbiter) createSweepTx(inputs []input.Input) (*wire.MsgTx, error) { + if len(inputs) == 0 { return nil, nil } diff --git a/contractcourt/breacharbiter_test.go b/contractcourt/breacharbiter_test.go index f0daae630..9207f2d3e 100644 --- a/contractcourt/breacharbiter_test.go +++ b/contractcourt/breacharbiter_test.go @@ -1949,7 +1949,6 @@ func TestBreachDelayedJusticeConfirmation(t *testing.T) { maxIndex = uint32(len(forceCloseTx.TxOut)) - 1 ) for i := 0; i < 2; i++ { - var tx *wire.MsgTx select { case tx = <-publTx: @@ -1989,7 +1988,6 @@ func TestBreachDelayedJusticeConfirmation(t *testing.T) { } select { - // The published tx should spend the same inputs as our second split. case tx := <-publTx: require.Len(t, tx.TxIn, len(splits[1].TxIn)) diff --git a/contractcourt/briefcase.go b/contractcourt/briefcase.go index e6d5e4cf0..73f1842a8 100644 --- a/contractcourt/briefcase.go +++ b/contractcourt/briefcase.go @@ -181,7 +181,7 @@ const ( // | | // | |-> StateFullyResolved: contract resolutions empty // | - // |-> StateFullyResolved: coop/breach(legacy) close trigger + // |-> StateFullyResolved: coop/breach(legacy) close trigger. // StateDefault is the default state. In this state, no major actions // need to be executed. diff --git a/contractcourt/chain_arbitrator.go b/contractcourt/chain_arbitrator.go index 364bcd7e3..ba007ea6b 100644 --- a/contractcourt/chain_arbitrator.go +++ b/contractcourt/chain_arbitrator.go @@ -429,7 +429,6 @@ func (c *ChainArbitrator) getArbChannel( // This is only to be done once all contracts which were live on the channel // before hitting the chain have been resolved. func (c *ChainArbitrator) ResolveContract(chanPoint wire.OutPoint) error { - log.Infof("Marking ChannelPoint(%v) fully resolved", chanPoint) // First, we'll we'll mark the channel as fully closed from the PoV of @@ -874,7 +873,6 @@ func (c *ChainArbitrator) rebroadcast(channel *channeldb.OpenChannel, } switch { - // This can happen for channels that had their closing tx published // before we started storing it to disk. case err == channeldb.ErrNoCloseTx: diff --git a/contractcourt/chain_watcher.go b/contractcourt/chain_watcher.go index 7e813ee4a..ef1c5a08a 100644 --- a/contractcourt/chain_watcher.go +++ b/contractcourt/chain_watcher.go @@ -787,7 +787,6 @@ func (c *chainWatcher) handleKnownRemoteState( ) switch { - // If we had no log entry at this height, this was not a revoked state. case err == channeldb.ErrLogEntryNotFound: return false, nil @@ -869,7 +868,6 @@ func (c *chainWatcher) handleUnknownRemoteState( "sweep our funds...", commitPoint.SerializeCompressed(), c.cfg.chanState.FundingOutpoint) - } else { log.Infof("ChannelPoint(%v) is tweakless, "+ "moving to sweep directly on chain", diff --git a/contractcourt/channel_arbitrator_test.go b/contractcourt/channel_arbitrator_test.go index 6a0af45d3..5738fbc34 100644 --- a/contractcourt/channel_arbitrator_test.go +++ b/contractcourt/channel_arbitrator_test.go @@ -1548,7 +1548,6 @@ func TestChannelArbitratorForceCloseBreachedChannel(t *testing.T) { // TestChannelArbitratorCommitFailure tests that the channel arbitrator is able // to recover from a failed CommitState call at restart. func TestChannelArbitratorCommitFailure(t *testing.T) { - testCases := []struct { // closeType is the type of channel close we want ot test. @@ -2221,6 +2220,7 @@ func TestRemoteCloseInitiator(t *testing.T) { if !alice.State().HasChanStatus( channeldb.ChanStatusRemoteCloseInitiator, ) { + t.Fatalf("expected remote close initiator, "+ "got: %v", alice.State().ChanStatus()) } @@ -2350,7 +2350,6 @@ func TestFindCommitmentDeadline(t *testing.T) { require.Equal(t, tc.deadline, deadline) }) } - } // TestSweepAnchors checks the sweep transactions are created using the @@ -2473,7 +2472,6 @@ func TestSweepAnchors(t *testing.T) { t, expectedRemoteDeadline, deadlines[2], "remote deadline not matched", ) - } // TestChannelArbitratorAnchors asserts that the commitment tx anchor is swept. @@ -2702,7 +2700,6 @@ func TestChannelArbitratorAnchors(t *testing.T) { htlcWithPreimage.RefundTimeout-heightHint, chanArbCtx.sweeper.deadlines[1], ) - } // putResolverReportInChannel returns a put report function which will pipe @@ -2738,6 +2735,7 @@ type mockChannel struct { func (m *mockChannel) NewAnchorResolutions() (*lnwallet.AnchorResolutions, error) { + if m.anchorResolutions != nil { return m.anchorResolutions, nil } diff --git a/contractcourt/commit_sweep_resolver.go b/contractcourt/commit_sweep_resolver.go index 03e75b928..8f81714c7 100644 --- a/contractcourt/commit_sweep_resolver.go +++ b/contractcourt/commit_sweep_resolver.go @@ -262,7 +262,6 @@ func (c *commitSweepResolver) Resolve() (ContractResolver, error) { // commitment this is. var witnessType input.WitnessType switch { - // Delayed output to us on our local commitment for a channel lease in // which we are the initiator. case isLocalCommitTx && c.hasCLTV(): diff --git a/contractcourt/commit_sweep_resolver_test.go b/contractcourt/commit_sweep_resolver_test.go index 1321c0328..8cdf5e584 100644 --- a/contractcourt/commit_sweep_resolver_test.go +++ b/contractcourt/commit_sweep_resolver_test.go @@ -347,7 +347,6 @@ func testCommitSweepResolverDelay(t *testing.T, sweepErr error) { t.Fatalf("unexpected resolver report. want=%v got=%v", expectedReport, report) } - } // TestCommitSweepResolverDelay tests resolution of a direct commitment output diff --git a/contractcourt/htlc_incoming_contest_resolver.go b/contractcourt/htlc_incoming_contest_resolver.go index ca4e05ddf..095caf158 100644 --- a/contractcourt/htlc_incoming_contest_resolver.go +++ b/contractcourt/htlc_incoming_contest_resolver.go @@ -180,7 +180,6 @@ func (h *htlcIncomingContestResolver) Resolve() (ContractResolver, error) { // Take action based on the type of resolution we have // received. switch resolution := e.(type) { - // If the htlc resolution was a settle, apply the // preimage and return a success resolver. case *invoices.HtlcSettleResolution: @@ -442,7 +441,6 @@ func (h *htlcIncomingContestResolver) SupplementState(_ *channeldb.OpenChannel) // decodePayload (re)decodes the hop payload of a received htlc. func (h *htlcIncomingContestResolver) decodePayload() (*hop.Payload, error) { - onionReader := bytes.NewReader(h.htlc.OnionBlob) iterator, err := h.OnionProcessor.ReconstructHopIterator( onionReader, h.htlc.RHash[:], diff --git a/contractcourt/htlc_incoming_resolver_test.go b/contractcourt/htlc_incoming_resolver_test.go index baef5e508..d2e5b7d24 100644 --- a/contractcourt/htlc_incoming_resolver_test.go +++ b/contractcourt/htlc_incoming_resolver_test.go @@ -140,6 +140,7 @@ func TestHtlcIncomingResolverExitSettle(t *testing.T) { if !bytes.Equal( ctx.onionProcessor.offeredOnionBlob, testOnionBlob, ) { + t.Fatal("unexpected onion blob") } } diff --git a/contractcourt/htlc_success_resolver_test.go b/contractcourt/htlc_success_resolver_test.go index 9c7a56097..a3a9c3cb4 100644 --- a/contractcourt/htlc_success_resolver_test.go +++ b/contractcourt/htlc_success_resolver_test.go @@ -389,7 +389,6 @@ func TestHtlcSuccessSecondStageResolutionSweeper(t *testing.T) { SpendingHeight: 10, } return nil - }, // incubating=true is used to signal that the // second-level transaction was confirmed. @@ -555,7 +554,6 @@ func runFromCheckpoint(t *testing.T, ctx *htlcResolverTestContext, t.Fatalf("expected checkpoint to be have "+ "incubating=%v, had %v", cp.incubating, incubating) - } // Check we go the expected reports. @@ -595,7 +593,6 @@ func runFromCheckpoint(t *testing.T, ctx *htlcResolverTestContext, if err := cp.preCheckpoint(ctx, resumed); err != nil { t.Fatalf("failure at stage %d: %v", i, err) } - } resumed = false diff --git a/contractcourt/htlc_timeout_resolver.go b/contractcourt/htlc_timeout_resolver.go index cb3a196a7..a1642bd9d 100644 --- a/contractcourt/htlc_timeout_resolver.go +++ b/contractcourt/htlc_timeout_resolver.go @@ -329,7 +329,6 @@ func (h *htlcTimeoutResolver) Resolve() (ContractResolver, error) { // transaction. func (h *htlcTimeoutResolver) spendHtlcOutput() (*chainntnfs.SpendDetail, error) { switch { - // If we have non-nil SignDetails, this means that have a 2nd level // HTLC transaction that is signed using sighash SINGLE|ANYONECANPAY // (the case for anchor type channels). In this case we can re-sign it @@ -441,7 +440,6 @@ func (h *htlcTimeoutResolver) handleCommitSpend( ) switch { - // If the sweeper is handling the second level transaction, wait for // the CSV and possible CLTV lock to expire, before sweeping the output // on the second-level. diff --git a/contractcourt/htlc_timeout_resolver_test.go b/contractcourt/htlc_timeout_resolver_test.go index 97305f783..6968a9b59 100644 --- a/contractcourt/htlc_timeout_resolver_test.go +++ b/contractcourt/htlc_timeout_resolver_test.go @@ -138,6 +138,7 @@ func TestHtlcTimeoutResolver(t *testing.T) { if reflect.DeepEqual( templateTx.TxIn[0].Witness, witness, ) { + return templateTx, nil } templateTx.TxIn[0].Witness = witness @@ -169,6 +170,7 @@ func TestHtlcTimeoutResolver(t *testing.T) { if reflect.DeepEqual( templateTx.TxIn[0].Witness, witness, ) { + return templateTx, nil } @@ -206,6 +208,7 @@ func TestHtlcTimeoutResolver(t *testing.T) { if reflect.DeepEqual( templateTx.TxIn[0].Witness, witness, ) { + return templateTx, nil } @@ -239,6 +242,7 @@ func TestHtlcTimeoutResolver(t *testing.T) { if reflect.DeepEqual( templateTx.TxIn[0].Witness, witness, ) { + return templateTx, nil } diff --git a/contractcourt/nursery_store.go b/contractcourt/nursery_store.go index 9715e0ba3..94cb9b642 100644 --- a/contractcourt/nursery_store.go +++ b/contractcourt/nursery_store.go @@ -291,7 +291,6 @@ func (ns *NurseryStore) Incubate(kids []kidOutput, babies []babyOutput) error { // will be stored as it waits out the kidOutput's CSV delay. func (ns *NurseryStore) CribToKinder(bby *babyOutput) error { return kvdb.Update(ns.db, func(tx kvdb.RwTx) error { - // First, retrieve or create the channel bucket corresponding to // the baby output's origin channel point. chanPoint := bby.OriginChanPoint() @@ -472,7 +471,6 @@ func (ns *NurseryStore) PreschoolToKinder(kid *kidOutput, // pruned from the height index as outputs are removed. func (ns *NurseryStore) GraduateKinder(height uint32, kid *kidOutput) error { return kvdb.Update(ns.db, func(tx kvdb.RwTx) error { - hghtBucket := ns.getHeightBucket(tx, height) if hghtBucket == nil { // Nothing to delete, bucket has already been removed. @@ -597,7 +595,6 @@ func (ns *NurseryStore) FetchClass( func (ns *NurseryStore) FetchPreschools() ([]kidOutput, error) { // nolint:golint var kids []kidOutput if err := kvdb.View(ns.db, func(tx kvdb.RTx) error { - // Retrieve the existing chain bucket for this nursery store. chainBucket := tx.ReadBucket(ns.pfxChainKey) if chainBucket == nil { diff --git a/contractcourt/utxonursery.go b/contractcourt/utxonursery.go index c6592bc3f..d5cc31a79 100644 --- a/contractcourt/utxonursery.go +++ b/contractcourt/utxonursery.go @@ -884,7 +884,8 @@ func (u *UtxoNursery) sweepCribOutput(classHeight uint32, baby *babyOutput) erro // notification for an htlc timeout transaction. If successful, a goroutine // will be spawned that will transition the provided baby output into the // kindergarten state within the nursery store. -func (u *UtxoNursery) registerTimeoutConf(baby *babyOutput, heightHint uint32) error { +func (u *UtxoNursery) registerTimeoutConf(baby *babyOutput, + heightHint uint32) error { birthTxID := baby.timeoutTx.TxHash() @@ -1052,7 +1053,7 @@ type ContractMaturityReport struct { } // HtlcMaturityReport provides a summary of a single htlc output, and is -// embedded as party of the overarching ContractMaturityReport +// embedded as party of the overarching ContractMaturityReport. type HtlcMaturityReport struct { // Outpoint is the final output that will be swept back to the wallet. Outpoint wire.OutPoint diff --git a/discovery/bootstrapper.go b/discovery/bootstrapper.go index 3ad9743b9..efe9418d7 100644 --- a/discovery/bootstrapper.go +++ b/discovery/bootstrapper.go @@ -308,6 +308,7 @@ var _ NetworkPeerBootstrapper = (*ChannelGraphBootstrapper)(nil) func NewDNSSeedBootstrapper( seeds [][2]string, net tor.Net, timeout time.Duration) NetworkPeerBootstrapper { + return &DNSSeedBootstrapper{dnsSeeds: seeds, net: net, timeout: timeout} } diff --git a/discovery/gossiper.go b/discovery/gossiper.go index 3910fed51..b463a0b24 100644 --- a/discovery/gossiper.go +++ b/discovery/gossiper.go @@ -1178,6 +1178,7 @@ func (d *AuthenticatedGossiper) networkHandler() { announcement.msg, sourceToPub(announcement.source), ) { + announcement.err <- fmt.Errorf("recently " + "rejected") continue @@ -1205,6 +1206,7 @@ func (d *AuthenticatedGossiper) networkHandler() { routing.ErrVBarrierShuttingDown, routing.ErrParentValidationFailed, ) { + log.Warnf("unexpected error "+ "during validation "+ "barrier shutdown: %v", @@ -1787,6 +1789,7 @@ func (d *AuthenticatedGossiper) processNetworkAnnouncement( routing.ErrIgnored, routing.ErrVBarrierShuttingDown, ) { + log.Error(err) } @@ -2314,8 +2317,8 @@ func (d *AuthenticatedGossiper) processNetworkAnnouncement( routing.ErrIgnored, routing.ErrVBarrierShuttingDown, ) { - log.Debug(err) + log.Debug(err) } else { key := newRejectCacheKey( msg.ShortChannelID.ToUint64(), @@ -2929,6 +2932,7 @@ func IsKeepAliveUpdate(update *lnwire.ChannelUpdate, // Both updates should be from the same direction. if update.ChannelFlags&lnwire.ChanUpdateDirection != prev.ChannelFlags&lnwire.ChanUpdateDirection { + return false } diff --git a/discovery/gossiper_test.go b/discovery/gossiper_test.go index d3e1d1e5c..e9c10f821 100644 --- a/discovery/gossiper_test.go +++ b/discovery/gossiper_test.go @@ -2893,6 +2893,7 @@ func TestRetransmit(t *testing.T) { if chanAnn != chanAnns || chanUpd != chanUpds || nodeAnn != nodeAnns { + t.Fatalf("unexpected number of announcements: "+ "chanAnn=%d, chanUpd=%d, nodeAnn=%d", chanAnn, chanUpd, nodeAnn) diff --git a/discovery/sync_manager_test.go b/discovery/sync_manager_test.go index f2113ff5b..5160c3f06 100644 --- a/discovery/sync_manager_test.go +++ b/discovery/sync_manager_test.go @@ -76,7 +76,6 @@ func TestSyncManagerNumActiveSyncers(t *testing.T) { pinnedSyncers[vertex] = struct{}{} pinnedPubkeys[vertex] = pubkey - } syncMgr := newPinnedTestSyncManager(numActiveSyncers, pinnedSyncers) diff --git a/discovery/syncer.go b/discovery/syncer.go index de6821e31..11424a61e 100644 --- a/discovery/syncer.go +++ b/discovery/syncer.go @@ -842,6 +842,7 @@ func (g *GossipSyncer) processChanRangeReply(msg *lnwire.ReplyChannelRange) erro // behind a few blocks from us. if replyLastHeight < queryLastHeight && g.numChanRangeRepliesRcvd < maxReplies { + return nil } } @@ -1377,6 +1378,7 @@ func (g *GossipSyncer) ProcessQueryMsg(msg lnwire.Message, peerQuit <-chan struc syncState := g.syncState() if syncState != waitingQueryRangeReply && syncState != waitingQueryChanReply { + return fmt.Errorf("received unexpected query reply "+ "message %T", msg) } diff --git a/discovery/syncer_test.go b/discovery/syncer_test.go index 40e759f91..e63c2fd76 100644 --- a/discovery/syncer_test.go +++ b/discovery/syncer_test.go @@ -951,7 +951,7 @@ func TestGossipSyncerReplyChanRangeQuery(t *testing.T) { // TestGossipSyncerReplyChanRangeQuery tests a variety of // QueryChannelRange messages to ensure the underlying queries are -// executed with the correct block range +// executed with the correct block range. func TestGossipSyncerReplyChanRangeQueryBlockRange(t *testing.T) { t.Parallel() @@ -1027,7 +1027,6 @@ func TestGossipSyncerReplyChanRangeQueryBlockRange(t *testing.T) { resultsCh <- capFilterReqs return } - } }() diff --git a/feature/deps_test.go b/feature/deps_test.go index f1d950df8..e1108fbe7 100644 --- a/feature/deps_test.go +++ b/feature/deps_test.go @@ -162,6 +162,5 @@ func testValidateDeps(t *testing.T, test depTest) { if !reflect.DeepEqual(err, test.expErr) { t.Fatalf("validation mismatch, want: %v, got: %v", test.expErr, err) - } } diff --git a/funding/commitment_type_negotiation.go b/funding/commitment_type_negotiation.go index b3e9f38a9..a4ec131ed 100644 --- a/funding/commitment_type_negotiation.go +++ b/funding/commitment_type_negotiation.go @@ -76,6 +76,7 @@ func explicitNegotiateCommitmentType(channelType lnwire.ChannelType, lnwire.AnchorsZeroFeeHtlcTxOptional, lnwire.StaticRemoteKeyOptional, ) { + return 0, errUnsupportedChannelType } return lnwallet.CommitmentTypeScriptEnforcedLease, nil @@ -90,6 +91,7 @@ func explicitNegotiateCommitmentType(channelType lnwire.ChannelType, lnwire.AnchorsZeroFeeHtlcTxOptional, lnwire.StaticRemoteKeyOptional, ) { + return 0, errUnsupportedChannelType } return lnwallet.CommitmentTypeAnchorsZeroFeeHtlcTx, nil diff --git a/funding/manager.go b/funding/manager.go index eed824792..6306f7d91 100644 --- a/funding/manager.go +++ b/funding/manager.go @@ -84,7 +84,7 @@ const ( // MaxBtcFundingAmountWumbo is a soft-limit on the maximum size of wumbo // channels. This limit is 10 BTC and is the only thing standing between - // you and limitless channel size (apart from 21 million cap) + // you and limitless channel size (apart from 21 million cap). MaxBtcFundingAmountWumbo = btcutil.Amount(1000000000) // MaxLtcFundingAmount is a soft-limit of the maximum channel size @@ -92,7 +92,7 @@ const ( // Protocol. MaxLtcFundingAmount = MaxBtcFundingAmount * chainreg.BtcToLtcConversionRate - // TODO(roasbeef): tune + // TODO(roasbeef): tune. msgBufferSize = 50 // maxWaitNumBlocksFundingConf is the maximum number of blocks to wait @@ -723,7 +723,6 @@ func (f *Manager) nextPendingChanID() [32]byte { // passed node. This will ensure any outputs which have been pre committed, // (and thus locked from coin selection), are properly freed. func (f *Manager) CancelPeerReservations(nodePub [33]byte) { - log.Debugf("Cancelling all reservations for peer %x", nodePub[:]) f.resMtx.Lock() @@ -939,7 +938,6 @@ func (f *Manager) stateStep(channel *channeldb.OpenChannel, chanID, shortChanID, channelState) switch channelState { - // The funding transaction was confirmed, but we did not successfully // send the fundingLocked message to the peer, so let's do that now. case markedOpen: @@ -1112,7 +1110,6 @@ func (f *Manager) advancePendingChannelState( }() return timeoutErr - } else if err != nil { return fmt.Errorf("error waiting for funding "+ "confirmation for ChannelPoint(%v): %v", @@ -1149,7 +1146,7 @@ func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) { // the funding workflow. // // TODO(roasbeef): add error chan to all, let channelManager handle -// error+propagate +// error+propagate. func (f *Manager) handleFundingOpen(peer lnpeer.Peer, msg *lnwire.OpenChannel) { @@ -2382,6 +2379,7 @@ func (f *Manager) waitForFundingConfirmation( // NOTE: This MUST be run as a goroutine. func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel, cancelChan <-chan struct{}, timeoutChan chan<- error) { + defer f.wg.Done() epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil) @@ -3295,6 +3293,7 @@ func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) { // maximum. if commitType.HasAnchors() && commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate { + commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate } diff --git a/funding/manager_test.go b/funding/manager_test.go index 8b16437be..68124acbb 100644 --- a/funding/manager_test.go +++ b/funding/manager_test.go @@ -996,6 +996,7 @@ func assertAddedToRouterGraph(t *testing.T, alice, bob *testNode, func assertChannelAnnouncements(t *testing.T, alice, bob *testNode, capacity btcutil.Amount, customMinHtlc []lnwire.MilliSatoshi, customMaxHtlc []lnwire.MilliSatoshi) { + t.Helper() // After the FundingLocked message is sent, Alice and Bob will each @@ -3362,7 +3363,6 @@ func TestGetUpfrontShutdownScript(t *testing.T) { t.Fatalf("expected address: %x, got: %x", test.expectedScript, addr) } - }) } } diff --git a/htlcswitch/circuit_map.go b/htlcswitch/circuit_map.go index 79028f879..10a0ee1eb 100644 --- a/htlcswitch/circuit_map.go +++ b/htlcswitch/circuit_map.go @@ -411,7 +411,6 @@ func (cm *circuitMap) cleanClosedChannels() error { return nil }) return err - }, func() { // Reset the sets. circuitKeySet = make(map[CircuitKey]struct{}) diff --git a/htlcswitch/circuit_map_test.go b/htlcswitch/circuit_map_test.go index b2faa61ca..74b2b3ecb 100644 --- a/htlcswitch/circuit_map_test.go +++ b/htlcswitch/circuit_map_test.go @@ -265,10 +265,8 @@ func TestCircuitMapCleanClosedChannels(t *testing.T) { for _, ks := range test.untouched { assertKeystoneNotDeleted(t, circuitMap, ks) } - }) } - } // createTestCircuit creates a circuit for testing with its incoming key being diff --git a/htlcswitch/link.go b/htlcswitch/link.go index f347a7f26..38e1bbd76 100644 --- a/htlcswitch/link.go +++ b/htlcswitch/link.go @@ -1130,6 +1130,7 @@ func (l *channelLink) htlcManager() { if !shouldAdjustCommitFee( newCommitFee, commitFee, minRelayFee, ) { + continue } @@ -2571,7 +2572,6 @@ func (l *channelLink) ShutdownIfChannelClean() error { // updateChannelFee updates the commitment fee-per-kw on this channel by // committing to an update_fee message. func (l *channelLink) updateChannelFee(feePerKw chainfee.SatPerKWeight) error { - l.log.Infof("updating commit fee to %v sat/kw", feePerKw) // We skip sending the UpdateFee message if the channel is not diff --git a/htlcswitch/link_test.go b/htlcswitch/link_test.go index 9bfd184cc..8def75aad 100644 --- a/htlcswitch/link_test.go +++ b/htlcswitch/link_test.go @@ -5752,7 +5752,6 @@ func TestForwardingAsymmetricTimeLockPolicies(t *testing.T) { // TestCheckHtlcForward tests that a link is properly enforcing the HTLC // forwarding policy. func TestCheckHtlcForward(t *testing.T) { - fetchLastChannelUpdate := func(lnwire.ShortChannelID) ( *lnwire.ChannelUpdate, error) { diff --git a/htlcswitch/mailbox.go b/htlcswitch/mailbox.go index bee7e12a5..8b4981cc0 100644 --- a/htlcswitch/mailbox.go +++ b/htlcswitch/mailbox.go @@ -590,7 +590,6 @@ func (m *memoryMailBox) AddMessage(msg lnwire.Message) error { func (m *memoryMailBox) AddPacket(pkt *htlcPacket) error { m.pktCond.L.Lock() switch htlc := pkt.htlc.(type) { - // Split off Settle/Fail packets into the repPkts queue. case *lnwire.UpdateFulfillHTLC, *lnwire.UpdateFailHTLC: if _, ok := m.repIndex[pkt.inKey()]; ok { @@ -674,6 +673,7 @@ func (m *memoryMailBox) DustPackets() (lnwire.MilliSatoshi, if m.isDust( m.feeRate, false, true, addPkt.amount.ToSatoshis(), ) { + localDustSum += addPkt.amount } @@ -681,6 +681,7 @@ func (m *memoryMailBox) DustPackets() (lnwire.MilliSatoshi, if m.isDust( m.feeRate, false, false, addPkt.amount.ToSatoshis(), ) { + remoteDustSum += addPkt.amount } } diff --git a/htlcswitch/mock.go b/htlcswitch/mock.go index d9ca346bd..951449a37 100644 --- a/htlcswitch/mock.go +++ b/htlcswitch/mock.go @@ -986,17 +986,18 @@ var _ htlcNotifier = (*mockHTLCNotifier)(nil) type mockHTLCNotifier struct{} func (h *mockHTLCNotifier) NotifyForwardingEvent(key HtlcKey, info HtlcInfo, - eventType HtlcEventType) { + eventType HtlcEventType) { // nolint:whitespace } func (h *mockHTLCNotifier) NotifyLinkFailEvent(key HtlcKey, info HtlcInfo, - eventType HtlcEventType, linkErr *LinkError, incoming bool) { + eventType HtlcEventType, linkErr *LinkError, + incoming bool) { // nolint:whitespace } func (h *mockHTLCNotifier) NotifyForwardingFailEvent(key HtlcKey, - eventType HtlcEventType) { + eventType HtlcEventType) { // nolint:whitespace } func (h *mockHTLCNotifier) NotifySettleEvent(key HtlcKey, - preimage lntypes.Preimage, eventType HtlcEventType) { + preimage lntypes.Preimage, eventType HtlcEventType) { // nolint:whitespace } diff --git a/htlcswitch/payment_result_test.go b/htlcswitch/payment_result_test.go index aa7cbc173..828c21231 100644 --- a/htlcswitch/payment_result_test.go +++ b/htlcswitch/payment_result_test.go @@ -215,6 +215,5 @@ func TestNetworkResultStore(t *testing.T) { if i >= 2 && err != ErrPaymentIDNotFound { t.Fatalf("expected ErrPaymentIDNotFound, got %v", err) } - } } diff --git a/htlcswitch/switch.go b/htlcswitch/switch.go index bdd174a23..860076d4d 100644 --- a/htlcswitch/switch.go +++ b/htlcswitch/switch.go @@ -728,7 +728,7 @@ func (s *Switch) ForwardPackets(linkQuit chan struct{}, return nil } -// logFwdErrs logs any errors received on `fwdChan` +// logFwdErrs logs any errors received on `fwdChan`. func (s *Switch) logFwdErrs(num *int, wg *sync.WaitGroup, fwdChan chan error) { defer s.wg.Done() diff --git a/htlcswitch/switch_test.go b/htlcswitch/switch_test.go index ca1745ad1..60f775426 100644 --- a/htlcswitch/switch_test.go +++ b/htlcswitch/switch_test.go @@ -2961,7 +2961,6 @@ func testHtcNotifier(t *testing.T, testOpts []serverOption, iterations int, checkHtlcEvents(t, aliceEvents.Updates(), alice) checkHtlcEvents(t, bobEvents.Updates(), bob) checkHtlcEvents(t, carolEvents.Updates(), carol) - } } diff --git a/input/script_utils.go b/input/script_utils.go index 659314d68..cd0af8b1f 100644 --- a/input/script_utils.go +++ b/input/script_utils.go @@ -381,6 +381,7 @@ func IsHtlcSpendRevoke(txIn *wire.TxIn, signDesc *SignDescriptor) ( if len(txIn.Witness) == 3 && bytes.Equal(txIn.Witness[1], revokeKey.SerializeCompressed()) { + return true, nil } @@ -798,7 +799,7 @@ func SecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey, // OP_DROP // // OP_ENDIF -// OP_CHECKSIG +// OP_CHECKSIG. func LeaseSecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey, csvDelay, cltvExpiry uint32) ([]byte, error) { diff --git a/input/script_utils_test.go b/input/script_utils_test.go index 9abc41791..35e0c1a7c 100644 --- a/input/script_utils_test.go +++ b/input/script_utils_test.go @@ -22,6 +22,7 @@ import ( // prints debug information to stdout. func assertEngineExecution(t *testing.T, testNum int, valid bool, newEngine func() (*txscript.Engine, error)) { + t.Helper() // Get a new VM to execute. diff --git a/input/size.go b/input/size.go index a8e18f1dd..ed6d4cb71 100644 --- a/input/size.go +++ b/input/size.go @@ -47,7 +47,7 @@ const ( // - max-size: 40 bytes UnknownWitnessSize = 1 + 1 + 40 - // P2PKHSize 25 bytes + // P2PKHSize 25 bytes. P2PKHSize = 25 // P2PKHOutputSize 34 bytes @@ -68,7 +68,7 @@ const ( // - pkscript (p2wsh): 34 bytes P2WSHOutputSize = 8 + 1 + P2WSHSize - // P2SHSize 23 bytes + // P2SHSize 23 bytes. P2SHSize = 23 // P2SHOutputSize 32 bytes @@ -205,16 +205,16 @@ const ( BaseAnchorCommitmentTxSize = 4 + 1 + FundingInputSize + 3 + 2*CommitmentDelayOutput + 2*CommitmentAnchorOutput + 4 - // BaseAnchorCommitmentTxWeight 900 weight + // BaseAnchorCommitmentTxWeight 900 weight. BaseAnchorCommitmentTxWeight = witnessScaleFactor * BaseAnchorCommitmentTxSize - // CommitWeight 724 weight + // CommitWeight 724 weight. CommitWeight = BaseCommitmentTxWeight + WitnessCommitmentTxWeight - // AnchorCommitWeight 1124 weight + // AnchorCommitWeight 1124 weight. AnchorCommitWeight = BaseAnchorCommitmentTxWeight + WitnessCommitmentTxWeight - // HTLCWeight 172 weight + // HTLCWeight 172 weight. HTLCWeight = witnessScaleFactor * HTLCSize // HtlcTimeoutWeight 663 weight @@ -358,7 +358,7 @@ const ( AcceptedHtlcScriptSize = 3*1 + 20 + 5*1 + 33 + 8*1 + 20 + 4*1 + 33 + 5*1 + 4 + 5*1 - // AcceptedHtlcScriptSizeConfirmed 143 bytes + // AcceptedHtlcScriptSizeConfirmed 143 bytes. AcceptedHtlcScriptSizeConfirmed = AcceptedHtlcScriptSize + HtlcConfirmedScriptOverhead @@ -371,7 +371,7 @@ const ( // - witness_script: (accepted_htlc_script) AcceptedHtlcTimeoutWitnessSize = 1 + 1 + 73 + 1 + 1 + AcceptedHtlcScriptSize - // AcceptedHtlcTimeoutWitnessSizeConfirmed 220 bytes + // AcceptedHtlcTimeoutWitnessSizeConfirmed 220 bytes. AcceptedHtlcTimeoutWitnessSizeConfirmed = 1 + 1 + 73 + 1 + 1 + AcceptedHtlcScriptSizeConfirmed @@ -385,7 +385,7 @@ const ( // - witness_script (accepted_htlc_script) AcceptedHtlcPenaltyWitnessSize = 1 + 1 + 73 + 1 + 33 + 1 + AcceptedHtlcScriptSize - // AcceptedHtlcPenaltyWitnessSizeConfirmed 253 bytes + // AcceptedHtlcPenaltyWitnessSizeConfirmed 253 bytes. AcceptedHtlcPenaltyWitnessSizeConfirmed = 1 + 1 + 73 + 1 + 33 + 1 + AcceptedHtlcScriptSizeConfirmed @@ -448,7 +448,7 @@ const ( // - OP_ENDIF: 1 byte OfferedHtlcScriptSize = 3*1 + 20 + 5*1 + 33 + 10*1 + 33 + 5*1 + 20 + 4*1 - // OfferedHtlcScriptSizeConfirmed 136 bytes + // OfferedHtlcScriptSizeConfirmed 136 bytes. OfferedHtlcScriptSizeConfirmed = OfferedHtlcScriptSize + HtlcConfirmedScriptOverhead @@ -462,7 +462,7 @@ const ( // - witness_script (offered_htlc_script) OfferedHtlcSuccessWitnessSize = 1 + 1 + 73 + 1 + 32 + 1 + OfferedHtlcScriptSize - // OfferedHtlcSuccessWitnessSizeConfirmed 245 bytes + // OfferedHtlcSuccessWitnessSizeConfirmed 245 bytes. OfferedHtlcSuccessWitnessSizeConfirmed = 1 + 1 + 73 + 1 + 32 + 1 + OfferedHtlcScriptSizeConfirmed @@ -497,7 +497,7 @@ const ( // - witness_script (offered_htlc_script) OfferedHtlcPenaltyWitnessSize = 1 + 1 + 73 + 1 + 33 + 1 + OfferedHtlcScriptSize - // OfferedHtlcPenaltyWitnessSizeConfirmed 246 bytes + // OfferedHtlcPenaltyWitnessSizeConfirmed 246 bytes. OfferedHtlcPenaltyWitnessSizeConfirmed = 1 + 1 + 73 + 1 + 33 + 1 + OfferedHtlcScriptSizeConfirmed diff --git a/input/size_test.go b/input/size_test.go index bddecdd7c..024c0b0d7 100644 --- a/input/size_test.go +++ b/input/size_test.go @@ -938,7 +938,6 @@ func genSuccessTx(chanType channeldb.ChannelType) (*wire.MsgTx, error) { successTx.TxIn[0].Witness = successWitness return successTx, nil - } type txSizeTest struct { diff --git a/input/witnessgen.go b/input/witnessgen.go index fa0048a3f..9fea91799 100644 --- a/input/witnessgen.go +++ b/input/witnessgen.go @@ -405,7 +405,6 @@ func (wt StandardWitnessType) WitnessGenerator(signer Signer, // NOTE: This is part of the WitnessType interface. func (wt StandardWitnessType) SizeUpperBound() (int, bool, error) { switch wt { - // Outputs on a remote commitment transaction that pay directly to us. case CommitSpendNoDelayTweakless: fallthrough diff --git a/invoices/invoice_expiry_watcher.go b/invoices/invoice_expiry_watcher.go index b5ce2fe99..5038e5e84 100644 --- a/invoices/invoice_expiry_watcher.go +++ b/invoices/invoice_expiry_watcher.go @@ -404,7 +404,6 @@ func (ew *InvoiceExpiryWatcher) mainLoop(blockNtfns *chainntnfs.BlockEpochEvent) cancelNext() select { - case newInvoices := <-ew.newInvoices: // Take newly forwarded invoices with higher priority // in order to not block the newInvoices channel. @@ -413,7 +412,6 @@ func (ew *InvoiceExpiryWatcher) mainLoop(blockNtfns *chainntnfs.BlockEpochEvent) default: select { - // Wait until the next invoice expires. case <-ew.nextTimestampExpiry(): cancelNext = ew.cancelNextExpiredInvoice diff --git a/invoices/invoiceregistry.go b/invoices/invoiceregistry.go index f76b5191c..6ba3b2386 100644 --- a/invoices/invoiceregistry.go +++ b/invoices/invoiceregistry.go @@ -176,8 +176,8 @@ func (i *InvoiceRegistry) scanInvoicesOnStart() error { removable = make([]channeldb.InvoiceDeleteRef, 0) } - scanFunc := func( - paymentHash lntypes.Hash, invoice *channeldb.Invoice) error { + scanFunc := func(paymentHash lntypes.Hash, + invoice *channeldb.Invoice) error { if invoice.IsPending() { expiryRef := makeInvoiceExpiry(paymentHash, invoice) @@ -428,7 +428,6 @@ func (i *InvoiceRegistry) dispatchToClients(event *invoiceEvent) { // event is added while we're catching up a new client. invState := event.invoice.State switch { - case invState == channeldb.ContractSettled: client.settleIndex = invoice.SettleIndex @@ -908,7 +907,6 @@ func (i *InvoiceRegistry) NotifyExitHopHtlc(rHash lntypes.Hash, } switch { - // If we are accepting spontaneous AMP payments and this payload // contains an AMP record, create an AMP invoice that will be settled // below. diff --git a/invoices/update.go b/invoices/update.go index 6001efb30..bdfc8ca17 100644 --- a/invoices/update.go +++ b/invoices/update.go @@ -128,7 +128,6 @@ func updateMpp(ctx *invoiceUpdateCtx, // Reject HTLCs to AMP invoices if they are missing an AMP payload, and // HTLCs to MPP invoices if they have an AMP payload. switch { - case inv.Terms.Features.RequiresFeature(lnwire.AMPRequired) && ctx.amp == nil: diff --git a/lncfg/cluster.go b/lncfg/cluster.go index 649778796..033074ce8 100644 --- a/lncfg/cluster.go +++ b/lncfg/cluster.go @@ -57,7 +57,6 @@ func (c *Cluster) Validate() error { } switch c.LeaderElector { - case cluster.EtcdLeaderElector: if c.EtcdElectionPrefix == "" { return fmt.Errorf("etcd-election-prefix must be set") diff --git a/lncfg/color_test.go b/lncfg/color_test.go index b4a0c9308..ae68be898 100644 --- a/lncfg/color_test.go +++ b/lncfg/color_test.go @@ -24,7 +24,6 @@ func TestParseHexColor(t *testing.T) { // Perform the table driven tests. for _, ct := range colorTestCases { - color, err := ParseHexColor(ct.test) if !ct.valid && err == nil { t.Fatalf("Invalid color string: %s, should return "+ diff --git a/lnd.go b/lnd.go index e1a0d1a7c..2e37952c6 100644 --- a/lnd.go +++ b/lnd.go @@ -12,7 +12,7 @@ import ( "io/ioutil" "net" "net/http" - _ "net/http/pprof" // Blank import to set up profiling HTTP handlers. + _ "net/http/pprof" // nolint:gosec // used to set up profiling HTTP handlers. "os" "runtime/pprof" "strings" diff --git a/lnrpc/invoicesrpc/addinvoice.go b/lnrpc/invoicesrpc/addinvoice.go index 25a57e8ff..44aa09ae2 100644 --- a/lnrpc/invoicesrpc/addinvoice.go +++ b/lnrpc/invoicesrpc/addinvoice.go @@ -157,7 +157,6 @@ func (d *AddInvoiceData) paymentHashAndPreimage() ( // The preimage will always be nil. func (d *AddInvoiceData) ampPaymentHashAndPreimage() (*lntypes.Preimage, lntypes.Hash, error) { switch { - // Preimages cannot be set on AMP invoice. case d.Preimage != nil: return nil, lntypes.Hash{}, @@ -285,7 +284,6 @@ func AddInvoice(ctx context.Context, cfg *AddInvoiceConfig, } switch { - // If expiry is set, specify it. If it is not provided, no expiry time // will be explicitly added to this payment request, which will imply // the default 3600 seconds. @@ -313,7 +311,6 @@ func AddInvoice(ctx context.Context, cfg *AddInvoiceConfig, // Otherwise, use the default AMP expiry. default: options = append(options, zpay32.Expiry(DefaultAMPInvoiceExpiry)) - } // If the description hash is set, then we add it do the list of options. @@ -661,7 +658,7 @@ func sufficientHints(numHints, maxHints, scalingFactor int, amount, // channels. The set of hop hints will be returned as a slice of functional // options that'll append the route hint to the set of all route hints. // -// TODO(roasbeef): do proper sub-set sum max hints usually << numChans +// TODO(roasbeef): do proper sub-set sum max hints usually << numChans. func SelectHopHints(amtMSat lnwire.MilliSatoshi, cfg *SelectHopHintsCfg, openChannels []*HopHintInfo, numMaxHophints int) [][]zpay32.HopHint { diff --git a/lnrpc/invoicesrpc/addinvoice_test.go b/lnrpc/invoicesrpc/addinvoice_test.go index 556a1c9ed..0757c5c54 100644 --- a/lnrpc/invoicesrpc/addinvoice_test.go +++ b/lnrpc/invoicesrpc/addinvoice_test.go @@ -461,7 +461,6 @@ func TestSelectHopHints(t *testing.T) { setMockChannelUsed( h, private1ShortID, privateChan1Policy, ) - }, // Add two channels that we'd want to use, but the // second one will be cut off due to our hop hint count diff --git a/lnrpc/invoicesrpc/utils.go b/lnrpc/invoicesrpc/utils.go index 731431b00..9d16b698b 100644 --- a/lnrpc/invoicesrpc/utils.go +++ b/lnrpc/invoicesrpc/utils.go @@ -38,7 +38,6 @@ func decodePayReq(invoice *channeldb.Invoice, "request: %v", err) } return decoded, nil - } // CreateRPCInvoice creates an *lnrpc.Invoice from the *channeldb.Invoice. @@ -179,7 +178,6 @@ func CreateRPCInvoice(invoice *channeldb.Invoice, rpcInvoice.AmpInvoiceState = make(map[string]*lnrpc.AMPInvoiceState) for setID, ampState := range invoice.AMPState { - setIDStr := hex.EncodeToString(setID[:]) var state lnrpc.InvoiceHTLCState diff --git a/lnrpc/marshall_utils.go b/lnrpc/marshall_utils.go index 013e1f9be..f809788da 100644 --- a/lnrpc/marshall_utils.go +++ b/lnrpc/marshall_utils.go @@ -27,7 +27,6 @@ func CalculateFeeLimit(feeLimit *FeeLimit, amount lnwire.MilliSatoshi) lnwire.MilliSatoshi { switch feeLimit.GetLimit().(type) { - case *FeeLimit_Fixed: return lnwire.NewMSatFromSatoshis( btcutil.Amount(feeLimit.GetFixed()), @@ -89,7 +88,6 @@ func MarshalUtxos(utxos []*lnwallet.Utxo, activeNetParams *chaincfg.Params) ( // address type. var addrType AddressType switch utxo.AddressType { - case lnwallet.WitnessPubKey: addrType = AddressType_WITNESS_PUBKEY_HASH diff --git a/lnrpc/routerrpc/router_backend.go b/lnrpc/routerrpc/router_backend.go index e9884c11f..a46a9de93 100644 --- a/lnrpc/routerrpc/router_backend.go +++ b/lnrpc/routerrpc/router_backend.go @@ -31,7 +31,7 @@ const ( // for MPP when the user is attempting to send a payment. // // TODO(roasbeef): make this value dynamic based on expected number of - // attempts for given amount + // attempts for given amount. DefaultMaxParts = 16 ) @@ -1008,7 +1008,6 @@ func UnmarshalMPP(reqMPP *lnrpc.MPPRecord) (*record.MPP, error) { reqAddr := reqMPP.PaymentAddr switch { - // No MPP fields were provided. case reqTotal == 0 && len(reqAddr) == 0: return nil, fmt.Errorf("missing total_msat and payment_addr") @@ -1110,7 +1109,6 @@ func marshallHtlcFailure(failure *channeldb.HTLCFailInfo) (*lnrpc.Failure, } switch failure.Reason { - case channeldb.HTLCFailUnknown: rpcFailure.Code = lnrpc.Failure_UNKNOWN_FAILURE @@ -1191,7 +1189,6 @@ func marshallWireError(msg lnwire.FailureMessage, response *lnrpc.Failure) error { switch onionErr := msg.(type) { - case *lnwire.FailIncorrectDetails: response.Code = lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS response.Height = onionErr.Height() @@ -1412,7 +1409,6 @@ func marshallPaymentFailureReason(reason *channeldb.FailureReason) ( } switch *reason { - case channeldb.FailureReasonTimeout: return lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT, nil diff --git a/lnrpc/routerrpc/router_backend_test.go b/lnrpc/routerrpc/router_backend_test.go index 629a8ce6d..52baa6f51 100644 --- a/lnrpc/routerrpc/router_backend_test.go +++ b/lnrpc/routerrpc/router_backend_test.go @@ -336,7 +336,6 @@ func TestUnmarshalMPP(t *testing.T) { func testUnmarshalMPP(t *testing.T, test unmarshalMPPTest) { mpp, err := UnmarshalMPP(test.mpp) switch test.outcome { - // Valid arguments should result in no error, a non-nil MPP record, and // the fields should be set correctly. case valid: diff --git a/lnrpc/routerrpc/subscribe_events.go b/lnrpc/routerrpc/subscribe_events.go index d0969dc5e..f738cf38c 100644 --- a/lnrpc/routerrpc/subscribe_events.go +++ b/lnrpc/routerrpc/subscribe_events.go @@ -141,9 +141,7 @@ func rpcFailReason(linkErr *htlcswitch.LinkError) (lnrpc.Failure_FailureCode, default: return 0, 0, fmt.Errorf("unknown failure "+ "detail type: %T", linkErr.FailureDetail) - } - } // rpcFailureResolution maps an invoice failure resolution to a rpc failure diff --git a/lnrpc/signrpc/signer_server.go b/lnrpc/signrpc/signer_server.go index c1b8e96d3..cd4a649d6 100644 --- a/lnrpc/signrpc/signer_server.go +++ b/lnrpc/signrpc/signer_server.go @@ -632,7 +632,6 @@ func (s *Server) DeriveSharedKey(_ context.Context, in *SharedKeyRequest) ( // is zero. func parseRawKeyBytes(rawKeyBytes []byte) (*btcec.PublicKey, error) { switch { - case len(rawKeyBytes) == 33: // If a proper raw key was provided, then we'll attempt // to decode and parse it. diff --git a/lnrpc/walletrpc/config_active.go b/lnrpc/walletrpc/config_active.go index 806dbca48..13cac7f56 100644 --- a/lnrpc/walletrpc/config_active.go +++ b/lnrpc/walletrpc/config_active.go @@ -15,7 +15,7 @@ import ( const ( // SubServerName is the name of the sub rpc server. We'll use this name // to register ourselves, and we also require that the main - // SubServerConfigDispatcher instance recognize as the name of our + // SubServerConfigDispatcher instance recognize as the name of our. SubServerName = "WalletKitRPC" ) diff --git a/lnrpc/walletrpc/walletkit_server.go b/lnrpc/walletrpc/walletkit_server.go index d0e807c6d..29f29f82a 100644 --- a/lnrpc/walletrpc/walletkit_server.go +++ b/lnrpc/walletrpc/walletkit_server.go @@ -1399,6 +1399,7 @@ func (w *WalletKit) ListAccounts(ctx context.Context, // wallet in the response if they don't have any keys imported. if account.AccountName == waddrmgr.ImportedAddrAccountName && account.ImportedKeyCount == 0 { + continue } diff --git a/lntest/harness_node.go b/lntest/harness_node.go index 984a91faa..04dda9293 100644 --- a/lntest/harness_node.go +++ b/lntest/harness_node.go @@ -295,7 +295,7 @@ func (cfg *BaseNodeConfig) GenArgs() []string { // ] // }, // "chanPoint2": ... -// } +// }. type policyUpdateMap map[string]map[string][]*lnrpc.RoutingPolicy // HarnessNode represents an instance of lnd running within our test network @@ -1189,7 +1189,6 @@ func (hn *HarnessNode) stop() error { return fmt.Errorf("error attempting to stop "+ "grpc client: %v", err) } - } return nil @@ -1207,7 +1206,7 @@ func (hn *HarnessNode) shutdown() error { return nil } -// kill kills the lnd process +// kill kills the lnd process. func (hn *HarnessNode) kill() error { return hn.cmd.Process.Kill() } @@ -1244,7 +1243,6 @@ type chanWatchRequest struct { } func (hn *HarnessNode) checkChanPointInGraph(chanPoint wire.OutPoint) bool { - ctxt, cancel := context.WithTimeout(hn.runCtx, DefaultTimeout) defer cancel() @@ -1288,7 +1286,6 @@ func (hn *HarnessNode) lightningNetworkWatcher() { for { select { - // A new graph update has just been received, so we'll examine // the current set of registered clients to see if we can // dispatch any requests. @@ -1767,7 +1764,6 @@ func (hn *HarnessNode) handlePolicyUpdateWatchRequest(req *chanWatchRequest) { // getChannelPolicies queries the channel graph and formats the policies into // the format defined in type policyUpdateMap. func (hn *HarnessNode) getChannelPolicies(include bool) policyUpdateMap { - ctxt, cancel := context.WithTimeout(hn.runCtx, DefaultTimeout) defer cancel() @@ -1782,7 +1778,6 @@ func (hn *HarnessNode) getChannelPolicies(include bool) policyUpdateMap { policyUpdates := policyUpdateMap{} for _, e := range graph.Edges { - policies := policyUpdates[e.ChanPoint] // If the map[op] is nil, we need to initialize the map first. diff --git a/lntest/itest/assertions.go b/lntest/itest/assertions.go index a0c659306..ea8959dad 100644 --- a/lntest/itest/assertions.go +++ b/lntest/itest/assertions.go @@ -527,7 +527,6 @@ func assertConnected(t *harnessTest, alice, bob *lntest.HarnessNode) { } return nil - }, defaultTimeout) require.NoError(t.t, err) } @@ -1004,6 +1003,7 @@ func assertChannelConstraintsEqual( func assertAmountPaid(t *harnessTest, channelName string, node *lntest.HarnessNode, chanPoint wire.OutPoint, amountSent, amountReceived int64) { + ctxb := context.Background() checkAmountPaid := func() error { @@ -1027,6 +1027,7 @@ func assertAmountPaid(t *harnessTest, channelName string, } if channel.TotalSatoshisReceived != amountReceived { + return fmt.Errorf("%v: incorrect amount"+ " received: %v != %v", channelName, @@ -1068,6 +1069,7 @@ func assertAmountPaid(t *harnessTest, channelName string, // node reports the expected number of pending channels. func assertNumPendingChannels(t *harnessTest, node *lntest.HarnessNode, expWaitingClose, expPendingForceClose int) { + ctxb := context.Background() var predErr error @@ -1394,6 +1396,7 @@ func verifyCloseUpdate(chanUpdate *lnrpc.ChannelEventUpdate, case *lnrpc.ChannelEventUpdate_ClosedChannel: if chanUpdate.Type != lnrpc.ChannelEventUpdate_CLOSED_CHANNEL { + return fmt.Errorf("update type mismatch: expected %v, got %v", lnrpc.ChannelEventUpdate_CLOSED_CHANNEL, chanUpdate.Type) @@ -1432,6 +1435,7 @@ func verifyCloseUpdate(chanUpdate *lnrpc.ChannelEventUpdate, // reaches the desired number of total channels. func assertNodeNumChannels(t *harnessTest, node *lntest.HarnessNode, numChannels int) { + ctxb := context.Background() // Poll node for its list of channels. diff --git a/lntest/itest/lnd_channel_force_close_test.go b/lntest/itest/lnd_channel_force_close_test.go index 9bc36e932..bcf72134d 100644 --- a/lntest/itest/lnd_channel_force_close_test.go +++ b/lntest/itest/lnd_channel_force_close_test.go @@ -1085,7 +1085,6 @@ func channelForceClosureTest(net *lntest.NetworkHarness, t *harnessTest, numBlocks := uint32(defaultCSV - 1) if channelType == lnrpc.CommitmentType_ANCHORS { numBlocks = defaultCSV - 2 - } _, err = net.Miner.Client.Generate(numBlocks) if err != nil { diff --git a/lntest/itest/lnd_channel_policy_test.go b/lntest/itest/lnd_channel_policy_test.go index dfad04baa..33230a5e3 100644 --- a/lntest/itest/lnd_channel_policy_test.go +++ b/lntest/itest/lnd_channel_policy_test.go @@ -909,5 +909,4 @@ func testUpdateChannelPolicyFeeRateAccuracy(net *lntest.NetworkHarness, assertPolicyUpdate( t, nodes, net.Alice.PubKeyStr, expectedPolicy, chanPoint, ) - } diff --git a/lntest/itest/lnd_etcd_failover_test.go b/lntest/itest/lnd_etcd_failover_test.go index 96ed6aa9f..81050e503 100644 --- a/lntest/itest/lnd_etcd_failover_test.go +++ b/lntest/itest/lnd_etcd_failover_test.go @@ -153,7 +153,6 @@ func testEtcdFailoverCase(net *lntest.NetworkHarness, ht *harnessTest, } failoverTimeout = 2 * time.Minute - } else { shutdownAndAssert(net, ht, carol1) failoverTimeout = 30 * time.Second diff --git a/lntest/itest/lnd_forward_interceptor_test.go b/lntest/itest/lnd_forward_interceptor_test.go index da0f7def9..2765445c1 100644 --- a/lntest/itest/lnd_forward_interceptor_test.go +++ b/lntest/itest/lnd_forward_interceptor_test.go @@ -425,7 +425,6 @@ func testForwardInterceptorBasic(net *lntest.NetworkHarness, t *harnessTest) { return err == nil && len(channels.Channels) > 0 }, defaultTimeout) require.NoError(t.t, err, "alice <> bob channel didn't re-activate") - } // interceptorTestContext is a helper struct to hold the test context and diff --git a/lntest/itest/lnd_funding_test.go b/lntest/itest/lnd_funding_test.go index 9043ccba8..0c23ecd47 100644 --- a/lntest/itest/lnd_funding_test.go +++ b/lntest/itest/lnd_funding_test.go @@ -77,7 +77,6 @@ func testBasicChannelFunding(net *lntest.NetworkHarness, t *harnessTest) { expType := carolCommitType switch daveCommitType { - // Dave supports anchors, type will be what // Carol supports. case lnrpc.CommitmentType_ANCHORS: diff --git a/lntest/itest/lnd_misc_test.go b/lntest/itest/lnd_misc_test.go index b96d588f3..8aed1c16c 100644 --- a/lntest/itest/lnd_misc_test.go +++ b/lntest/itest/lnd_misc_test.go @@ -473,7 +473,6 @@ func testListChannels(net *lntest.NetworkHarness, t *harnessTest) { assertChannelConstraintsEqual( t, aliceChannel.RemoteConstraints, bobChannel.LocalConstraints, ) - } // testMaxPendingChannels checks that error is returned from remote peer if @@ -523,6 +522,7 @@ func testMaxPendingChannels(net *lntest.NetworkHarness, t *harnessTest) { } else if !strings.Contains( err.Error(), lnwire.ErrMaxPendingChannels.Error(), ) { + t.Fatalf("not expected error was received: %v", err) } @@ -773,7 +773,6 @@ func testGarbageCollectLinkNodes(net *lntest.NetworkHarness, t *harnessTest) { predErr = checkNumForceClosedChannels(pendingChanResp, 0) return predErr == nil - }, defaultTimeout) if err != nil { t.Fatalf("channels not marked as fully resolved: %v", predErr) diff --git a/lntest/itest/lnd_multi-hop-payments_test.go b/lntest/itest/lnd_multi-hop-payments_test.go index f282d9d95..d0538be44 100644 --- a/lntest/itest/lnd_multi-hop-payments_test.go +++ b/lntest/itest/lnd_multi-hop-payments_test.go @@ -369,6 +369,7 @@ func assertHtlcEvents(t *harnessTest, fwdCount, fwdFailCount, settleCount int, // type is different from the htlc event type (forward, link failure etc). func assertEventAndType(t *harnessTest, eventType routerrpc.HtlcEvent_EventType, client routerrpc.Router_SubscribeHtlcEventsClient) *routerrpc.HtlcEvent { + event, err := client.Recv() if err != nil { t.Fatalf("could not get event") diff --git a/lntest/itest/lnd_multi-hop_htlc_aggregation_test.go b/lntest/itest/lnd_multi-hop_htlc_aggregation_test.go index f17db42fe..bdce29711 100644 --- a/lntest/itest/lnd_multi-hop_htlc_aggregation_test.go +++ b/lntest/itest/lnd_multi-hop_htlc_aggregation_test.go @@ -299,7 +299,6 @@ func testMultiHopHtlcAggregation(net *lntest.NetworkHarness, t *harnessTest, break } } - } // In case of anchor we expect all the timeout and success second @@ -311,7 +310,6 @@ func testMultiHopHtlcAggregation(net *lntest.NetworkHarness, t *harnessTest, } else { require.Len(t.t, timeoutTxs, numInvoices) require.Len(t.t, successTxs, numInvoices) - } // All mempool transactions should be spending from the commitment diff --git a/lntest/itest/lnd_multi-hop_test.go b/lntest/itest/lnd_multi-hop_test.go index 008e89ea4..10c5e20e5 100644 --- a/lntest/itest/lnd_multi-hop_test.go +++ b/lntest/itest/lnd_multi-hop_test.go @@ -16,7 +16,6 @@ import ( ) func testMultiHopHtlcClaims(net *lntest.NetworkHarness, t *harnessTest) { - type testCase struct { name string test func(net *lntest.NetworkHarness, t *harnessTest, alice, @@ -180,7 +179,6 @@ func checkPaymentStatus(node *lntest.HarnessNode, preimage lntypes.Preimage, } switch status { - // If this expected status is SUCCEEDED, we expect the final preimage. case lnrpc.Payment_SUCCEEDED: if p.PaymentPreimage != preimage.String() { @@ -195,7 +193,6 @@ func checkPaymentStatus(node *lntest.HarnessNode, preimage lntypes.Preimage, p.PaymentPreimage) } } - } if !found { diff --git a/lntest/itest/lnd_recovery_test.go b/lntest/itest/lnd_recovery_test.go index af56c7a6f..1dc1484bf 100644 --- a/lntest/itest/lnd_recovery_test.go +++ b/lntest/itest/lnd_recovery_test.go @@ -77,6 +77,7 @@ func testGetRecoveryInfo(net *lntest.NetworkHarness, t *harnessTest) { if recoveryMode != expectedRecoveryMode || recoveryFinished != expectedRecoveryFinished || progress != expectedProgress { + return false } diff --git a/lntest/itest/lnd_revocation_test.go b/lntest/itest/lnd_revocation_test.go index 4de83d436..be996e001 100644 --- a/lntest/itest/lnd_revocation_test.go +++ b/lntest/itest/lnd_revocation_test.go @@ -1072,7 +1072,6 @@ func testRevokedCloseRetributionAltruistWatchtowerCase( ) if err != nil { return err - } if bkpStats == nil { return errors.New("no active backup sessions") diff --git a/lntest/itest/lnd_routing_test.go b/lntest/itest/lnd_routing_test.go index 99ba3c322..61989e42f 100644 --- a/lntest/itest/lnd_routing_test.go +++ b/lntest/itest/lnd_routing_test.go @@ -725,9 +725,8 @@ func testSendToRouteErrorPropagation(net *lntest.NetworkHarness, t *harnessTest) // At this place we should get an rpc error with notification // that edge is not found on hop(0) - if _, err := alicePayStream.Recv(); err != nil && strings.Contains(err.Error(), - "edge not found") { - + _, err = alicePayStream.Recv() + if err != nil && strings.Contains(err.Error(), "edge not found") { } else if err != nil { t.Fatalf("payment stream has been closed but fake route has consumed: %v", err) } @@ -1423,7 +1422,7 @@ func testMultiHopOverPrivateChannels(net *lntest.NetworkHarness, t *harnessTest) closeChannelAndAssert(t, net, carol, chanPointCarol, false) } -// computeFee calculates the payment fee as specified in BOLT07 +// computeFee calculates the payment fee as specified in BOLT07. func computeFee(baseFee, feeRate, amt lnwire.MilliSatoshi) lnwire.MilliSatoshi { return baseFee + amt*feeRate/1000000 } diff --git a/lntest/itest/lnd_send_multi_path_payment_test.go b/lntest/itest/lnd_send_multi_path_payment_test.go index 45b25b446..2e3d23e1b 100644 --- a/lntest/itest/lnd_send_multi_path_payment_test.go +++ b/lntest/itest/lnd_send_multi_path_payment_test.go @@ -129,7 +129,6 @@ func testSendMultiPathPayment(net *lntest.NetworkHarness, t *harnessTest) { if htlc.State == lnrpc.InvoiceHTLCState_SETTLED { settled++ } - } if settled != succeeded { t.Fatalf("expected invoice to be settled "+ diff --git a/lntest/itest/lnd_switch_test.go b/lntest/itest/lnd_switch_test.go index 4892ef543..6d09e1b5a 100644 --- a/lntest/itest/lnd_switch_test.go +++ b/lntest/itest/lnd_switch_test.go @@ -211,7 +211,6 @@ func testSwitchCircuitPersistence(net *lntest.NetworkHarness, t *harnessTest) { err = wait.Predicate(func() bool { predErr = assertNumActiveHtlcs(nodes, 0) return predErr == nil - }, defaultTimeout) if err != nil { t.Fatalf("htlc mismatch: %v", predErr) @@ -737,7 +736,6 @@ func testSwitchOfflineDeliveryPersistence(net *lntest.NetworkHarness, t *harness err = wait.Predicate(func() bool { predErr = assertNumActiveHtlcs(nodes, numPayments) return predErr == nil - }, defaultTimeout) if err != nil { t.Fatalf("htlc mismatch: %v", predErr) diff --git a/lntest/itest/lnd_test.go b/lntest/itest/lnd_test.go index f88026c32..ebffaa91c 100644 --- a/lntest/itest/lnd_test.go +++ b/lntest/itest/lnd_test.go @@ -42,7 +42,7 @@ var ( "split test cases with the given (0-based) index", ) - // dbBackendFlag specifies the backend to use + // dbBackendFlag specifies the backend to use. dbBackendFlag = flag.String("dbbackend", "bbolt", "Database backend "+ "(bbolt, etcd, postgres)") ) diff --git a/lntest/itest/test_harness.go b/lntest/itest/test_harness.go index 494db9d42..c6f16e4d4 100644 --- a/lntest/itest/test_harness.go +++ b/lntest/itest/test_harness.go @@ -97,7 +97,6 @@ func (h *harnessTest) Fatalf(format string, a ...interface{}) { // RunTestCase executes a harness test case. Any errors or panics will be // represented as fatal. func (h *harnessTest) RunTestCase(testCase *testCase) { - h.testCase = testCase defer func() { h.testCase = nil diff --git a/lntest/itest/utils.go b/lntest/itest/utils.go index 84c3d776e..1cab926fb 100644 --- a/lntest/itest/utils.go +++ b/lntest/itest/utils.go @@ -136,7 +136,7 @@ func completePaymentRequests(client lnrpc.LightningClient, return nil } -// makeFakePayHash creates random pre image hash +// makeFakePayHash creates random pre image hash. func makeFakePayHash(t *harnessTest) []byte { randBuf := make([]byte, 32) @@ -190,7 +190,6 @@ func createPayReqs(node *lntest.HarnessNode, paymentAmt btcutil.Amount, // getChanInfo is a helper method for getting channel info for a node's sole // channel. func getChanInfo(node *lntest.HarnessNode) (*lnrpc.Channel, error) { - ctxb := context.Background() ctx, cancel := context.WithTimeout(ctxb, defaultTimeout) defer cancel() @@ -301,7 +300,6 @@ func calculateMaxHtlc(chanCap btcutil.Amount) uint64 { // waitForNodeBlockHeight queries the node for its current block height until // it reaches the passed height. func waitForNodeBlockHeight(node *lntest.HarnessNode, height int32) error { - ctxb := context.Background() ctx, cancel := context.WithTimeout(ctxb, defaultTimeout) defer cancel() diff --git a/lnwallet/btcwallet/btcwallet.go b/lnwallet/btcwallet/btcwallet.go index dcd90bd9e..e6ff3a919 100644 --- a/lnwallet/btcwallet/btcwallet.go +++ b/lnwallet/btcwallet/btcwallet.go @@ -940,11 +940,9 @@ func (b *BtcWallet) ListUnspentWitness(minConfs, maxConfs int32, // network (either in the mempool or chain) no error will be returned. func (b *BtcWallet) PublishTransaction(tx *wire.MsgTx, label string) error { if err := b.wallet.PublishTransaction(tx, label); err != nil { - // If we failed to publish the transaction, check whether we // got an error of known type. switch err.(type) { - // If the wallet reports a double spend, convert it to our // internal ErrDoubleSpend and return. case *base.ErrDoubleSpend: @@ -1384,6 +1382,7 @@ func (b *BtcWallet) GetRecoveryInfo() (bool, float64, error) { // rollback happens. In that case, we will return zero progress here. if syncState.Height < birthdayBlock.Height || bestHeight < birthdayBlock.Height { + return isRecoveryMode, progress, nil } diff --git a/lnwallet/chainfee/estimator.go b/lnwallet/chainfee/estimator.go index 0eedee64a..c8a0edd9e 100644 --- a/lnwallet/chainfee/estimator.go +++ b/lnwallet/chainfee/estimator.go @@ -85,7 +85,6 @@ type StaticEstimator struct { // NewStaticEstimator returns a new static fee estimator instance. func NewStaticEstimator(feePerKW, relayFee SatPerKWeight) *StaticEstimator { - return &StaticEstimator{ feePerKW: feePerKW, relayFee: relayFee, diff --git a/lnwallet/chainfee/estimator_test.go b/lnwallet/chainfee/estimator_test.go index 0ac92a562..4146c4dca 100644 --- a/lnwallet/chainfee/estimator_test.go +++ b/lnwallet/chainfee/estimator_test.go @@ -321,5 +321,4 @@ func TestGetCachedFee(t *testing.T) { require.ErrorIs(t, err, tc.expectErr) }) } - } diff --git a/lnwallet/chancloser/chancloser.go b/lnwallet/chancloser/chancloser.go index 2eaa83288..6512dddf5 100644 --- a/lnwallet/chancloser/chancloser.go +++ b/lnwallet/chancloser/chancloser.go @@ -334,7 +334,6 @@ func (c *ChanCloser) ProcessCloseMsg(msg lnwire.Message) ([]lnwire.Message, bool, error) { switch c.state { - // If we're in the close idle state, and we're receiving a channel closure // related message, then this indicates that we're on the receiving side of // an initiated channel closure. @@ -662,7 +661,6 @@ func calcCompromiseFee(chanPoint wire.OutPoint, ourIdealFee, lastSentFee, // Otherwise, we'll need to attempt to make a fee compromise if this is the // second round, and neither side has agreed on fees. switch { - // If their proposed fee is identical to our ideal fee, then we'll go with // that as we can short circuit the fee negotiation. Similarly, if we // haven't sent an offer yet, we'll default to our ideal fee. diff --git a/lnwallet/chanfunding/coin_select.go b/lnwallet/chanfunding/coin_select.go index e73a11b8d..6f1ac3735 100644 --- a/lnwallet/chanfunding/coin_select.go +++ b/lnwallet/chanfunding/coin_select.go @@ -73,7 +73,6 @@ func calculateFees(utxos []Coin, feeRate chainfee.SatPerKWeight) (btcutil.Amount var weightEstimate input.TxWeightEstimator for _, utxo := range utxos { switch { - case txscript.IsPayToWitnessPubKeyHash(utxo.PkScript): weightEstimate.AddP2WKHInput() @@ -151,7 +150,6 @@ func CoinSelect(feeRate chainfee.SatPerKWeight, amt, dustLimit btcutil.Amount, var changeAmt btcutil.Amount switch { - // If the excess amount isn't enough to pay for fees based on // fee rate and estimated size without using a change output, // then increase the requested coin amount by the estimate @@ -171,7 +169,6 @@ func CoinSelect(feeRate chainfee.SatPerKWeight, amt, dustLimit btcutil.Amount, // change output. default: changeAmt = 0 - } if changeAmt < dustLimit { diff --git a/lnwallet/chanfunding/psbt_assembler.go b/lnwallet/chanfunding/psbt_assembler.go index 945359c2d..830bb3b6d 100644 --- a/lnwallet/chanfunding/psbt_assembler.go +++ b/lnwallet/chanfunding/psbt_assembler.go @@ -428,7 +428,6 @@ func (i *PsbtIntent) Inputs() []wire.OutPoint { var inputs []wire.OutPoint switch i.State { - // We return the inputs to the pending psbt. case PsbtVerified: for _, in := range i.PendingPsbt.UnsignedTx.TxIn { @@ -453,7 +452,6 @@ func (i *PsbtIntent) Inputs() []wire.OutPoint { // know about. These are only known after the PSBT has been verified. func (i *PsbtIntent) Outputs() []*wire.TxOut { switch i.State { - // We return the outputs of the pending psbt. case PsbtVerified: return i.PendingPsbt.UnsignedTx.TxOut diff --git a/lnwallet/channel.go b/lnwallet/channel.go index ea6d185a5..fe519d8c9 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -1541,7 +1541,6 @@ func (lc *LightningChannel) localLogUpdateToPayDesc(logUpdate *channeldb.LogUpda // Since Add updates aren't saved to disk under this key, the update will // never be an Add. switch wireMsg := logUpdate.UpdateMsg.(type) { - // For HTLCs that we settled, we'll fetch the original offered HTLC from // the remote update log so we can retrieve the same PaymentDescriptor that // ReceiveHTLCSettle would produce. @@ -1621,7 +1620,6 @@ func (lc *LightningChannel) remoteLogUpdateToPayDesc(logUpdate *channeldb.LogUpd error) { switch wireMsg := logUpdate.UpdateMsg.(type) { - case *lnwire.UpdateAddHTLC: pd := &PaymentDescriptor{ RHash: wireMsg.PaymentHash, @@ -1884,7 +1882,6 @@ func (lc *LightningChannel) restoreStateLogs( // To ensure proper channel operation, we restore the add's addCommitHeightLocal // field to the height of our local commitment. for _, logUpdate := range unsignedAckedUpdates { - var htlcIdx uint64 switch wireMsg := logUpdate.UpdateMsg.(type) { case *lnwire.UpdateFulfillHTLC: @@ -1912,7 +1909,6 @@ func (lc *LightningChannel) restoreStateLogs( // To ensure proper channel operation, we restore the add's addCommitHeightRemote // field to the height of the remote commitment. for _, logUpdate := range remoteUnsignedLocalUpdates { - var htlcIdx uint64 switch wireMsg := logUpdate.UpdateMsg.(type) { case *lnwire.UpdateFulfillHTLC: @@ -3004,6 +3000,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, chanType, true, false, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, ) { + continue } @@ -3058,6 +3055,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, chanType, false, false, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, ) { + continue } @@ -3507,7 +3505,8 @@ func (lc *LightningChannel) validateCommitmentSanity(theirLogCounter, // any). The HTLC signatures are sorted according to the BIP 69 order of the // HTLC's on the commitment transaction. Finally, the new set of pending HTLCs // for the remote party's commitment are also returned. -func (lc *LightningChannel) SignNextCommitment() (lnwire.Sig, []lnwire.Sig, []channeldb.HTLC, error) { +func (lc *LightningChannel) SignNextCommitment() (lnwire.Sig, []lnwire.Sig, + []channeldb.HTLC, error) { lc.Lock() defer lc.Unlock() @@ -3531,7 +3530,6 @@ func (lc *LightningChannel) SignNextCommitment() (lnwire.Sig, []lnwire.Sig, []ch // new state, we consume a prior revocation point. commitPoint := lc.channelState.RemoteNextRevocation if lc.remoteCommitChain.hasUnackedCommitment() || commitPoint == nil { - return sig, htlcSigs, nil, ErrNoWindow } @@ -4054,6 +4052,7 @@ func (lc *LightningChannel) computeView(view *htlcView, remoteChain bool, lc.channelState.ChanType, false, !remoteChain, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, ) { + continue } @@ -4064,6 +4063,7 @@ func (lc *LightningChannel) computeView(view *htlcView, remoteChain bool, lc.channelState.ChanType, true, !remoteChain, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, ) { + continue } @@ -4567,7 +4567,6 @@ func (lc *LightningChannel) oweCommitment(local bool) bool { // have added to our remote commitment tx yet. remoteUpdatesPending = lastLocalCommit.theirMessageIndex != lastRemoteCommit.theirMessageIndex - } else { perspective = "remote" @@ -5029,6 +5028,7 @@ func (lc *LightningChannel) GetDustSum(remote bool) lnwire.MilliSatoshi { if HtlcIsDust( chanType, false, !remote, feeRate, amt, dustLimit, ) { + dustSum += pd.Amount } } @@ -5047,6 +5047,7 @@ func (lc *LightningChannel) GetDustSum(remote bool) lnwire.MilliSatoshi { if HtlcIsDust( chanType, true, !remote, feeRate, amt, dustLimit, ) { + dustSum += pd.Amount } } @@ -6152,6 +6153,7 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, ourCommit bool, chanType, htlc.Incoming, ourCommit, feePerKw, htlc.Amt.ToSatoshis(), dustLimit, ) { + continue } @@ -7071,7 +7073,6 @@ func (lc *LightningChannel) IdealCommitFeeRate(netFeeRate, minRelayFeeRate, // Otherwise, cap the fee rate at the max fee rate. switch lc.channelState.ChanType.HasAnchors() && maxFeeRate > maxAnchorCommitFeeRate { - case true: commitFeeRate = chainfee.SatPerKWeight( math.Min( diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 030320ffc..08a5d6f0e 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -2576,6 +2576,7 @@ func TestUpdateFeeSenderCommits(t *testing.T) { if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) == fee { + t.Fatalf("bob's feePerKw was unexpectedly locked in") } @@ -2589,6 +2590,7 @@ func TestUpdateFeeSenderCommits(t *testing.T) { if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) != fee { + t.Fatalf("bob's feePerKw was not locked in") } @@ -2617,6 +2619,7 @@ func TestUpdateFeeSenderCommits(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) == fee { + t.Fatalf("alice's feePerKw was unexpectedly locked in") } @@ -2630,6 +2633,7 @@ func TestUpdateFeeSenderCommits(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) != fee { + t.Fatalf("alice's feePerKw was not locked in") } @@ -2728,6 +2732,7 @@ func TestUpdateFeeReceiverCommits(t *testing.T) { if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) == fee { + t.Fatalf("bob's feePerKw was unexpectedly locked in") } @@ -2742,6 +2747,7 @@ func TestUpdateFeeReceiverCommits(t *testing.T) { if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) != fee { + t.Fatalf("bob's feePerKw was not locked in") } @@ -2769,6 +2775,7 @@ func TestUpdateFeeReceiverCommits(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) == fee { + t.Fatalf("alice's feePerKw was unexpectedly locked in") } @@ -2782,6 +2789,7 @@ func TestUpdateFeeReceiverCommits(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) != fee { + t.Fatalf("Alice's feePerKw was not locked in") } @@ -2871,6 +2879,7 @@ func TestUpdateFeeMultipleUpdates(t *testing.T) { if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) == fee { + t.Fatalf("bob's feePerKw was unexpectedly locked in") } @@ -2896,6 +2905,7 @@ func TestUpdateFeeMultipleUpdates(t *testing.T) { if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) != fee { + t.Fatalf("bob's feePerKw was not locked in") } @@ -2923,6 +2933,7 @@ func TestUpdateFeeMultipleUpdates(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) == fee { + t.Fatalf("alice's feePerKw was unexpectedly locked in") } @@ -2936,6 +2947,7 @@ func TestUpdateFeeMultipleUpdates(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) != fee { + t.Fatalf("alice's feePerKw was not locked in") } @@ -4632,11 +4644,13 @@ func TestChannelRetransmissionFeeUpdate(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) != newFeeRate { + t.Fatalf("alice's feePerKw was not locked in") } if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) != newFeeRate { + t.Fatalf("bob's feePerKw was not locked in") } @@ -4851,11 +4865,13 @@ func TestFeeUpdateOldDiskFormat(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) != newFeeRate { + t.Fatalf("alice's feePerKw was not locked in") } if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) != newFeeRate { + t.Fatalf("bob's feePerKw was not locked in") } @@ -4880,11 +4896,13 @@ func TestFeeUpdateOldDiskFormat(t *testing.T) { if chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) != newFeeRate { + t.Fatalf("alice's feePerKw was not locked in") } if chainfee.SatPerKWeight( bobChannel.channelState.LocalCommitment.FeePerKw, ) != newFeeRate { + t.Fatalf("bob's feePerKw was not locked in") } } @@ -8506,7 +8524,6 @@ func TestFetchParent(t *testing.T) { test.parentIndex, parent.HtlcIndex) } }) - } } diff --git a/lnwallet/commitment.go b/lnwallet/commitment.go index 6260318ea..86b5a1c0c 100644 --- a/lnwallet/commitment.go +++ b/lnwallet/commitment.go @@ -293,7 +293,6 @@ func CommitScriptToRemote(chanType channeldb.ChannelType, initiator bool, WitnessScript: p2wkh, PkScript: p2wkh, }, 0, nil - } } @@ -554,6 +553,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, cb.chanState.ChanType, false, isOurs, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, ) { + continue } @@ -564,6 +564,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, cb.chanState.ChanType, true, isOurs, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, ) { + continue } @@ -647,6 +648,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, cb.chanState.ChanType, false, isOurs, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, ) { + continue } @@ -664,6 +666,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, cb.chanState.ChanType, true, isOurs, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, ) { + continue } diff --git a/lnwallet/reservation.go b/lnwallet/reservation.go index c5e7dfc34..038a80fa9 100644 --- a/lnwallet/reservation.go +++ b/lnwallet/reservation.go @@ -349,7 +349,6 @@ func NewChannelReservation(capacity, localFundingAmt btcutil.Amount, default: chanType |= channeldb.NoFundingTxBit } - } else { // Otherwise, this is a dual funder channel, and no side is // technically the "initiator" @@ -435,6 +434,7 @@ func (r *ChannelReservation) SetNumConfsRequired(numConfs uint16) { // if the parameters are seemed unsound. func (r *ChannelReservation) CommitConstraints(c *channeldb.ChannelConstraints, maxLocalCSVDelay uint16, responder bool) error { + r.Lock() defer r.Unlock() diff --git a/lnwallet/test/test_interface.go b/lnwallet/test/test_interface.go index 66da4f587..c956bba2a 100644 --- a/lnwallet/test/test_interface.go +++ b/lnwallet/test/test_interface.go @@ -1735,6 +1735,7 @@ func txFromOutput(tx *wire.MsgTx, signer input.Signer, fromPubKey, // new, unconfirmed tx that spends this output to pubKey. func newTx(t *testing.T, r *rpctest.Harness, pubKey *btcec.PublicKey, alice *lnwallet.LightningWallet, rbf bool) *wire.MsgTx { + t.Helper() keyScript, err := scriptFromKey(pubKey) @@ -3224,6 +3225,7 @@ func TestLightningWallet(t *testing.T, targetBackEnd string) { if !runTests(t, walletDriver, backEnd, miningNode, rpcConfig, chainNotifier) { + return } } @@ -3521,10 +3523,12 @@ func runTests(t *testing.T, walletDriver *lnwallet.WalletDriver, success := t.Run(testName, func(t *testing.T) { if backEnd == "neutrino" && strings.Contains(walletTest.name, "dual funder") { + t.Skip("skipping dual funder tests for neutrino") } if backEnd == "neutrino" && strings.Contains(walletTest.name, "spend unconfirmed") { + t.Skip("skipping spend unconfirmed tests for neutrino") } @@ -3539,6 +3543,7 @@ func runTests(t *testing.T, walletDriver *lnwallet.WalletDriver, // wipe buckets if err := clearWalletStates(alice, bob); err != nil && err != kvdb.ErrBucketNotFound { + t.Fatalf("unable to wipe wallet state: %v", err) } } diff --git a/lnwallet/wallet.go b/lnwallet/wallet.go index 284d58723..15240ee52 100644 --- a/lnwallet/wallet.go +++ b/lnwallet/wallet.go @@ -941,7 +941,6 @@ func (l *LightningWallet) currentNumAnchorChans() (int, error) { if c.ChanType.HasAnchors() { numAnchors++ } - } for _, c := range chans { @@ -1084,7 +1083,6 @@ func (l *LightningWallet) CheckReservedValueTx(req CheckReservedValueTxReq) ( inputs, req.Tx.TxOut, numAnchors, ) switch { - // If the error returned from CheckReservedValue is // ErrReservedValueInvalidated, then it did nonetheless return // the required reserved value and we check for the optional diff --git a/lnwire/accept_channel_test.go b/lnwire/accept_channel_test.go index a1ab2be48..714ee8441 100644 --- a/lnwire/accept_channel_test.go +++ b/lnwire/accept_channel_test.go @@ -63,6 +63,7 @@ func TestDecodeAcceptChannel(t *testing.T) { if !bytes.Equal( decoded.UpfrontShutdownScript, encoded.UpfrontShutdownScript, ) { + t.Fatalf("decoded script: %x does not equal encoded script: %x", decoded.UpfrontShutdownScript, encoded.UpfrontShutdownScript) } diff --git a/lnwire/extra_bytes_test.go b/lnwire/extra_bytes_test.go index 88ffcc307..6e840a2a6 100644 --- a/lnwire/extra_bytes_test.go +++ b/lnwire/extra_bytes_test.go @@ -60,7 +60,6 @@ func TestExtraOpaqueDataEncodeDecode(t *testing.T) { // time, we'll actually feed in blank bytes. quickCfg := &quick.Config{ Values: func(v []reflect.Value, r *rand.Rand) { - var newTestCase testCase if r.Int31()%2 == 0 { newTestCase.emptyBytes = true diff --git a/lnwire/features_test.go b/lnwire/features_test.go index d4be13d4c..a945eeb3e 100644 --- a/lnwire/features_test.go +++ b/lnwire/features_test.go @@ -89,7 +89,6 @@ func TestFeatureVectorSetUnset(t *testing.T) { t.Errorf("Expectation failed in case %d, bit %d", i, j) break } - } for _, bit := range test.bits { diff --git a/lnwire/message.go b/lnwire/message.go index 72782356b..e6de25d25 100644 --- a/lnwire/message.go +++ b/lnwire/message.go @@ -70,7 +70,6 @@ func ErrorPayloadTooLarge(size int) error { "but maximum message payload is %d bytes", size, MaxMsgBody, ) - } // String return the string representation of message type. diff --git a/lnwire/message_test.go b/lnwire/message_test.go index 55e0c0153..4883ac612 100644 --- a/lnwire/message_test.go +++ b/lnwire/message_test.go @@ -200,7 +200,6 @@ func BenchmarkWriteMessage(b *testing.B) { m := msg // Run each message as a sub benchmark test. b.Run(msg.MsgType().String(), func(b *testing.B) { - b.ResetTimer() for i := 0; i < b.N; i++ { // Fetch a buffer from the pool and reset it. diff --git a/lnwire/open_channel.go b/lnwire/open_channel.go index 273129ad2..ce15fd5d5 100644 --- a/lnwire/open_channel.go +++ b/lnwire/open_channel.go @@ -236,7 +236,6 @@ func (o *OpenChannel) Encode(w *bytes.Buffer, pver uint32) error { if err := WritePublicKey(w, o.HtlcPoint); err != nil { return err - } if err := WritePublicKey(w, o.FirstCommitmentPoint); err != nil { diff --git a/lnwire/query_short_chan_ids_test.go b/lnwire/query_short_chan_ids_test.go index 6a2ecb62d..e42184044 100644 --- a/lnwire/query_short_chan_ids_test.go +++ b/lnwire/query_short_chan_ids_test.go @@ -49,7 +49,6 @@ var ( // TestQueryShortChanIDsUnsorted tests that decoding a QueryShortChanID request // that contains duplicate or unsorted ids returns an ErrUnsortedSIDs failure. func TestQueryShortChanIDsUnsorted(t *testing.T) { - for _, test := range unsortedSidTests { test := test t.Run(test.name, func(t *testing.T) { diff --git a/macaroons/constraints.go b/macaroons/constraints.go index 480339b67..642f8edcf 100644 --- a/macaroons/constraints.go +++ b/macaroons/constraints.go @@ -229,7 +229,6 @@ func GetCustomCaveatCondition(mac *macaroon.Macaroon, "%s %s ", CondLndCustom, customCaveatName, )) for _, caveat := range mac.Caveats() { - // The caveat id has a format of // "lnd-custom [custom-caveat-name] [custom-caveat-condition]" // and we only want the condition part. If we match the prefix diff --git a/macaroons/constraints_test.go b/macaroons/constraints_test.go index db3b73ab8..8bceb0b32 100644 --- a/macaroons/constraints_test.go +++ b/macaroons/constraints_test.go @@ -76,6 +76,7 @@ func TestTimeoutConstraint(t *testing.T) { string(testMacaroon.Caveats()[0].Id), expectedTimeCaveatSubstring, ) { + t.Fatalf("Added caveat '%s' does not meet the expectations!", testMacaroon.Caveats()[0].Id) } diff --git a/macaroons/service.go b/macaroons/service.go index c0c0c2cbe..49cb1c6da 100644 --- a/macaroons/service.go +++ b/macaroons/service.go @@ -246,6 +246,7 @@ func (svc *Service) ListMacaroonIDs(ctxt context.Context) ([][]byte, error) { // found and deleted, it will be returned. func (svc *Service) DeleteMacaroonID(ctxt context.Context, rootKeyID []byte) ([]byte, error) { + return svc.rks.DeleteMacaroonID(ctxt, rootKeyID) } diff --git a/macaroons/store.go b/macaroons/store.go index 867fb3a30..51d1c2253 100644 --- a/macaroons/store.go +++ b/macaroons/store.go @@ -385,7 +385,6 @@ func (r *RootKeyStorage) ListMacaroonIDs(_ context.Context) ([][]byte, error) { // Read all the items in the bucket and append the keys, which are the // root key IDs we want. err := kvdb.View(r.Backend, func(tx kvdb.RTx) error { - // appendRootKey is a function closure that appends root key ID // to rootKeySlice. appendRootKey := func(k, _ []byte) error { diff --git a/netann/host_ann.go b/netann/host_ann.go index 3e87c4b0f..c96b1af8e 100644 --- a/netann/host_ann.go +++ b/netann/host_ann.go @@ -83,7 +83,6 @@ func (h *HostAnnouncer) hostWatcher() { ipMapping := make(map[string]net.Addr) refreshHosts := func() { - // We'll now run through each of our hosts to check if they had // their backing IPs changed. If so, we'll want to re-announce // them. diff --git a/netann/host_ann_test.go b/netann/host_ann_test.go index 4f6573f5a..c8bbcac25 100644 --- a/netann/host_ann_test.go +++ b/netann/host_ann_test.go @@ -236,7 +236,6 @@ func TestHostAnnouncerUpdates(t *testing.T) { // If we expect an update, then we'll assert that we received // the proper set of modified addresses. if testCase.updateTriggered { - select { // The receive update should match exactly what the // test case dictates. diff --git a/peer/brontide.go b/peer/brontide.go index fb6335801..576143824 100644 --- a/peer/brontide.go +++ b/peer/brontide.go @@ -617,7 +617,6 @@ func (p *Brontide) Start() error { // initGossipSync initializes either a gossip syncer or an initial routing // dump, depending on the negotiated synchronization method. func (p *Brontide) initGossipSync() { - // If the remote peer knows of the new gossip queries feature, then // we'll create a new gossipSyncer in the AuthenticatedGossiper for it. if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) { @@ -1244,7 +1243,6 @@ func waitUntilLinkActive(p *Brontide, // channel this stream forwards to is held in scope to prevent unnecessary // lookups. func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream { - var chanLink htlcswitch.ChannelUpdateHandler apply := func(msg lnwire.Message) { @@ -1568,7 +1566,6 @@ func (p *Brontide) handleError(msg *lnwire.Error) bool { p.storeError(msg) switch { - // In the case of an all-zero channel ID we want to forward the error to // all channels with this peer. case msg.ChanID == lnwire.ConnectionWideID: diff --git a/record/mpp.go b/record/mpp.go index db6c95211..a5457e502 100644 --- a/record/mpp.go +++ b/record/mpp.go @@ -80,7 +80,6 @@ func MPPDecoder(r io.Reader, val interface{}, buf *[8]byte, l uint64) error { v.totalMsat = lnwire.MilliSatoshi(total) return nil - } return tlv.NewTypeForDecodingErr(val, "MPP", l, maxMPPLength) } diff --git a/routing/bandwidth.go b/routing/bandwidth.go index e6084649b..8abf025ab 100644 --- a/routing/bandwidth.go +++ b/routing/bandwidth.go @@ -72,6 +72,7 @@ func newBandwidthManager(graph routingGraph, sourceNode route.Vertex, // is interpreted as the link being offline. func (b *bandwidthManager) getBandwidth(cid lnwire.ShortChannelID, amount lnwire.MilliSatoshi) lnwire.MilliSatoshi { + link, err := b.getLink(cid) if err != nil { // If the link isn't online, then we'll report that it has diff --git a/routing/chainview/neutrino.go b/routing/chainview/neutrino.go index 205043911..86d6098c7 100644 --- a/routing/chainview/neutrino.go +++ b/routing/chainview/neutrino.go @@ -64,6 +64,7 @@ var _ FilteredChainView = (*CfFilteredChainView)(nil) // this function. func NewCfFilteredChainView(node *neutrino.ChainService, blockCache *blockcache.BlockCache) (*CfFilteredChainView, error) { + return &CfFilteredChainView{ blockQueue: newBlockEventQueue(), quit: make(chan struct{}), diff --git a/routing/localchans/manager.go b/routing/localchans/manager.go index ff95478d1..4484d5f62 100644 --- a/routing/localchans/manager.go +++ b/routing/localchans/manager.go @@ -190,7 +190,6 @@ func (r *Manager) updateEdge(tx kvdb.RTx, chanPoint wire.OutPoint, // We now update the edge max htlc value. switch { - // If a non-zero max htlc was specified, use it to update the edge. // Otherwise keep the value unchanged. case newSchema.MaxHTLC != 0: diff --git a/routing/missioncontrol_state_test.go b/routing/missioncontrol_state_test.go index 3bed1cd8b..178a9cded 100644 --- a/routing/missioncontrol_state_test.go +++ b/routing/missioncontrol_state_test.go @@ -90,5 +90,4 @@ func TestMissionControlStateSetLastPairResult(t *testing.T) { SuccessAmt: 50, } require.Equal(t, expected, result[to]) - } diff --git a/routing/mock_test.go b/routing/mock_test.go index e32e002d5..983ff5a52 100644 --- a/routing/mock_test.go +++ b/routing/mock_test.go @@ -632,6 +632,7 @@ var _ PaymentSession = (*mockPaymentSession)(nil) func (m *mockPaymentSession) RequestRoute(maxAmt, feeLimit lnwire.MilliSatoshi, activeShards, height uint32) (*route.Route, error) { + args := m.Called(maxAmt, feeLimit, activeShards, height) return args.Get(0).(*route.Route), args.Error(1) } diff --git a/routing/pathfind_test.go b/routing/pathfind_test.go index 926813bcb..981639148 100644 --- a/routing/pathfind_test.go +++ b/routing/pathfind_test.go @@ -1556,6 +1556,7 @@ func TestNewRoute(t *testing.T) { if !reflect.DeepEqual( finalHop.MPP, testCase.expectedMPP, ) { + t.Errorf("Expected final hop mpp field: %v, "+ " but got: %v instead", testCase.expectedMPP, finalHop.MPP) @@ -1713,7 +1714,6 @@ func runDestTLVGraphFallback(t *testing.T, useCache bool) { sourceNode, err := ctx.graph.SourceNode() if err != nil { t.Fatalf("unable to fetch source node: %v", err) - } find := func(r *RestrictParams, diff --git a/routing/payment_lifecycle.go b/routing/payment_lifecycle.go index b38fc1aa4..2816ebd67 100644 --- a/routing/payment_lifecycle.go +++ b/routing/payment_lifecycle.go @@ -180,7 +180,6 @@ lifecycle: // TODO(yy): sanity check all the states to make sure // everything is expected. switch { - // We have a terminal condition and no active shards, we are // ready to exit. case currentState.terminated(): @@ -470,7 +469,6 @@ type shardResult struct { // given HTLC attempt to be available then handle its result. It will fail the // payment with the control tower if a terminal error is encountered. func (p *shardHandler) collectResultAsync(attempt *channeldb.HTLCAttemptInfo) { - // errToSend is the error to be sent to sh.shardErrors. var errToSend error @@ -557,7 +555,6 @@ func (p *shardHandler) collectResult(attempt *channeldb.HTLCAttemptInfo) ( attempt.AttemptID, p.identifier, errorDecryptor, ) switch { - // If this attempt ID is unknown to the Switch, it means it was never // checkpointed and forwarded by the switch before a restart. In this // case we can safely send a new payment attempt, and wait for its @@ -780,7 +777,8 @@ func (p *shardHandler) handleSendError(attempt *channeldb.HTLCAttemptInfo, // Fail the payment via control tower. if err := p.router.cfg.Control.Fail( - p.identifier, *reason); err != nil { + p.identifier, *reason, + ); err != nil { log.Errorf("unable to report failure to control "+ "tower: %v", err) @@ -968,7 +966,6 @@ func marshallError(sendError error, time time.Time) *channeldb.HTLCFailInfo { } switch sendError { - case htlcswitch.ErrPaymentIDNotFound: response.Reason = channeldb.HTLCFailInternal return response diff --git a/routing/payment_lifecycle_test.go b/routing/payment_lifecycle_test.go index dd729faa2..40a0b17d9 100644 --- a/routing/payment_lifecycle_test.go +++ b/routing/payment_lifecycle_test.go @@ -570,7 +570,6 @@ func testPaymentLifecycle(t *testing.T, test paymentLifecycleTestCase, } switch step { - case routerInitPayment: var args initArgs select { @@ -934,7 +933,6 @@ func TestPaymentState(t *testing.T) { ) }) } - } // TestUpdatePaymentState checks that the method updatePaymentState updates the @@ -1071,7 +1069,6 @@ func TestUpdatePaymentState(t *testing.T) { ct.On("FetchPayment", paymentHash).Return( nil, dummyErr, ) - } else { // Otherwise we will return the payment. ct.On("FetchPayment", paymentHash).Return( @@ -1096,10 +1093,8 @@ func TestUpdatePaymentState(t *testing.T) { t, tc.expectedState, state, "state not updated as expected", ) - }) } - } func makeActiveAttempt(total, fee int) channeldb.HTLCAttempt { diff --git a/routing/payment_session.go b/routing/payment_session.go index 4d593113f..fdf334b42 100644 --- a/routing/payment_session.go +++ b/routing/payment_session.go @@ -72,7 +72,7 @@ var ( DefaultShardMinAmt = lnwire.NewMSatFromSatoshis(10000) ) -// Error returns the string representation of the noRouteError +// Error returns the string representation of the noRouteError. func (e noRouteError) Error() string { switch e { case errNoTlvPayload: diff --git a/routing/payment_session_test.go b/routing/payment_session_test.go index 11823d4c7..a090fb768 100644 --- a/routing/payment_session_test.go +++ b/routing/payment_session_test.go @@ -76,7 +76,6 @@ func TestValidateCLTVLimit(t *testing.T) { // TestUpdateAdditionalEdge checks that we can update the additional edges as // expected. func TestUpdateAdditionalEdge(t *testing.T) { - var ( testChannelID = uint64(12345) oldFeeBaseMSat = uint32(1000) diff --git a/routing/probability_estimator.go b/routing/probability_estimator.go index 7cd2df169..851cecf16 100644 --- a/routing/probability_estimator.go +++ b/routing/probability_estimator.go @@ -118,7 +118,6 @@ func (p *probabilityEstimator) getNodeProbability(now time.Time, for _, result := range results { switch { - // Weigh success with a constant high weight of 1. There is no // decay. Amt is never zero, so this clause is never executed // when result.SuccessAmt is zero. diff --git a/routing/probability_estimator_test.go b/routing/probability_estimator_test.go index 094c0550e..3bfb0536a 100644 --- a/routing/probability_estimator_test.go +++ b/routing/probability_estimator_test.go @@ -9,7 +9,7 @@ import ( ) const ( - // Define node identifiers + // Define node identifiers. node1 = 1 node2 = 2 node3 = 3 diff --git a/routing/router.go b/routing/router.go index 7d9d482eb..27ae7bbd6 100644 --- a/routing/router.go +++ b/routing/router.go @@ -2110,7 +2110,6 @@ func (r *ChannelRouter) preparePayment(payment *LightningPayment) ( // this payment. var shardTracker shards.ShardTracker switch { - // If this is an AMP payment, we'll use the AMP shard tracker. case payment.amp != nil: shardTracker = amp.NewShardTracker( diff --git a/routing/router_test.go b/routing/router_test.go index 5fb39d0fa..e5c4da601 100644 --- a/routing/router_test.go +++ b/routing/router_test.go @@ -3822,7 +3822,6 @@ func TestSendMPPaymentSucceedOnExtraShards(t *testing.T) { payment.HTLCs[i] = attempt return } - }) // Setup ReportPaymentFail to return nil reason and error so the @@ -4006,7 +4005,6 @@ func TestSendMPPaymentFailed(t *testing.T) { ), } return - } // We will make the rest attempts failed with temporary error. @@ -4035,7 +4033,6 @@ func TestSendMPPaymentFailed(t *testing.T) { payment.HTLCs[i] = attempt return } - }) // Setup ReportPaymentFail to return nil reason and error so the diff --git a/rpcperms/interceptor.go b/rpcperms/interceptor.go index add82e206..0ec9e7d6e 100644 --- a/rpcperms/interceptor.go +++ b/rpcperms/interceptor.go @@ -695,7 +695,6 @@ func (r *InterceptorChain) checkRPCState(srv interface{}) error { r.RUnlock() switch state { - // Do not accept any RPC calls (unless to the state service) until LND // has not started. case waitingToStart: diff --git a/rpcserver.go b/rpcserver.go index d83443427..e003a6092 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -255,7 +255,6 @@ func calculateFeeRate(satPerByte, satPerVByte uint64, targetConf uint32, } return feeRate, nil - } // GetAllPermissions returns all the permissions required to interact with lnd. @@ -282,7 +281,6 @@ func GetAllPermissions() []bakery.Op { allPerms, perm, ) } - } else { allPermsMap[entity] = make(map[string]struct{}) allPermsMap[entity][action] = struct{}{} @@ -1652,8 +1650,9 @@ func (r *rpcServer) ConnectPeer(ctx context.Context, ) } - if err := r.server.ConnectToPeer(peerAddr, - in.Perm, timeout); err != nil { + if err := r.server.ConnectToPeer( + peerAddr, in.Perm, timeout, + ); err != nil { rpcsLog.Errorf( "[connectpeer]: error connecting to peer: %v", err, @@ -1936,7 +1935,6 @@ func (r *rpcServer) parseOpenChannelReq(in *lnrpc.OpenChannelRequest, // not present, we'll fallback to the deprecated version that parses the // key from a hex string if this is for REST for backwards compatibility. switch { - // Parse the raw bytes of the node key into a pubkey object so we can // easily manipulate it. case len(in.NodePubkey) > 0: @@ -3472,7 +3470,6 @@ func (r *rpcServer) fetchWaitingCloseChannels() (waitingCloseChannels, remoteCommitDiff, err := waitingClose.RemoteCommitChainTip() switch { - // Don't set hash if there is no pending remote commit. case err == channeldb.ErrNoPendingCommit: @@ -3598,7 +3595,6 @@ func (r *rpcServer) arbitratorPopulateForceCloseResp(chanPoint *wire.OutPoint, for _, report := range reports { switch report.Type { - // For a direct output, populate/update the top level // response properties. case contractcourt.ReportOutputUnencumbered: @@ -3645,7 +3641,6 @@ func (r *rpcServer) arbitratorPopulateForceCloseResp(chanPoint *wire.OutPoint, // limbo, lost and recovered. Derive the current state // from the limbo and recovered balances. switch { - case report.RecoveredBalance != 0: forceClose.Anchor = lnrpc.PendingChannelsResponse_ForceClosedChannel_RECOVERED @@ -7090,7 +7085,6 @@ func (r *rpcServer) BakeMacaroon(ctx context.Context, } else if !stringInSlice(op.Action, validActions) { return nil, fmt.Errorf("invalid permission action. %s", helpMsg) - } requestedPermissions[idx] = bakery.Op{ @@ -7252,7 +7246,6 @@ func (r *rpcServer) FundingStateStep(ctx context.Context, var pendingChanID [32]byte switch { - // If this is a message to register a new shim that is an external // channel point, then we'll contact the wallet to register this new // shim. A user will use this method to register a new channel funding diff --git a/server.go b/server.go index eb85b98e8..b729dc97c 100644 --- a/server.go +++ b/server.go @@ -122,7 +122,7 @@ var ( // At the moment, this value depends on which chain is active. It is set // to the value under the Bitcoin chain as default. // - // TODO(roasbeef): add command line param to modify + // TODO(roasbeef): add command line param to modify. MaxFundingAmount = funding.MaxBtcFundingAmount ) @@ -340,7 +340,6 @@ func (s *server) updatePersistentPeerAddrs() error { for { select { - case <-s.quit: return @@ -1639,16 +1638,16 @@ func (s *server) Started() bool { // cleaner is used to aggregate "cleanup" functions during an operation that // starts several subsystems. In case one of the subsystem fails to start // and a proper resource cleanup is required, the "run" method achieves this -// by running all these added "cleanup" functions +// by running all these added "cleanup" functions. type cleaner []func() error // add is used to add a cleanup function to be called when -// the run function is executed +// the run function is executed. func (c cleaner) add(cleanup func() error) cleaner { return append(c, cleanup) } -// run is used to run all the previousely added cleanup functions +// run is used to run all the previousely added cleanup functions. func (c cleaner) run() { for i := len(c) - 1; i >= 0; i-- { if err := c[i](); err != nil { diff --git a/sweep/backend_mock_test.go b/sweep/backend_mock_test.go index f8d039ba3..16cfb1cef 100644 --- a/sweep/backend_mock_test.go +++ b/sweep/backend_mock_test.go @@ -89,6 +89,7 @@ func (b *mockBackend) PublishTransaction(tx *wire.MsgTx, _ string) error { func (b *mockBackend) ListUnspentWitnessFromDefaultAccount(minConfs, maxConfs int32) ( []*lnwallet.Utxo, error) { + b.lock.Lock() defer b.lock.Unlock() diff --git a/sweep/sweeper.go b/sweep/sweeper.go index f60c0283c..af067445a 100644 --- a/sweep/sweeper.go +++ b/sweep/sweeper.go @@ -544,6 +544,7 @@ func (s *UtxoSweeper) collector(blockEpochs <-chan *chainntnfs.BlockEpoch) { var prevExclGroup *uint64 if pendInput.params.ExclusiveGroup != nil && input.params.ExclusiveGroup == nil { + prevExclGroup = new(uint64) *prevExclGroup = *pendInput.params.ExclusiveGroup } @@ -801,7 +802,7 @@ func (s *UtxoSweeper) bucketForFeeRate( // createInputClusters creates a list of input clusters from the set of pending // inputs known by the UtxoSweeper. It clusters inputs by // 1) Required tx locktime -// 2) Similar fee rates +// 2) Similar fee rates. func (s *UtxoSweeper) createInputClusters() []inputCluster { inputs := s.pendingInputs @@ -982,7 +983,6 @@ func zipClusters(as, bs []inputCluster) []inputCluster { a := as[i] switch { - // If the fee rate for the next one from bs is at least a's, we // merge. case j < len(bs) && bs[j].sweepFeeRate >= a.sweepFeeRate: @@ -1017,7 +1017,6 @@ func mergeClusters(a, b inputCluster) []inputCluster { newCluster := inputCluster{} switch { - // Incompatible locktimes, return the sets without merging them. case a.lockTime != nil && b.lockTime != nil && *a.lockTime != *b.lockTime: return []inputCluster{a, b} diff --git a/sweep/sweeper_test.go b/sweep/sweeper_test.go index e01544066..c73c0feea 100644 --- a/sweep/sweeper_test.go +++ b/sweep/sweeper_test.go @@ -1763,7 +1763,6 @@ func TestLockTimes(t *testing.T) { t.Fatalf("Input required locktime %v, sweep "+ "tx had locktime %v", lt, sweepTx.LockTime) } - } } diff --git a/sweep/test_utils.go b/sweep/test_utils.go index 5e0c67626..475aaf5af 100644 --- a/sweep/test_utils.go +++ b/sweep/test_utils.go @@ -174,7 +174,7 @@ func (m *MockNotifier) Start() error { return nil } -// Started checks if started +// Started checks if started. func (m *MockNotifier) Started() bool { return true } diff --git a/sweep/tx_input_set.go b/sweep/tx_input_set.go index 2f2ff9704..0a2a9738d 100644 --- a/sweep/tx_input_set.go +++ b/sweep/tx_input_set.go @@ -210,7 +210,6 @@ func (t *txInputSet) addToState(inp input.Input, constraints addConstraints) *tx inputYield := s.totalOutput() - t.totalOutput() switch constraints { - // Don't sweep inputs that cost us more to sweep than they give us. case constraintsRegular: if inputYield <= 0 { diff --git a/sweep/tx_input_set_test.go b/sweep/tx_input_set_test.go index 4dc31285a..bfed67a83 100644 --- a/sweep/tx_input_set_test.go +++ b/sweep/tx_input_set_test.go @@ -234,7 +234,6 @@ func TestTxInputSetRequiredOutput(t *testing.T) { change = set.changeOutput if change != 1000 { t.Fatalf("expected change to be %v, had %v", 1000, change) - } require.True(t, set.enoughInput()) } diff --git a/tor/cmd_onion_test.go b/tor/cmd_onion_test.go index e7356cb07..e7502e941 100644 --- a/tor/cmd_onion_test.go +++ b/tor/cmd_onion_test.go @@ -181,7 +181,6 @@ func TestPrepareAddOnion(t *testing.T) { store.AssertExpectations(t) }) } - } // mockStore implements a mock of the interface OnionStore. diff --git a/tor/controller_test.go b/tor/controller_test.go index d2dd91103..64c6ae8bf 100644 --- a/tor/controller_test.go +++ b/tor/controller_test.go @@ -258,7 +258,6 @@ func TestReadResponse(t *testing.T) { for _, tc := range testCase { tc := tc t.Run(tc.name, func(t *testing.T) { - // Let the server mocks a given response. _, err := server.Write([]byte(tc.serverResp)) require.NoError(t, err, "server failed to write") diff --git a/walletunlocker/service_test.go b/walletunlocker/service_test.go index 001872383..88274459b 100644 --- a/walletunlocker/service_test.go +++ b/walletunlocker/service_test.go @@ -89,6 +89,7 @@ func createTestWalletWithPw(t *testing.T, pubPw, privPw []byte, dir string, func createSeedAndMnemonic(t *testing.T, pass []byte) (*aezeed.CipherSeed, aezeed.Mnemonic) { + cipherSeed, err := aezeed.New( keychain.KeyDerivationVersion, &testEntropy, time.Now(), ) diff --git a/watchtower/lookout/justice_descriptor_test.go b/watchtower/lookout/justice_descriptor_test.go index dcc79d3fd..5edf5f8a7 100644 --- a/watchtower/lookout/justice_descriptor_test.go +++ b/watchtower/lookout/justice_descriptor_test.go @@ -156,7 +156,6 @@ func testJusticeDescriptor(t *testing.T, blobType blob.Type) { // As it should be. toRemoteSigningScript = toRemoteRedeemScript - } else { toRemoteRedeemScript = toRemotePK.SerializeCompressed() toRemoteScriptHash, err = input.CommitScriptUnencumbered( diff --git a/watchtower/wtdb/client_db.go b/watchtower/wtdb/client_db.go index 88bf93cb8..611dd7c47 100644 --- a/watchtower/wtdb/client_db.go +++ b/watchtower/wtdb/client_db.go @@ -631,7 +631,7 @@ func createSessionKeyIndexKey(towerID TowerID, blobType blob.Type) []byte { return keyBytes[:] } -// getSessionKeyIndex is a helper method +// getSessionKeyIndex is a helper method. func getSessionKeyIndex(keyIndexes kvdb.RwBucket, towerID TowerID, blobType blob.Type) (uint32, error) { diff --git a/watchtower/wtmock/signer.go b/watchtower/wtmock/signer.go index 89421d6ad..d082c23ce 100644 --- a/watchtower/wtmock/signer.go +++ b/watchtower/wtmock/signer.go @@ -31,6 +31,7 @@ func NewMockSigner() *MockSigner { // signature without the signhash flag. func (s *MockSigner) SignOutputRaw(tx *wire.MsgTx, signDesc *input.SignDescriptor) (input.Signature, error) { + s.mu.Lock() defer s.mu.Unlock() diff --git a/zpay32/invoice_test.go b/zpay32/invoice_test.go index c9f7256f7..4656447dc 100644 --- a/zpay32/invoice_test.go +++ b/zpay32/invoice_test.go @@ -951,7 +951,6 @@ func TestInvoiceChecksumMalleability(t *testing.T) { if err == nil { t.Fatalf("Did not get expected error when decoding invoice") } - } func compareInvoices(expected, actual *Invoice) error {