From a10c741a26b900715319ad4006e4e67388d82042 Mon Sep 17 00:00:00 2001 From: Slyghtning Date: Thu, 5 Mar 2026 12:18:05 +0100 Subject: [PATCH] lint: fix linter issues --- client.go | 7 +- cmd/loop/instantout.go | 3 +- cmd/loop/loopout.go | 3 +- cmd/loop/main.go | 2 +- cmd/loop/swaps.go | 3 +- executor.go | 14 +- fsm/fsm.go | 2 +- instantout/fsm.go | 12 +- instantout/instantout.go | 4 +- instantout/reservation/fsm.go | 12 +- instantout/reservation/manager_test.go | 3 +- liquidity/autoloop_testcontext_test.go | 6 +- liquidity/liquidity.go | 6 +- loopd/daemon.go | 98 +++-------- loopd/log.go | 8 +- loopd/register_default.go | 1 - loopd/swapclient_server.go | 24 +-- loopd/sweep_htlc_test.go | 12 +- loopdb/codec_test.go | 2 +- loopdb/migrate.go | 6 +- loopdb/migration_04_updates_test.go | 16 +- loopdb/postgres.go | 2 +- loopdb/protocol_version.go | 5 +- loopdb/raw_db_test.go | 14 +- loopdb/sql_store.go | 2 +- loopdb/sql_test.go | 8 +- loopdb/store_test.go | 12 +- loopdb/test_sqlite.go | 1 - loopin.go | 6 +- loopin_testcontext_test.go | 4 +- loopout.go | 8 +- loopout_feerate.go | 5 +- loopout_test.go | 23 ++- notifications/manager.go | 2 +- notifications/manager_test.go | 25 +-- staticaddr/address/manager_test.go | 3 +- staticaddr/deposit/fsm.go | 12 +- staticaddr/loopin/fsm.go | 8 +- staticaddr/loopin/loopin.go | 2 +- staticaddr/loopin/manager.go | 10 +- staticaddr/openchannel/manager_test.go | 4 +- staticaddr/staticutil/utils.go | 6 +- staticaddr/withdraw/manager.go | 2 +- swap/log.go | 6 +- swap_server_client.go | 7 +- sweepbatcher/greedy_batch_selection.go | 5 +- sweepbatcher/log.go | 6 +- sweepbatcher/sweep_batch.go | 14 +- sweepbatcher/sweep_batcher.go | 26 +-- sweepbatcher/sweep_batcher_test.go | 233 ++++++++----------------- test/chainnotifier_mock.go | 22 +-- test/lightning_client_mock.go | 4 +- utils.go | 2 +- utils/musig.go | 4 +- 54 files changed, 269 insertions(+), 468 deletions(-) diff --git a/client.go b/client.go index 3f0a45c8..66ee81e6 100644 --- a/client.go +++ b/client.go @@ -442,10 +442,7 @@ func (s *Client) Run(ctx context.Context, statusChan chan<- SwapInfo) error { } // Start goroutine to deliver all pending swaps to the main loop. - s.wg.Add(1) - go func() { - defer s.wg.Done() - + s.wg.Go(func() { s.resumeSwaps(mainCtx, pendingLoopOutSwaps, pendingLoopInSwaps) // Signal that new requests can be accepted. Otherwise, the new @@ -453,7 +450,7 @@ func (s *Client) Run(ctx context.Context, statusChan chan<- SwapInfo) error { // this goroutine as being a swap that needs to be resumed. // Resulting in two goroutines executing the same swap. close(s.resumeReady) - }() + }) // Main event loop. err = s.executor.run(mainCtx, statusChan, s.abandonChans) diff --git a/cmd/loop/instantout.go b/cmd/loop/instantout.go index 5a558f24..a78100b8 100644 --- a/cmd/loop/instantout.go +++ b/cmd/loop/instantout.go @@ -41,8 +41,7 @@ func instantOut(ctx context.Context, cmd *cli.Command) error { // element. var outgoingChanSet []uint64 if cmd.IsSet("channel") { - chanStrings := strings.Split(cmd.String("channel"), ",") - for _, chanString := range chanStrings { + for chanString := range strings.SplitSeq(cmd.String("channel"), ",") { chanID, err := strconv.ParseUint(chanString, 10, 64) if err != nil { return fmt.Errorf("error parsing channel id "+ diff --git a/cmd/loop/loopout.go b/cmd/loop/loopout.go index 2fe3c6e2..f1da46f6 100644 --- a/cmd/loop/loopout.go +++ b/cmd/loop/loopout.go @@ -159,8 +159,7 @@ func loopOut(ctx context.Context, cmd *cli.Command) error { return fmt.Errorf("channel flag is not supported when " + "looping out assets") } - chanStrings := strings.Split(cmd.String("channel"), ",") - for _, chanString := range chanStrings { + for chanString := range strings.SplitSeq(cmd.String("channel"), ",") { chanID, err := strconv.ParseUint(chanString, 10, 64) if err != nil { return fmt.Errorf("error parsing channel id "+ diff --git a/cmd/loop/main.go b/cmd/loop/main.go index 14db1c58..77dc533a 100644 --- a/cmd/loop/main.go +++ b/cmd/loop/main.go @@ -132,7 +132,7 @@ const ( envVarMacaroonPath = "LOOPCLI_MACAROONPATH" ) -func printJSON(resp interface{}) { +func printJSON(resp any) { b, err := json.Marshal(resp) if err != nil { fatal(err) diff --git a/cmd/loop/swaps.go b/cmd/loop/swaps.go index fae25c3c..9aa298d2 100644 --- a/cmd/loop/swaps.go +++ b/cmd/loop/swaps.go @@ -77,8 +77,7 @@ func listSwaps(ctx context.Context, cmd *cli.Command) error { // element. var outgoingChanSet []uint64 if cmd.IsSet(channelFlag.Name) { - chanStrings := strings.Split(cmd.String(channelFlag.Name), ",") - for _, chanString := range chanStrings { + for chanString := range strings.SplitSeq(cmd.String(channelFlag.Name), ",") { chanID, err := strconv.ParseUint(chanString, 10, 64) if err != nil { return fmt.Errorf("error parsing channel id "+ diff --git a/executor.go b/executor.go index cfaa5ea7..8fccef63 100644 --- a/executor.go +++ b/executor.go @@ -123,10 +123,7 @@ func (s *executor) run(mainCtx context.Context, batcherErrChan = make(chan error, 1) - s.wg.Add(1) - go func() { - defer s.wg.Done() - + s.wg.Go(func() { err := s.batcher.Run(mainCtx) if err != nil && !errors.Is(err, context.Canceled) { select { @@ -134,7 +131,7 @@ func (s *executor) run(mainCtx context.Context, case <-mainCtx.Done(): } } - }() + }) // Start main event loop. log.Infof("Starting event loop at height %v", height) @@ -164,10 +161,7 @@ func (s *executor) run(mainCtx context.Context, swapID := nextSwapID blockEpochQueues[swapID] = queue - s.wg.Add(1) - go func() { - defer s.wg.Done() - + s.wg.Go(func() { err := newSwap.execute(mainCtx, &executeConfig{ statusChan: statusChan, sweeper: s.sweeper, @@ -200,7 +194,7 @@ func (s *executor) run(mainCtx context.Context, case swapDoneChan <- swapID: case <-mainCtx.Done(): } - }() + }) nextSwapID++ diff --git a/fsm/fsm.go b/fsm/fsm.go index 6990b750..8c182547 100644 --- a/fsm/fsm.go +++ b/fsm/fsm.go @@ -51,7 +51,7 @@ type EventType string // EventContext represents the context to be passed to the action // implementation. -type EventContext interface{} +type EventContext = any // Action represents the action to be executed in a given state. type Action func(ctx context.Context, eventCtx EventContext) EventType diff --git a/instantout/fsm.go b/instantout/fsm.go index 9cb0c994..c188b158 100644 --- a/instantout/fsm.go +++ b/instantout/fsm.go @@ -352,33 +352,33 @@ func (f *FSM) updateInstantOut(ctx context.Context, } // Infof logs an info message with the reservation hash as prefix. -func (f *FSM) Infof(format string, args ...interface{}) { +func (f *FSM) Infof(format string, args ...any) { log.Infof( "InstantOut %v: "+format, append( - []interface{}{f.InstantOut.swapPreimage.Hash()}, + []any{f.InstantOut.swapPreimage.Hash()}, args..., )..., ) } // Debugf logs a debug message with the reservation hash as prefix. -func (f *FSM) Debugf(format string, args ...interface{}) { +func (f *FSM) Debugf(format string, args ...any) { log.Debugf( "InstantOut %v: "+format, append( - []interface{}{f.InstantOut.swapPreimage.Hash()}, + []any{f.InstantOut.swapPreimage.Hash()}, args..., )..., ) } // Errorf logs an error message with the reservation hash as prefix. -func (f *FSM) Errorf(format string, args ...interface{}) { +func (f *FSM) Errorf(format string, args ...any) { log.Errorf( "InstantOut %v: "+format, append( - []interface{}{f.InstantOut.swapPreimage.Hash()}, + []any{f.InstantOut.swapPreimage.Hash()}, args..., )..., ) diff --git a/instantout/instantout.go b/instantout/instantout.go index b703b4de..f8c89eb0 100644 --- a/instantout/instantout.go +++ b/instantout/instantout.go @@ -443,7 +443,7 @@ func (i *InstantOut) generateHtlcSweepTx(ctx context.Context, // htlcWeight returns the weight for the htlc transaction. func htlcWeight(numInputs int) lntypes.WeightUnit { var weightEstimator input.TxWeightEstimator - for i := 0; i < numInputs; i++ { + for range numInputs { weightEstimator.AddTaprootKeySpendInput( txscript.SigHashDefault, ) @@ -457,7 +457,7 @@ func htlcWeight(numInputs int) lntypes.WeightUnit { // sweeplessSweepWeight returns the weight for the sweepless sweep transaction. func sweeplessSweepWeight(numInputs int) lntypes.WeightUnit { var weightEstimator input.TxWeightEstimator - for i := 0; i < numInputs; i++ { + for range numInputs { weightEstimator.AddTaprootKeySpendInput( txscript.SigHashDefault, ) diff --git a/instantout/reservation/fsm.go b/instantout/reservation/fsm.go index 620c78a0..946d5102 100644 --- a/instantout/reservation/fsm.go +++ b/instantout/reservation/fsm.go @@ -259,26 +259,26 @@ func (r *FSM) updateReservation(ctx context.Context, } } -func (r *FSM) Infof(format string, args ...interface{}) { +func (r *FSM) Infof(format string, args ...any) { log.Infof( "Reservation %v %x: "+format, - append([]interface{}{r.reservation.ProtocolVersion, r.reservation.ID}, + append([]any{r.reservation.ProtocolVersion, r.reservation.ID}, args...)..., ) } -func (r *FSM) Debugf(format string, args ...interface{}) { +func (r *FSM) Debugf(format string, args ...any) { log.Debugf( "Reservation %v %x: "+format, - append([]interface{}{r.reservation.ProtocolVersion, r.reservation.ID}, + append([]any{r.reservation.ProtocolVersion, r.reservation.ID}, args...)..., ) } -func (r *FSM) Errorf(format string, args ...interface{}) { +func (r *FSM) Errorf(format string, args ...any) { log.Errorf( "Reservation %v %x: "+format, - append([]interface{}{r.reservation.ProtocolVersion, r.reservation.ID}, + append([]any{r.reservation.ProtocolVersion, r.reservation.ID}, args...)..., ) } diff --git a/instantout/reservation/manager_test.go b/instantout/reservation/manager_test.go index b5cd3df0..79455750 100644 --- a/instantout/reservation/manager_test.go +++ b/instantout/reservation/manager_test.go @@ -21,8 +21,7 @@ var ( ) func TestManager(t *testing.T) { - ctxb, cancel := context.WithCancel(context.Background()) - defer cancel() + ctxb := t.Context() testContext := newManagerTestContext(t) diff --git a/liquidity/autoloop_testcontext_test.go b/liquidity/autoloop_testcontext_test.go index a0c608af..380e9cb3 100644 --- a/liquidity/autoloop_testcontext_test.go +++ b/liquidity/autoloop_testcontext_test.go @@ -324,7 +324,7 @@ func (c *autoloopTestCtx) autoloop(step *autoloopStep) { amt2expected[expected.request.Amount] = expected } - for i := 0; i < len(step.quotesIn); i++ { + for range len(step.quotesIn) { request := <-c.quoteRequestIn // Get the expected item, using amount as a key. @@ -459,7 +459,7 @@ func (c *autoloopTestCtx) matchLoopOuts(swaps []loopOutRequestResp, length := len(swapsCopy) - for i := 0; i < length; i++ { + for range length { actual := <-c.outRequest if !keepDestAddr { @@ -494,7 +494,7 @@ func (c *autoloopTestCtx) matchLoopIns( swapsCopy := make([]loopInRequestResp, len(swaps)) copy(swapsCopy, swaps) - for i := 0; i < len(swapsCopy); i++ { + for range len(swapsCopy) { actual := <-c.inRequest inner: diff --git a/liquidity/liquidity.go b/liquidity/liquidity.go index 6858b4c4..b31e2b00 100644 --- a/liquidity/liquidity.go +++ b/liquidity/liquidity.go @@ -622,9 +622,7 @@ func (m *Manager) dispatchBestEasyAutoloopSwap(ctx context.Context) error { // Calculate the amount that we want to loop out. If it exceeds the max // allowed clamp it to max. amount := localTotal - m.params.EasyAutoloopTarget - if amount > restrictions.Maximum { - amount = restrictions.Maximum - } + amount = min(amount, restrictions.Maximum) // If the amount we want to loop out is less than the minimum we can't // proceed with a swap, so we return early. @@ -1516,7 +1514,7 @@ func (m *Manager) dispatchStickyLoopOut(ctx context.Context, m.activeStickyLock.Unlock() }() - for i := 0; i < int(retryCount); i++ { + for range int(retryCount) { // Dispatch the swap. swap, err := m.cfg.LoopOut(ctx, &out) if err != nil { diff --git a/loopd/daemon.go b/loopd/daemon.go index 529a2eb8..32371df1 100644 --- a/loopd/daemon.go +++ b/loopd/daemon.go @@ -5,6 +5,7 @@ import ( "crypto/tls" "errors" "fmt" + "maps" "net" "net/http" "strings" @@ -335,10 +336,7 @@ func (d *Daemon) startWebServers() error { ReadHeaderTimeout: 5 * time.Second, } - d.wg.Add(1) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("REST proxy listening on %s", d.restListener.Addr()) err := d.restServer.Serve(d.restListener) @@ -351,16 +349,13 @@ func (d *Daemon) startWebServers() error { // channel is sufficiently buffered. d.internalErrChan <- err } - }() + }) } else { infof("REST proxy disabled") } // Start the grpc server. - d.wg.Add(1) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("RPC server listening on %s", d.grpcListener.Addr()) err = d.grpcServer.Serve(d.grpcListener) if err != nil && !errors.Is(err, grpc.ErrServerStopped) { @@ -370,7 +365,7 @@ func (d *Daemon) startWebServers() error { // channel is sufficiently buffered. d.internalErrChan <- err } - }() + }) return nil } @@ -511,9 +506,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { // Add our debug permissions to our main set of required permissions // if compiled in. - for endpoint, perm := range debugRequiredPermissions { - loop_looprpc.RequiredPermissions[endpoint] = perm - } + maps.Copy(loop_looprpc.RequiredPermissions, debugRequiredPermissions) rks, db, err := lndclient.NewBoltMacaroonStore( d.cfg.DataDir, "macaroons.db", loopdb.DefaultLoopDBTimeout, @@ -569,17 +562,14 @@ func (d *Daemon) initialize(withMacaroonService bool) error { } notificationManager := notifications.NewManager(notificationCfg) - d.wg.Add(1) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting notification manager") err := notificationManager.Run(d.mainCtx) if err != nil { d.internalErrChan <- err errorf("Notification manager stopped: %v", err) } - }() + }) var ( staticAddressManager *address.Manager @@ -752,7 +742,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { liquidityMgr: getLiquidityManager(swapClient), lnd: &d.lnd.LndServices, swaps: make(map[lntypes.Hash]loop.SwapInfo), - subscribers: make(map[int]chan<- interface{}), + subscribers: make(map[int]chan<- any), statusChan: make(chan loop.SwapInfo), mainCtx: d.mainCtx, reservationManager: reservationManager, @@ -792,10 +782,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { } // Start the swap client itself. - d.wg.Add(1) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting swap client") err := d.impl.Run(d.mainCtx, d.statusChan) if err != nil { @@ -806,21 +793,15 @@ func (d *Daemon) initialize(withMacaroonService bool) error { d.internalErrChan <- err } infof("Swap client stopped") - }() + }) // Start a goroutine that broadcasts swap updates to clients. - d.wg.Add(1) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Waiting for updates") d.processStatusUpdates(d.mainCtx) - }() - - d.wg.Add(1) - go func() { - defer d.wg.Done() + }) + d.wg.Go(func() { infof("Starting liquidity manager") err := d.liquidityMgr.Run(d.mainCtx) if err != nil && !errors.Is(err, context.Canceled) { @@ -828,17 +809,14 @@ func (d *Daemon) initialize(withMacaroonService bool) error { } infof("Liquidity manager stopped") - }() + }) initManagerTimeout := 10 * time.Second // Start the reservation manager. if d.reservationManager != nil { - d.wg.Add(1) initChan := make(chan struct{}) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting reservation manager") defer infof("Reservation manager stopped") @@ -848,7 +826,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { if err != nil && !errors.Is(err, context.Canceled) { d.internalErrChan <- err } - }() + }) // Wait for the reservation server to be ready before starting // the grpc server. @@ -868,11 +846,8 @@ func (d *Daemon) initialize(withMacaroonService bool) error { // Start the instant out manager. if d.instantOutManager != nil { - d.wg.Add(1) initChan := make(chan struct{}) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting instantout manager") defer infof("Instantout manager stopped") @@ -880,7 +855,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { if err != nil && !errors.Is(err, context.Canceled) { d.internalErrChan <- err } - }() + }) // Wait for the instantout server to be ready before starting // the grpc server. @@ -900,11 +875,8 @@ func (d *Daemon) initialize(withMacaroonService bool) error { // Start the static address manager. if staticAddressManager != nil { - d.wg.Add(1) initChan := make(chan struct{}) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting static address manager...") defer infof("Static address manager stopped") @@ -912,7 +884,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { if shouldReportManagerErr(err) { d.internalErrChan <- err } - }() + }) // Wait for the static address manager to be ready before // starting the grpc server. @@ -932,11 +904,8 @@ func (d *Daemon) initialize(withMacaroonService bool) error { // Start the static address deposit manager. if depositManager != nil { - d.wg.Add(1) initChan := make(chan struct{}) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting static address deposit manager...") defer infof("Static address deposit manager stopped") @@ -944,7 +913,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { if shouldReportManagerErr(err) { d.internalErrChan <- err } - }() + }) // Wait for the static address manager to be ready before // starting the grpc server. @@ -964,11 +933,8 @@ func (d *Daemon) initialize(withMacaroonService bool) error { // Start the static address deposit withdrawal manager. if withdrawalManager != nil { - d.wg.Add(1) initChan := make(chan struct{}) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting static address withdrawal manager...") defer infof("Static address withdrawal manager stopped") @@ -976,7 +942,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { if shouldReportManagerErr(err) { d.internalErrChan <- err } - }() + }) // We need a higher timeout here, because withdrawalManager // publishes transactions and each PublishTransaction call can @@ -1000,33 +966,27 @@ func (d *Daemon) initialize(withMacaroonService bool) error { } // Start the static address open channel manager. if openChannelManager != nil { - d.wg.Add(1) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting static address open channel manager") err := openChannelManager.Run(d.mainCtx) if err != nil && !errors.Is(context.Canceled, err) { d.internalErrChan <- err } infof("Static address open channel manager stopped") - }() + }) } // Start the static address loop-in manager. if staticLoopInManager != nil { - d.wg.Add(1) initChan := make(chan struct{}) - go func() { - defer d.wg.Done() - + d.wg.Go(func() { infof("Starting static address loop-in manager...") defer infof("Static address loop-in manager stopped") err := staticLoopInManager.Run(d.mainCtx, initChan) if shouldReportManagerErr(err) { d.internalErrChan <- err } - }() + }) // Wait for the static address loop-in manager to be ready before // starting the grpc server. diff --git a/loopd/log.go b/loopd/log.go index 0b29d4b3..6d102bc5 100644 --- a/loopd/log.go +++ b/loopd/log.go @@ -39,22 +39,22 @@ func setLogger(logger btclog.Logger) { } // tracef logs a message with level TRACE. -func tracef(format string, params ...interface{}) { +func tracef(format string, params ...any) { log().Tracef(format, params...) } // infof logs a message with level INFO. -func infof(format string, params ...interface{}) { +func infof(format string, params ...any) { log().Infof(format, params...) } // warnf logs a message with level WARN. -func warnf(format string, params ...interface{}) { +func warnf(format string, params ...any) { log().Warnf(format, params...) } // errorf logs a message with level ERROR. -func errorf(format string, params ...interface{}) { +func errorf(format string, params ...any) { log().Errorf(format, params...) } diff --git a/loopd/register_default.go b/loopd/register_default.go index 27a09741..01b25224 100644 --- a/loopd/register_default.go +++ b/loopd/register_default.go @@ -1,5 +1,4 @@ //go:build !dev -// +build !dev package loopd diff --git a/loopd/swapclient_server.go b/loopd/swapclient_server.go index 1345a0b8..62187d3e 100644 --- a/loopd/swapclient_server.go +++ b/loopd/swapclient_server.go @@ -102,7 +102,7 @@ type swapClientServer struct { openChannelManager *openchannel.Manager assetClient *assets.TapdClient swaps map[lntypes.Hash]loop.SwapInfo - subscribers map[int]chan<- interface{} + subscribers map[int]chan<- any statusChan chan loop.SwapInfo nextSubscriberID int swapsLock sync.Mutex @@ -678,14 +678,8 @@ func filterSwap(swapInfo *loop.SwapInfo, filter *looprpc.ListSwapsFilter) bool { if swapInfo.SwapType == swap.TypeOut && filter.OutgoingChanSet != nil { // First we sort both channel sets to make sure we can compare // them. - sort.Slice(swapInfo.OutgoingChanSet, func(i, j int) bool { - return swapInfo.OutgoingChanSet[i] < - swapInfo.OutgoingChanSet[j] - }) - sort.Slice(filter.OutgoingChanSet, func(i, j int) bool { - return filter.OutgoingChanSet[i] < - filter.OutgoingChanSet[j] - }) + slices.Sort(swapInfo.OutgoingChanSet) + slices.Sort(filter.OutgoingChanSet) // Compare the outgoing channel set by using reflect.DeepEqual // which compares the underlying arrays. @@ -1244,6 +1238,7 @@ func (s *swapClientServer) GetL402Tokens(ctx context.Context, } // GetLsatTokens returns all tokens that are contained in the L402 token store. +// // Deprecated: use GetL402Tokens. // This API is provided to maintain backward compatibility with gRPC clients // (e.g. `loop listauth`, Terminal Web, RTL). @@ -1809,12 +1804,7 @@ func (s *swapClientServer) ListStaticAddressDeposits(ctx context.Context, var filteredDeposits []*looprpc.Deposit if len(outpoints) > 0 { f := func(d *deposit.Deposit) bool { - for _, outpoint := range outpoints { - if outpoint == d.OutPoint.String() { - return true - } - } - return false + return slices.Contains(outpoints, d.OutPoint.String()) } filteredDeposits = filter(allDeposits, f) @@ -2179,7 +2169,7 @@ func (s *swapClientServer) populateBlocksUntilExpiry(ctx context.Context, if err != nil { return err } - for i := 0; i < len(deposits); i++ { + for i := range len(deposits) { deposits[i].BlocksUntilExpiry = deposits[i].ConfirmationHeight + int64(params.Expiry) - bestBlockHeight @@ -2646,7 +2636,7 @@ func hasBandwidth(channels []lndclient.ChannelInfo, amt btcutil.Amount, tracef("Trying to split %v sats into %v parts", amt, shard) paid := false - for i := 0; i < len(localBalances); i++ { + for i := range len(localBalances) { // TODO(hieblmi): Consider channel reserves because the // channel can't send its full local balance. if localBalances[i] >= split { diff --git a/loopd/sweep_htlc_test.go b/loopd/sweep_htlc_test.go index 3829066e..139eca82 100644 --- a/loopd/sweep_htlc_test.go +++ b/loopd/sweep_htlc_test.go @@ -545,37 +545,37 @@ func (f *formatLogger) record(format string) { } // Tracef logs a trace and records its format. -func (f *formatLogger) Tracef(format string, params ...interface{}) { +func (f *formatLogger) Tracef(format string, params ...any) { f.record(format) f.Logger.Tracef(format, params...) } // Debugf logs a debug message and records its format. -func (f *formatLogger) Debugf(format string, params ...interface{}) { +func (f *formatLogger) Debugf(format string, params ...any) { f.record(format) f.Logger.Debugf(format, params...) } // Infof logs an info message and records its format. -func (f *formatLogger) Infof(format string, params ...interface{}) { +func (f *formatLogger) Infof(format string, params ...any) { f.record(format) f.Logger.Infof(format, params...) } // Warnf logs a warning and records its format. -func (f *formatLogger) Warnf(format string, params ...interface{}) { +func (f *formatLogger) Warnf(format string, params ...any) { f.record(format) f.Logger.Warnf(format, params...) } // Errorf logs an error and records its format. -func (f *formatLogger) Errorf(format string, params ...interface{}) { +func (f *formatLogger) Errorf(format string, params ...any) { f.record(format) f.Logger.Errorf(format, params...) } // Criticalf logs a critical message and records its format. -func (f *formatLogger) Criticalf(format string, params ...interface{}) { +func (f *formatLogger) Criticalf(format string, params ...any) { f.record(format) f.Logger.Criticalf(format, params...) } diff --git a/loopdb/codec_test.go b/loopdb/codec_test.go index 3afbda9b..372c64b5 100644 --- a/loopdb/codec_test.go +++ b/loopdb/codec_test.go @@ -24,7 +24,7 @@ func TestProtocolVersionMarshalUnMarshal(t *testing.T) { bogusVersion := []byte{0xFF, 0xFF, 0xFF, 0xFF} invalidSlice := []byte{0xFF, 0xFF, 0xFF} - for i := 0; i < len(testVersions); i++ { + for i := range len(testVersions) { testVersion := testVersions[i] // Test that unmarshal(marshal(v)) == v. diff --git a/loopdb/migrate.go b/loopdb/migrate.go index 36d36944..954807d6 100644 --- a/loopdb/migrate.go +++ b/loopdb/migrate.go @@ -390,7 +390,7 @@ func NewMigrationError(err error) *migrationError { return &migrationError{Err: err} } -func equalValues(src interface{}, dst interface{}) error { +func equalValues(src any, dst any) error { mt := &mockTesting{} require.EqualValues(mt, src, dst) @@ -405,14 +405,14 @@ type mockTesting struct { failNow bool fail bool format string - args []interface{} + args []any } func (m *mockTesting) FailNow() { m.failNow = true } -func (m *mockTesting) Errorf(format string, args ...interface{}) { +func (m *mockTesting) Errorf(format string, args ...any) { m.format = format m.args = args } diff --git a/loopdb/migration_04_updates_test.go b/loopdb/migration_04_updates_test.go index ad06f91e..37f05466 100644 --- a/loopdb/migration_04_updates_test.go +++ b/loopdb/migration_04_updates_test.go @@ -19,25 +19,25 @@ func TestMigrationUpdates(t *testing.T) { legacyDbVersion = Hex("00000003") ) - legacyDb := map[string]interface{}{ - "metadata": map[string]interface{}{ + legacyDb := map[string]any{ + "metadata": map[string]any{ "dbp": legacyDbVersion, }, - "loop-in": map[string]interface{}{ - Hex("acae09fec9020b7996042613eede68a9eaf29eb28c21ea9943b19e344365a4bb"): map[string]interface{}{ + "loop-in": map[string]any{ + Hex("acae09fec9020b7996042613eede68a9eaf29eb28c21ea9943b19e344365a4bb"): map[string]any{ "contract": Hex("161b25277262bdb5c7c2827b975b2cbc7eb13e222b30cf88ea6daef4bcf22bdac4116c23071472cb000000000000ea6003f2f513a8fd7958b6a229dfb8835f6ab2c9c63cc3e138784d3e8c0e0ebbdd4e61033f26c40666977ed497eea4694d6dd3f07dbcf037089234ff665cd0a07fea329400007b8a00000000000059a600000000000009ca000077a20000000600000000000000000000000000000000000000000000000000000000000000000000"), - "updates": map[string]interface{}{ + "updates": map[string]any{ Hex("0000000000000001"): Hex("161b252772cb524508000000000000000000000000000000000000000000000000"), Hex("0000000000000002"): Hex("161b252837115e9b09ffffffffffff1f6a00000000000000000000000000000000"), Hex("0000000000000003"): Hex("161b252ab670360d0200000000000009ca00000000000000000000000000000000"), }, }, }, - "uncharge-swaps": map[string]interface{}{ - Hex("c3b3d7a145dbd2bab5aa1f505305f31ee432fe23b0801f065fac453dd9b1f923"): map[string]interface{}{ + "uncharge-swaps": map[string]any{ + Hex("c3b3d7a145dbd2bab5aa1f505305f31ee432fe23b0801f065fac453dd9b1f923"): map[string]any{ "contract": Hex("161b2526643767387ca76e58c964a8f2b6c0a13392b2dea93bde260226a263fb836954054ed1756b000000000000c350fd11016c6e6263727431333337306e3170303072343775707035366c7671663836753565766135647868686c706c78303733756a70676e3979767977376130766a37746d307678793276683576716471327770657832757270307963717a7279787139377a76757173703570373232733970686a6e6e6e706c3778716e796a78353373706863346c396735306b396e347836703761793577707539306b6673397179397173717a353766676a7a67676838343439377375716b383436787a3333336a713036736c6b38637a323872657466363672796b7876396a746e6a3072683979666a6170777065617265713071396679797a666664676d6874687973617370757565746e6b72306b32376370326173366a750269d66fd2cea620dc06f1f7de7838f0c8b145b82c7033080c398862f3421a23230382cb637badbb07f9926a06ecd88b6150513ea0060dc8d6dc1c1fb623926b0a0f000077d400000000000b458c00000000000005f10000000000000024000077a22c6263727431713271756332666777737971376463617a73666e3332636a7874667671647671366a6c70706574fd0f016c6e626372743530313834306e317030307234377570703563776561306732396d30667434646432726167397870306e726d6a72396c33726b7a717037706a6c34337a6e6d6b64336c79337364713877646d6b7a757163717a7279787139377a767571737035616478717538766168643730743776747165777578366d6d64337977636639767835736476717567753833327230676e373466733971793971737168746773636638386e377664767136716e71307a657775366d7471616e326c7a306e7534737a72376c6b36646d343673336c78726572656e333972616b7a6c777378346c613538733966773630356d6767766b766879716e743339713976737367777879367571707236713273780000000600000000000003f20000000000000000161b25262710ce00"), "outgoing-chan-set": nil, - "updates": map[string]interface{}{ + "updates": map[string]any{ Hex("0000000000000001"): Hex("161b252a770e649b01000000000000053900000000000000000000000000000001"), Hex("0000000000000002"): Hex("161b252ab671bdd90200000000000005f10000000000001a9c0000000000000003"), }, diff --git a/loopdb/postgres.go b/loopdb/postgres.go index 32fbbbde..3058b1a6 100644 --- a/loopdb/postgres.go +++ b/loopdb/postgres.go @@ -33,7 +33,7 @@ type PostgresConfig struct { Host string `long:"host" description:"Database server hostname."` Port int `long:"port" description:"Database server port."` User string `long:"user" description:"Database user."` - Password string `long:"password" description:"Database user's password."` + Password string `long:"password" description:"Database user's password."` //nolint:gosec DBName string `long:"dbname" description:"Database name to use."` MaxOpenConnections int32 `long:"maxconnections" description:"Max open connections to keep alive to the database server."` RequireSSL bool `long:"requiressl" description:"Whether to require using SSL (mode: require) when connecting to the server."` diff --git a/loopdb/protocol_version.go b/loopdb/protocol_version.go index 4674f6c7..025d63ac 100644 --- a/loopdb/protocol_version.go +++ b/loopdb/protocol_version.go @@ -47,8 +47,9 @@ const ( // the server to perform a probe to test inbound liquidty. ProtocolVersionProbe ProtocolVersion = 8 - // The client may ask the server to use a custom routing helper plugin - // in order to enhance off-chain payments corresponding to a swap. + // ProtocolVersionRoutingPlugin indicates that the client may ask the + // server to use a custom routing helper plugin in order to enhance + // off-chain payments corresponding to a swap. ProtocolVersionRoutingPlugin = 9 // ProtocolVersionHtlcV3 indicates that the client will now use the new diff --git a/loopdb/raw_db_test.go b/loopdb/raw_db_test.go index 26db043c..ac52946b 100644 --- a/loopdb/raw_db_test.go +++ b/loopdb/raw_db_test.go @@ -14,8 +14,8 @@ import ( // // Example output: // -// map[string]interface{}{ -// Hex("1234"): map[string]interface{}{ +// map[string]any{ +// Hex("1234"): map[string]any{ // "human-readable": Hex("102030"), // Hex("1111"): Hex("5783492373"), // }, @@ -36,7 +36,7 @@ func DumpDB(tx *bbolt.Tx) error { // nolint: unused } func dumpBucket(bucket *bbolt.Bucket) error { // nolint: unused - fmt.Printf("map[string]interface{} {\n") + fmt.Printf("map[string]any {\n") err := bucket.ForEach(func(k, v []byte) error { key := toString(k) fmt.Printf("%v: ", key) @@ -63,11 +63,11 @@ func dumpBucket(bucket *bbolt.Bucket) error { // nolint: unused } // RestoreDB primes the database with the given data set. -func RestoreDB(tx *bbolt.Tx, data map[string]interface{}) error { +func RestoreDB(tx *bbolt.Tx, data map[string]any) error { for k, v := range data { key := []byte(k) - value := v.(map[string]interface{}) + value := v.(map[string]any) subBucket, err := tx.CreateBucket(key) if err != nil { @@ -83,7 +83,7 @@ func RestoreDB(tx *bbolt.Tx, data map[string]interface{}) error { return nil } -func restoreDB(bucket *bbolt.Bucket, data map[string]interface{}) error { +func restoreDB(bucket *bbolt.Bucket, data map[string]any) error { for k, v := range data { key := []byte(k) @@ -104,7 +104,7 @@ func restoreDB(bucket *bbolt.Bucket, data map[string]interface{}) error { } // Key contains a sub-bucket. - case map[string]interface{}: + case map[string]any: subBucket, err := bucket.CreateBucket(key) if err != nil { return err diff --git a/loopdb/sql_store.go b/loopdb/sql_store.go index 21374f7f..da83f49a 100644 --- a/loopdb/sql_store.go +++ b/loopdb/sql_store.go @@ -740,7 +740,7 @@ func (db *BaseDB) convertLoopInRow(row sqlc.GetLoopInSwapsRow, func getSwapEvents(updates []sqlc.SwapUpdate) ([]*LoopEvent, error) { events := make([]*LoopEvent, len(updates)) - for i := 0; i < len(events); i++ { + for i := range len(events) { events[i] = &LoopEvent{ SwapStateData: SwapStateData{ State: SwapState(updates[i].UpdateState), diff --git a/loopdb/sql_test.go b/loopdb/sql_test.go index 225dc175..8312a793 100644 --- a/loopdb/sql_test.go +++ b/loopdb/sql_test.go @@ -569,14 +569,14 @@ func randomBytes(length int) []byte { return b } -func randomStruct(v interface{}) error { +func randomStruct(v any) error { val := reflect.ValueOf(v) if val.Kind() != reflect.Ptr || val.Elem().Kind() != reflect.Struct { return errors.New("Input should be a pointer to a struct type") } val = val.Elem() - for i := 0; i < val.NumField(); i++ { + for i := range val.NumField() { field := val.Field(i) switch field.Kind() { @@ -598,12 +598,12 @@ func randomStruct(v interface{}) error { } case reflect.Struct: - if field.Type() == reflect.TypeOf(time.Time{}) { + if field.Type() == reflect.TypeFor[time.Time]() { if field.CanSet() { field.Set(reflect.ValueOf(time.Now())) } } - if field.Type() == reflect.TypeOf(route.Vertex{}) { + if field.Type() == reflect.TypeFor[route.Vertex]() { if field.CanSet() { vertex, err := route.NewVertexFromBytes( randomBytes(route.VertexSize), diff --git a/loopdb/store_test.go b/loopdb/store_test.go index c0252674..4a61062b 100644 --- a/loopdb/store_test.go +++ b/loopdb/store_test.go @@ -442,15 +442,15 @@ func TestLegacyOutgoingChannel(t *testing.T) { ctxb := context.Background() - legacyDb := map[string]interface{}{ - "loop-in": map[string]interface{}{}, - "metadata": map[string]interface{}{ + legacyDb := map[string]any{ + "loop-in": map[string]any{}, + "metadata": map[string]any{ "dbp": legacyDbVersion, }, - "uncharge-swaps": map[string]interface{}{ - Hex("2a595d79a55168970532805ae20c9b5fac98f04db79ba4c6ae9b9ac0f206359e"): map[string]interface{}{ + "uncharge-swaps": map[string]any{ + Hex("2a595d79a55168970532805ae20c9b5fac98f04db79ba4c6ae9b9ac0f206359e"): map[string]any{ "contract": Hex("1562d6fbec140000010101010202020203030303040404040101010102020202030303030404040400000000000000640d707265706179696e766f69636501010101010101010101010101010101010101010101010101010101010101010201010101010101010101010101010101010101010101010101010101010101010300000090000000000000000a0000000000000014000000000000002800000063223347454e556d6e4552745766516374344e65676f6d557171745a757a5947507742530b73776170696e766f69636500000002000000000000001e") + legacyOutgoingChannel + Hex("1562d6fbec140000"), - "updates": map[string]interface{}{ + "updates": map[string]any{ Hex("0000000000000001"): Hex("1508290a92d4c00001000000000000000000000000000000000000000000000000"), Hex("0000000000000002"): Hex("1508290a92d4c00006000000000000000000000000000000000000000000000000"), }, diff --git a/loopdb/test_sqlite.go b/loopdb/test_sqlite.go index e60547c7..89dd8a1e 100644 --- a/loopdb/test_sqlite.go +++ b/loopdb/test_sqlite.go @@ -1,5 +1,4 @@ //go:build !test_db_postgres -// +build !test_db_postgres package loopdb diff --git a/loopin.go b/loopin.go index 548aeaa2..989d6733 100644 --- a/loopin.go +++ b/loopin.go @@ -530,13 +530,11 @@ func (s *loopInSwap) execute(mainCtx context.Context, subCtx, cancel := context.WithCancel(mainCtx) defer cancel() - s.wg.Add(1) - go func() { - defer s.wg.Done() + s.wg.Go(func() { subscribeAndLogUpdates( subCtx, s.hash, s.log, s.server.SubscribeLoopInUpdates, ) - }() + }) // Announce swap by sending out an initial update. err := s.sendUpdate(mainCtx) diff --git a/loopin_testcontext_test.go b/loopin_testcontext_test.go index bc566b60..d8a46012 100644 --- a/loopin_testcontext_test.go +++ b/loopin_testcontext_test.go @@ -23,7 +23,7 @@ type loopInTestContext struct { cfg *executeConfig statusChan chan SwapInfo errChan chan error - blockEpochChan chan interface{} + blockEpochChan chan any swapInvoiceSubscription *test.SingleInvoiceSubscription } @@ -34,7 +34,7 @@ func newLoopInTestContext(t *testing.T) *loopInTestContext { store := loopdb.NewStoreMock(t) sweeper := sweep.Sweeper{Lnd: &lnd.LndServices} - blockEpochChan := make(chan interface{}) + blockEpochChan := make(chan any) statusChan := make(chan SwapInfo) errChan := make(chan error) diff --git a/loopout.go b/loopout.go index b3d8b643..11990d57 100644 --- a/loopout.go +++ b/loopout.go @@ -104,7 +104,7 @@ type executeConfig struct { sweeper *sweep.Sweeper batcher *sweepbatcher.Batcher statusChan chan<- SwapInfo - blockEpochChan <-chan interface{} + blockEpochChan <-chan any timerFactory func(time.Duration) <-chan time.Time loopOutMaxParts uint32 totalPaymentTimeout time.Duration @@ -386,13 +386,11 @@ func (s *loopOutSwap) execute(mainCtx context.Context, subCtx, cancel := context.WithCancel(mainCtx) defer cancel() - s.wg.Add(1) - go func() { - defer s.wg.Done() + s.wg.Go(func() { subscribeAndLogUpdates( subCtx, s.hash, s.log, s.server.SubscribeLoopOutUpdates, ) - }() + }) // Execute swap. err := s.executeAndFinalize(mainCtx) diff --git a/loopout_feerate.go b/loopout_feerate.go index 4540644c..ec1b5d45 100644 --- a/loopout_feerate.go +++ b/loopout_feerate.go @@ -155,10 +155,7 @@ func (p *loopOutSweepFeerateProvider) GetConfTargetAndFeeRate( if confTarget <= DefaultSweepConfTargetDelta { // If confTarget is already <= urgentSweepConfTarget, don't // increase it. - newConfTarget := int32(urgentSweepConfTarget) - if confTarget < newConfTarget { - newConfTarget = confTarget - } + newConfTarget := min(confTarget, int32(urgentSweepConfTarget)) log.Infof("Swap %x is about to expire (blocksUntilExpiry=%d), "+ "reducing its confTarget from %d to %d and multiplying"+ diff --git a/loopout_test.go b/loopout_test.go index 1b3c6b32..fb1622b4 100644 --- a/loopout_test.go +++ b/loopout_test.go @@ -66,7 +66,7 @@ func testLoopOutPaymentParameters(t *testing.T) { sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices} - blockEpochChan := make(chan interface{}) + blockEpochChan := make(chan any) statusChan := make(chan SwapInfo) const maxParts = uint32(5) @@ -205,7 +205,7 @@ func testLateHtlcPublish(t *testing.T) { sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices} - blockEpochChan := make(chan interface{}) + blockEpochChan := make(chan any) statusChan := make(chan SwapInfo) errChan := make(chan error) @@ -308,7 +308,7 @@ func testCustomSweepConfTarget(t *testing.T) { // // TODO: create test context similar to loopInTestContext. sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices} - blockEpochChan := make(chan interface{}) + blockEpochChan := make(chan any) statusChan := make(chan SwapInfo) expiryChan := make(chan time.Time) timerFactory := func(expiry time.Duration) <-chan time.Time { @@ -330,8 +330,7 @@ func testCustomSweepConfTarget(t *testing.T) { lnd.ChainParams, batcherStore, sweepStore, ) - tctx, cancel := context.WithCancel(context.Background()) - defer cancel() + tctx := t.Context() go func() { err := batcher.Run(tctx) @@ -415,7 +414,7 @@ func testCustomSweepConfTarget(t *testing.T) { // Try MuSig2 signing first and fail it so that we go for a // normal sweep. - for i := 0; i < maxMusigSweepRetries; i++ { + for range maxMusigSweepRetries { expiryChan <- time.Now() preimage := <-server.preimagePush require.Equal(t, swap.Preimage, preimage) @@ -546,7 +545,7 @@ func testPreimagePush(t *testing.T) { // Set up the required dependencies to execute the swap. sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices} - blockEpochChan := make(chan interface{}) + blockEpochChan := make(chan any) statusChan := make(chan SwapInfo) expiryChan := make(chan time.Time) timerFactory := func(_ time.Duration) <-chan time.Time { @@ -568,8 +567,7 @@ func testPreimagePush(t *testing.T) { lnd.ChainParams, batcherStore, sweepStore, ) - tctx, cancel := context.WithCancel(context.Background()) - defer cancel() + tctx := t.Context() go func() { err := batcher.Run(tctx) @@ -804,7 +802,7 @@ func testFailedOffChainCancelation(t *testing.T) { // Set up the required dependencies to execute the swap. sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices} - blockEpochChan := make(chan interface{}) + blockEpochChan := make(chan any) statusChan := make(chan SwapInfo) expiryChan := make(chan time.Time) timerFactory := func(_ time.Duration) <-chan time.Time { @@ -958,7 +956,7 @@ func TestLoopOutMuSig2Sweep(t *testing.T) { // Set up the required dependencies to execute the swap. sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices} - blockEpochChan := make(chan interface{}) + blockEpochChan := make(chan any) statusChan := make(chan SwapInfo) expiryChan := make(chan time.Time) timerFactory := func(_ time.Duration) <-chan time.Time { @@ -988,8 +986,7 @@ func TestLoopOutMuSig2Sweep(t *testing.T) { lnd.ChainParams, batcherStore, sweepStore, ) - tctx, cancel := context.WithCancel(context.Background()) - defer cancel() + tctx := t.Context() go func() { err := batcher.Run(tctx) diff --git a/notifications/manager.go b/notifications/manager.go index 11f43a1f..bd1ac417 100644 --- a/notifications/manager.go +++ b/notifications/manager.go @@ -93,7 +93,7 @@ func NewManager(cfg *Config) *Manager { type subscriber struct { subCtx context.Context - recvChan interface{} + recvChan any } // SubscribeReservations subscribes to the reservation notifications. diff --git a/notifications/manager_test.go b/notifications/manager_test.go index e0d0e01d..9a06503e 100644 --- a/notifications/manager_test.go +++ b/notifications/manager_test.go @@ -85,11 +85,11 @@ func (m *mockSubscribeNotificationsClient) Context() context.Context { return context.TODO() } -func (m *mockSubscribeNotificationsClient) SendMsg(interface{}) error { +func (m *mockSubscribeNotificationsClient) SendMsg(any) error { return nil } -func (m *mockSubscribeNotificationsClient) RecvMsg(interface{}) error { +func (m *mockSubscribeNotificationsClient) RecvMsg(any) error { return nil } @@ -125,8 +125,7 @@ func TestManager_ReservationNotification(t *testing.T) { subChan := mgr.SubscribeReservations(subCtx) // Run the manager. - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() go func() { err := mgr.Run(ctx) @@ -229,13 +228,11 @@ func TestManager_Backoff(t *testing.T) { defer cancel() var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { // We ignore the returned error because the Manager returns // nil on context cancel. _ = mgr.Run(ctx) - }() + }) // Wait long enough to see at least 3 subscription attempts using // the Manager's default pattern. @@ -318,11 +315,9 @@ func TestManager_MinAliveConnTime(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { _ = mgr.Run(ctx) - }() + }) // Let the subscription stay alive for 2s, which is >1s (minAlive). // Then force an error to end the subscription. The manager sees @@ -407,13 +402,11 @@ func TestManager_Backoff_Pending_Token(t *testing.T) { defer cancel() var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { // We ignore the returned error because the Manager returns // nil on context cancel. _ = mgr.Run(ctx) - }() + }) // Wait long enough to see at least 3 token calls, so we can see that // we'll indeed backoff when the token is pending. diff --git a/staticaddr/address/manager_test.go b/staticaddr/address/manager_test.go index 83cbff5d..c23f246c 100644 --- a/staticaddr/address/manager_test.go +++ b/staticaddr/address/manager_test.go @@ -100,8 +100,7 @@ func (m *mockStaticAddressClient) ServerNewAddress(ctx context.Context, // TestManager tests the static address manager generates the corerct static // taproot address from the given test parameters. func TestManager(t *testing.T) { - ctxb, cancel := context.WithCancel(context.Background()) - defer cancel() + ctxb := t.Context() testContext := NewAddressManagerTestContext(t) diff --git a/staticaddr/deposit/fsm.go b/staticaddr/deposit/fsm.go index 341283a3..197bf2ee 100644 --- a/staticaddr/deposit/fsm.go +++ b/staticaddr/deposit/fsm.go @@ -475,33 +475,33 @@ func isUpdateSkipped(notification fsm.Notification, } // Infof logs an info message with the deposit outpoint. -func (f *FSM) Infof(format string, args ...interface{}) { +func (f *FSM) Infof(format string, args ...any) { log.Infof( "Deposit %v: "+format, append( - []interface{}{f.deposit.OutPoint}, + []any{f.deposit.OutPoint}, args..., )..., ) } // Debugf logs a debug message with the deposit outpoint. -func (f *FSM) Debugf(format string, args ...interface{}) { +func (f *FSM) Debugf(format string, args ...any) { log.Debugf( "Deposit %v: "+format, append( - []interface{}{f.deposit.OutPoint}, + []any{f.deposit.OutPoint}, args..., )..., ) } // Errorf logs an error message with the deposit outpoint. -func (f *FSM) Errorf(format string, args ...interface{}) { +func (f *FSM) Errorf(format string, args ...any) { log.Errorf( "Deposit %v: "+format, append( - []interface{}{f.deposit.OutPoint}, + []any{f.deposit.OutPoint}, args..., )..., ) diff --git a/staticaddr/loopin/fsm.go b/staticaddr/loopin/fsm.go index a4725359..ea6e610f 100644 --- a/staticaddr/loopin/fsm.go +++ b/staticaddr/loopin/fsm.go @@ -303,7 +303,7 @@ func isUpdateSkipped(notification fsm.Notification, } // Infof logs an info message with the loop-in swap hash. -func (f *FSM) Infof(format string, args ...interface{}) { +func (f *FSM) Infof(format string, args ...any) { if f.loopIn == nil { log.Infof(format, args...) return @@ -315,7 +315,7 @@ func (f *FSM) Infof(format string, args ...interface{}) { } // Debugf logs a debug message with the loop-in swap hash. -func (f *FSM) Debugf(format string, args ...interface{}) { +func (f *FSM) Debugf(format string, args ...any) { if f.loopIn == nil { log.Debugf(format, args...) return @@ -327,7 +327,7 @@ func (f *FSM) Debugf(format string, args ...interface{}) { } // Warnf logs a warning message with the loop-in swap hash. -func (f *FSM) Warnf(format string, args ...interface{}) { +func (f *FSM) Warnf(format string, args ...any) { if f.loopIn == nil { log.Warnf(format, args...) return @@ -339,7 +339,7 @@ func (f *FSM) Warnf(format string, args ...interface{}) { } // Errorf logs an error message with the loop-in swap hash. -func (f *FSM) Errorf(format string, args ...interface{}) { +func (f *FSM) Errorf(format string, args ...any) { if f.loopIn == nil { log.Errorf(format, args...) return diff --git a/staticaddr/loopin/loopin.go b/staticaddr/loopin/loopin.go index e6194f5f..37616c67 100644 --- a/staticaddr/loopin/loopin.go +++ b/staticaddr/loopin/loopin.go @@ -321,7 +321,7 @@ func (l *StaticAddressLoopIn) isHtlcTimedOut(height int32) bool { // htlcWeight returns the weight for the htlc transaction. func (l *StaticAddressLoopIn) htlcWeight(hasChange bool) lntypes.WeightUnit { var weightEstimator input.TxWeightEstimator - for i := 0; i < len(l.Deposits); i++ { + for range len(l.Deposits) { weightEstimator.AddTaprootKeySpendInput( txscript.SigHashDefault, ) diff --git a/staticaddr/loopin/manager.go b/staticaddr/loopin/manager.go index fcae218c..444ab585 100644 --- a/staticaddr/loopin/manager.go +++ b/staticaddr/loopin/manager.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "slices" "sort" "sync/atomic" "time" @@ -986,14 +987,7 @@ func mapDepositsToIndices( depositToIdxMap := make(map[string]int) for reqOutpoint := range req.DepositToNonces { - hasDeposit := false - for _, depositOutpoint := range loopIn.DepositOutpoints { - if depositOutpoint == reqOutpoint { - hasDeposit = true - break - } - } - if !hasDeposit { + if !slices.Contains(loopIn.DepositOutpoints, reqOutpoint) { return nil, fmt.Errorf("deposit outpoint not part of " + "loop-in") } diff --git a/staticaddr/openchannel/manager_test.go b/staticaddr/openchannel/manager_test.go index 2a6edb86..f408da16 100644 --- a/staticaddr/openchannel/manager_test.go +++ b/staticaddr/openchannel/manager_test.go @@ -660,8 +660,8 @@ func (m *mockClientStream) CloseSend() error { return nil } func (m *mockClientStream) Context() context.Context { return context.Background() } -func (m *mockClientStream) SendMsg(_ interface{}) error { return nil } -func (m *mockClientStream) RecvMsg(_ interface{}) error { return nil } +func (m *mockClientStream) SendMsg(_ any) error { return nil } +func (m *mockClientStream) RecvMsg(_ any) error { return nil } // mockOpenChanStream implements lnrpc.Lightning_OpenChannelClient. It returns // queued messages from Recv(), then returns finalErr once the queue is diff --git a/staticaddr/staticutil/utils.go b/staticaddr/staticutil/utils.go index 3c663735..7ef33201 100644 --- a/staticaddr/staticutil/utils.go +++ b/staticaddr/staticutil/utils.go @@ -56,7 +56,7 @@ func CreateMusig2Sessions(ctx context.Context, clientNonces := make([][]byte, len(deposits)) // Create the sessions and nonces from the deposits. - for i := 0; i < len(deposits); i++ { + for i := range len(deposits) { session, err := CreateMusig2Session( ctx, signer, addrParams, staticAddress, ) @@ -161,7 +161,7 @@ func bip69inputLess(input1, input2 *swapserverrpc.PrevoutInfo) bool { // At this point, the hashes are not equal, so reverse them to // big-endian and return the result of the comparison. const hashSize = chainhash.HashSize - for b := 0; b < hashSize/2; b++ { + for b := range hashSize / 2 { ihash[b], ihash[hashSize-1-b] = ihash[hashSize-1-b], ihash[b] jhash[b], jhash[hashSize-1-b] = jhash[hashSize-1-b], jhash[b] } @@ -227,7 +227,7 @@ func estimateFee(numInputs int, feeRate chainfee.SatPerKWeight, commitmentType lnrpc.CommitmentType) btcutil.Amount { var we input.TxWeightEstimator - for i := 0; i < numInputs; i++ { + for range numInputs { we.AddTaprootKeySpendInput(txscript.SigHashDefault) } diff --git a/staticaddr/withdraw/manager.go b/staticaddr/withdraw/manager.go index c9f8ab98..99fddd26 100644 --- a/staticaddr/withdraw/manager.go +++ b/staticaddr/withdraw/manager.go @@ -1081,7 +1081,7 @@ func WithdrawalTxWeight(numInputs int, sweepAddress btcutil.Address, hasChange bool) (lntypes.WeightUnit, error) { var weightEstimator input.TxWeightEstimator - for i := 0; i < numInputs; i++ { + for range numInputs { weightEstimator.AddTaprootKeySpendInput( txscript.SigHashDefault, ) diff --git a/swap/log.go b/swap/log.go index 6812c0d8..5345e68b 100644 --- a/swap/log.go +++ b/swap/log.go @@ -18,7 +18,7 @@ type PrefixLog struct { // Infof formats message according to format specifier and writes to // log with LevelInfo. -func (s *PrefixLog) Infof(format string, params ...interface{}) { +func (s *PrefixLog) Infof(format string, params ...any) { s.Logger.Infof( fmt.Sprintf("%v %s", ShortHash(&s.Hash), format), params..., @@ -27,7 +27,7 @@ func (s *PrefixLog) Infof(format string, params ...interface{}) { // Warnf formats message according to format specifier and writes to log with // LevelError. -func (s *PrefixLog) Warnf(format string, params ...interface{}) { +func (s *PrefixLog) Warnf(format string, params ...any) { s.Logger.Warnf( fmt.Sprintf("%v %s", ShortHash(&s.Hash), format), params..., @@ -36,7 +36,7 @@ func (s *PrefixLog) Warnf(format string, params ...interface{}) { // Errorf formats message according to format specifier and writes to log with // LevelError. -func (s *PrefixLog) Errorf(format string, params ...interface{}) { +func (s *PrefixLog) Errorf(format string, params ...any) { s.Logger.Errorf( fmt.Sprintf("%v %s", ShortHash(&s.Hash), format), params..., diff --git a/swap_server_client.go b/swap_server_client.go index 310b17ee..fcec06be 100644 --- a/swap_server_client.go +++ b/swap_server_client.go @@ -574,10 +574,7 @@ func (s *grpcSwapServerClient) makeServerUpdate(ctx context.Context, updateChan := make(chan *ServerUpdate) // Create a goroutine that will pipe updates in to our updates channel. - s.wg.Add(1) - go func() { - defer s.wg.Done() - + s.wg.Go(func() { for { // Try to receive from our stream. If there are no items // to consume, this call will block. If our stream is @@ -623,7 +620,7 @@ func (s *grpcSwapServerClient) makeServerUpdate(ctx context.Context, return } } - }() + }) return updateChan, errChan } diff --git a/sweepbatcher/greedy_batch_selection.go b/sweepbatcher/greedy_batch_selection.go index e1056a18..6ad5288c 100644 --- a/sweepbatcher/greedy_batch_selection.go +++ b/sweepbatcher/greedy_batch_selection.go @@ -273,10 +273,7 @@ func (e feeDetails) fee() btcutil.Amount { // combine returns new feeDetails, combining properties. func (e1 feeDetails) combine(e2 feeDetails) feeDetails { // The fee rate is max of two fee rates. - feeRate := e1.FeeRate - if feeRate < e2.FeeRate { - feeRate = e2.FeeRate - } + feeRate := max(e1.FeeRate, e2.FeeRate) return feeDetails{ FeeRate: feeRate, diff --git a/sweepbatcher/log.go b/sweepbatcher/log.go index 1149de0a..eeebf8a2 100644 --- a/sweepbatcher/log.go +++ b/sweepbatcher/log.go @@ -37,16 +37,16 @@ func UseLogger(logger btclog.Logger) { } // debugf logs a message with level DEBUG. -func debugf(format string, params ...interface{}) { +func debugf(format string, params ...any) { log().Debugf(format, params...) } // infof logs a message with level INFO. -func infof(format string, params ...interface{}) { +func infof(format string, params ...any) { log().Infof(format, params...) } // warnf logs a message with level WARN. -func warnf(format string, params ...interface{}) { +func warnf(format string, params ...any) { log().Warnf(format, params...) } diff --git a/sweepbatcher/sweep_batch.go b/sweepbatcher/sweep_batch.go index 9f4b99be..b77024f9 100644 --- a/sweepbatcher/sweep_batch.go +++ b/sweepbatcher/sweep_batch.go @@ -465,22 +465,22 @@ func (b *batch) setLog(logger btclog.Logger) { } // Debugf logs a message with level DEBUG. -func (b *batch) Debugf(format string, params ...interface{}) { +func (b *batch) Debugf(format string, params ...any) { b.log().Debugf(format, params...) } // Infof logs a message with level INFO. -func (b *batch) Infof(format string, params ...interface{}) { +func (b *batch) Infof(format string, params ...any) { b.log().Infof(format, params...) } // Warnf logs a message with level WARN. -func (b *batch) Warnf(format string, params ...interface{}) { +func (b *batch) Warnf(format string, params ...any) { b.log().Warnf(format, params...) } // Errorf logs a message with level ERROR. -func (b *batch) Errorf(format string, params ...interface{}) { +func (b *batch) Errorf(format string, params ...any) { b.log().Errorf(format, params...) } @@ -2034,10 +2034,8 @@ func (b *batch) monitorConfirmations(ctx context.Context) error { return err } - b.wg.Add(1) - go func() { + b.wg.Go(func() { defer cancel() - defer b.wg.Done() select { case conf := <-confChan: @@ -2055,7 +2053,7 @@ func (b *batch) monitorConfirmations(ctx context.Context) error { case <-ctx.Done(): } - }() + }) return nil } diff --git a/sweepbatcher/sweep_batcher.go b/sweepbatcher/sweep_batcher.go index 85a0c272..05b27386 100644 --- a/sweepbatcher/sweep_batcher.go +++ b/sweepbatcher/sweep_batcher.go @@ -1093,17 +1093,14 @@ func (b *Batcher) spinUpBatch(ctx context.Context, fast bool) (*batch, error) { // We add the batch to our map of batches and start it. b.batches[id] = batch - b.wg.Add(1) - go func() { - defer b.wg.Done() - + b.wg.Go(func() { err := batch.Run(ctx) if err != nil { b.writeToErrChan( ctx, fmt.Errorf("new batch failed: %w", err), ) } - }() + }) return batch, nil } @@ -1201,17 +1198,14 @@ func (b *Batcher) spinUpBatchFromDB(ctx context.Context, batch *batch) error { // We add the batch to our map of batches and start it. b.batches[batch.id] = newBatch - b.wg.Add(1) - go func() { - defer b.wg.Done() - + b.wg.Go(func() { err := newBatch.Run(ctx) if err != nil { b.writeToErrChan( ctx, fmt.Errorf("db batch failed: %w", err), ) } - }() + }) return nil } @@ -1306,10 +1300,8 @@ func (b *Batcher) monitorSpendAndNotify(ctx context.Context, sweeps []*sweep, return err } - b.wg.Add(1) - go func() { + b.wg.Go(func() { defer cancel() - defer b.wg.Done() infof("Batcher monitoring spend for swap %x", sweep.swapHash[:6]) @@ -1395,7 +1387,7 @@ func (b *Batcher) monitorSpendAndNotify(ctx context.Context, sweeps []*sweep, case <-ctx.Done(): return } - }() + }) return nil } @@ -1433,10 +1425,8 @@ func (b *Batcher) monitorConfAndNotify(ctx context.Context, sweep *sweep, return err } - b.wg.Add(1) - go func() { + b.wg.Go(func() { defer cancel() - defer b.wg.Done() select { case conf := <-confChan: @@ -1472,7 +1462,7 @@ func (b *Batcher) monitorConfAndNotify(ctx context.Context, sweep *sweep, case <-ctx.Done(): } - }() + }) return nil } diff --git a/sweepbatcher/sweep_batcher_test.go b/sweepbatcher/sweep_batcher_test.go index c7c48c24..a57541f2 100644 --- a/sweepbatcher/sweep_batcher_test.go +++ b/sweepbatcher/sweep_batcher_test.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "fmt" + "maps" "os" "sync" "testing" @@ -166,10 +167,7 @@ func (b *batch) snapshot(ctx context.Context) *batch { var snapshot *batch b.testRunInEventLoop(ctx, func() { // Deep copy sweeps. - sweeps := make(map[wire.OutPoint]sweep, len(b.sweeps)) - for o, s := range b.sweeps { - sweeps[o] = s - } + sweeps := maps.Clone(b.sweeps) // Deep copy cfg. cfg := *b.cfg @@ -527,11 +525,9 @@ func testTxLabeler(t *testing.T, store testStore, wg sync.WaitGroup ) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Create a sweep request. op1 := wire.OutPoint{ @@ -609,11 +605,9 @@ func testTxLabeler(t *testing.T, store testStore, batcherStore, sweepStore, WithTxLabeler(txLabeler)) ctx, cancel = context.WithCancel(context.Background()) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Expect batch to register for spending. <-lnd.RegisterSpendChannel @@ -684,11 +678,9 @@ func testPublishErrorHandler(t *testing.T, store testStore, wg sync.WaitGroup ) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Create a sweep request. sweepReq1 := SweepRequest{ @@ -1195,12 +1187,10 @@ func testSweepBatcherSkippedTxns(t *testing.T, store testStore, batcherStore, sweepStore, ) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -1278,11 +1268,9 @@ func testSweepBatcherSkippedTxns(t *testing.T, store testStore, op1.Hash: {}, }), ) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -1341,7 +1329,7 @@ type wrappedLogger struct { } // Debugf logs debug message. -func (l *wrappedLogger) Debugf(format string, params ...interface{}) { +func (l *wrappedLogger) Debugf(format string, params ...any) { l.mu.Lock() defer l.mu.Unlock() @@ -1350,7 +1338,7 @@ func (l *wrappedLogger) Debugf(format string, params ...interface{}) { } // Infof logs info message. -func (l *wrappedLogger) Infof(format string, params ...interface{}) { +func (l *wrappedLogger) Infof(format string, params ...any) { l.mu.Lock() defer l.mu.Unlock() @@ -1359,7 +1347,7 @@ func (l *wrappedLogger) Infof(format string, params ...interface{}) { } // Warnf logs a warning message. -func (l *wrappedLogger) Warnf(format string, params ...interface{}) { +func (l *wrappedLogger) Warnf(format string, params ...any) { l.mu.Lock() defer l.mu.Unlock() @@ -1402,13 +1390,11 @@ func testDelays(t *testing.T, store testStore, batcherStore testBatcherStore) { ) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -1452,24 +1438,18 @@ func testDelays(t *testing.T, store testStore, batcherStore testBatcherStore) { // so catch these actions from two separate goroutines. var wg2 sync.WaitGroup - wg2.Add(1) - go func() { - defer wg2.Done() - + wg2.Go(func() { // Since a batch was created we check that it registered for its // primary sweep's spend. <-lnd.RegisterSpendChannel - }() + }) - wg2.Add(1) var delays []time.Duration - go func() { - defer wg2.Done() - + wg2.Go(func() { // Expect two timers: initialDelay and publishDelay. delays = append(delays, <-tickSignal) delays = append(delays, <-tickSignal) - }() + }) // Wait for RegisterSpend and for timer registrations. wg2.Wait() @@ -1560,11 +1540,9 @@ func testDelays(t *testing.T, store testStore, batcherStore testBatcherStore) { WithPublishDelay(publishDelay), WithClock(testClock), ) ctx, cancel = context.WithCancel(context.Background()) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -1574,26 +1552,20 @@ func testDelays(t *testing.T, store testStore, batcherStore testBatcherStore) { // these actions from two separate goroutines. var wg3 sync.WaitGroup - wg3.Add(1) - go func() { - defer wg3.Done() - + wg3.Go(func() { // Since a batch was created we check that it registered for its // primary sweep's spend. <-lnd.RegisterSpendChannel // Wait for tx to be published. <-lnd.TxPublishChannel - }() + }) - wg3.Add(1) delays = nil - go func() { - defer wg3.Done() - + wg3.Go(func() { // Expect one timer: publishDelay (0). delays = append(delays, <-tickSignal) - }() + }) // Wait for RegisterSpend and for timer registration. wg3.Wait() @@ -1667,11 +1639,9 @@ func testDelays(t *testing.T, store testStore, batcherStore testBatcherStore) { WithPublishDelay(publishDelay), WithClock(testClock), ) ctx, cancel = context.WithCancel(context.Background()) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -1682,23 +1652,17 @@ func testDelays(t *testing.T, store testStore, batcherStore testBatcherStore) { // these actions from two separate goroutines. var wg4 sync.WaitGroup - wg4.Add(1) - go func() { - defer wg4.Done() - + wg4.Go(func() { // Since a batch was created we check that it registered for its // primary sweep's spend. <-lnd.RegisterSpendChannel - }() + }) - wg4.Add(1) delays = nil - go func() { - defer wg4.Done() - + wg4.Go(func() { // Expect one timer: publishDelay (0). delays = append(delays, <-tickSignal) - }() + }) // Wait for RegisterSpend and for timer registration. wg4.Wait() @@ -1754,24 +1718,18 @@ func testDelays(t *testing.T, store testStore, batcherStore testBatcherStore) { // parallel, so catch these actions from two separate goroutines. var wg5 sync.WaitGroup - wg5.Add(1) - go func() { - defer wg5.Done() - + wg5.Go(func() { // Since a batch was created we check that it registered for its // primary sweep's spend. <-lnd.RegisterSpendChannel - }() + }) - wg5.Add(1) delays = nil - go func() { - defer wg5.Done() - + wg5.Go(func() { // Expect two timer: largeInitialDelay, publishDelay. delays = append(delays, <-tickSignal) delays = append(delays, <-tickSignal) - }() + }) // Wait for RegisterSpend and for timers' registrations. wg5.Wait() @@ -1920,13 +1878,11 @@ func testCustomDelays(t *testing.T, store testStore, ) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -1968,24 +1924,18 @@ func testCustomDelays(t *testing.T, store testStore, // so catch these actions from two separate goroutines. var wg2 sync.WaitGroup - wg2.Add(1) - go func() { - defer wg2.Done() - + wg2.Go(func() { // Since a batch was created we check that it registered for its // primary sweep's spend. <-lnd.RegisterSpendChannel - }() + }) - wg2.Add(1) var delays []time.Duration - go func() { - defer wg2.Done() - + wg2.Go(func() { // Expect two timers: initialDelay and publishDelay. delays = append(delays, <-tickSignal) delays = append(delays, <-tickSignal) - }() + }) // Wait for RegisterSpend and for timer registrations. wg2.Wait() @@ -2124,13 +2074,11 @@ func testMaxSweepsPerBatch(t *testing.T, store testStore, ) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -2141,7 +2089,7 @@ func testMaxSweepsPerBatch(t *testing.T, store testStore, expectedBatches := (swapsNum + MaxSweepsPerBatch - 1) / MaxSweepsPerBatch - for i := 0; i < swapsNum; i++ { + for i := range swapsNum { preimage := lntypes.Preimage{2, byte(i % 256), byte(i / 256)} swapHash := preimage.Hash() @@ -2212,14 +2160,14 @@ func testMaxSweepsPerBatch(t *testing.T, store testStore, // Expect mockSigner.SignOutputRaw calls to sign non-cooperative // sweeps. - for i := 0; i < expectedBatches; i++ { + for range expectedBatches { <-lnd.SignOutputRawChannel } // Wait for txs to be published. inputsNum := 0 const maxWeight = lntypes.WeightUnit(400_000) - for i := 0; i < expectedBatches; i++ { + for range expectedBatches { tx := <-lnd.TxPublishChannel inputsNum += len(tx.TxIn) @@ -3226,13 +3174,11 @@ func testRestoringEmptyBatch(t *testing.T, store testStore, batcherStore, sweepStore) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -3407,13 +3353,11 @@ func testHandleSweepTwice(t *testing.T, backend testStore, batcherStore, sweepStore) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -3613,13 +3557,11 @@ func testRestoringPreservesConfTarget(t *testing.T, store testStore, batcherStore, sweepStore) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -3707,11 +3649,9 @@ func testRestoringPreservesConfTarget(t *testing.T, store testStore, testMuSig2SignSweep, testVerifySchnorrSig, lnd.ChainParams, batcherStore, sweepStore) ctx, cancel = context.WithCancel(context.Background()) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -3862,13 +3802,11 @@ func testSweepFetcher(t *testing.T, store testStore, WithCustomSignMuSig2(testSignMuSig2func)) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -3976,9 +3914,7 @@ func testSweepBatcherCloseDuringAdding(t *testing.T, store testStore, } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { // Add many sweeps. for i := byte(1); i < 255; i++ { // Create a sweep request. @@ -4007,15 +3943,13 @@ func testSweepBatcherCloseDuringAdding(t *testing.T, store testStore, } require.NoError(t, err) } - }() + }) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { // Close sweepbatcher during addings. time.Sleep(1 * time.Millisecond) cancel() - }() + }) // We don't know how many spend notification registrations will be // issued, so accept them while waiting for two goroutines to stop. @@ -4063,11 +3997,9 @@ func testSweepBatcherHandleSweepRace(t *testing.T, store testStore, var wg sync.WaitGroup var runErr error - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) <-batcher.initDone @@ -4147,10 +4079,7 @@ func testSweepBatcherHandleSweepRace(t *testing.T, store testStore, confCtx, confCancel := context.WithCancel(ctx) defer confCancel() - addWG.Add(1) - go func() { - defer addWG.Done() - + addWG.Go(func() { // After this goroutine completes, stop the goroutine that // handles registrations as well. Give it one second to finish // the last AddSweep to prevent goroutine leaks. @@ -4170,7 +4099,7 @@ func testSweepBatcherHandleSweepRace(t *testing.T, store testStore, return } } - }() + }) // Wait a bit so the AddSweep loop runs and keeps handleSweep busy. time.Sleep(100 * time.Millisecond) @@ -4178,9 +4107,7 @@ func testSweepBatcherHandleSweepRace(t *testing.T, store testStore, // This goroutine handles spending and confirmation registrations. // One spending registration has been created above, so the loop starts // with the next step - notifying about spending. - addWG.Add(1) - go func() { - defer addWG.Done() + addWG.Go(func() { for { spendingTx := publishedTx spendingHash := spendingTx.TxHash() @@ -4230,7 +4157,7 @@ func testSweepBatcherHandleSweepRace(t *testing.T, store testStore, return } } - }() + }) addWG.Wait() @@ -4596,12 +4523,10 @@ func TestSweepBatcherConfirmedBatchIncompleteSweeps(t *testing.T) { ) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx1) - }() + }) <-batcher.initDone @@ -4661,13 +4586,11 @@ func testCustomSignMuSig2(t *testing.T, store testStore, sweepStore, WithCustomSignMuSig2(testSignMuSig2func)) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -4786,13 +4709,11 @@ func testWithMixedBatch(t *testing.T, store testStore, ) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone @@ -4969,13 +4890,11 @@ func testWithMixedBatchCustom(t *testing.T, store testStore, ) var wg sync.WaitGroup - wg.Add(1) var runErr error - go func() { - defer wg.Done() + wg.Go(func() { runErr = batcher.Run(ctx) - }() + }) // Wait for the batcher to be initialized. <-batcher.initDone diff --git a/test/chainnotifier_mock.go b/test/chainnotifier_mock.go index 44de19f8..9b4623bd 100644 --- a/test/chainnotifier_mock.go +++ b/test/chainnotifier_mock.go @@ -71,10 +71,7 @@ func (c *mockChainNotifier) RegisterSpendNtfn(ctx context.Context, spendChan := make(chan *chainntnfs.SpendDetail, 1) errChan := make(chan error, 1) - c.wg.Add(1) - go func() { - defer c.wg.Done() - + c.wg.Go(func() { select { case m := <-c.lnd.SpendChannel: select { @@ -96,7 +93,7 @@ func (c *mockChainNotifier) RegisterSpendNtfn(ctx context.Context, case <-ctx.Done(): } - }() + }) return spendChan, errChan, nil } @@ -117,13 +114,11 @@ func (c *mockChainNotifier) RegisterBlockEpochNtfn(ctx context.Context) ( ) c.lnd.lock.Unlock() - c.wg.Add(1) - go func() { - defer c.wg.Done() + c.wg.Go(func() { defer func() { c.lnd.lock.Lock() defer c.lnd.lock.Unlock() - for i := 0; i < len(c.lnd.blockHeightListeners); i++ { + for i := range len(c.lnd.blockHeightListeners) { if c.lnd.blockHeightListeners[i] == blockEpochChan { c.lnd.blockHeightListeners = append( c.lnd.blockHeightListeners[:i], @@ -143,7 +138,7 @@ func (c *mockChainNotifier) RegisterBlockEpochNtfn(ctx context.Context) ( c.lnd.lock.Unlock() <-ctx.Done() - }() + }) return blockEpochChan, blockErrorChan, nil } @@ -170,10 +165,7 @@ func (c *mockChainNotifier) RegisterConfirmationsNtfn(ctx context.Context, errChan := make(chan error, 1) - c.wg.Add(1) - go func() { - defer c.wg.Done() - + c.wg.Go(func() { select { case m := <-c.lnd.ConfChannel: c.Lock() @@ -205,7 +197,7 @@ func (c *mockChainNotifier) RegisterConfirmationsNtfn(ctx context.Context, case <-ctx.Done(): } - }() + }) select { case c.lnd.RegisterConfChannel <- reg: diff --git a/test/lightning_client_mock.go b/test/lightning_client_mock.go index cd92634d..8732b444 100644 --- a/test/lightning_client_mock.go +++ b/test/lightning_client_mock.go @@ -280,9 +280,7 @@ func (h *mockLightningClient) ListPayments(_ context.Context, } lastIndexOffset := req.Offset + req.MaxPayments - if lastIndexOffset > uint64(len(h.lnd.Payments)) { - lastIndexOffset = uint64(len(h.lnd.Payments)) - } + lastIndexOffset = min(lastIndexOffset, uint64(len(h.lnd.Payments))) result := h.lnd.Payments[req.Offset:lastIndexOffset] diff --git a/utils.go b/utils.go index 32863431..69d79fda 100644 --- a/utils.go +++ b/utils.go @@ -438,7 +438,7 @@ func invoicesrpcSelectHopHints(amtMSat lnwire.MilliSatoshi, cfg *SelectHopHintsC // or if the sum of available bandwidth in the routing hints exceeds 2x // the payment amount. We do 2x here to account for a margin of error // if some of the selected channels no longer become operable. - for i := 0; i < len(openChannels); i++ { + for i := range len(openChannels) { enoughHopHints := sufficientHints( len(hopHints), numMaxHophints, hopHintFactor, amtMSat, totalHintBandwidth, diff --git a/utils/musig.go b/utils/musig.go index d7442339..74626c2a 100644 --- a/utils/musig.go +++ b/utils/musig.go @@ -31,10 +31,10 @@ func MuSig2Sign(version input.MuSig2Version, privKeys []*btcec.PrivateKey, // Next we'll pass around all public nonces to all MuSig2 sessions so // that they become usable for creating the partial signatures. - for i := 0; i < len(privKeys); i++ { + for i := range len(privKeys) { nonce := sessions[i].PublicNonce() - for j := 0; j < len(privKeys); j++ { + for j := range len(privKeys) { if i == j { // Step over if it's the same session. continue