diff --git a/client.go b/client.go index e7f693db..37217ca0 100644 --- a/client.go +++ b/client.go @@ -93,6 +93,8 @@ var ( // Client performs the client side part of swaps. This interface exists to be // able to implement a stub. type Client struct { + clientConfig + started uint32 // To be used atomically. errChan chan error @@ -107,8 +109,6 @@ type Client struct { resumeReady chan struct{} wg sync.WaitGroup - - clientConfig } // ClientConfig is the exported configuration structure that is required to diff --git a/cmd/loop/instantout.go b/cmd/loop/instantout.go index e299f5e1..699e5006 100644 --- a/cmd/loop/instantout.go +++ b/cmd/loop/instantout.go @@ -187,7 +187,6 @@ func instantOut(ctx *cli.Context) error { DestAddr: ctx.String("addr"), }, ) - if err != nil { return err } @@ -228,5 +227,6 @@ func listInstantOuts(ctx *cli.Context) error { } printRespJSON(resp) + return nil } diff --git a/cmd/loop/loopin.go b/cmd/loop/loopin.go index dcbdc168..05501807 100644 --- a/cmd/loop/loopin.go +++ b/cmd/loop/loopin.go @@ -207,6 +207,7 @@ func loopIn(ctx *cli.Context) error { fmt.Printf("Swap initiated\n") fmt.Printf("ID: %v\n", resp.Id) + if resp.HtlcAddressP2Tr != "" { fmt.Printf("HTLC address (P2TR): %v\n", resp.HtlcAddressP2Tr) } else { diff --git a/cmd/loop/loopout.go b/cmd/loop/loopout.go index 76d56117..57ad2c76 100644 --- a/cmd/loop/loopout.go +++ b/cmd/loop/loopout.go @@ -176,8 +176,10 @@ func loopOut(ctx *cli.Context) error { "address to sweep the loop amount to") } - var destAddr string - var account string + var ( + destAddr string + account string + ) switch { case ctx.IsSet("addr"): destAddr = ctx.String("addr") diff --git a/cmd/loop/staticaddr.go b/cmd/loop/staticaddr.go index c9e08db5..8906f77b 100644 --- a/cmd/loop/staticaddr.go +++ b/cmd/loop/staticaddr.go @@ -417,6 +417,7 @@ func utxosToOutpoints(utxos []string) ([]*looprpc.OutPoint, error) { if len(utxos) == 0 { return nil, fmt.Errorf("no utxos specified") } + for _, utxo := range utxos { outpoint, err := NewProtoOutPoint(utxo) if err != nil { diff --git a/cost_migration.go b/cost_migration.go index c21fd97c..14fa2c87 100644 --- a/cost_migration.go +++ b/cost_migration.go @@ -25,7 +25,7 @@ func CalculateLoopOutCost(params *chaincfg.Params, loopOutSwap *loopdb.LoopOut, paymentFees map[lntypes.Hash]lnwire.MilliSatoshi) (loopdb.SwapCost, error) { - // First make sure that this swap is actually finished. + // First, make sure that this swap is actually finished. if loopOutSwap.State().State.IsPending() { return loopdb.SwapCost{}, fmt.Errorf("swap is not yet finished") } @@ -41,8 +41,8 @@ func CalculateLoopOutCost(params *chaincfg.Params, loopOutSwap *loopdb.LoopOut, } // The swap hash is given and we don't need to get it from the - // swap invoice, however we'll decode it anyway to get the invoice amount - // that was paid in case we don't have the payment anymore. + // swap invoice, however we'll decode it anyway to get the invoice + // amount that was paid in case we don't have the payment anymore. _, _, swapHash, swapPaymentAmount, err := swap.DecodeInvoice( params, loopOutSwap.Contract.SwapInvoice, ) @@ -195,6 +195,6 @@ func MigrateLoopOutCosts(ctx context.Context, lnd lndclient.LndServices, return err } - // Finally mark the migration as done. + // Finally, mark the migration as done. return db.SetMigration(ctx, costMigrationID) } diff --git a/executor.go b/executor.go index 4428ace3..cfaa5ea7 100644 --- a/executor.go +++ b/executor.go @@ -42,17 +42,14 @@ type executorConfig struct { } // executor is responsible for executing swaps. -// -// TODO(roasbeef): rename to SubSwapper. type executor struct { + sync.Mutex + executorConfig + wg sync.WaitGroup newSwaps chan genericSwap currentHeight uint32 ready chan struct{} - - sync.Mutex - - executorConfig } // newExecutor returns a new swap executor instance. @@ -80,7 +77,6 @@ func (s *executor) run(mainCtx context.Context, for { blockEpochChan, blockErrorChan, err = s.lnd.ChainNotifier.RegisterBlockEpochNtfn(mainCtx) - if err == nil { break } diff --git a/fsm/fsm.go b/fsm/fsm.go index a16a3356..abc0d729 100644 --- a/fsm/fsm.go +++ b/fsm/fsm.go @@ -138,7 +138,7 @@ func NewStateMachine(states States, observerSize int) *StateMachine { func NewStateMachineWithState(states States, current StateType, observerSize int) *StateMachine { - observers := []Observer{} + var observers []Observer var defaultObserver *CachedObserver if observerSize > 0 { diff --git a/fsm/observer.go b/fsm/observer.go index b0c1a5de..0adc4b38 100644 --- a/fsm/observer.go +++ b/fsm/observer.go @@ -194,10 +194,10 @@ func (c *CachedObserver) WaitForStateAsync(ctx context.Context, state StateType, // FixedSizeSlice is a slice with a fixed size. type FixedSizeSlice[T any] struct { + sync.Mutex + data []T maxLen int - - sync.Mutex } // NewFixedSizeSlice initializes a new FixedSlice with a given maximum length. diff --git a/instantout/manager.go b/instantout/manager.go index 4b8567a0..37ccb681 100644 --- a/instantout/manager.go +++ b/instantout/manager.go @@ -22,6 +22,8 @@ var ( // Manager manages the instantout state machines. type Manager struct { + sync.Mutex + // cfg contains all the services that the reservation manager needs to // operate. cfg *Config @@ -36,8 +38,6 @@ type Manager struct { blockEpochChan chan int32 runCtx context.Context - - sync.Mutex } // NewInstantOutManager creates a new instantout manager. diff --git a/instantout/reservation/manager.go b/instantout/reservation/manager.go index f2833c07..600febfe 100644 --- a/instantout/reservation/manager.go +++ b/instantout/reservation/manager.go @@ -15,14 +15,14 @@ import ( // Manager manages the reservation state machines. type Manager struct { + sync.Mutex + // cfg contains all the services that the reservation manager needs to // operate. cfg *Config // activeReservations contains all the active reservationsFSMs. activeReservations map[ID]*FSM - - sync.Mutex } // NewManager creates a new reservation manager. diff --git a/interface.go b/interface.go index 310bda33..b31c24f9 100644 --- a/interface.go +++ b/interface.go @@ -115,18 +115,18 @@ type OutRequest struct { // Out contains the full details of a loop out request. This includes things // like the payment hash, the total value, and the final CTLV delay of the -// swap. We'll use this to track an active swap throughout that various swap +// swap. We'll use this to track an active swap throughout those various swap // stages. type Out struct { + // SwapInfoKit contains shared data amongst all swap types. + SwapInfoKit + // LoopOutContract describes the details of this loop.Out. Using these - // details,the full swap can be executed. + // details, the full swap can be executed. loopdb.LoopOutContract // State is the current state of the target swap. State loopdb.SwapState - - // SwapInfoKit contains shared data amongst all swap types. - SwapInfoKit } // LoopOutQuoteRequest specifies the swap parameters for which a quote is diff --git a/liquidity/liquidity.go b/liquidity/liquidity.go index bdaff64e..77895bcf 100644 --- a/liquidity/liquidity.go +++ b/liquidity/liquidity.go @@ -271,8 +271,8 @@ type Manager struct { } // Run periodically checks whether we should automatically dispatch a loop out. -// We run this loop even if automated swaps are not currently enabled rather -// than managing starting and stopping the ticker as our parameters are updated. +// We run this loop even if automated swaps are not currently enabled, instead +// of starting and stopping the ticker whenever our parameters are updated. func (m *Manager) Run(ctx context.Context) error { m.cfg.AutoloopTicker.Resume() defer m.cfg.AutoloopTicker.Stop() diff --git a/loopdb/postgres.go b/loopdb/postgres.go index 60483e93..32fbbbde 100644 --- a/loopdb/postgres.go +++ b/loopdb/postgres.go @@ -59,9 +59,9 @@ func (s *PostgresConfig) DSN(hidePassword bool) string { // PostgresStore is a database store implementation that uses a Postgres // backend. type PostgresStore struct { - cfg *PostgresConfig - *BaseDB + + cfg *PostgresConfig } // In migration of sweeps table from outpoint_txid and outpoint_index to diff --git a/loopdb/protocol_version_test.go b/loopdb/protocol_version_test.go index b7f3c253..b9bbc69c 100644 --- a/loopdb/protocol_version_test.go +++ b/loopdb/protocol_version_test.go @@ -48,7 +48,7 @@ func TestProtocolVersionSanity(t *testing.T) { require.Equal(t, uint32(version), uint32(rpcVersions[i])) } - // Finally test that the current version contants are up to date + // Finally, test that the current version constants are up to date require.Equal(t, CurrentProtocolVersion(), versions[len(versions)-1], diff --git a/loopdb/sqlite.go b/loopdb/sqlite.go index 58b1cee3..0a0188e5 100644 --- a/loopdb/sqlite.go +++ b/loopdb/sqlite.go @@ -40,9 +40,9 @@ type SqliteConfig struct { // SqliteSwapStore is a sqlite3 based database for the loop daemon. type SqliteSwapStore struct { - cfg *SqliteConfig - *BaseDB + + cfg *SqliteConfig } // NewSqliteStore attempts to open a new sqlite database based on the passed @@ -174,11 +174,11 @@ func NewTestSqliteDB(t *testing.T) *SqliteSwapStore { // BaseDB is the base database struct that each implementation can embed to // gain some common functionality. type BaseDB struct { - network *chaincfg.Params - *sql.DB *sqlc.Queries + + network *chaincfg.Params } // BeginTx wraps the normal sql specific BeginTx method with the TxOptions diff --git a/loopin.go b/loopin.go index 45f639a0..dc9bf3fb 100644 --- a/loopin.go +++ b/loopin.go @@ -240,6 +240,7 @@ func newLoopInSwap(globalCtx context.Context, cfg *swapConfig, request.Amount, senderKey, senderInternalPubKey, swapInvoice, probeInvoice, request.LastHop, request.Initiator, ) + probeWaitCancel() if err != nil { return nil, wrapGrpcError("cannot initiate swap", err) @@ -352,6 +353,7 @@ func awaitProbe(ctx context.Context, lnd lndclient.LndServices, switch update.State { case invpkg.ContractAccepted: log.Infof("Server probe successful") + probeResult <- nil // Cancel probe invoice so that the diff --git a/loopout.go b/loopout.go index 70f8adcd..2417a516 100644 --- a/loopout.go +++ b/loopout.go @@ -538,7 +538,7 @@ func (s *loopOutSwap) handlePaymentResult(ctx context.Context, } } -// executeSwap executes the swap, but returns as soon as the swap outcome is +// executeSwap executes the swap but returns as soon as the swap outcome is // final. At that point, there may still be pending off-chain payment(s). func (s *loopOutSwap) executeSwap(globalCtx context.Context) error { // Decode the prepay invoice so we can ensure that we account for the @@ -1192,7 +1192,7 @@ func (s *loopOutSwap) waitForHtlcSpendConfirmedV2(globalCtx context.Context, } var ( - // paymentComplete tracks whether our payment is complete, and + // paymentComplete tracks whether our payment is complete and // is used to decide whether we need to push our preimage to // the server. paymentComplete bool diff --git a/notifications/manager.go b/notifications/manager.go index 4dbdc383..acf64f38 100644 --- a/notifications/manager.go +++ b/notifications/manager.go @@ -62,12 +62,13 @@ type Config struct { // Manager is a manager for notifications that the swap server sends to the // client. type Manager struct { + sync.Mutex + cfg *Config hasL402 bool subscribers map[NotificationType][]subscriber - sync.Mutex } // NewManager creates a new notification manager. diff --git a/notifications/manager_test.go b/notifications/manager_test.go index 5b04f3a5..6f94a5a0 100644 --- a/notifications/manager_test.go +++ b/notifications/manager_test.go @@ -23,11 +23,12 @@ var ( // mockNotificationsClient implements the NotificationsClient interface for testing. type mockNotificationsClient struct { + sync.Mutex + mockStream swapserverrpc.SwapServer_SubscribeNotificationsClient subscribeErr error attemptTimes []time.Time timesCalled int - sync.Mutex } func (m *mockNotificationsClient) SubscribeNotifications(ctx context.Context, @@ -49,6 +50,7 @@ func (m *mockNotificationsClient) SubscribeNotifications(ctx context.Context, // mockSubscribeNotificationsClient simulates the server stream. type mockSubscribeNotificationsClient struct { grpc.ClientStream + recvChan chan *swapserverrpc.SubscribeNotificationsResponse recvErrChan chan error } diff --git a/routing_plugin.go b/routing_plugin.go index 91709eee..8bc0cf9f 100644 --- a/routing_plugin.go +++ b/routing_plugin.go @@ -2,6 +2,7 @@ package loop import ( "context" + "errors" "fmt" "sort" "sync" @@ -92,7 +93,7 @@ func AcquireRoutingPlugin(ctx context.Context, pluginType RoutingPluginType, // Initialize the plugin with the passed parameters. err := routingPluginInstance.Init(ctx, target, routeHints, amt) if err != nil { - if err == ErrRoutingPluginNotApplicable { + if errors.Is(err, ErrRoutingPluginNotApplicable) { // Since the routing plugin is not applicable for this // payment, we can immediately destruct it. if err := routingPluginInstance.Done(ctx); err != nil { @@ -100,7 +101,7 @@ func AcquireRoutingPlugin(ctx context.Context, pluginType RoutingPluginType, "plugin: %v", err) } - // ErrRoutingPluginNotApplicable is non critical, so + // ErrRoutingPluginNotApplicable is non-critical, so // we're masking this error as we can continue the swap // flow without the routing plugin. err = nil diff --git a/staticaddr/address/manager.go b/staticaddr/address/manager.go index 122c8742..1d63bd7f 100644 --- a/staticaddr/address/manager.go +++ b/staticaddr/address/manager.go @@ -49,10 +49,10 @@ type ManagerConfig struct { // Manager manages the address state machines. type Manager struct { - cfg *ManagerConfig - sync.Mutex + cfg *ManagerConfig + currentHeight atomic.Int32 } diff --git a/staticaddr/deposit/deposit.go b/staticaddr/deposit/deposit.go index 6da9e729..b2a1e5ca 100644 --- a/staticaddr/deposit/deposit.go +++ b/staticaddr/deposit/deposit.go @@ -29,15 +29,17 @@ func (r *ID) FromByteSlice(b []byte) error { // Deposit bundles an utxo at a static address together with manager-relevant // data. type Deposit struct { + sync.Mutex + + // Outpoint of the deposit. + wire.OutPoint + // ID is the unique identifier of the deposit. ID ID // state is the current state of the deposit. state fsm.StateType - // Outpoint of the deposit. - wire.OutPoint - // Value is the amount of the deposit. Value btcutil.Amount @@ -52,11 +54,9 @@ type Deposit struct { // ExpirySweepTxid is the transaction id of the expiry sweep. ExpirySweepTxid chainhash.Hash - // FinalizedWithdrawalTx is the coop signed withdrawal transaction. It + // FinalizedWithdrawalTx is the coop-signed withdrawal transaction. It // is republished on new block arrivals and on client restarts. FinalizedWithdrawalTx *wire.MsgTx - - sync.Mutex } // IsInFinalState returns true if the deposit is final. diff --git a/staticaddr/loopin/actions.go b/staticaddr/loopin/actions.go index add35b4a..6299c167 100644 --- a/staticaddr/loopin/actions.go +++ b/staticaddr/loopin/actions.go @@ -689,7 +689,7 @@ func (f *FSM) SweepHtlcTimeoutAction(ctx context.Context, select { case <-ctx.Done(): - f.Errorf(ctx.Err().Error()) + f.Errorf("%v", ctx.Err()) default: <-time.After(1 * time.Hour) diff --git a/swap.go b/swap.go index 2267daed..94de7d10 100644 --- a/swap.go +++ b/swap.go @@ -13,6 +13,8 @@ import ( ) type swapKit struct { + swapConfig + hash lntypes.Hash height int32 //nolint:structcheck @@ -28,8 +30,6 @@ type swapKit struct { contract *loopdb.SwapContract swapType swap.Type - - swapConfig } func newSwapKit(hash lntypes.Hash, swapType swap.Type, cfg *swapConfig, diff --git a/test/chainnotifier_mock.go b/test/chainnotifier_mock.go index d9a82202..44de19f8 100644 --- a/test/chainnotifier_mock.go +++ b/test/chainnotifier_mock.go @@ -15,8 +15,8 @@ import ( type mockChainNotifier struct { lndclient.ChainNotifierClient - sync.Mutex + lnd *LndMockServices confRegistrations []*ConfRegistration wg sync.WaitGroup diff --git a/test/lightning_client_mock.go b/test/lightning_client_mock.go index bcd38e7b..cd92634d 100644 --- a/test/lightning_client_mock.go +++ b/test/lightning_client_mock.go @@ -21,12 +21,12 @@ import ( ) type mockLightningClient struct { - lnd *LndMockServices - wg sync.WaitGroup - // Embed lndclient's interface so that lndclient can be expanded // without the need to implement unused functions on the mock. lndclient.LightningClient + + lnd *LndMockServices + wg sync.WaitGroup } // PayInvoice pays an invoice. diff --git a/test/router_mock.go b/test/router_mock.go index 9ef84947..7eda1d7e 100644 --- a/test/router_mock.go +++ b/test/router_mock.go @@ -9,6 +9,7 @@ import ( type mockRouter struct { lndclient.RouterClient + lnd *LndMockServices } diff --git a/utils.go b/utils.go index 333c3a5b..54edf4a5 100644 --- a/utils.go +++ b/utils.go @@ -36,7 +36,6 @@ func isPublicNode(ctx context.Context, lndClient lndclient.LightningClient, // GetNodeInfo doesn't report our private channels with the queried node // so, we can use it to determine if the node is considered public. nodeInfo, err := lndClient.GetNodeInfo(ctx, pubKey, true) - if err != nil { return false, err }