diff --git a/autopilot/agent.go b/autopilot/agent.go index 6fe72f98..837716eb 100644 --- a/autopilot/agent.go +++ b/autopilot/agent.go @@ -386,9 +386,8 @@ func mergeChanState(pendingChans map[NodeID]Channel, numChans := len(pendingChans) + len(activeChans) totalChans := make([]Channel, 0, numChans) - for _, activeChan := range activeChans.Channels() { - totalChans = append(totalChans, activeChan) - } + totalChans = append(totalChans, activeChans.Channels()...) + for _, pendingChan := range pendingChans { totalChans = append(totalChans, pendingChan) } @@ -649,7 +648,7 @@ func (a *Agent) openChans(availableFunds btcutil.Amount, numChans uint32, // to open channels to. scores, err = chooseN(numChans, scores) if err != nil { - return fmt.Errorf("Unable to make weighted choice: %v", + return fmt.Errorf("unable to make weighted choice: %v", err) } diff --git a/autopilot/choice_test.go b/autopilot/choice_test.go index 850b4440..bde48b0d 100644 --- a/autopilot/choice_test.go +++ b/autopilot/choice_test.go @@ -139,10 +139,7 @@ func assertChoice(w []float64, iterations int) bool { } // The sum of choices must be exactly iterations of course. - if totalChoices != iterations { - return false - } - return true + return totalChoices == iterations } diff --git a/autopilot/combinedattach.go b/autopilot/combinedattach.go index 98ca472d..80d32e65 100644 --- a/autopilot/combinedattach.go +++ b/autopilot/combinedattach.go @@ -130,7 +130,7 @@ func (c *WeightedCombAttachment) NodeScores(g ChannelGraph, chans []Channel, // Sanity check the new score. case score.Score < 0 || score.Score > 1.0: - return nil, fmt.Errorf("Invalid node score from "+ + return nil, fmt.Errorf("invalid node score from "+ "combination: %v", score.Score) } diff --git a/breacharbiter.go b/breacharbiter.go index f454aad3..a5925203 100644 --- a/breacharbiter.go +++ b/breacharbiter.go @@ -1358,8 +1358,8 @@ func (rs *retributionStore) Remove(chanPoint *wire.OutPoint) error { // to remove a finalized retribution state that is not already // stored in the db. if retBucket == nil { - return errors.New("Unable to remove retribution " + - "because the retribution bucket doesn't exist.") + return errors.New("unable to remove retribution " + + "because the retribution bucket doesn't exist") } // Serialize the channel point we are intending to remove. diff --git a/brontide/noise.go b/brontide/noise.go index f7a66855..17e0322f 100644 --- a/brontide/noise.go +++ b/brontide/noise.go @@ -492,7 +492,7 @@ func (b *Machine) RecvActOne(actOne [ActOneSize]byte) error { // If the handshake version is unknown, then the handshake fails // immediately. if actOne[0] != HandshakeVersion { - return fmt.Errorf("Act One: invalid handshake version: %v, "+ + return fmt.Errorf("act one: invalid handshake version: %v, "+ "only %v is valid, msg=%x", actOne[0], HandshakeVersion, actOne[:]) } @@ -564,7 +564,7 @@ func (b *Machine) RecvActTwo(actTwo [ActTwoSize]byte) error { // If the handshake version is unknown, then the handshake fails // immediately. if actTwo[0] != HandshakeVersion { - return fmt.Errorf("Act Two: invalid handshake version: %v, "+ + return fmt.Errorf("act two: invalid handshake version: %v, "+ "only %v is valid, msg=%x", actTwo[0], HandshakeVersion, actTwo[:]) } @@ -630,7 +630,7 @@ func (b *Machine) RecvActThree(actThree [ActThreeSize]byte) error { // If the handshake version is unknown, then the handshake fails // immediately. if actThree[0] != HandshakeVersion { - return fmt.Errorf("Act Three: invalid handshake version: %v, "+ + return fmt.Errorf("act three: invalid handshake version: %v, "+ "only %v is valid, msg=%x", actThree[0], HandshakeVersion, actThree[:]) } diff --git a/chainntnfs/txnotifier.go b/chainntnfs/txnotifier.go index 94a959d5..c28abb44 100644 --- a/chainntnfs/txnotifier.go +++ b/chainntnfs/txnotifier.go @@ -1690,7 +1690,7 @@ func (n *TxNotifier) DisconnectTip(blockHeight uint32) error { defer n.Unlock() if blockHeight != n.currentHeight { - return fmt.Errorf("Received blocks out of order: "+ + return fmt.Errorf("received blocks out of order: "+ "current height=%d, disconnected height=%d", n.currentHeight, blockHeight) } diff --git a/chainregistry.go b/chainregistry.go index cd5a3787..4f5320fa 100644 --- a/chainregistry.go +++ b/chainregistry.go @@ -201,7 +201,7 @@ func newChainControlFromConfig(cfg *config, chanDB *channeldb.DB, defaultLitecoinStaticFeePerKW, 0, ) default: - return nil, fmt.Errorf("Default routing policy for chain %v is "+ + return nil, fmt.Errorf("default routing policy for chain %v is "+ "unknown", registeredChains.PrimaryChain()) } diff --git a/channeldb/graph.go b/channeldb/graph.go index e0105043..0bbd790e 100644 --- a/channeldb/graph.go +++ b/channeldb/graph.go @@ -3086,7 +3086,7 @@ func (c *ChannelGraph) IsPublicNode(pubKey [33]byte) (bool, error) { // genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys. func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) { if len(aPub) != 33 || len(bPub) != 33 { - return nil, fmt.Errorf("Pubkey size error. Compressed " + + return nil, fmt.Errorf("pubkey size error. Compressed " + "pubkeys only") } @@ -3833,7 +3833,7 @@ func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64, byteOrder.PutUint64(edgeKey[33:], channelID) if edges.Get(edgeKey[:]) != nil { - return fmt.Errorf("Cannot write unknown policy for channel %v "+ + return fmt.Errorf("cannot write unknown policy for channel %v "+ " when there is already a policy present", channelID) } diff --git a/channeldb/invoices.go b/channeldb/invoices.go index f1954bf3..23c10dc6 100644 --- a/channeldb/invoices.go +++ b/channeldb/invoices.go @@ -1218,7 +1218,7 @@ func deserializeInvoice(r io.Reader) (Invoice, error) { // deserializeHtlcs reads a list of invoice htlcs from a reader and returns it // as a map. func deserializeHtlcs(r io.Reader) (map[CircuitKey]*InvoiceHTLC, error) { - htlcs := make(map[CircuitKey]*InvoiceHTLC, 0) + htlcs := make(map[CircuitKey]*InvoiceHTLC) for { // Read the length of the tlv stream for this htlc. diff --git a/channeldb/payments_test.go b/channeldb/payments_test.go index 1c6f09e6..b5228722 100644 --- a/channeldb/payments_test.go +++ b/channeldb/payments_test.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "math" - "math/rand" "reflect" "testing" "time" @@ -15,16 +14,13 @@ import ( "github.com/lightningnetwork/lnd/lntypes" "github.com/lightningnetwork/lnd/record" "github.com/lightningnetwork/lnd/routing/route" - "github.com/lightningnetwork/lnd/tlv" ) var ( priv, _ = btcec.NewPrivateKey(btcec.S256()) pub = priv.PubKey() - tlvBytes = []byte{1, 2, 3} - tlvEncoder = tlv.StubEncoder(tlvBytes) - testHop1 = &route.Hop{ + testHop1 = &route.Hop{ PubKeyBytes: route.NewVertex(pub), ChannelID: 12345, OutgoingTimeLock: 111, @@ -77,18 +73,6 @@ func makeFakeInfo() (*PaymentCreationInfo, *HTLCAttemptInfo) { return c, a } -// randomBytes creates random []byte with length in range [minLen, maxLen) -func randomBytes(minLen, maxLen int) ([]byte, error) { - randBuf := make([]byte, minLen+rand.Intn(maxLen-minLen)) - - if _, err := rand.Read(randBuf); err != nil { - return nil, fmt.Errorf("Internal error. "+ - "Cannot generate random string: %v", err) - } - - return randBuf, nil -} - func TestSentPaymentSerialization(t *testing.T) { t.Parallel() diff --git a/channelnotifier/log.go b/channelnotifier/log.go index 009129ab..5756f699 100644 --- a/channelnotifier/log.go +++ b/channelnotifier/log.go @@ -27,19 +27,3 @@ func DisableLog() { func UseLogger(logger btclog.Logger) { log = logger } - -// logClosure is used to provide a closure over expensive logging operations so -// don't have to be performed when the logging level doesn't warrant it. -type logClosure func() string // nolint:unused - -// String invokes the underlying function and returns the result. -func (c logClosure) String() string { - return c() -} - -// newLogClosure returns a new closure over a function that returns a string -// which itself provides a Stringer interface so that it can be used with the -// logging system. -func newLogClosure(c func() string) logClosure { // nolint:unused - return logClosure(c) -} diff --git a/config.go b/config.go index 6816b0e8..4228dc03 100644 --- a/config.go +++ b/config.go @@ -1150,7 +1150,7 @@ func loadConfig() (*config, error) { // the wallet. _, err = parseHexColor(cfg.Color) if err != nil { - return nil, fmt.Errorf("Unable to parse node color: %v", err) + return nil, fmt.Errorf("unable to parse node color: %v", err) } // Warn about missing config file only after all other configuration is diff --git a/contractcourt/chain_watcher.go b/contractcourt/chain_watcher.go index 99565505..aab395c6 100644 --- a/contractcourt/chain_watcher.go +++ b/contractcourt/chain_watcher.go @@ -314,7 +314,6 @@ func (c *chainWatcher) SubscribeChannelEvents() *ChainEventSubscription { c.Lock() delete(c.clientSubscriptions, clientID) c.Unlock() - return }, } diff --git a/fundingmanager.go b/fundingmanager.go index 95e6464e..ae4c1f93 100644 --- a/fundingmanager.go +++ b/fundingmanager.go @@ -1929,7 +1929,7 @@ func (f *fundingManager) handleFundingSigned(fmsg *fundingSignedMsg) { delete(f.signedReservations, fmsg.msg.ChanID) f.resMtx.Unlock() if !ok { - err := fmt.Errorf("Unable to find signed reservation for "+ + err := fmt.Errorf("unable to find signed reservation for "+ "chan_id=%x", fmsg.msg.ChanID) fndgLog.Warnf(err.Error()) f.failFundingFlow(fmsg.peer, fmsg.msg.ChanID, err) @@ -2562,7 +2562,7 @@ func (f *fundingManager) annAfterSixConfs(completeChan *channeldb.OpenChannel, completeChan.FundingBroadcastHeight, ) if err != nil { - return fmt.Errorf("Unable to register for "+ + return fmt.Errorf("unable to register for "+ "confirmation of ChannelPoint(%v): %v", completeChan.FundingOutpoint, err) } @@ -3217,7 +3217,7 @@ func (f *fundingManager) handleInitFundingMsg(msg *initFundingMsg) { UpfrontShutdownScript: shutdown, } if err := msg.peer.SendMessage(true, &fundingOpen); err != nil { - e := fmt.Errorf("Unable to send funding request message: %v", + e := fmt.Errorf("unable to send funding request message: %v", err) fndgLog.Errorf(e.Error()) @@ -3233,34 +3233,6 @@ func (f *fundingManager) handleInitFundingMsg(msg *initFundingMsg) { } } -// waitUntilChannelOpen is designed to prevent other lnd subsystems from -// sending new update messages to a channel before the channel is fully -// opened. -func (f *fundingManager) waitUntilChannelOpen(targetChan lnwire.ChannelID, - quit <-chan struct{}) error { - - f.barrierMtx.RLock() - barrier, ok := f.newChanBarriers[targetChan] - f.barrierMtx.RUnlock() - if ok { - fndgLog.Tracef("waiting for chan barrier signal for ChanID(%v)", - targetChan) - - select { - case <-barrier: - case <-quit: - return ErrFundingManagerShuttingDown - case <-f.quit: - return ErrFundingManagerShuttingDown - } - - fndgLog.Tracef("barrier for ChanID(%v) closed", targetChan) - return nil - } - - return nil -} - // processFundingError sends a message to the fundingManager allowing it to // process the occurred generic error. func (f *fundingManager) processFundingError(err *lnwire.Error, @@ -3529,7 +3501,7 @@ func (f *fundingManager) deleteChannelOpeningState(chanPoint *wire.OutPoint) err return kvdb.Update(f.cfg.Wallet.Cfg.Database, func(tx kvdb.RwTx) error { bucket := tx.ReadWriteBucket(channelOpeningStateBucket) if bucket == nil { - return fmt.Errorf("Bucket not found") + return fmt.Errorf("bucket not found") } var outpointBytes bytes.Buffer diff --git a/fundingmanager_test.go b/fundingmanager_test.go index b222bf94..408c1052 100644 --- a/fundingmanager_test.go +++ b/fundingmanager_test.go @@ -2839,7 +2839,7 @@ func TestFundingManagerRejectPush(t *testing.T) { // Assert Bob responded with an ErrNonZeroPushAmount error. err := assertFundingMsgSent(t, bob.msgChan, "Error").(*lnwire.Error) - if !strings.Contains(err.Error(), "Non-zero push amounts are disabled") { + if !strings.Contains(err.Error(), "non-zero push amounts are disabled") { t.Fatalf("expected ErrNonZeroPushAmount error, got \"%v\"", err.Error()) } diff --git a/htlcswitch/circuit_test.go b/htlcswitch/circuit_test.go index 3dc0f470..1b5d59e8 100644 --- a/htlcswitch/circuit_test.go +++ b/htlcswitch/circuit_test.go @@ -535,7 +535,7 @@ func TestCircuitMapPersistence(t *testing.T) { // Check that the circuit map is empty, even after restarting. assertNumCircuitsWithHash(t, circuitMap, hash3, 0) - cfg, circuitMap = restartCircuitMap(t, cfg) + _, circuitMap = restartCircuitMap(t, cfg) assertNumCircuitsWithHash(t, circuitMap, hash3, 0) } @@ -717,7 +717,7 @@ func TestCircuitMapCommitCircuits(t *testing.T) { // to be loaded from disk. Since the keystone was never set, subsequent // attempts to commit the circuit should cause the circuit map to // indicate that the HTLC should be failed back. - cfg, circuitMap = restartCircuitMap(t, cfg) + _, circuitMap = restartCircuitMap(t, cfg) actions, err = circuitMap.CommitCircuits(circuit) if err != nil { @@ -837,7 +837,7 @@ func TestCircuitMapOpenCircuits(t *testing.T) { // // NOTE: The channel db doesn't have any channel data, so no keystones // will be trimmed. - cfg, circuitMap = restartCircuitMap(t, cfg) + _, circuitMap = restartCircuitMap(t, cfg) // Check that we can still query for the open circuit. circuit2 = circuitMap.LookupOpenCircuit(keystone.OutKey) @@ -1081,7 +1081,7 @@ func TestCircuitMapTrimOpenCircuits(t *testing.T) { // Restart the circuit map one last time to make sure the changes are // persisted. - cfg, circuitMap = restartCircuitMap(t, cfg) + _, circuitMap = restartCircuitMap(t, cfg) assertCircuitsOpenedPostRestart( t, @@ -1179,7 +1179,7 @@ func TestCircuitMapCloseOpenCircuits(t *testing.T) { // // NOTE: The channel db doesn't have any channel data, so no keystones // will be trimmed. - cfg, circuitMap = restartCircuitMap(t, cfg) + _, circuitMap = restartCircuitMap(t, cfg) // Close the open circuit for the first time, which should succeed. _, err = circuitMap.FailCircuit(circuit.Incoming) @@ -1237,7 +1237,7 @@ func TestCircuitMapCloseUnopenedCircuit(t *testing.T) { // Now, restart the circuit map, which will result in the circuit being // reopened, since no attempt to delete the circuit was made. - cfg, circuitMap = restartCircuitMap(t, cfg) + _, circuitMap = restartCircuitMap(t, cfg) // Close the open circuit for the first time, which should succeed. _, err = circuitMap.FailCircuit(circuit.Incoming) @@ -1301,7 +1301,7 @@ func TestCircuitMapDeleteUnopenedCircuit(t *testing.T) { // Now, restart the circuit map, and check that the deletion survived // the restart. - cfg, circuitMap = restartCircuitMap(t, cfg) + _, circuitMap = restartCircuitMap(t, cfg) circuit2 = circuitMap.LookupCircuit(circuit.Incoming) if circuit2 != nil { @@ -1374,7 +1374,7 @@ func TestCircuitMapDeleteOpenCircuit(t *testing.T) { // Now, restart the circuit map, and check that the deletion survived // the restart. - cfg, circuitMap = restartCircuitMap(t, cfg) + _, circuitMap = restartCircuitMap(t, cfg) circuit2 = circuitMap.LookupOpenCircuit(keystone.OutKey) if circuit2 != nil { diff --git a/htlcswitch/decayedlog.go b/htlcswitch/decayedlog.go index 3a60e112..11d6054c 100644 --- a/htlcswitch/decayedlog.go +++ b/htlcswitch/decayedlog.go @@ -17,9 +17,6 @@ const ( // defaultDbDirectory is the default directory where our decayed log // will store our (sharedHash, CLTV) key-value pairs. defaultDbDirectory = "sharedhashes" - - // dbPermissions sets the database permissions to user write-and-readable. - dbPermissions = 0600 ) var ( @@ -96,7 +93,7 @@ func (d *DecayedLog) Start() error { kvdb.BoltBackendName, d.dbPath, true, ) if err != nil { - return fmt.Errorf("Could not open boltdb: %v", err) + return fmt.Errorf("could not open boltdb: %v", err) } // Initialize the primary buckets used by the decayed log. @@ -108,7 +105,7 @@ func (d *DecayedLog) Start() error { if d.notifier != nil { epochClient, err := d.notifier.RegisterBlockEpochNtfn(nil) if err != nil { - return fmt.Errorf("Unable to register for epoch "+ + return fmt.Errorf("unable to register for epoch "+ "notifications: %v", err) } diff --git a/htlcswitch/decayedlog_test.go b/htlcswitch/decayedlog_test.go index 6cf97c50..7ebe1f10 100644 --- a/htlcswitch/decayedlog_test.go +++ b/htlcswitch/decayedlog_test.go @@ -122,7 +122,7 @@ func TestDecayedLogGarbageCollector(t *testing.T) { time.Sleep(500 * time.Millisecond) // Assert that hashedSecret is not in the sharedHashBucket - val, err = d.Get(hashedSecret) + _, err = d.Get(hashedSecret) if err == nil { t.Fatalf("CLTV was not deleted") } diff --git a/htlcswitch/link.go b/htlcswitch/link.go index 3290573a..019ba007 100644 --- a/htlcswitch/link.go +++ b/htlcswitch/link.go @@ -634,7 +634,7 @@ func (l *channelLink) syncChanStates() error { } if err := l.cfg.Peer.SendMessage(true, localChanSyncMsg); err != nil { - return fmt.Errorf("Unable to send chan sync message for "+ + return fmt.Errorf("unable to send chan sync message for "+ "ChannelPoint(%v): %v", l.channel.ChannelPoint(), err) } diff --git a/htlcswitch/link_test.go b/htlcswitch/link_test.go index 935ccde3..bbe418c9 100644 --- a/htlcswitch/link_test.go +++ b/htlcswitch/link_test.go @@ -2040,7 +2040,7 @@ func TestChannelLinkBandwidthConsistency(t *testing.T) { // Next, we'll add another HTLC initiated by the switch (of the same // amount as the prior one). - invoice, htlc, _, err = generatePayment(htlcAmt, htlcAmt, 5, mockBlob) + _, htlc, _, err = generatePayment(htlcAmt, htlcAmt, 5, mockBlob) if err != nil { t.Fatalf("unable to create payment: %v", err) } @@ -2143,7 +2143,7 @@ func TestChannelLinkBandwidthConsistency(t *testing.T) { } htlc.ID = 0 - bobIndex, err = bobChannel.AddHTLC(htlc, nil) + _, err = bobChannel.AddHTLC(htlc, nil) if err != nil { t.Fatalf("unable to add htlc: %v", err) } @@ -2253,7 +2253,7 @@ func TestChannelLinkBandwidthConsistency(t *testing.T) { // HTLC we add, hence it should have an ID of 1 (Alice's channel // link will set this automatically for her side). htlc.ID = 1 - bobIndex, err = bobChannel.AddHTLC(htlc, nil) + _, err = bobChannel.AddHTLC(htlc, nil) if err != nil { t.Fatalf("unable to add htlc: %v", err) } diff --git a/htlcswitch/switch.go b/htlcswitch/switch.go index 06c597bf..e1967206 100644 --- a/htlcswitch/switch.go +++ b/htlcswitch/switch.go @@ -421,7 +421,7 @@ func (s *Switch) GetPaymentResult(paymentID uint64, paymentHash lntypes.Hash, deobfuscator, n, paymentID, paymentHash, ) if err != nil { - e := fmt.Errorf("Unable to extract result: %v", err) + e := fmt.Errorf("unable to extract result: %v", err) log.Error(e) resultChan <- &PaymentResult{ Error: e, @@ -770,7 +770,7 @@ func (s *Switch) routeAsync(packet *htlcPacket, errChan chan error, case <-linkQuit: return ErrLinkShuttingDown case <-s.quit: - return errors.New("Htlc Switch was stopped") + return errors.New("htlc switch was stopped") } } @@ -962,7 +962,7 @@ func (s *Switch) extractResult(deobfuscator ErrorDecrypter, n *networkResult, }, nil default: - return nil, fmt.Errorf("Received unknown response type: %T", + return nil, fmt.Errorf("received unknown response type: %T", htlc) } } diff --git a/input/script_utils.go b/input/script_utils.go index 318d1fae..dc3c4ccf 100644 --- a/input/script_utils.go +++ b/input/script_utils.go @@ -49,7 +49,7 @@ func WitnessScriptHash(witnessScript []byte) ([]byte, error) { // pubkeys. func GenMultiSigScript(aPub, bPub []byte) ([]byte, error) { if len(aPub) != 33 || len(bPub) != 33 { - return nil, fmt.Errorf("Pubkey size error. Compressed pubkeys only") + return nil, fmt.Errorf("pubkey size error: compressed pubkeys only") } // Swap to sort pubkeys if needed. Keys are sorted in lexicographical diff --git a/input/test_utils.go b/input/test_utils.go index 5b004417..201858b2 100644 --- a/input/test_utils.go +++ b/input/test_utils.go @@ -64,7 +64,7 @@ func (m *MockSigner) SignOutputRaw(tx *wire.MsgTx, hash160 := btcutil.Hash160(pubkey.SerializeCompressed()) privKey := m.findKey(hash160, signDesc.SingleTweak, signDesc.DoubleTweak) if privKey == nil { - return nil, fmt.Errorf("Mock signer does not have key") + return nil, fmt.Errorf("mock signer does not have key") } sig, err := txscript.RawTxInWitnessSignature(tx, signDesc.SigHashes, @@ -93,7 +93,7 @@ func (m *MockSigner) ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor privKey := m.findKey(addresses[0].ScriptAddress(), signDesc.SingleTweak, signDesc.DoubleTweak) if privKey == nil { - return nil, fmt.Errorf("Mock signer does not have key for "+ + return nil, fmt.Errorf("mock signer does not have key for "+ "address %v", addresses[0]) } @@ -111,7 +111,7 @@ func (m *MockSigner) ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor privKey := m.findKey(addresses[0].ScriptAddress(), signDesc.SingleTweak, signDesc.DoubleTweak) if privKey == nil { - return nil, fmt.Errorf("Mock signer does not have key for "+ + return nil, fmt.Errorf("mock signer does not have key for "+ "address %v", addresses[0]) } @@ -125,7 +125,7 @@ func (m *MockSigner) ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor return &Script{Witness: witnessScript}, nil default: - return nil, fmt.Errorf("Unexpected script type: %v", scriptType) + return nil, fmt.Errorf("unexpected script type: %v", scriptType) } } diff --git a/invoices/log.go b/invoices/log.go index 71e23c50..5e3a0b17 100644 --- a/invoices/log.go +++ b/invoices/log.go @@ -27,19 +27,3 @@ func DisableLog() { func UseLogger(logger btclog.Logger) { log = logger } - -// logClosure is used to provide a closure over expensive logging operations so -// don't have to be performed when the logging level doesn't warrant it. -type logClosure func() string - -// String invokes the underlying function and returns the result. -func (c logClosure) String() string { - return c() -} - -// newLogClosure returns a new closure over a function that returns a string -// which itself provides a Stringer interface so that it can be used with the -// logging system. -func newLogClosure(c func() string) logClosure { - return logClosure(c) -} diff --git a/lnd.go b/lnd.go index faffac1f..98603c39 100644 --- a/lnd.go +++ b/lnd.go @@ -209,7 +209,7 @@ func Main(lisCfg ListenerCfg) error { if cfg.CPUProfile != "" { f, err := os.Create(cfg.CPUProfile) if err != nil { - err := fmt.Errorf("Unable to create CPU profile: %v", + err := fmt.Errorf("unable to create CPU profile: %v", err) ltndLog.Error(err) return err @@ -237,7 +237,7 @@ func Main(lisCfg ListenerCfg) error { channeldb.OptionSetSyncFreelist(cfg.SyncFreelist), ) if err != nil { - err := fmt.Errorf("Unable to open channeldb: %v", err) + err := fmt.Errorf("unable to open channeldb: %v", err) ltndLog.Error(err) return err } @@ -256,7 +256,7 @@ func Main(lisCfg ListenerCfg) error { cfg.TLSExtraDomains, cfg.RPCListeners, ) if err != nil { - err := fmt.Errorf("Unable to load TLS credentials: %v", err) + err := fmt.Errorf("unable to load TLS credentials: %v", err) ltndLog.Error(err) return err } @@ -289,7 +289,7 @@ func Main(lisCfg ListenerCfg) error { mainChain.ChainDir, ) if err != nil { - err := fmt.Errorf("Unable to initialize neutrino "+ + err := fmt.Errorf("unable to initialize neutrino "+ "backend: %v", err) ltndLog.Error(err) return err @@ -364,7 +364,7 @@ func Main(lisCfg ListenerCfg) error { restProxyDest, tlsCfg, walletUnlockerListeners, ) if err != nil { - err := fmt.Errorf("Unable to set up wallet password "+ + err := fmt.Errorf("unable to set up wallet password "+ "listeners: %v", err) ltndLog.Error(err) return err @@ -388,7 +388,7 @@ func Main(lisCfg ListenerCfg) error { networkDir, macaroons.IPLockChecker, ) if err != nil { - err := fmt.Errorf("Unable to set up macaroon "+ + err := fmt.Errorf("unable to set up macaroon "+ "authentication: %v", err) ltndLog.Error(err) return err @@ -398,7 +398,7 @@ func Main(lisCfg ListenerCfg) error { // Try to unlock the macaroon store with the private password. err = macaroonService.CreateUnlock(&privateWalletPw) if err != nil { - err := fmt.Errorf("Unable to unlock macaroons: %v", err) + err := fmt.Errorf("unable to unlock macaroons: %v", err) ltndLog.Error(err) return err } @@ -412,7 +412,7 @@ func Main(lisCfg ListenerCfg) error { cfg.ReadMacPath, cfg.InvoiceMacPath, ) if err != nil { - err := fmt.Errorf("Unable to create macaroons "+ + err := fmt.Errorf("unable to create macaroons "+ "%v", err) ltndLog.Error(err) return err @@ -429,7 +429,7 @@ func Main(lisCfg ListenerCfg) error { walletInitParams.Wallet, neutrinoCS, ) if err != nil { - err := fmt.Errorf("Unable to create chain control: %v", err) + err := fmt.Errorf("unable to create chain control: %v", err) ltndLog.Error(err) return err } @@ -448,7 +448,7 @@ func Main(lisCfg ListenerCfg) error { }, }) if err != nil { - err := fmt.Errorf("Unable to derive node private key: %v", err) + err := fmt.Errorf("unable to derive node private key: %v", err) ltndLog.Error(err) return err } @@ -467,7 +467,7 @@ func Main(lisCfg ListenerCfg) error { var err error towerClientDB, err = wtdb.OpenClientDB(graphDir) if err != nil { - err := fmt.Errorf("Unable to open watchtower client "+ + err := fmt.Errorf("unable to open watchtower client "+ "database: %v", err) ltndLog.Error(err) return err @@ -508,7 +508,7 @@ func Main(lisCfg ListenerCfg) error { towerDB, err := wtdb.OpenTowerDB(towerDBDir) if err != nil { - err := fmt.Errorf("Unable to open watchtower "+ + err := fmt.Errorf("unable to open watchtower "+ "database: %v", err) ltndLog.Error(err) return err @@ -524,7 +524,7 @@ func Main(lisCfg ListenerCfg) error { }, ) if err != nil { - err := fmt.Errorf("Unable to derive watchtower "+ + err := fmt.Errorf("unable to derive watchtower "+ "private key: %v", err) ltndLog.Error(err) return err @@ -561,7 +561,7 @@ func Main(lisCfg ListenerCfg) error { wtConfig, err := cfg.Watchtower.Apply(wtCfg, lncfg.NormalizeAddresses) if err != nil { - err := fmt.Errorf("Unable to configure watchtower: %v", + err := fmt.Errorf("unable to configure watchtower: %v", err) ltndLog.Error(err) return err @@ -569,7 +569,7 @@ func Main(lisCfg ListenerCfg) error { tower, err = watchtower.New(wtConfig) if err != nil { - err := fmt.Errorf("Unable to create watchtower: %v", err) + err := fmt.Errorf("unable to create watchtower: %v", err) ltndLog.Error(err) return err } @@ -586,7 +586,7 @@ func Main(lisCfg ListenerCfg) error { torController, ) if err != nil { - err := fmt.Errorf("Unable to create server: %v", err) + err := fmt.Errorf("unable to create server: %v", err) ltndLog.Error(err) return err } @@ -596,19 +596,19 @@ func Main(lisCfg ListenerCfg) error { // it at will. atplCfg, err := initAutoPilot(server, cfg.Autopilot, mainChain) if err != nil { - err := fmt.Errorf("Unable to initialize autopilot: %v", err) + err := fmt.Errorf("unable to initialize autopilot: %v", err) ltndLog.Error(err) return err } atplManager, err := autopilot.NewManager(atplCfg) if err != nil { - err := fmt.Errorf("Unable to create autopilot manager: %v", err) + err := fmt.Errorf("unable to create autopilot manager: %v", err) ltndLog.Error(err) return err } if err := atplManager.Start(); err != nil { - err := fmt.Errorf("Unable to start autopilot manager: %v", err) + err := fmt.Errorf("unable to start autopilot manager: %v", err) ltndLog.Error(err) return err } @@ -636,12 +636,12 @@ func Main(lisCfg ListenerCfg) error { tower, tlsCfg, rpcListeners, chainedAcceptor, ) if err != nil { - err := fmt.Errorf("Unable to create RPC server: %v", err) + err := fmt.Errorf("unable to create RPC server: %v", err) ltndLog.Error(err) return err } if err := rpcServer.Start(); err != nil { - err := fmt.Errorf("Unable to start RPC server: %v", err) + err := fmt.Errorf("unable to start RPC server: %v", err) ltndLog.Error(err) return err } @@ -656,7 +656,7 @@ func Main(lisCfg ListenerCfg) error { _, bestHeight, err := activeChainControl.chainIO.GetBestBlock() if err != nil { - err := fmt.Errorf("Unable to determine chain tip: %v", + err := fmt.Errorf("unable to determine chain tip: %v", err) ltndLog.Error(err) return err @@ -672,7 +672,7 @@ func Main(lisCfg ListenerCfg) error { synced, _, err := activeChainControl.wallet.IsSynced() if err != nil { - err := fmt.Errorf("Unable to determine if "+ + err := fmt.Errorf("unable to determine if "+ "wallet is synced: %v", err) ltndLog.Error(err) return err @@ -687,7 +687,7 @@ func Main(lisCfg ListenerCfg) error { _, bestHeight, err = activeChainControl.chainIO.GetBestBlock() if err != nil { - err := fmt.Errorf("Unable to determine chain tip: %v", + err := fmt.Errorf("unable to determine chain tip: %v", err) ltndLog.Error(err) return err @@ -700,7 +700,7 @@ func Main(lisCfg ListenerCfg) error { // With all the relevant chains initialized, we can finally start the // server itself. if err := server.Start(); err != nil { - err := fmt.Errorf("Unable to start server: %v", err) + err := fmt.Errorf("unable to start server: %v", err) ltndLog.Error(err) return err } @@ -711,7 +711,7 @@ func Main(lisCfg ListenerCfg) error { // stopped together with the autopilot service. if cfg.Autopilot.Active { if err := atplManager.StartAgent(); err != nil { - err := fmt.Errorf("Unable to start autopilot agent: %v", + err := fmt.Errorf("unable to start autopilot agent: %v", err) ltndLog.Error(err) return err @@ -720,7 +720,7 @@ func Main(lisCfg ListenerCfg) error { if cfg.Watchtower.Active { if err := tower.Start(); err != nil { - err := fmt.Errorf("Unable to start watchtower: %v", err) + err := fmt.Errorf("unable to start watchtower: %v", err) ltndLog.Error(err) return err } diff --git a/lntest/harness.go b/lntest/harness.go index 045fd478..eb75d0fe 100644 --- a/lntest/harness.go +++ b/lntest/harness.go @@ -211,12 +211,13 @@ func (n *NetworkHarness) SetUp(lndArgs []string) error { // Now block until both wallets have fully synced up. expectedBalance := int64(btcutil.SatoshiPerBitcoin * 10) balReq := &lnrpc.WalletBalanceRequest{} - balanceTicker := time.Tick(time.Millisecond * 50) + balanceTicker := time.NewTicker(time.Millisecond * 50) + defer balanceTicker.Stop() balanceTimeout := time.After(time.Second * 30) out: for { select { - case <-balanceTicker: + case <-balanceTicker.C: aliceResp, err := n.Alice.WalletBalance(ctxb, balReq) if err != nil { return err @@ -684,7 +685,7 @@ func (n *NetworkHarness) SaveProfilesPages() { for _, node := range n.activeNodes { if err := saveProfilesPage(node); err != nil { - fmt.Println(err) + fmt.Printf("Error: %v\n", err) } } } @@ -698,16 +699,16 @@ func saveProfilesPage(node *HarnessNode) error { ), ) if err != nil { - return fmt.Errorf("Failed to get profile page "+ - "(node_id=%d, name=%s): %v\n", + return fmt.Errorf("failed to get profile page "+ + "(node_id=%d, name=%s): %v", node.NodeID, node.Cfg.Name, err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { - return fmt.Errorf("Failed to read profile page "+ - "(node_id=%d, name=%s): %v\n", + return fmt.Errorf("failed to read profile page "+ + "(node_id=%d, name=%s): %v", node.NodeID, node.Cfg.Name, err) } @@ -718,16 +719,16 @@ func saveProfilesPage(node *HarnessNode) error { logFile, err := os.Create(fileName) if err != nil { - return fmt.Errorf("Failed to create file for profile page "+ - "(node_id=%d, name=%s): %v\n", + return fmt.Errorf("failed to create file for profile page "+ + "(node_id=%d, name=%s): %v", node.NodeID, node.Cfg.Name, err) } defer logFile.Close() _, err = logFile.Write(body) if err != nil { - return fmt.Errorf("Failed to save profile page "+ - "(node_id=%d, name=%s): %v\n", + return fmt.Errorf("failed to save profile page "+ + "(node_id=%d, name=%s): %v", node.NodeID, node.Cfg.Name, err) } return nil @@ -871,10 +872,10 @@ func (n *NetworkHarness) OpenChannel(ctx context.Context, // prevents any funding workflows from being kicked off if the chain // isn't yet synced. if err := srcNode.WaitForBlockchainSync(ctx); err != nil { - return nil, fmt.Errorf("Unable to sync srcNode chain: %v", err) + return nil, fmt.Errorf("enable to sync srcNode chain: %v", err) } if err := destNode.WaitForBlockchainSync(ctx); err != nil { - return nil, fmt.Errorf("Unable to sync destNode chain: %v", err) + return nil, fmt.Errorf("unable to sync destNode chain: %v", err) } minConfs := int32(1) @@ -940,10 +941,10 @@ func (n *NetworkHarness) OpenPendingChannel(ctx context.Context, // Wait until srcNode and destNode have blockchain synced if err := srcNode.WaitForBlockchainSync(ctx); err != nil { - return nil, fmt.Errorf("Unable to sync srcNode chain: %v", err) + return nil, fmt.Errorf("unable to sync srcNode chain: %v", err) } if err := destNode.WaitForBlockchainSync(ctx); err != nil { - return nil, fmt.Errorf("Unable to sync destNode chain: %v", err) + return nil, fmt.Errorf("unable to sync destNode chain: %v", err) } openReq := &lnrpc.OpenChannelRequest{ diff --git a/lntest/node.go b/lntest/node.go index b08e9935..0649dd6e 100644 --- a/lntest/node.go +++ b/lntest/node.go @@ -1122,7 +1122,7 @@ func (hn *HarnessNode) WaitForBlockchainSync(ctx context.Context) error { case err := <-errChan: return err case <-ctx.Done(): - return fmt.Errorf("Timeout while waiting for blockchain sync") + return fmt.Errorf("timeout while waiting for blockchain sync") } } diff --git a/lnwallet/channel.go b/lnwallet/channel.go index 600820f2..0f37a46c 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -3920,7 +3920,7 @@ func genHtlcSigValidationJobs(localCommitmentView *commitment, // Make sure there are more signatures left. if i >= len(htlcSigs) { return nil, fmt.Errorf("not enough HTLC " + - "signatures.") + "signatures") } // With the sighash generated, we'll also store the @@ -3974,7 +3974,7 @@ func genHtlcSigValidationJobs(localCommitmentView *commitment, // Make sure there are more signatures left. if i >= len(htlcSigs) { return nil, fmt.Errorf("not enough HTLC " + - "signatures.") + "signatures") } // With the sighash generated, we'll also store the diff --git a/lnwallet/errors.go b/lnwallet/errors.go index 79ab10f7..36d18d35 100644 --- a/lnwallet/errors.go +++ b/lnwallet/errors.go @@ -34,7 +34,7 @@ func ErrZeroCapacity() ReservationError { func ErrChainMismatch(knownChain, unknownChain *chainhash.Hash) ReservationError { return ReservationError{ - fmt.Errorf("Unknown chain=%v. Supported chain=%v", + fmt.Errorf("unknown chain=%v, supported chain=%v", unknownChain, knownChain), } } @@ -44,7 +44,7 @@ func ErrChainMismatch(knownChain, func ErrFunderBalanceDust(commitFee, funderBalance, minBalance int64) ReservationError { return ReservationError{ - fmt.Errorf("Funder balance too small (%v) with fee=%v sat, "+ + fmt.Errorf("funder balance too small (%v) with fee=%v sat, "+ "minimum=%v sat required", funderBalance, commitFee, minBalance), } @@ -73,7 +73,7 @@ func ErrChanReserveTooSmall(reserve, dustLimit btcutil.Amount) ReservationError func ErrChanReserveTooLarge(reserve, maxReserve btcutil.Amount) ReservationError { return ReservationError{ - fmt.Errorf("Channel reserve is too large: %v sat, max "+ + fmt.Errorf("channel reserve is too large: %v sat, max "+ "is %v sat", int64(reserve), int64(maxReserve)), } } @@ -82,7 +82,7 @@ func ErrChanReserveTooLarge(reserve, // FundingOpen request for a channel with non-zero push amount while // they have 'rejectpush' enabled. func ErrNonZeroPushAmount() ReservationError { - return ReservationError{errors.New("Non-zero push amounts are disabled")} + return ReservationError{errors.New("non-zero push amounts are disabled")} } // ErrMinHtlcTooLarge returns an error indicating that the MinHTLC value the @@ -90,7 +90,7 @@ func ErrNonZeroPushAmount() ReservationError { func ErrMinHtlcTooLarge(minHtlc, maxMinHtlc lnwire.MilliSatoshi) ReservationError { return ReservationError{ - fmt.Errorf("Minimum HTLC value is too large: %v, max is %v", + fmt.Errorf("minimum HTLC value is too large: %v, max is %v", minHtlc, maxMinHtlc), } } diff --git a/lnwallet/interface.go b/lnwallet/interface.go index 41052503..cf36ff80 100644 --- a/lnwallet/interface.go +++ b/lnwallet/interface.go @@ -43,7 +43,7 @@ var ( // ErrDoubleSpend is returned from PublishTransaction in case the // tx being published is spending an output spent by a conflicting // transaction. - ErrDoubleSpend = errors.New("Transaction rejected: output already spent") + ErrDoubleSpend = errors.New("transaction rejected: output already spent") // ErrNotMine is an error denoting that a WalletController instance is // unable to spend a specified output. diff --git a/lnwallet/interface_test.go b/lnwallet/interface_test.go index 16fc7ce4..94e34a45 100644 --- a/lnwallet/interface_test.go +++ b/lnwallet/interface_test.go @@ -753,7 +753,7 @@ func testReservationInitiatorBalanceBelowDustCancel(miner *rpctest.Harness, t.Fatalf("initialization should have failed due to " + "insufficient local amount") - case !strings.Contains(err.Error(), "Funder balance too small"): + case !strings.Contains(err.Error(), "funder balance too small"): t.Fatalf("incorrect error: %v", err) } } diff --git a/lnwallet/wallet.go b/lnwallet/wallet.go index 3349d29e..2b41aedc 100644 --- a/lnwallet/wallet.go +++ b/lnwallet/wallet.go @@ -1268,7 +1268,6 @@ func (l *LightningWallet) handleSingleContribution(req *addSingleContributionMsg chanState.RemoteCurrentRevocation = theirContribution.FirstCommitmentPoint req.err <- nil - return } // verifyFundingInputs attempts to verify all remote inputs to the funding diff --git a/lnwire/lnwire.go b/lnwire/lnwire.go index 4e9871b2..ca0e449e 100644 --- a/lnwire/lnwire.go +++ b/lnwire/lnwire.go @@ -419,7 +419,7 @@ func WriteElement(w io.Writer, element interface{}) error { return err } default: - return fmt.Errorf("Unknown type in WriteElement: %T", e) + return fmt.Errorf("unknown type in WriteElement: %T", e) } return nil @@ -818,14 +818,14 @@ func ReadElement(r io.Reader, element interface{}) error { var addrBytes [deliveryAddressMaxSize]byte if length > deliveryAddressMaxSize { - return fmt.Errorf("Cannot read %d bytes into addrBytes", length) + return fmt.Errorf("cannot read %d bytes into addrBytes", length) } if _, err = io.ReadFull(r, addrBytes[:length]); err != nil { return err } *e = addrBytes[:length] default: - return fmt.Errorf("Unknown type in ReadElement: %T", e) + return fmt.Errorf("unknown type in ReadElement: %T", e) } return nil diff --git a/monitoring/log.go b/monitoring/log.go index 4781f625..a35af852 100644 --- a/monitoring/log.go +++ b/monitoring/log.go @@ -27,19 +27,3 @@ func DisableLog() { func UseLogger(logger btclog.Logger) { log = logger } - -// logClosure is used to provide a closure over expensive logging operations so -// don't have to be performed when the logging level doesn't warrant it. -type logClosure func() string // nolint:unused - -// String invokes the underlying function and returns the result. -func (c logClosure) String() string { - return c() -} - -// newLogClosure returns a new closure over a function that returns a string -// which itself provides a Stringer interface so that it can be used with the -// logging system. -func newLogClosure(c func() string) logClosure { // nolint:unused - return logClosure(c) -} diff --git a/netann/chan_status_manager_test.go b/netann/chan_status_manager_test.go index da42bc68..f18774c3 100644 --- a/netann/chan_status_manager_test.go +++ b/netann/chan_status_manager_test.go @@ -225,9 +225,7 @@ func (g *mockGraph) chans() []*channeldb.OpenChannel { defer g.mu.Unlock() channels := make([]*channeldb.OpenChannel, 0, len(g.channels)) - for _, channel := range g.channels { - channels = append(channels, channel) - } + channels = append(channels, g.channels...) return channels } diff --git a/netann/log.go b/netann/log.go index 32d9aae3..85d8d68c 100644 --- a/netann/log.go +++ b/netann/log.go @@ -27,19 +27,3 @@ func DisableLog() { func UseLogger(logger btclog.Logger) { log = logger } - -// logClosure is used to provide a closure over expensive logging operations so -// don't have to be performed when the logging level doesn't warrant it. -type logClosure func() string // nolint:unused - -// String invokes the underlying function and returns the result. -func (c logClosure) String() string { - return c() -} - -// newLogClosure returns a new closure over a function that returns a string -// which itself provides a Stringer interface so that it can be used with the -// logging system. -func newLogClosure(c func() string) logClosure { // nolint:unused - return logClosure(c) -} diff --git a/nursery_store.go b/nursery_store.go index bc20d1bc..83f54067 100644 --- a/nursery_store.go +++ b/nursery_store.go @@ -1145,32 +1145,6 @@ func (ns *nurseryStore) createHeightChanBucket(tx kvdb.RwTx, return hghtBucket.CreateBucketIfNotExists(chanBytes) } -// getHeightChanBucket retrieves an existing height-channel bucket from the -// nursery store, using the provided block height and channel point. if the -// bucket does not exist, or any bucket along its path does not exist, a nil -// value is returned. -func (ns *nurseryStore) getHeightChanBucket(tx kvdb.ReadTx, // nolint:unused - height uint32, chanPoint *wire.OutPoint) kvdb.ReadBucket { - - // Retrieve the existing height bucket from this nursery store. - hghtBucket := ns.getHeightBucket(tx, height) - if hghtBucket == nil { - return nil - } - - // Serialize the provided channel point, which generates the key for - // looking up the proper height-channel bucket inside the height bucket. - var chanBuffer bytes.Buffer - if err := writeOutpoint(&chanBuffer, chanPoint); err != nil { - return nil - } - chanBytes := chanBuffer.Bytes() - - // Finally, return the height bucket specified by the serialized channel - // point. - return hghtBucket.NestedReadBucket(chanBytes) -} - // getHeightChanBucketWrite retrieves an existing height-channel bucket from the // nursery store, using the provided block height and channel point. if the // bucket does not exist, or any bucket along its path does not exist, a nil diff --git a/peer.go b/peer.go index 3ae99777..f73e8c5c 100644 --- a/peer.go +++ b/peer.go @@ -1115,7 +1115,7 @@ func (p *peer) readHandler() { // We'll stop the timer after a new messages is received, and also // reset it after we process the next message. idleTimer := time.AfterFunc(idleTimeout, func() { - err := fmt.Errorf("Peer %s no answer for %s -- disconnecting", + err := fmt.Errorf("peer %s no answer for %s -- disconnecting", p, idleTimeout) p.Disconnect(err) }) @@ -1657,7 +1657,7 @@ func (p *peer) writeHandler() { // We'll stop the timer after a new messages is sent, and also reset it // after we process the next message. idleTimer := time.AfterFunc(idleTimeout, func() { - err := fmt.Errorf("Peer %s no write for %s -- disconnecting", + err := fmt.Errorf("peer %s no write for %s -- disconnecting", p, idleTimeout) p.Disconnect(err) }) @@ -2724,7 +2724,7 @@ func (p *peer) resendChanSyncMsg(cid lnwire.ChannelID) error { "peer %v", cid, p) if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil { - return fmt.Errorf("Failed resending channel sync "+ + return fmt.Errorf("failed resending channel sync "+ "message to peer %v: %v", p, err) } diff --git a/pilot.go b/pilot.go index 923c7865..b3acc423 100644 --- a/pilot.go +++ b/pilot.go @@ -39,7 +39,7 @@ func validateAtplCfg(cfg *autoPilotConfig) ([]*autopilot.WeightedHeuristic, a, ok := autopilot.AvailableHeuristics[name] if !ok { // No heuristic matching this config option was found. - return nil, fmt.Errorf("Heuristic %v not available. %v", + return nil, fmt.Errorf("heuristic %v not available. %v", name, availStr) } @@ -58,11 +58,11 @@ func validateAtplCfg(cfg *autoPilotConfig) ([]*autopilot.WeightedHeuristic, // Check found heuristics. We must have at least one to operate. if len(heuristics) == 0 { - return nil, fmt.Errorf("No active heuristics. %v", availStr) + return nil, fmt.Errorf("no active heuristics: %v", availStr) } if sum != 1.0 { - return nil, fmt.Errorf("Heuristic weights must sum to 1.0") + return nil, fmt.Errorf("heuristic weights must sum to 1.0") } return heuristics, nil } diff --git a/queue/gc_queue.go b/queue/gc_queue.go index 7698f324..965e841d 100644 --- a/queue/gc_queue.go +++ b/queue/gc_queue.go @@ -2,7 +2,6 @@ package queue import ( "container/list" - "sync" "time" "github.com/lightningnetwork/lnd/ticker" @@ -44,7 +43,6 @@ type GCQueue struct { // increasing time of arrival. freeList *list.List - wg sync.WaitGroup quit chan struct{} } diff --git a/routing/errors.go b/routing/errors.go index 3beac229..a8bd6fba 100644 --- a/routing/errors.go +++ b/routing/errors.go @@ -34,15 +34,6 @@ func (e *routerError) Error() string { // A compile time check to ensure routerError implements the error interface. var _ error = (*routerError)(nil) -// newErr creates a routerError by the given error description and its -// corresponding error code. -func newErr(code errorCode, a interface{}) *routerError { - return &routerError{ - code: code, - err: errors.New(a), - } -} - // newErrf creates a routerError by the given error formatted description and // its corresponding error code. func newErrf(code errorCode, format string, a ...interface{}) *routerError { diff --git a/routing/missioncontrol.go b/routing/missioncontrol.go index 40e2ab4f..f48f8f5f 100644 --- a/routing/missioncontrol.go +++ b/routing/missioncontrol.go @@ -228,7 +228,7 @@ func (m *MissionControl) init() error { } log.Debugf("Mission control state reconstruction finished: "+ - "n=%v, time=%v", len(results), time.Now().Sub(start)) + "n=%v, time=%v", len(results), time.Since(start)) return nil } diff --git a/routing/notifications.go b/routing/notifications.go index 2014121c..e4b260e7 100644 --- a/routing/notifications.go +++ b/routing/notifications.go @@ -386,7 +386,7 @@ func addToTopologyChange(graph *channeldb.ChannelGraph, update *TopologyChange, return nil default: - return fmt.Errorf("Unable to add to topology change, "+ + return fmt.Errorf("unable to add to topology change, "+ "unknown message type %T", msg) } } diff --git a/routing/pathfind_test.go b/routing/pathfind_test.go index deaccb28..de7c16c6 100644 --- a/routing/pathfind_test.go +++ b/routing/pathfind_test.go @@ -36,12 +36,6 @@ const ( // connecting them. basicGraphFilePath = "testdata/basic_graph.json" - // excessiveHopsGraphFilePath is a file path which stores the JSON dump - // of a graph which was previously triggering an erroneous excessive - // hops error. The error has since been fixed, but a test case - // exercising it is kept around to guard against regressions. - excessiveHopsGraphFilePath = "testdata/excessive_hops.json" - // specExampleFilePath is a file path which stores an example which // implementations will use in order to ensure that they're calculating // the payload for each hop in path properly. @@ -443,8 +437,7 @@ func createTestGraphFromChannels(testChannels []*testChannel, source string) ( addNodeWithAlias := func(alias string, features *lnwire.FeatureVector) ( *channeldb.LightningNode, error) { - keyBytes := make([]byte, 32) - keyBytes = []byte{ + keyBytes := []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, diff --git a/routing/router.go b/routing/router.go index c3773fe6..21d9e4ea 100644 --- a/routing/router.go +++ b/routing/router.go @@ -2197,7 +2197,7 @@ func (r *ChannelRouter) ForAllOutgoingChannels(cb func(*channeldb.ChannelEdgeInf e, _ *channeldb.ChannelEdgePolicy) error { if e == nil { - return fmt.Errorf("Channel from self node has no policy") + return fmt.Errorf("channel from self node has no policy") } return cb(c, e) diff --git a/server.go b/server.go index 3fdffb2c..bf751557 100644 --- a/server.go +++ b/server.go @@ -547,7 +547,7 @@ func newServer(listenAddrs []net.Addr, chanDB *channeldb.DB, pmp, err := nat.DiscoverPMP(discoveryTimeout) if err != nil { - err := fmt.Errorf("Unable to discover a "+ + err := fmt.Errorf("unable to discover a "+ "NAT-PMP enabled device on the local "+ "network: %v", err) srvrLog.Error(err) @@ -598,10 +598,9 @@ func newServer(listenAddrs []net.Addr, chanDB *channeldb.DB, if err != nil { return nil, err } + selfAddrs := make([]net.Addr, 0, len(externalIPs)) - for _, ip := range externalIPs { - selfAddrs = append(selfAddrs, ip) - } + selfAddrs = append(selfAddrs, externalIPs...) chanGraph := chanDB.ChannelGraph() @@ -1996,7 +1995,7 @@ func (s *server) createNewHiddenService() error { }, ) if err != nil { - return fmt.Errorf("Unable to generate new node "+ + return fmt.Errorf("unable to generate new node "+ "announcement: %v", err) } @@ -2449,7 +2448,7 @@ func (s *server) nextPeerBackoff(pubStr string, // The peer succeeded in starting. If the connection didn't last long // enough to be considered stable, we'll continue to back off retries // with this peer. - connDuration := time.Now().Sub(startTime) + connDuration := time.Since(startTime) if connDuration < defaultStableConnDuration { return computeNextBackoff(backoff) } diff --git a/tlv/truncated_test.go b/tlv/truncated_test.go index eb0f83a7..f530d0b6 100644 --- a/tlv/truncated_test.go +++ b/tlv/truncated_test.go @@ -77,7 +77,7 @@ func TestTUint16(t *testing.T) { t.Fatalf("unable to encode tuint16: %v", err) } - if bytes.Compare(b.Bytes(), test.bytes) != 0 { + if !bytes.Equal(b.Bytes(), test.bytes) { t.Fatalf("encoding mismatch, "+ "expected: %x, got: %x", test.bytes, b.Bytes()) @@ -201,7 +201,7 @@ func TestTUint32(t *testing.T) { t.Fatalf("unable to encode tuint32: %v", err) } - if bytes.Compare(b.Bytes(), test.bytes) != 0 { + if !bytes.Equal(b.Bytes(), test.bytes) { t.Fatalf("encoding mismatch, "+ "expected: %x, got: %x", test.bytes, b.Bytes()) @@ -371,7 +371,7 @@ func TestTUint64(t *testing.T) { t.Fatalf("unable to encode tuint64: %v", err) } - if bytes.Compare(b.Bytes(), test.bytes) != 0 { + if !bytes.Equal(b.Bytes(), test.bytes) { t.Fatalf("encoding mismatch, "+ "expected: %x, got: %x", test.bytes, b.Bytes()) diff --git a/tlv/varint_test.go b/tlv/varint_test.go index 75cc1085..30a2f851 100644 --- a/tlv/varint_test.go +++ b/tlv/varint_test.go @@ -80,7 +80,7 @@ func testWriteVarInt(t *testing.T, test varIntTest) { test.Value, err) } - if bytes.Compare(w.Bytes(), test.Bytes) != 0 { + if !bytes.Equal(w.Bytes(), test.Bytes) { t.Fatalf("expected bytes: %v, got %v", test.Bytes, w.Bytes()) } diff --git a/utxonursery_test.go b/utxonursery_test.go index cbc91269..5b4424c5 100644 --- a/utxonursery_test.go +++ b/utxonursery_test.go @@ -628,21 +628,6 @@ func createOutgoingRes(onLocalCommitment bool) *lnwallet.OutgoingHtlcResolution return &outgoingRes } -func createCommitmentRes() *lnwallet.CommitOutputResolution { - // Set up a commitment output resolution to hand off to nursery. - commitRes := lnwallet.CommitOutputResolution{ - SelfOutPoint: wire.OutPoint{}, - SelfOutputSignDesc: input.SignDescriptor{ - Output: &wire.TxOut{ - Value: 10000, - }, - }, - MaturityDelay: 2, - } - - return &commitRes -} - func incubateTestOutput(t *testing.T, nursery *utxoNursery, onLocalCommitment bool) *lnwallet.OutgoingHtlcResolution { diff --git a/watchtower/log.go b/watchtower/log.go index 7aebd7e7..8ce96131 100644 --- a/watchtower/log.go +++ b/watchtower/log.go @@ -31,19 +31,3 @@ func UseLogger(logger btclog.Logger) { lookout.UseLogger(logger) wtserver.UseLogger(logger) } - -// logClosure is used to provide a closure over expensive logging operations so -// don't have to be performed when the logging level doesn't warrant it. -type logClosure func() string // nolint:unused - -// String invokes the underlying function and returns the result. -func (c logClosure) String() string { - return c() -} - -// newLogClosure returns a new closure over a function that returns a string -// which itself provides a Stringer interface so that it can be used with the -// logging system. -func newLogClosure(c func() string) logClosure { // nolint:unused - return logClosure(c) -} diff --git a/watchtower/standalone.go b/watchtower/standalone.go index b1a36bb5..6dd3fe6d 100644 --- a/watchtower/standalone.go +++ b/watchtower/standalone.go @@ -212,9 +212,7 @@ func (w *Standalone) ListeningAddrs() []net.Addr { // NOTE: Part of the watchtowerrpc.WatchtowerBackend interface. func (w *Standalone) ExternalIPs() []net.Addr { addrs := make([]net.Addr, 0, len(w.cfg.ExternalIPs)) - for _, addr := range w.cfg.ExternalIPs { - addrs = append(addrs, addr) - } + addrs = append(addrs, w.cfg.ExternalIPs...) return addrs } diff --git a/zpay32/amountunits.go b/zpay32/amountunits.go index c13f1a13..f53f3ff0 100644 --- a/zpay32/amountunits.go +++ b/zpay32/amountunits.go @@ -127,10 +127,6 @@ func decodeAmount(amount string) (lnwire.MilliSatoshi, error) { // encodeAmount encodes the provided millisatoshi amount using as few characters // as possible. func encodeAmount(msat lnwire.MilliSatoshi) (string, error) { - if msat < 0 { - return "", fmt.Errorf("amount must be positive: %v", msat) - } - // If possible to express in BTC, that will always be the shortest // representation. if msat%mSatPerBtc == 0 { diff --git a/zpay32/invoice.go b/zpay32/invoice.go index 691c0169..1c183231 100644 --- a/zpay32/invoice.go +++ b/zpay32/invoice.go @@ -571,11 +571,6 @@ func validateInvoice(invoice *Invoice) error { return fmt.Errorf("net params not set") } - // Ensure that if there is an amount set, it is not negative. - if invoice.MilliSat != nil && *invoice.MilliSat < 0 { - return fmt.Errorf("negative amount: %v", *invoice.MilliSat) - } - // The invoice must contain a payment hash. if invoice.PaymentHash == nil { return fmt.Errorf("no payment hash found")