multi: fix newly detected linter issues

This commit is contained in:
Oliver Gugger 2022-02-07 13:58:25 +01:00
parent 369627901f
commit ffee7d1bcf
No known key found for this signature in database
GPG Key ID: 8E4256593F177720
30 changed files with 106 additions and 118 deletions

View File

@ -419,7 +419,7 @@ func testBlockEpochNotification(miner *rpctest.Harness,
// hash. // hash.
blockEpoch := <-epochClient.Epochs blockEpoch := <-epochClient.Epochs
if blockEpoch.BlockHeader == nil { if blockEpoch.BlockHeader == nil {
fmt.Println(i) t.Logf("%d", i)
clientErrors <- fmt.Errorf("block " + clientErrors <- fmt.Errorf("block " +
"header is nil") "header is nil")
return return

View File

@ -22,77 +22,77 @@ const (
// fieldMismatchError returns a merge error for a named field when we get two // fieldMismatchError returns a merge error for a named field when we get two
// channel acceptor responses which have different values set. // channel acceptor responses which have different values set.
func fieldMismatchError(name string, current, new interface{}) error { func fieldMismatchError(name string, current, newValue interface{}) error {
return fmt.Errorf("multiple values set for: %v, %v and %v", return fmt.Errorf("multiple values set for: %v, %v and %v",
name, current, new) name, current, newValue)
} }
// mergeInt64 merges two int64 values, failing if they have different non-zero // mergeInt64 merges two int64 values, failing if they have different non-zero
// values. // values.
func mergeInt64(name string, current, new int64) (int64, error) { func mergeInt64(name string, current, newValue int64) (int64, error) {
switch { switch {
case current == 0: case current == 0:
return new, nil return newValue, nil
case new == 0: case newValue == 0:
return current, nil return current, nil
case current != new: case current != newValue:
return 0, fieldMismatchError(name, current, new) return 0, fieldMismatchError(name, current, newValue)
default: default:
return new, nil return newValue, nil
} }
} }
// mergeMillisatoshi merges two msat values, failing if they have different // mergeMillisatoshi merges two msat values, failing if they have different
// non-zero values. // non-zero values.
func mergeMillisatoshi(name string, current, func mergeMillisatoshi(name string, current,
new lnwire.MilliSatoshi) (lnwire.MilliSatoshi, error) { newValue lnwire.MilliSatoshi) (lnwire.MilliSatoshi, error) {
switch { switch {
case current == 0: case current == 0:
return new, nil return newValue, nil
case new == 0: case newValue == 0:
return current, nil return current, nil
case current != new: case current != newValue:
return 0, fieldMismatchError(name, current, new) return 0, fieldMismatchError(name, current, newValue)
default: default:
return new, nil return newValue, nil
} }
} }
// mergeDeliveryAddress merges two delivery address values, failing if they have // mergeDeliveryAddress merges two delivery address values, failing if they have
// different non-zero values. // different non-zero values.
func mergeDeliveryAddress(name string, current, func mergeDeliveryAddress(name string, current,
new lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) { newValue lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
switch { switch {
case current == nil: case current == nil:
return new, nil return newValue, nil
case new == nil: case newValue == nil:
return current, nil return current, nil
case !bytes.Equal(current, new): case !bytes.Equal(current, newValue):
return nil, fieldMismatchError(name, current, new) return nil, fieldMismatchError(name, current, newValue)
default: default:
return new, nil return newValue, nil
} }
} }
// mergeResponse takes two channel accept responses, and attempts to merge their // mergeResponse takes two channel accept responses, and attempts to merge their
// fields, failing if any fields conflict (are non-zero and not equal). It // fields, failing if any fields conflict (are non-zero and not equal). It
// returns a new response that has all the merged fields in it. // returns a new response that has all the merged fields in it.
func mergeResponse(current, new ChannelAcceptResponse) (ChannelAcceptResponse, func mergeResponse(current,
error) { newValue ChannelAcceptResponse) (ChannelAcceptResponse, error) {
csv, err := mergeInt64( csv, err := mergeInt64(
fieldCSV, int64(current.CSVDelay), int64(new.CSVDelay), fieldCSV, int64(current.CSVDelay), int64(newValue.CSVDelay),
) )
if err != nil { if err != nil {
return current, err return current, err
@ -101,7 +101,7 @@ func mergeResponse(current, new ChannelAcceptResponse) (ChannelAcceptResponse,
htlcLimit, err := mergeInt64( htlcLimit, err := mergeInt64(
fieldHtlcLimit, int64(current.HtlcLimit), fieldHtlcLimit, int64(current.HtlcLimit),
int64(new.HtlcLimit), int64(newValue.HtlcLimit),
) )
if err != nil { if err != nil {
return current, err return current, err
@ -110,7 +110,7 @@ func mergeResponse(current, new ChannelAcceptResponse) (ChannelAcceptResponse,
minDepth, err := mergeInt64( minDepth, err := mergeInt64(
fieldMinDep, int64(current.MinAcceptDepth), fieldMinDep, int64(current.MinAcceptDepth),
int64(new.MinAcceptDepth), int64(newValue.MinAcceptDepth),
) )
if err != nil { if err != nil {
return current, err return current, err
@ -118,7 +118,7 @@ func mergeResponse(current, new ChannelAcceptResponse) (ChannelAcceptResponse,
current.MinAcceptDepth = uint16(minDepth) current.MinAcceptDepth = uint16(minDepth)
reserve, err := mergeInt64( reserve, err := mergeInt64(
fieldReserve, int64(current.Reserve), int64(new.Reserve), fieldReserve, int64(current.Reserve), int64(newValue.Reserve),
) )
if err != nil { if err != nil {
return current, err return current, err
@ -126,7 +126,7 @@ func mergeResponse(current, new ChannelAcceptResponse) (ChannelAcceptResponse,
current.Reserve = btcutil.Amount(reserve) current.Reserve = btcutil.Amount(reserve)
current.MinHtlcIn, err = mergeMillisatoshi( current.MinHtlcIn, err = mergeMillisatoshi(
fieldMinIn, current.MinHtlcIn, new.MinHtlcIn, fieldMinIn, current.MinHtlcIn, newValue.MinHtlcIn,
) )
if err != nil { if err != nil {
return current, err return current, err
@ -134,7 +134,7 @@ func mergeResponse(current, new ChannelAcceptResponse) (ChannelAcceptResponse,
current.InFlightTotal, err = mergeMillisatoshi( current.InFlightTotal, err = mergeMillisatoshi(
fieldInFlightTotal, current.InFlightTotal, fieldInFlightTotal, current.InFlightTotal,
new.InFlightTotal, newValue.InFlightTotal,
) )
if err != nil { if err != nil {
return current, err return current, err
@ -142,7 +142,7 @@ func mergeResponse(current, new ChannelAcceptResponse) (ChannelAcceptResponse,
current.UpfrontShutdown, err = mergeDeliveryAddress( current.UpfrontShutdown, err = mergeDeliveryAddress(
fieldUpfrontShutdown, current.UpfrontShutdown, fieldUpfrontShutdown, current.UpfrontShutdown,
new.UpfrontShutdown, newValue.UpfrontShutdown,
) )
if err != nil { if err != nil {
return current, err return current, err

View File

@ -495,7 +495,7 @@ func TestPaymentControlDeleteNonInFligt(t *testing.T) {
var s, i int var s, i int
for _, p := range dbPayments { for _, p := range dbPayments {
fmt.Println("fetch payment has status", p.Status) t.Log("fetch payment has status", p.Status)
switch p.Status { switch p.Status {
case StatusSucceeded: case StatusSucceeded:
s++ s++

View File

@ -389,7 +389,6 @@ func sendPayment(ctx *cli.Context) error {
if err != nil { if err != nil {
return err return err
} }
args = args.Tail()
req.FinalCltvDelta = int32(delta) req.FinalCltvDelta = int32(delta)
} }
@ -1288,7 +1287,6 @@ func forwardingHistory(ctx *cli.Context) error {
return fmt.Errorf("unable to decode max_events: %v", err) return fmt.Errorf("unable to decode max_events: %v", err)
} }
maxEvents = uint32(m) maxEvents = uint32(m)
args = args.Tail()
} }
req := &lnrpc.ForwardingHistoryRequest{ req := &lnrpc.ForwardingHistoryRequest{

View File

@ -806,7 +806,7 @@ func askRecoveryWindow() (int32, error) {
return defaultRecoveryWindow, nil return defaultRecoveryWindow, nil
} }
lookAhead, err := strconv.Atoi(answer) lookAhead, err := strconv.ParseInt(answer, 10, 32)
if err != nil { if err != nil {
fmt.Printf("Unable to parse recovery window: %v\n", err) fmt.Printf("Unable to parse recovery window: %v\n", err)
continue continue

View File

@ -29,7 +29,7 @@ type profileEntry struct {
LndDir string `json:"lnddir"` LndDir string `json:"lnddir"`
Chain string `json:"chain"` Chain string `json:"chain"`
Network string `json:"network"` Network string `json:"network"`
NoMacaroons bool `json:"no-macaroons,omitempty"` NoMacaroons bool `json:"no-macaroons,omitempty"` // nolint:tagliatelle
TLSCert string `json:"tlscert"` TLSCert string `json:"tlscert"`
Macaroons *macaroonJar `json:"macaroons"` Macaroons *macaroonJar `json:"macaroons"`
} }

View File

@ -1908,7 +1908,7 @@ func extractBitcoindRPCParams(networkName string,
dataDir = string(dataDirSubmatches[1]) dataDir = string(dataDirSubmatches[1])
} }
chainDir := "" var chainDir string
switch networkName { switch networkName {
case "mainnet": case "mainnet":
chainDir = "" chainDir = ""

View File

@ -487,8 +487,8 @@ func (c *commitSweepResolver) report() *ContractReport {
c.reportLock.Lock() c.reportLock.Lock()
defer c.reportLock.Unlock() defer c.reportLock.Unlock()
copy := c.currentReport cpy := c.currentReport
return &copy return &cpy
} }
// initReport initializes the pending channels report for this resolver. // initReport initializes the pending channels report for this resolver.

View File

@ -515,8 +515,8 @@ func (h *htlcSuccessResolver) report() *ContractReport {
h.reportLock.Lock() h.reportLock.Lock()
defer h.reportLock.Unlock() defer h.reportLock.Unlock()
copy := h.currentReport cpy := h.currentReport
return &copy return &cpy
} }
func (h *htlcSuccessResolver) initReport() { func (h *htlcSuccessResolver) initReport() {

View File

@ -529,7 +529,7 @@ func (h *htlcTimeoutResolver) handleCommitSpend(
case h.htlcResolution.SignedTimeoutTx != nil: case h.htlcResolution.SignedTimeoutTx != nil:
log.Infof("%T(%v): waiting for nursery/sweeper to spend CSV "+ log.Infof("%T(%v): waiting for nursery/sweeper to spend CSV "+
"delayed output", h, claimOutpoint) "delayed output", h, claimOutpoint)
sweep, err := waitForSpend( sweepTx, err := waitForSpend(
&claimOutpoint, &claimOutpoint,
h.htlcResolution.SweepSignDesc.Output.PkScript, h.htlcResolution.SweepSignDesc.Output.PkScript,
h.broadcastHeight, h.Notifier, h.quit, h.broadcastHeight, h.Notifier, h.quit,
@ -539,7 +539,7 @@ func (h *htlcTimeoutResolver) handleCommitSpend(
} }
// Update the spend txid to the hash of the sweep transaction. // Update the spend txid to the hash of the sweep transaction.
spendTxID = sweep.SpenderTxHash spendTxID = sweepTx.SpenderTxHash
// Once our sweep of the timeout tx has confirmed, we add a // Once our sweep of the timeout tx has confirmed, we add a
// resolution for our timeoutTx tx first stage transaction. // resolution for our timeoutTx tx first stage transaction.
@ -603,8 +603,8 @@ func (h *htlcTimeoutResolver) report() *ContractReport {
h.reportLock.Lock() h.reportLock.Lock()
defer h.reportLock.Unlock() defer h.reportLock.Unlock()
copy := h.currentReport cpy := h.currentReport
return &copy return &cpy
} }
func (h *htlcTimeoutResolver) initReport() { func (h *htlcTimeoutResolver) initReport() {

View File

@ -1218,7 +1218,7 @@ func TestHtlcTimeoutSecondStageSweeperRemoteSpend(t *testing.T) {
// expect the resolver to re-subscribe to a // expect the resolver to re-subscribe to a
// spend, hence we must resend it. // spend, hence we must resend it.
if resumed { if resumed {
fmt.Println("resumed") t.Logf("resumed")
ctx.notifier.SpendChan <- &chainntnfs.SpendDetail{ ctx.notifier.SpendChan <- &chainntnfs.SpendDetail{
SpendingTx: spendTx, SpendingTx: spendTx,
SpenderTxHash: &spendTxHash, SpenderTxHash: &spendTxHash,

View File

@ -1058,18 +1058,18 @@ func (ns *NurseryStore) createHeightBucket(tx kvdb.RwTx,
// store, using the provided block height. If the bucket does not exist, or any // store, using the provided block height. If the bucket does not exist, or any
// bucket along its path does not exist, a nil value is returned. // bucket along its path does not exist, a nil value is returned.
func (ns *NurseryStore) getHeightBucketPath(tx kvdb.RTx, func (ns *NurseryStore) getHeightBucketPath(tx kvdb.RTx,
height uint32) (kvdb.RBucket, kvdb.RBucket, kvdb.RBucket) { height uint32) (kvdb.RBucket, kvdb.RBucket) {
// Retrieve the existing chain bucket for this nursery store. // Retrieve the existing chain bucket for this nursery store.
chainBucket := tx.ReadBucket(ns.pfxChainKey) chainBucket := tx.ReadBucket(ns.pfxChainKey)
if chainBucket == nil { if chainBucket == nil {
return nil, nil, nil return nil, nil
} }
// Retrieve the existing channel index. // Retrieve the existing channel index.
hghtIndex := chainBucket.NestedReadBucket(heightIndexKey) hghtIndex := chainBucket.NestedReadBucket(heightIndexKey)
if hghtIndex == nil { if hghtIndex == nil {
return nil, nil, nil return nil, nil
} }
// Serialize the provided block height and return the bucket matching // Serialize the provided block height and return the bucket matching
@ -1077,25 +1077,25 @@ func (ns *NurseryStore) getHeightBucketPath(tx kvdb.RTx,
var heightBytes [4]byte var heightBytes [4]byte
byteOrder.PutUint32(heightBytes[:], height) byteOrder.PutUint32(heightBytes[:], height)
return chainBucket, hghtIndex, hghtIndex.NestedReadBucket(heightBytes[:]) return chainBucket, hghtIndex.NestedReadBucket(heightBytes[:])
} }
// getHeightBucketPathWrite retrieves an existing height bucket from the nursery // getHeightBucketPathWrite retrieves an existing height bucket from the nursery
// store, using the provided block height. If the bucket does not exist, or any // store, using the provided block height. If the bucket does not exist, or any
// bucket along its path does not exist, a nil value is returned. // bucket along its path does not exist, a nil value is returned.
func (ns *NurseryStore) getHeightBucketPathWrite(tx kvdb.RwTx, func (ns *NurseryStore) getHeightBucketPathWrite(tx kvdb.RwTx,
height uint32) (kvdb.RwBucket, kvdb.RwBucket, kvdb.RwBucket) { height uint32) (kvdb.RwBucket, kvdb.RwBucket) {
// Retrieve the existing chain bucket for this nursery store. // Retrieve the existing chain bucket for this nursery store.
chainBucket := tx.ReadWriteBucket(ns.pfxChainKey) chainBucket := tx.ReadWriteBucket(ns.pfxChainKey)
if chainBucket == nil { if chainBucket == nil {
return nil, nil, nil return nil, nil
} }
// Retrieve the existing channel index. // Retrieve the existing channel index.
hghtIndex := chainBucket.NestedReadWriteBucket(heightIndexKey) hghtIndex := chainBucket.NestedReadWriteBucket(heightIndexKey)
if hghtIndex == nil { if hghtIndex == nil {
return nil, nil, nil return nil, nil
} }
// Serialize the provided block height and return the bucket matching // Serialize the provided block height and return the bucket matching
@ -1103,7 +1103,7 @@ func (ns *NurseryStore) getHeightBucketPathWrite(tx kvdb.RwTx,
var heightBytes [4]byte var heightBytes [4]byte
byteOrder.PutUint32(heightBytes[:], height) byteOrder.PutUint32(heightBytes[:], height)
return chainBucket, hghtIndex, hghtIndex.NestedReadWriteBucket( return hghtIndex, hghtIndex.NestedReadWriteBucket(
heightBytes[:], heightBytes[:],
) )
} }
@ -1113,7 +1113,8 @@ func (ns *NurseryStore) getHeightBucketPathWrite(tx kvdb.RwTx,
// along its path does not exist, a nil value is returned. // along its path does not exist, a nil value is returned.
func (ns *NurseryStore) getHeightBucket(tx kvdb.RTx, func (ns *NurseryStore) getHeightBucket(tx kvdb.RTx,
height uint32) kvdb.RBucket { height uint32) kvdb.RBucket {
_, _, hghtBucket := ns.getHeightBucketPath(tx, height)
_, hghtBucket := ns.getHeightBucketPath(tx, height)
return hghtBucket return hghtBucket
} }
@ -1124,7 +1125,7 @@ func (ns *NurseryStore) getHeightBucket(tx kvdb.RTx,
func (ns *NurseryStore) getHeightBucketWrite(tx kvdb.RwTx, func (ns *NurseryStore) getHeightBucketWrite(tx kvdb.RwTx,
height uint32) kvdb.RwBucket { height uint32) kvdb.RwBucket {
_, _, hghtBucket := ns.getHeightBucketPathWrite(tx, height) _, hghtBucket := ns.getHeightBucketPathWrite(tx, height)
return hghtBucket return hghtBucket
} }
@ -1190,7 +1191,7 @@ func (ns *NurseryStore) forEachHeightPrefix(tx kvdb.RTx, prefix []byte,
// Start by retrieving the height bucket corresponding to the provided // Start by retrieving the height bucket corresponding to the provided
// block height. // block height.
chainBucket, _, hghtBucket := ns.getHeightBucketPath(tx, height) chainBucket, hghtBucket := ns.getHeightBucketPath(tx, height)
if hghtBucket == nil { if hghtBucket == nil {
return nil return nil
} }
@ -1345,7 +1346,7 @@ func (ns *NurseryStore) removeOutputFromHeight(tx kvdb.RwTx, height uint32,
// this invocation successfully pruned the height bucket. // this invocation successfully pruned the height bucket.
func (ns *NurseryStore) pruneHeight(tx kvdb.RwTx, height uint32) (bool, error) { func (ns *NurseryStore) pruneHeight(tx kvdb.RwTx, height uint32) (bool, error) {
// Fetch the existing height index and height bucket. // Fetch the existing height index and height bucket.
_, hghtIndex, hghtBucket := ns.getHeightBucketPathWrite(tx, height) hghtIndex, hghtBucket := ns.getHeightBucketPathWrite(tx, height)
if hghtBucket == nil { if hghtBucket == nil {
return false, nil return false, nil
} }

View File

@ -1130,7 +1130,7 @@ func (s *Switch) handlePacketForward(packet *htlcPacket) error {
// this htlc. The reason for randomization is to evenly // this htlc. The reason for randomization is to evenly
// distribute the htlc load without making assumptions about // distribute the htlc load without making assumptions about
// what the best channel is. // what the best channel is.
destination := destinations[rand.Intn(len(destinations))] destination := destinations[rand.Intn(len(destinations))] // nolint:gosec
// Retrieve the incoming link by its ShortChannelID. Note that // Retrieve the incoming link by its ShortChannelID. Note that
// the incomingChanID is never set to hop.Source here. // the incomingChanID is never set to hop.Source here.

View File

@ -2909,7 +2909,7 @@ func testHtcNotifier(t *testing.T, testOpts []serverOption, iterations int,
// Add the htlcNotifier option to any other options // Add the htlcNotifier option to any other options
// set in the test. // set in the test.
options := append(testOpts, notifierOption) options := append(testOpts, notifierOption) // nolint:gocritic
n := newThreeHopNetwork( n := newThreeHopNetwork(
t, channels.aliceToBob, t, channels.aliceToBob,

View File

@ -58,11 +58,11 @@ func assertEngineExecution(t *testing.T, testNum int, valid bool,
done, err = vm.Step() done, err = vm.Step()
if err != nil && valid { if err != nil && valid {
fmt.Println(debugBuf.String()) t.Log(debugBuf.String())
t.Fatalf("spend test case #%v failed, spend "+ t.Fatalf("spend test case #%v failed, spend "+
"should be valid: %v", testNum, err) "should be valid: %v", testNum, err)
} else if err == nil && !valid && done { } else if err == nil && !valid && done {
fmt.Println(debugBuf.String()) t.Log(debugBuf.String())
t.Fatalf("spend test case #%v succeed, spend "+ t.Fatalf("spend test case #%v succeed, spend "+
"should be invalid: %v", testNum, err) "should be invalid: %v", testNum, err)
} }
@ -79,7 +79,7 @@ func assertEngineExecution(t *testing.T, testNum int, valid bool,
validity = "valid" validity = "valid"
} }
fmt.Println(debugBuf.String()) t.Log(debugBuf.String())
t.Fatalf("%v spend test case #%v execution ended with: %v", validity, testNum, vmErr) t.Fatalf("%v spend test case #%v execution ended with: %v", validity, testNum, vmErr)
} }

View File

@ -23,11 +23,11 @@ type WtClient struct {
func (c *WtClient) Validate() error { func (c *WtClient) Validate() error {
// TODO(wilmer): remove in v0.9.0 release. // TODO(wilmer): remove in v0.9.0 release.
if len(c.PrivateTowerURIs) > 0 { if len(c.PrivateTowerURIs) > 0 {
fmt.Println("The `wtclient.private-tower-uris` option has " + return fmt.Errorf("the `wtclient.private-tower-uris` option " +
"been deprecated as of v0.8.0-beta and will be " + "has been deprecated as of v0.8.0-beta and will be " +
"removed in v0.9.0-beta. To setup watchtowers for " + "removed in v0.9.0-beta. To setup watchtowers for " +
"the client, set `wtclient.active` and run " + "the client, set `wtclient.active` and run " +
"`lncli wtclient -h` for more information.") "`lncli wtclient -h` for more information")
} }
return nil return nil

View File

@ -7,6 +7,7 @@ import (
"io" "io"
"net/http" "net/http"
"sync" "sync"
"testing"
"github.com/lightningnetwork/lnd/lnwallet/chainfee" "github.com/lightningnetwork/lnd/lnwallet/chainfee"
) )
@ -22,6 +23,8 @@ const (
type feeService struct { type feeService struct {
feeEstimates feeEstimates
t *testing.T
srv *http.Server srv *http.Server
wg sync.WaitGroup wg sync.WaitGroup
@ -36,9 +39,10 @@ type feeEstimates struct {
} }
// startFeeService spins up a go-routine to serve fee estimates. // startFeeService spins up a go-routine to serve fee estimates.
func startFeeService() *feeService { func startFeeService(t *testing.T) *feeService {
port := NextAvailablePort() port := NextAvailablePort()
f := feeService{ f := feeService{
t: t,
url: fmt.Sprintf("http://localhost:%v/fee-estimates.json", port), url: fmt.Sprintf("http://localhost:%v/fee-estimates.json", port),
} }
@ -59,7 +63,7 @@ func startFeeService() *feeService {
defer f.wg.Done() defer f.wg.Done()
if err := f.srv.ListenAndServe(); err != http.ErrServerClosed { if err := f.srv.ListenAndServe(); err != http.ErrServerClosed {
fmt.Printf("error: cannot start fee api: %v", err) f.t.Errorf("error: cannot start fee api: %v", err)
} }
}() }()
@ -73,23 +77,21 @@ func (f *feeService) handleRequest(w http.ResponseWriter, r *http.Request) {
bytes, err := json.Marshal(f.feeEstimates) bytes, err := json.Marshal(f.feeEstimates)
if err != nil { if err != nil {
fmt.Printf("error: cannot serialize "+ f.t.Errorf("error: cannot serialize estimates: %v", err)
"estimates: %v", err)
return return
} }
_, err = io.WriteString(w, string(bytes)) _, err = io.WriteString(w, string(bytes))
if err != nil { if err != nil {
fmt.Printf("error: cannot send estimates: %v", f.t.Errorf("error: cannot send estimates: %v", err)
err)
} }
} }
// stop stops the web server. // stop stops the web server.
func (f *feeService) stop() { func (f *feeService) stop() {
if err := f.srv.Shutdown(context.Background()); err != nil { if err := f.srv.Shutdown(context.Background()); err != nil {
fmt.Printf("error: cannot stop fee api: %v", err) f.t.Errorf("error: cannot stop fee api: %v", err)
} }
f.wg.Wait() f.wg.Wait()

View File

@ -11,7 +11,7 @@ import (
// TestFeeService tests the itest fee estimating web service. // TestFeeService tests the itest fee estimating web service.
func TestFeeService(t *testing.T) { func TestFeeService(t *testing.T) {
service := startFeeService() service := startFeeService(t)
defer service.stop() defer service.stop()
service.setFee(5000) service.setFee(5000)

View File

@ -96,8 +96,6 @@ type NetworkHarness struct {
func NewNetworkHarness(m *HarnessMiner, b BackendConfig, lndBinary string, func NewNetworkHarness(m *HarnessMiner, b BackendConfig, lndBinary string,
dbBackend DatabaseBackend) (*NetworkHarness, error) { dbBackend DatabaseBackend) (*NetworkHarness, error) {
feeService := startFeeService()
ctxt, cancel := context.WithCancel(context.Background()) ctxt, cancel := context.WithCancel(context.Background())
n := NetworkHarness{ n := NetworkHarness{
@ -107,7 +105,6 @@ func NewNetworkHarness(m *HarnessMiner, b BackendConfig, lndBinary string,
netParams: m.ActiveNet, netParams: m.ActiveNet,
Miner: m, Miner: m,
BackendCfg: b, BackendCfg: b,
feeService: feeService,
runCtx: ctxt, runCtx: ctxt,
cancel: cancel, cancel: cancel,
lndBinary: lndBinary, lndBinary: lndBinary,
@ -150,6 +147,7 @@ func (n *NetworkHarness) SetUp(t *testing.T,
fakeLogger := grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard) fakeLogger := grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard)
grpclog.SetLoggerV2(fakeLogger) grpclog.SetLoggerV2(fakeLogger)
n.currentTestCase = testCase n.currentTestCase = testCase
n.feeService = startFeeService(t)
// Start the initial seeder nodes within the test network, then connect // Start the initial seeder nodes within the test network, then connect
// their respective RPC clients. // their respective RPC clients.

View File

@ -228,7 +228,7 @@ func (cfg *BaseNodeConfig) GenArgs() []string {
fmt.Sprintf("--invoicemacaroonpath=%v", cfg.InvoiceMacPath), fmt.Sprintf("--invoicemacaroonpath=%v", cfg.InvoiceMacPath),
fmt.Sprintf("--trickledelay=%v", trickleDelay), fmt.Sprintf("--trickledelay=%v", trickleDelay),
fmt.Sprintf("--profile=%d", cfg.ProfilePort), fmt.Sprintf("--profile=%d", cfg.ProfilePort),
fmt.Sprintf("--caches.rpc-graph-cache-duration=0"), fmt.Sprintf("--caches.rpc-graph-cache-duration=%d", 0),
} }
args = append(args, nodeArgs...) args = append(args, nodeArgs...)
@ -988,9 +988,9 @@ func (hn *HarnessNode) FetchNodeInfo() error {
return nil return nil
} }
// AddToLog adds a line of choice to the node's logfile. This is useful // AddToLogf adds a line of choice to the node's logfile. This is useful
// to interleave test output with output from the node. // to interleave test output with output from the node.
func (hn *HarnessNode) AddToLog(format string, a ...interface{}) { func (hn *HarnessNode) AddToLogf(format string, a ...interface{}) {
// If this node was not set up with a log file, just return early. // If this node was not set up with a log file, just return early.
if hn.logFile == nil { if hn.logFile == nil {
return return
@ -998,7 +998,7 @@ func (hn *HarnessNode) AddToLog(format string, a ...interface{}) {
desc := fmt.Sprintf("itest: %s\n", fmt.Sprintf(format, a...)) desc := fmt.Sprintf("itest: %s\n", fmt.Sprintf(format, a...))
if _, err := hn.logFile.WriteString(desc); err != nil { if _, err := hn.logFile.WriteString(desc); err != nil {
hn.PrintErr("write to log err: %v", err) hn.PrintErrf("write to log err: %v", err)
} }
} }
@ -1281,7 +1281,7 @@ func (hn *HarnessNode) lightningNetworkWatcher() {
err := hn.receiveTopologyClientStream(graphUpdates) err := hn.receiveTopologyClientStream(graphUpdates)
if err != nil { if err != nil {
hn.PrintErr("receive topology client stream "+ hn.PrintErrf("receive topology client stream "+
"got err:%v", err) "got err:%v", err)
} }
}() }()
@ -1505,9 +1505,9 @@ func (hn *HarnessNode) WaitForBalance(expectedBalance btcutil.Amount,
return nil return nil
} }
// PrintErr prints an error to the console. // PrintErrf prints an error to the console.
func (hn *HarnessNode) PrintErr(format string, a ...interface{}) { func (hn *HarnessNode) PrintErrf(format string, a ...interface{}) {
fmt.Printf("itest error from [node:%s]: %s\n", fmt.Printf("itest error from [node:%s]: %s\n", // nolint:forbidigo
hn.Cfg.Name, fmt.Sprintf(format, a...)) hn.Cfg.Name, fmt.Sprintf(format, a...))
} }
@ -1521,7 +1521,7 @@ func (hn *HarnessNode) handleChannelEdgeUpdates(
for _, newChan := range updates { for _, newChan := range updates {
op, err := MakeOutpoint(newChan.ChanPoint) op, err := MakeOutpoint(newChan.ChanPoint)
if err != nil { if err != nil {
hn.PrintErr("failed to create outpoint for %v "+ hn.PrintErrf("failed to create outpoint for %v "+
"got err: %v", newChan.ChanPoint, err) "got err: %v", newChan.ChanPoint, err)
return return
} }
@ -1607,7 +1607,7 @@ func (hn *HarnessNode) handleClosedChannelUpdate(
for _, closedChan := range updates { for _, closedChan := range updates {
op, err := MakeOutpoint(closedChan.ChanPoint) op, err := MakeOutpoint(closedChan.ChanPoint)
if err != nil { if err != nil {
hn.PrintErr("failed to create outpoint for %v "+ hn.PrintErrf("failed to create outpoint for %v "+
"got err: %v", closedChan.ChanPoint, err) "got err: %v", closedChan.ChanPoint, err)
return return
} }
@ -1775,7 +1775,7 @@ func (hn *HarnessNode) getChannelPolicies(include bool) policyUpdateMap {
IncludeUnannounced: include, IncludeUnannounced: include,
}) })
if err != nil { if err != nil {
hn.PrintErr("DescribeGraph got err: %v", err) hn.PrintErrf("DescribeGraph got err: %v", err)
return nil return nil
} }
@ -1813,7 +1813,7 @@ func (hn *HarnessNode) getChannelPolicies(include bool) policyUpdateMap {
func renameFile(fromFileName, toFileName string) { func renameFile(fromFileName, toFileName string) {
err := os.Rename(fromFileName, toFileName) err := os.Rename(fromFileName, toFileName)
if err != nil { if err != nil {
fmt.Printf("could not rename %s to %s: %v\n", fmt.Printf("could not rename %s to %s: %v\n", // nolint:forbidigo
fromFileName, toFileName, err) fromFileName, toFileName, err)
} }
} }

View File

@ -1626,10 +1626,8 @@ func getSpendingTxInMempool(t *harnessTest, miner *rpcclient.Client,
for _, txIn := range msgTx.TxIn { for _, txIn := range msgTx.TxIn {
input := txIn.PreviousOutPoint input := txIn.PreviousOutPoint
if _, ok := inputSet[input]; ok {
delete(inputSet, input) delete(inputSet, input)
} }
}
if len(inputSet) > 0 { if len(inputSet) > 0 {
// Missing input, check next transaction // Missing input, check next transaction

View File

@ -69,6 +69,9 @@ func testEtcdFailoverCase(net *lntest.NetworkHarness, ht *harnessTest,
ctxb := context.Background() ctxb := context.Background()
tmpDir, err := ioutil.TempDir("", "etcd") tmpDir, err := ioutil.TempDir("", "etcd")
if err != nil {
ht.Fatalf("Failed to create temp dir: %v", err)
}
etcdCfg, cleanup, err := kvdb.StartEtcdTestBackend( etcdCfg, cleanup, err := kvdb.StartEtcdTestBackend(
tmpDir, uint16(lntest.NextAvailablePort()), tmpDir, uint16(lntest.NextAvailablePort()),
uint16(lntest.NextAvailablePort()), "", uint16(lntest.NextAvailablePort()), "",
@ -100,6 +103,9 @@ func testEtcdFailoverCase(net *lntest.NetworkHarness, ht *harnessTest,
ctxt, _ := context.WithTimeout(ctxb, defaultTimeout) ctxt, _ := context.WithTimeout(ctxb, defaultTimeout)
info1, err := carol1.GetInfo(ctxt, &lnrpc.GetInfoRequest{}) info1, err := carol1.GetInfo(ctxt, &lnrpc.GetInfoRequest{})
if err != nil {
ht.Fatalf("unable to get info: %v", err)
}
net.ConnectNodes(ht.t, carol1, net.Alice) net.ConnectNodes(ht.t, carol1, net.Alice)
@ -172,6 +178,9 @@ func testEtcdFailoverCase(net *lntest.NetworkHarness, ht *harnessTest,
// Make sure Carol-1 and Carol-2 have the same identity. // Make sure Carol-1 and Carol-2 have the same identity.
info2, err := carol2.GetInfo(ctxt, &lnrpc.GetInfoRequest{}) info2, err := carol2.GetInfo(ctxt, &lnrpc.GetInfoRequest{})
if err != nil {
ht.Fatalf("unable to get info: %v", err)
}
if info1.IdentityPubkey != info2.IdentityPubkey { if info1.IdentityPubkey != info2.IdentityPubkey {
ht.Fatalf("Carol-1 and Carol-2 must have the same identity: "+ ht.Fatalf("Carol-1 and Carol-2 must have the same identity: "+
"%v vs %v", info1.IdentityPubkey, info2.IdentityPubkey) "%v vs %v", info1.IdentityPubkey, info2.IdentityPubkey)

View File

@ -139,7 +139,7 @@ test:
"---- basic channel funding subtest %s ----\n", "---- basic channel funding subtest %s ----\n",
testName, testName,
) )
net.Alice.AddToLog(logLine) net.Alice.AddToLogf(logLine)
success := t.t.Run(testName, func(t *testing.T) { success := t.t.Run(testName, func(t *testing.T) {
testFunding(cc, dc) testFunding(cc, dc)

View File

@ -99,7 +99,7 @@ func testMultiHopHtlcClaims(net *lntest.NetworkHarness, t *harnessTest) {
"%s/%s ----\n", "%s/%s ----\n",
testName, subTest.name, testName, subTest.name,
) )
net.Alice.AddToLog(logLine) net.Alice.AddToLogf(logLine)
success := ht.t.Run(subTest.name, func(t *testing.T) { success := ht.t.Run(subTest.name, func(t *testing.T) {
ht := newHarnessTest(t, net) ht := newHarnessTest(t, net)

View File

@ -232,8 +232,8 @@ func TestLightningNetworkDaemon(t *testing.T) {
testCase.name, testCase.name,
) )
lndHarness.Alice.AddToLog(logLine) lndHarness.Alice.AddToLogf(logLine)
lndHarness.Bob.AddToLog(logLine) lndHarness.Bob.AddToLogf(logLine)
// Start every test with the default static fee estimate. // Start every test with the default static fee estimate.
lndHarness.SetFeeEstimate(12500) lndHarness.SetFeeEstimate(12500)

View File

@ -18,7 +18,6 @@ import (
"github.com/btcsuite/btcutil/hdkeychain" "github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/btcwallet/chain" "github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/waddrmgr" "github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wallet"
base "github.com/btcsuite/btcwallet/wallet" base "github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/btcwallet/wallet/txauthor" "github.com/btcsuite/btcwallet/wallet/txauthor"
"github.com/btcsuite/btcwallet/wallet/txrules" "github.com/btcsuite/btcwallet/wallet/txrules"
@ -200,7 +199,7 @@ func LoaderWithExternalWalletDB(db kvdb.Backend) LoaderOption {
// NewWalletLoader constructs a wallet loader. // NewWalletLoader constructs a wallet loader.
func NewWalletLoader(chainParams *chaincfg.Params, recoveryWindow uint32, func NewWalletLoader(chainParams *chaincfg.Params, recoveryWindow uint32,
opts ...LoaderOption) (*wallet.Loader, error) { opts ...LoaderOption) (*base.Loader, error) {
cfg := &loaderCfg{} cfg := &loaderCfg{}

View File

@ -657,7 +657,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance,
if err != nil { if err != nil {
return nil, err return nil, err
} }
cltvs = append(cltvs, htlc.Timeout) cltvs = append(cltvs, htlc.Timeout) // nolint:makezero
} }
for _, htlc := range filteredHTLCView.theirUpdates { for _, htlc := range filteredHTLCView.theirUpdates {
if HtlcIsDust( if HtlcIsDust(
@ -674,7 +674,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance,
if err != nil { if err != nil {
return nil, err return nil, err
} }
cltvs = append(cltvs, htlc.Timeout) cltvs = append(cltvs, htlc.Timeout) // nolint:makezero
} }
// Set the state hint of the commitment transaction to facilitate // Set the state hint of the commitment transaction to facilitate

3
log.go
View File

@ -39,7 +39,6 @@ import (
"github.com/lightningnetwork/lnd/peer" "github.com/lightningnetwork/lnd/peer"
"github.com/lightningnetwork/lnd/peernotifier" "github.com/lightningnetwork/lnd/peernotifier"
"github.com/lightningnetwork/lnd/routing" "github.com/lightningnetwork/lnd/routing"
"github.com/lightningnetwork/lnd/routing/localchans"
"github.com/lightningnetwork/lnd/rpcperms" "github.com/lightningnetwork/lnd/rpcperms"
"github.com/lightningnetwork/lnd/signal" "github.com/lightningnetwork/lnd/signal"
"github.com/lightningnetwork/lnd/sweep" "github.com/lightningnetwork/lnd/sweep"
@ -156,7 +155,7 @@ func SetupLoggers(root *build.RotatingLogWriter, interceptor signal.Interceptor)
AddSubLogger(root, "PEER", interceptor, peer.UseLogger) AddSubLogger(root, "PEER", interceptor, peer.UseLogger)
AddSubLogger(root, "CHCL", interceptor, chancloser.UseLogger) AddSubLogger(root, "CHCL", interceptor, chancloser.UseLogger)
AddSubLogger(root, routing.Subsystem, interceptor, routing.UseLogger, localchans.UseLogger) AddSubLogger(root, routing.Subsystem, interceptor, routing.UseLogger)
AddSubLogger(root, routerrpc.Subsystem, interceptor, routerrpc.UseLogger) AddSubLogger(root, routerrpc.Subsystem, interceptor, routerrpc.UseLogger)
AddSubLogger(root, chanfitness.Subsystem, interceptor, chanfitness.UseLogger) AddSubLogger(root, chanfitness.Subsystem, interceptor, chanfitness.UseLogger)
AddSubLogger(root, verrpc.Subsystem, interceptor, verrpc.UseLogger) AddSubLogger(root, verrpc.Subsystem, interceptor, verrpc.UseLogger)

View File

@ -1,16 +0,0 @@
package localchans
import (
"github.com/btcsuite/btclog"
)
// log is a logger that is initialized with no output filters. This
// means the package will not perform any logging by default until the caller
// requests it.
var log btclog.Logger
// UseLogger uses a specified Logger to output package logging info. This
// function is called from the parent package htlcswitch logger initialization.
func UseLogger(logger btclog.Logger) {
log = logger
}

View File

@ -185,7 +185,7 @@ func (r *Manager) updateEdge(tx kvdb.RTx, chanPoint wire.OutPoint,
// Retrieve negotiated channel htlc amt limits. // Retrieve negotiated channel htlc amt limits.
amtMin, amtMax, err := r.getHtlcAmtLimits(tx, chanPoint) amtMin, amtMax, err := r.getHtlcAmtLimits(tx, chanPoint)
if err != nil { if err != nil {
return nil return err
} }
// We now update the edge max htlc value. // We now update the edge max htlc value.