From 26ae424d10c362963b4a751429df6c649f9ca88a Mon Sep 17 00:00:00 2001 From: KonradStaniec Date: Wed, 20 Nov 2024 12:44:29 +0100 Subject: [PATCH 1/8] fix linter file --- .golangci.yml | 63 ++++++++++++++++----------------------------------- 1 file changed, 19 insertions(+), 44 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 891b3fd6d..430555e3d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,7 @@ run: timeout: 5m + +linters: disable-all: true enable: - asasalint @@ -8,96 +10,69 @@ run: - bodyclose - containedctx - contextcheck - - cyclop - decorder - - depguard - dogsled - - dupl - durationcheck - errcheck - errchkjson - errname - errorlint - - execinquery - exhaustive - - exhaustivestruct - - exhaustruct - - exportloopref - forbidigo - forcetypeassert - - funlen - - gci - - gochecknoglobals - - gochecknoinits - - gocognit - goconst - gocritic - gocyclo - - godot - - godox - - goerr113 - - gofumpt - goheader - - golint - - gomnd - - gomoddirectives - gomodguard - goprintffuncname - - gosec - gosimple - govet - grouper - - ifshort - importas - ineffassign - - interfacebloat - - interfacer - - ireturn - - lll - loggercheck - maintidx - makezero - - maligned - misspell - nakedret - - nestif - nilerr - - nilnil - - nlreturn +# - nlreturn # Style wise I personally like this one, todo(lazar): unlax at somepoint, good practice - noctx - - nolintlint - nonamedreturns - - nosnakecase - nosprintfhostport - paralleltest - - prealloc - - predeclared - - promlinter - reassign - revive - rowserrcheck - - scopelint - sqlclosecheck - staticcheck - - structcheck - stylecheck - - tagliatelle - tenv - testableexamples - - testpackage - - thelper - tparallel - typecheck - unconvert - unparam - - unused - usestdlibvars - - varcheck - - varnamelen + - unused - wastedassign - whitespace - - wrapcheck - - wsl +# - wrapcheck # we really should be using this, lax for now todo(lazar): unlax at somepoint, good practice issues: max-same-issues: 0 + # Default: https://golangci-lint.run/usage/false-positives/#default-exclusions + exclude-dirs: + - e2etest + exclude-rules: + # Exclude some linters from running on tests files. + - path: _test\.go + linters: + - gocyclo + - errcheck + - dupl + - gosec + - path-except: _test\.go + linters: + - forbidigo From 80b538c2eeb95559eacc96abee3a3ffbce368e3b Mon Sep 17 00:00:00 2001 From: KonradStaniec Date: Wed, 20 Nov 2024 12:46:35 +0100 Subject: [PATCH 2/8] changelog update --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 87eb60ec0..9e418e111 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,7 @@ making params valid for btc light client ranges - [#289](https://github.com/babylonlabs-io/babylon/pull/289) hotfix: Invalid minUnbondingTime for verifying inclusion proof ## v0.17.0 +- [#282](https://github.com/babylonlabs-io/babylon/pull/282) Fix linter config and issues ### State Breaking From ec2b9c8c2e5562413f92ab560c74251902b0522d Mon Sep 17 00:00:00 2001 From: KonradStaniec Date: Wed, 20 Nov 2024 13:05:19 +0100 Subject: [PATCH 3/8] fix trailing new lines --- btcstaking/staking.go | 5 ----- btcstaking/types.go | 2 -- btctxformatter/formatter.go | 4 ---- btctxformatter/formatter_test.go | 1 - testutil/bitcoin/utils.go | 1 - types/btc_schnorr_sig.go | 1 - x/btccheckpoint/keeper/keeper.go | 3 --- x/btccheckpoint/keeper/msg_server.go | 1 - x/btccheckpoint/types/btcutils.go | 2 -- x/btclightclient/keeper/grpc_query.go | 1 - x/btclightclient/types/btc_light_client.go | 5 ----- x/btclightclient/types/codec.go | 1 - x/btcstaking/keeper/btc_delegations.go | 1 - x/btcstaking/types/btc_slashing_tx.go | 2 -- x/btcstaking/types/pop.go | 2 -- x/checkpointing/types/codec.go | 1 - x/checkpointing/types/types.go | 1 - x/epoching/keeper/keeper.go | 2 +- x/epoching/types/genesis.go | 1 - 19 files changed, 1 insertion(+), 36 deletions(-) diff --git a/btcstaking/staking.go b/btcstaking/staking.go index 2a1a5d7b6..ed66f356a 100644 --- a/btcstaking/staking.go +++ b/btcstaking/staking.go @@ -330,7 +330,6 @@ func validateSlashingTx( slashingChangeLockTime uint16, net *chaincfg.Params, ) error { - if err := CheckPreSignedSlashingTxSanity(slashingTx); err != nil { return fmt.Errorf("invalid slashing tx: %w", err) } @@ -470,7 +469,6 @@ func signTxWithOneScriptSpendInputFromTapLeafInternal( fundingOutput *wire.TxOut, privKey *btcec.PrivateKey, tapLeaf txscript.TapLeaf) (*schnorr.Signature, error) { - inputFetcher := txscript.NewCannedPrevOutputFetcher( fundingOutput.PkScript, fundingOutput.Value, @@ -558,7 +556,6 @@ func SignTxWithOneScriptSpendInputStrict( signedScriptPath []byte, privKey *btcec.PrivateKey, ) (*schnorr.Signature, error) { - if err := checkTxBeforeSigning(txToSign, fundingTx, fundingOutputIdx); err != nil { return nil, fmt.Errorf("invalid tx: %w", err) } @@ -579,7 +576,6 @@ func EncSignTxWithOneScriptSpendInputStrict( privKey *btcec.PrivateKey, encKey *asig.EncryptionKey, ) (*asig.AdaptorSignature, error) { - if err := checkTxBeforeSigning(txToSign, fundingTx, fundingOutputIdx); err != nil { return nil, fmt.Errorf("invalid tx: %w", err) } @@ -650,7 +646,6 @@ func VerifyTransactionSigWithOutput( script []byte, pubKey *btcec.PublicKey, signature []byte) error { - if fundingOutput == nil { return fmt.Errorf("funding output must not be nil") } diff --git a/btcstaking/types.go b/btcstaking/types.go index 482238035..c19649361 100644 --- a/btcstaking/types.go +++ b/btcstaking/types.go @@ -65,7 +65,6 @@ func DeriveTaprootAddress( tapScriptTree *txscript.IndexedTapScriptTree, internalPubKey *btcec.PublicKey, net *chaincfg.Params) (*btcutil.AddressTaproot, error) { - tapScriptRootHash := tapScriptTree.RootNode.TapHash() outputKey := txscript.ComputeTaprootOutputKey( @@ -222,7 +221,6 @@ func SpendInfoFromRevealedScript( revealedScript []byte, internalKey *btcec.PublicKey, tree *txscript.IndexedTapScriptTree) (*SpendInfo, error) { - revealedLeaf := txscript.NewBaseTapLeaf(revealedScript) leafHash := revealedLeaf.TapHash() diff --git a/btctxformatter/formatter.go b/btctxformatter/formatter.go index 14dde7b8b..b3aeaac6c 100644 --- a/btctxformatter/formatter.go +++ b/btctxformatter/formatter.go @@ -103,7 +103,6 @@ func encodeFirstOpRetrun( bitMap []byte, submitterAddress []byte, ) []byte { - var serializedBytes = []byte{} serializedBytes = append(serializedBytes, encodeHeader(tag, version, firstPartIndex)...) @@ -148,7 +147,6 @@ func EncodeCheckpointData( version FormatVersion, rawBTCCheckpoint *RawBtcCheckpoint, ) ([]byte, []byte, error) { - if len(tag) != TagLength { return nil, nil, errors.New("tag should have 4 bytes") } @@ -247,7 +245,6 @@ func GetCheckpointData( partIndex uint8, data []byte, ) ([]byte, error) { - if partIndex > 1 { return nil, errors.New("invalid part index") } @@ -290,7 +287,6 @@ func IsBabylonCheckpointData( version FormatVersion, data []byte, ) (*BabylonData, error) { - var idx uint8 = 0 for idx < NumberOfParts { diff --git a/btctxformatter/formatter_test.go b/btctxformatter/formatter_test.go index 1215a81cf..1cd004722 100644 --- a/btctxformatter/formatter_test.go +++ b/btctxformatter/formatter_test.go @@ -19,7 +19,6 @@ func FuzzEncodingDecoding(f *testing.F) { f.Add(uint64(2000), randNBytes(TagLength), randNBytes(BlockHashLength), randNBytes(BitMapLength), randNBytes(BlsSigLength), randNBytes(AddressLength)) f.Fuzz(func(t *testing.T, epoch uint64, tag []byte, appHash []byte, bitMap []byte, blsSig []byte, address []byte) { - if len(tag) < TagLength { t.Skip("Tag should have 4 bytes") } diff --git a/testutil/bitcoin/utils.go b/testutil/bitcoin/utils.go index 505a1c1d1..485051c1a 100644 --- a/testutil/bitcoin/utils.go +++ b/testutil/bitcoin/utils.go @@ -14,7 +14,6 @@ import ( // https://github.com/lightningnetwork/lnd/blob/master/input/script_utils_test.go#L24 func AssertEngineExecution(t *testing.T, testNum int, valid bool, newEngine func() (*txscript.Engine, error)) { - t.Helper() // Get a new VM to execute. diff --git a/types/btc_schnorr_sig.go b/types/btc_schnorr_sig.go index 336cf037b..bf2cfea73 100644 --- a/types/btc_schnorr_sig.go +++ b/types/btc_schnorr_sig.go @@ -12,7 +12,6 @@ type BIP340Signature []byte const BIP340SignatureLen = schnorr.SignatureSize func NewBIP340Signature(data []byte) (*BIP340Signature, error) { - var sig BIP340Signature err := sig.Unmarshal(data) diff --git a/x/btccheckpoint/keeper/keeper.go b/x/btccheckpoint/keeper/keeper.go index 265abf17d..b9219f4b5 100644 --- a/x/btccheckpoint/keeper/keeper.go +++ b/x/btccheckpoint/keeper/keeper.go @@ -66,7 +66,6 @@ func NewKeeper( powLimit *big.Int, authority string, ) Keeper { - return Keeper{ cdc: cdc, storeService: storeService, @@ -126,7 +125,6 @@ func (k Keeper) checkAncestors( submisionEpoch uint64, newSubmissionInfo *types.SubmissionBtcInfo, ) error { - if submisionEpoch <= 1 { // do not need to check ancestors for epoch 0 and 1 return nil @@ -215,7 +213,6 @@ func (k Keeper) getEpochChanges( ctx context.Context, parentEpochBestSubmission *types.SubmissionBtcInfo, ed *types.EpochData) *epochChangesSummary { - var submissionsToKeep []*types.SubmissionKey var submissionsToDelete []*types.SubmissionKey var currentEpochBestSubmission *types.SubmissionBtcInfo diff --git a/x/btccheckpoint/keeper/msg_server.go b/x/btccheckpoint/keeper/msg_server.go index c46fd6fdf..8af0084b4 100644 --- a/x/btccheckpoint/keeper/msg_server.go +++ b/x/btccheckpoint/keeper/msg_server.go @@ -26,7 +26,6 @@ func NewMsgServerImpl(keeper Keeper) types.MsgServer { // TODO emit some events for external consumers. Those should be probably emitted // at EndBlockerCallback func (ms msgServer) InsertBTCSpvProof(ctx context.Context, req *types.MsgInsertBTCSpvProof) (*types.MsgInsertBTCSpvProofResponse, error) { - // Get the SDK wrapped context sdkCtx := sdk.UnwrapSDKContext(ctx) diff --git a/x/btccheckpoint/types/btcutils.go b/x/btccheckpoint/types/btcutils.go index 02dedcd74..0edeb5d47 100644 --- a/x/btccheckpoint/types/btcutils.go +++ b/x/btccheckpoint/types/btcutils.go @@ -57,7 +57,6 @@ func min(a, b uint) uint { // of the leaf which supposed to be proven // it returns list of hashes required to prove given index func createBranch(nodes []*chainhash.Hash, numfLeafs uint, idx uint) []*chainhash.Hash { - var branch []*chainhash.Hash // size represents number of merkle nodes at given level. At 0 level, number of @@ -71,7 +70,6 @@ func createBranch(nodes []*chainhash.Hash, numfLeafs uint, idx uint) []*chainhas var i uint = 0 for size > 1 { - // index^1 means we want to get sibling of the node we are proving // ie. for index=2, index^1 = 3 and for index=3 index^1=2 // so xoring last bit by 1, select node opposite to the node we want the proof diff --git a/x/btclightclient/keeper/grpc_query.go b/x/btclightclient/keeper/grpc_query.go index 9024cc605..53081ea36 100644 --- a/x/btclightclient/keeper/grpc_query.go +++ b/x/btclightclient/keeper/grpc_query.go @@ -195,7 +195,6 @@ func (k Keeper) BaseHeader(ctx context.Context, req *types.QueryBaseHeaderReques } func (k Keeper) HeaderDepth(ctx context.Context, req *types.QueryHeaderDepthRequest) (*types.QueryHeaderDepthResponse, error) { - if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/btclightclient/types/btc_light_client.go b/x/btclightclient/types/btc_light_client.go index 25ad59f70..aa25f0f6b 100644 --- a/x/btclightclient/types/btc_light_client.go +++ b/x/btclightclient/types/btc_light_client.go @@ -31,7 +31,6 @@ var _ blockchain.ChainCtx = (*lightChainCtx)(nil) func newLightChainCtx(params *chaincfg.Params, blocksPerRetarget int32, minRetargetTimespan, maxRetargetTimespan int64) *lightChainCtx { - return &lightChainCtx{ params: params, blocksPerRetarget: blocksPerRetarget, @@ -90,7 +89,6 @@ func newLocalHeaderInfo( header *wire.BlockHeader, height uint32, totalWork sdkmath.Uint) *localHeaderInfo { - return &localHeaderInfo{ header: header, height: height, @@ -142,7 +140,6 @@ var _ blockchain.HeaderCtx = (*lightHeaderCtx)(nil) func newLightHeaderCtx(height uint32, header *wire.BlockHeader, store *storeWithExtensionChain) *lightHeaderCtx { - return &lightHeaderCtx{ height: height, bits: header.Bits, @@ -176,7 +173,6 @@ func (l *lightHeaderCtx) Parent() blockchain.HeaderCtx { func (l *lightHeaderCtx) RelativeAncestorCtx( distance int32) blockchain.HeaderCtx { - ancestorHeight := l.Height() - distance if ancestorHeight < 0 { @@ -273,7 +269,6 @@ func newStoreWithExtensionChain( store BtcChainReadStore, maxExentsionHeaders int, ) *storeWithExtensionChain { - return &storeWithExtensionChain{ // large capacity to avoid reallocation headers: make([]*localHeaderInfo, 0, maxExentsionHeaders), diff --git a/x/btclightclient/types/codec.go b/x/btclightclient/types/codec.go index c1e243974..4ac4ea8d9 100644 --- a/x/btclightclient/types/codec.go +++ b/x/btclightclient/types/codec.go @@ -11,7 +11,6 @@ func RegisterCodec(_ *codec.LegacyAmino) { } func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - // Register messages registry.RegisterImplementations((*sdk.Msg)(nil), &MsgInsertHeaders{}, diff --git a/x/btcstaking/keeper/btc_delegations.go b/x/btcstaking/keeper/btc_delegations.go index 83cf1b571..c4d940e7f 100644 --- a/x/btcstaking/keeper/btc_delegations.go +++ b/x/btcstaking/keeper/btc_delegations.go @@ -150,7 +150,6 @@ func (k Keeper) addCovenantSigsToBTCDelegation( panic(fmt.Errorf("failed to emit emit for the new verified BTC delegation: %w", err)) } } - } } diff --git a/x/btcstaking/types/btc_slashing_tx.go b/x/btcstaking/types/btc_slashing_tx.go index 7258fdea6..d420a3bf0 100644 --- a/x/btcstaking/types/btc_slashing_tx.go +++ b/x/btcstaking/types/btc_slashing_tx.go @@ -237,14 +237,12 @@ func (tx *BTCSlashingTx) EncVerifyAdaptorSignatures( valPKs []bbn.BIP340PubKey, sigs [][]byte, ) error { - _, err := tx.ParseEncVerifyAdaptorSignatures(fundingOut, slashingSpendInfo, pk, valPKs, sigs) if err != nil { return err } return nil - } // findFPIdxInWitness returns the index of the finality provider's signature diff --git a/x/btcstaking/types/pop.go b/x/btcstaking/types/pop.go index bbfbaafc1..97b014cf9 100644 --- a/x/btcstaking/types/pop.go +++ b/x/btcstaking/types/pop.go @@ -92,7 +92,6 @@ func newBIP322Sig[A btcutil.Address]( net *chaincfg.Params, bip322SignFn bip322Sign[A], ) ([]byte, error) { - address, witnessSignture, err := bip322SignFn( msgToSign, btcSK, @@ -259,7 +258,6 @@ func isSupportedAddressAndWitness( } return nil - }, nil } diff --git a/x/checkpointing/types/codec.go b/x/checkpointing/types/codec.go index 6f5610d04..210cb05da 100644 --- a/x/checkpointing/types/codec.go +++ b/x/checkpointing/types/codec.go @@ -11,7 +11,6 @@ func RegisterCodec(cdc *codec.LegacyAmino) { } func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - // Register messages registry.RegisterImplementations((*sdk.Msg)(nil), &MsgWrappedCreateValidator{}, diff --git a/x/checkpointing/types/types.go b/x/checkpointing/types/types.go index aaeba6b2c..73893b2b3 100644 --- a/x/checkpointing/types/types.go +++ b/x/checkpointing/types/types.go @@ -57,7 +57,6 @@ func (cm *RawCheckpointWithMeta) Accumulate( signerBlsKey bls12381.PublicKey, sig bls12381.Signature, totalPower int64) error { - // the checkpoint should be accumulating if cm.Status != Accumulating { return ErrCkptNotAccumulating diff --git a/x/epoching/keeper/keeper.go b/x/epoching/keeper/keeper.go index f0eacc6c0..bb75139ae 100644 --- a/x/epoching/keeper/keeper.go +++ b/x/epoching/keeper/keeper.go @@ -2,6 +2,7 @@ package keeper import ( "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" corestoretypes "cosmossdk.io/core/store" @@ -32,7 +33,6 @@ func NewKeeper( stk types.StakingKeeper, authority string, ) Keeper { - return Keeper{ cdc: cdc, storeService: storeService, diff --git a/x/epoching/types/genesis.go b/x/epoching/types/genesis.go index 9fec52433..2b7ca883f 100644 --- a/x/epoching/types/genesis.go +++ b/x/epoching/types/genesis.go @@ -20,6 +20,5 @@ func NewGenesis(params Params) *GenesisState { // Validate performs basic genesis state validation returning an error upon any // failure. func (gs GenesisState) Validate() error { - return gs.Params.Validate() } From a6407be5470b089991de44527b0a4facc6a03274 Mon Sep 17 00:00:00 2001 From: RafilxTenfen Date: Wed, 20 Nov 2024 20:55:30 -0300 Subject: [PATCH 4/8] fix: lint issueson btc utils --- x/btccheckpoint/keeper/submissions.go | 9 +++++---- x/btccheckpoint/types/btcutils.go | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/x/btccheckpoint/keeper/submissions.go b/x/btccheckpoint/keeper/submissions.go index 3ea2cc2b1..50f284600 100644 --- a/x/btccheckpoint/keeper/submissions.go +++ b/x/btccheckpoint/keeper/submissions.go @@ -3,9 +3,10 @@ package keeper import ( "context" "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" "math" + sdk "github.com/cosmos/cosmos-sdk/types" + "cosmossdk.io/store/prefix" bbn "github.com/babylonlabs-io/babylon/types" "github.com/babylonlabs-io/babylon/x/btccheckpoint/types" @@ -123,11 +124,11 @@ func (k Keeper) checkSubmissionStatus(ctx context.Context, info *types.Submissio subDepth := info.SubmissionDepth() if subDepth >= k.GetParams(ctx).CheckpointFinalizationTimeout { return types.Finalized - } else if subDepth >= k.GetParams(ctx).BtcConfirmationDepth { + } + if subDepth >= k.GetParams(ctx).BtcConfirmationDepth { return types.Confirmed - } else { - return types.Submitted } + return types.Submitted } func (k Keeper) GetSubmissionBtcInfo(ctx context.Context, sk types.SubmissionKey) (*types.SubmissionBtcInfo, error) { diff --git a/x/btccheckpoint/types/btcutils.go b/x/btccheckpoint/types/btcutils.go index 0edeb5d47..17ad852da 100644 --- a/x/btccheckpoint/types/btcutils.go +++ b/x/btccheckpoint/types/btcutils.go @@ -81,11 +81,11 @@ func createBranch(nodes []*chainhash.Hash, numfLeafs uint, idx uint) []*chainhas branch = append(branch, nodes[i+j]) // divide index by 2 as there are two times less nodes on second level - index = index >> 1 + index >>= 1 // after getting node at this level we move to next one by advancing i by // the size of the current level - i = i + size + i += size // update the size to the next level size i.e (current level size / 2) // + 1 is needed to correctly account for cases that the last node of the level From da1ed05569687bc1c1e31d4ee356bdc04502442b Mon Sep 17 00:00:00 2001 From: RafilxTenfen Date: Wed, 20 Nov 2024 21:11:21 -0300 Subject: [PATCH 5/8] fix: lint issues --- .golangci.yml | 4 +-- x/btccheckpoint/client/cli/query.go | 2 +- x/btccheckpoint/genesis_test.go | 2 ++ x/btccheckpoint/keeper/grpc_query_test.go | 3 +- x/btccheckpoint/keeper/keeper_test.go | 4 ++- x/btccheckpoint/keeper/msg_server.go | 5 --- x/btccheckpoint/keeper/msg_server_test.go | 35 ++++++++++++--------- x/btccheckpoint/keeper/params_test.go | 1 + x/btccheckpoint/module.go | 9 +++--- x/btccheckpoint/types/btcutils_test.go | 14 ++++----- x/btccheckpoint/types/genesis_test.go | 3 ++ x/btccheckpoint/types/mock_keepers.go | 38 +++++++++++------------ x/btccheckpoint/types/params_test.go | 1 + 13 files changed, 66 insertions(+), 55 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 430555e3d..7aa12c5e2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -37,9 +37,9 @@ linters: - misspell - nakedret - nilerr -# - nlreturn # Style wise I personally like this one, todo(lazar): unlax at somepoint, good practice + # - nlreturn # Style wise I personally like this one, todo(lazar): unlax at somepoint, good practice - noctx - - nonamedreturns + # - nonamedreturns # Named returns in functions help understand what they do - nosprintfhostport - paralleltest - reassign diff --git a/x/btccheckpoint/client/cli/query.go b/x/btccheckpoint/client/cli/query.go index 43124c93c..b95bc8d29 100644 --- a/x/btccheckpoint/client/cli/query.go +++ b/x/btccheckpoint/client/cli/query.go @@ -14,7 +14,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(queryRoute string) *cobra.Command { +func GetQueryCmd() *cobra.Command { // Group btccheckpoint queries under a subcommand cmd := &cobra.Command{ Use: types.ModuleName, diff --git a/x/btccheckpoint/genesis_test.go b/x/btccheckpoint/genesis_test.go index 3032f15dd..f3d854f95 100644 --- a/x/btccheckpoint/genesis_test.go +++ b/x/btccheckpoint/genesis_test.go @@ -11,6 +11,7 @@ import ( ) func TestExportGenesis(t *testing.T) { + t.Parallel() app := simapp.Setup(t, false) ctx := app.BaseApp.NewContext(false) @@ -23,6 +24,7 @@ func TestExportGenesis(t *testing.T) { } func TestInitGenesis(t *testing.T) { + t.Parallel() app := simapp.Setup(t, false) ctx := app.BaseApp.NewContext(false) diff --git a/x/btccheckpoint/keeper/grpc_query_test.go b/x/btccheckpoint/keeper/grpc_query_test.go index 7767124cf..ef3fdc976 100644 --- a/x/btccheckpoint/keeper/grpc_query_test.go +++ b/x/btccheckpoint/keeper/grpc_query_test.go @@ -14,6 +14,7 @@ import ( ) func TestBtcCheckpointInfo(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) epoch := uint64(1) raw, btcRaw := dg.RandomRawCheckpointDataForEpoch(r, epoch) @@ -40,7 +41,7 @@ func TestBtcCheckpointInfo(t *testing.T) { // gather info for verifying with response. btcInfo := resp.Info - blkHeight, err := tk.BTCLightClient.BlockHeight(tk.Ctx, nil) + blkHeight, err := tk.BTCLightClient.BlockHeight(tk.SdkCtx, nil) require.NoErrorf(t, err, "Unexpected message processing error: %v", err) rawSubmission, err := types.ParseSubmission(msg, tk.BTCCheckpoint.GetPowLimit(), tk.BTCCheckpoint.GetExpectedTag(tk.SdkCtx)) diff --git a/x/btccheckpoint/keeper/keeper_test.go b/x/btccheckpoint/keeper/keeper_test.go index f1a0ded46..f102390e1 100644 --- a/x/btccheckpoint/keeper/keeper_test.go +++ b/x/btccheckpoint/keeper/keeper_test.go @@ -11,6 +11,7 @@ import ( ) func TestKeeper_GetSubmissionBtcInfo(t *testing.T) { + t.Parallel() type TxKeyDesc struct { TxIdx uint32 Depth uint32 @@ -37,6 +38,7 @@ func TestKeeper_GetSubmissionBtcInfo(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) k := InitTestKeepers(t) @@ -77,7 +79,7 @@ func FuzzGetSubmissionBtcInfo(f *testing.F) { if txidx1 == txidx2 { // transaction indexes must be different to cover the case where transactions are // in the same block. - txidx1 = txidx1 + 1 + txidx1++ } k := InitTestKeepers(t) diff --git a/x/btccheckpoint/keeper/msg_server.go b/x/btccheckpoint/keeper/msg_server.go index 8af0084b4..90814767e 100644 --- a/x/btccheckpoint/keeper/msg_server.go +++ b/x/btccheckpoint/keeper/msg_server.go @@ -30,19 +30,16 @@ func (ms msgServer) InsertBTCSpvProof(ctx context.Context, req *types.MsgInsertB sdkCtx := sdk.UnwrapSDKContext(ctx) rawSubmission, err := types.ParseSubmission(req, ms.k.GetPowLimit(), ms.k.GetExpectedTag(sdkCtx)) - if err != nil { return nil, types.ErrInvalidCheckpointProof.Wrap(err.Error()) } submissionKey := rawSubmission.GetSubmissionKey() - if ms.k.HasSubmission(sdkCtx, submissionKey) { return nil, types.ErrDuplicatedSubmission } newSubmissionOldestHeaderDepth, err := ms.k.GetSubmissionBtcInfo(sdkCtx, submissionKey) - if err != nil { return nil, types.ErrInvalidHeader.Wrap(err.Error()) } @@ -54,7 +51,6 @@ func (ms msgServer) InsertBTCSpvProof(ctx context.Context, req *types.MsgInsertB // - this is new checkpoint submission // Verify if this is expected checkpoint err = ms.k.checkpointingKeeper.VerifyCheckpoint(sdkCtx, rawSubmission.CheckpointData) - if err != nil { return nil, err } @@ -64,7 +60,6 @@ func (ms msgServer) InsertBTCSpvProof(ctx context.Context, req *types.MsgInsertB epochNum := rawSubmission.CheckpointData.Epoch err = ms.k.checkAncestors(sdkCtx, epochNum, newSubmissionOldestHeaderDepth) - if err != nil { return nil, err } diff --git a/x/btccheckpoint/keeper/msg_server_test.go b/x/btccheckpoint/keeper/msg_server_test.go index 3d4c7266c..a998dbccd 100644 --- a/x/btccheckpoint/keeper/msg_server_test.go +++ b/x/btccheckpoint/keeper/msg_server_test.go @@ -2,7 +2,7 @@ package keeper_test import ( "bytes" - "context" + "errors" "math" "math/rand" "testing" @@ -23,7 +23,6 @@ import ( type TestKeepers struct { SdkCtx sdk.Context - Ctx context.Context BTCLightClient *btcctypes.MockBTCLightClientKeeper Checkpointing *btcctypes.MockCheckpointingKeeper Incentive *btcctypes.MockIncentiveKeeper @@ -51,12 +50,10 @@ func InitTestKeepers( ic := btcctypes.NewMockIncentiveKeeper() k, ctx := keepertest.NewBTCCheckpointKeeper(t, lc, cc, ic, chaincfg.SimNetParams.PowLimit) - srv := bkeeper.NewMsgServerImpl(*k) return &TestKeepers{ SdkCtx: ctx, - Ctx: ctx, BTCLightClient: lc, Checkpointing: cc, Incentive: ic, @@ -66,7 +63,7 @@ func InitTestKeepers( } func (k *TestKeepers) insertProofMsg(msg *btcctypes.MsgInsertBTCSpvProof) (*btcctypes.MsgInsertBTCSpvProofResponse, error) { - return k.MsgSrv.InsertBTCSpvProof(k.Ctx, msg) + return k.MsgSrv.InsertBTCSpvProof(k.SdkCtx, msg) } func (k *TestKeepers) GetEpochData(e uint64) *btcctypes.EpochData { @@ -82,6 +79,7 @@ func (k *TestKeepers) onTipChange() { } func TestUpdateParams(t *testing.T) { + t.Parallel() tk := InitTestKeepers(t) // Try to update params with a different checkpoint finalization timeout @@ -92,7 +90,7 @@ func TestUpdateParams(t *testing.T) { }, } - _, err := tk.MsgSrv.UpdateParams(tk.Ctx, msg) + _, err := tk.MsgSrv.UpdateParams(tk.SdkCtx, msg) require.ErrorIs(t, err, govtypes.ErrInvalidProposalMsg, "should not be able to change CheckpointFinalizationTimeout parameter") @@ -103,6 +101,7 @@ func TestUpdateParams(t *testing.T) { } func TestRejectDuplicatedSubmission(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) epoch := uint64(1) raw, _ := dg.RandomRawCheckpointDataForEpoch(r, epoch) @@ -132,12 +131,13 @@ func TestRejectDuplicatedSubmission(t *testing.T) { t.Fatalf("Submission should have failed due to duplicated submission") } - if err != btcctypes.ErrDuplicatedSubmission { + if !errors.Is(err, btcctypes.ErrDuplicatedSubmission) { t.Fatalf("Error should indicate duplicated submissions") } } func TestRejectUnknownToBtcLightClient(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) epoch := uint64(1) raw, _ := dg.RandomRawCheckpointDataForEpoch(r, epoch) @@ -162,6 +162,7 @@ func TestRejectUnknownToBtcLightClient(t *testing.T) { } func TestSubmitValidNewCheckpoint(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) epoch := uint64(1) raw, rawBtcCheckpoint := dg.RandomRawCheckpointDataForEpoch(r, epoch) @@ -228,6 +229,7 @@ func TestSubmitValidNewCheckpoint(t *testing.T) { } func TestRejectSubmissionWithoutSubmissionsForPreviousEpoch(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) epoch := uint64(2) raw, _ := dg.RandomRawCheckpointDataForEpoch(r, epoch) @@ -254,6 +256,7 @@ func TestRejectSubmissionWithoutSubmissionsForPreviousEpoch(t *testing.T) { } func TestRejectSubmissionWithoutAncestorsOnMainchainInPreviousEpoch(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) epoch := uint64(1) raw, _ := dg.RandomRawCheckpointDataForEpoch(r, epoch) @@ -322,12 +325,11 @@ func TestRejectSubmissionWithoutAncestorsOnMainchainInPreviousEpoch(t *testing.T tk.BTCLightClient.SetDepth(epoch2Block2.HeaderBytes.Hash(), uint32(2)) _, err = tk.insertProofMsg(msg2) - require.NoErrorf(t, err, "Unexpected message processing error: %v", err) - } func TestClearChildEpochsWhenNoParenNotOnMainChain(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) tk := InitTestKeepers(t) @@ -412,6 +414,7 @@ func TestClearChildEpochsWhenNoParenNotOnMainChain(t *testing.T) { } func TestLeaveOnlyBestSubmissionWhenEpochFinalized(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) tk := InitTestKeepers(t) defaultParams := btcctypes.DefaultParams() @@ -461,6 +464,7 @@ func TestLeaveOnlyBestSubmissionWhenEpochFinalized(t *testing.T) { } func TestTxIdxShouldBreakTies(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) tk := InitTestKeepers(t) defaultParams := btcctypes.DefaultParams() @@ -510,6 +514,7 @@ func TestTxIdxShouldBreakTies(t *testing.T) { } func TestStateTransitionOfValidSubmission(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) epoch := uint64(1) defaultParams := btcctypes.DefaultParams() @@ -612,32 +617,32 @@ func FuzzConfirmAndDinalizeManyEpochs(f *testing.F) { if epoch <= uint64(numFinalizedEpochs) { tk.BTCLightClient.SetDepth(blck1.HeaderBytes.Hash(), uint32(finalizationDepth)) - finalizationDepth = finalizationDepth - 1 + finalizationDepth-- tk.BTCLightClient.SetDepth(blck2.HeaderBytes.Hash(), uint32(finalizationDepth)) // first submission is always deepest one, and second block is the most recent one if j == 1 { bestSumbissionInfos[epoch] = uint32(finalizationDepth) } - finalizationDepth = finalizationDepth - 1 + finalizationDepth-- } else if epoch <= uint64(numFinalizedEpochs+numConfirmedEpochs) { tk.BTCLightClient.SetDepth(blck1.HeaderBytes.Hash(), confirmationDepth) - confirmationDepth = confirmationDepth - 1 + confirmationDepth-- tk.BTCLightClient.SetDepth(blck2.HeaderBytes.Hash(), confirmationDepth) // first submission is always deepest one, and second block is the most recent one if j == 1 { bestSumbissionInfos[epoch] = confirmationDepth } - confirmationDepth = confirmationDepth - 1 + confirmationDepth-- } else { tk.BTCLightClient.SetDepth(blck1.HeaderBytes.Hash(), sumbissionDepth) - sumbissionDepth = sumbissionDepth - 1 + sumbissionDepth-- tk.BTCLightClient.SetDepth(blck2.HeaderBytes.Hash(), sumbissionDepth) // first submission is always deepest one, and second block is the most recent one if j == 1 { bestSumbissionInfos[epoch] = sumbissionDepth } - sumbissionDepth = sumbissionDepth - 1 + sumbissionDepth-- } _, err := tk.insertProofMsg(msg) diff --git a/x/btccheckpoint/keeper/params_test.go b/x/btccheckpoint/keeper/params_test.go index 08b049012..ace20bb03 100644 --- a/x/btccheckpoint/keeper/params_test.go +++ b/x/btccheckpoint/keeper/params_test.go @@ -9,6 +9,7 @@ import ( ) func TestGetParams(t *testing.T) { + t.Parallel() k, ctx := testkeeper.NewBTCCheckpointKeeper(t, nil, nil, nil, nil) params := types.DefaultParams() diff --git a/x/btccheckpoint/module.go b/x/btccheckpoint/module.go index c91660855..9ff07a09a 100644 --- a/x/btccheckpoint/module.go +++ b/x/btccheckpoint/module.go @@ -2,10 +2,11 @@ package btccheckpoint import ( "context" - "cosmossdk.io/core/appmodule" "encoding/json" "fmt" + "cosmossdk.io/core/appmodule" + "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" @@ -66,7 +67,7 @@ func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { } // ValidateGenesis performs genesis state validation for the capability module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { var genState types.GenesisState if err := cdc.UnmarshalJSON(bz, &genState); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -75,7 +76,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod } // RegisterRESTRoutes registers the capability module's REST service handlers. -func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) { } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. @@ -92,7 +93,7 @@ func (a AppModuleBasic) GetTxCmd() *cobra.Command { // GetQueryCmd returns the capability module's root query command. func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(types.StoreKey) + return cli.GetQueryCmd() } // ---------------------------------------------------------------------------- diff --git a/x/btccheckpoint/types/btcutils_test.go b/x/btccheckpoint/types/btcutils_test.go index c632ee3ff..5b8b292ef 100644 --- a/x/btccheckpoint/types/btcutils_test.go +++ b/x/btccheckpoint/types/btcutils_test.go @@ -20,6 +20,7 @@ import ( // Sanity test checking mostly btcd code, that we can really parse bitcoin transaction func TestBtcTransactionParsing(t *testing.T) { + t.Parallel() // Few randomly chosen btc valid btc transactions tests := []struct { bitcoinTransactionHex string @@ -29,7 +30,7 @@ func TestBtcTransactionParsing(t *testing.T) { {"0100000001f0606dd02119ee3660156250762a26bf17be8edef3789dcf67a12586a8be4676000000006a47304402202e02ef95a2958bd302668a0b64e7ed8e886efaea7103b077f1882c576ae443db022059f8d853d17b5bdeedbe0cd41be98ad412237743c8bf07dbb6e90d4627a02ac1012103e13e1a05703b972b47e228bc9459be59e09dad0bc3a54d7d8d9dc20f63b4af48ffffffff02404b4c000000000017a914df6122d5edb7697b466f7201a862b4fd67ea2ac18750ce9000000000001976a914c5b58a131b5a2d751a8176a8f54d1f039ebf9d6188ac00000000", "fb2a3934e40d82744150fd3db3b3b5c09ad5f33f2b873a1b058da0acb5a3838d"}, {"01000000027c918745a69ce4ff8e674fbf059fea3dfdf222f2c15df217b9c4bb218ddb0d38010000008b4830450221008259debd856a0afaf33c918351a75759742061738c5fc0790b5813cbef95566a022022ff0311284290f3a84b4b1d6fd550ed5f71c9d522551e2f225537138050c9a40141048aa0d470b7a9328889c84ef0291ed30346986e22558e80c3ae06199391eae21308a00cdcfb34febc0ea9c80dfd16b01f26c7ec67593cb8ab474aca8fa1d7029dffffffff83a1289fe5b1c5b4bcbd5beeac029fc88ff87272b8deb431155240b952bc00b8000000008a473044022071a59dfccc514273fd9a3f765ea58c7a24cd81a34c8158b636e3507ee374531702200fc40b8689b43469c1607da8bb78f3565e98ad87c7196f00a497dcd17dea57720141048aa0d470b7a9328889c84ef0291ed30346986e22558e80c3ae06199391eae21308a00cdcfb34febc0ea9c80dfd16b01f26c7ec67593cb8ab474aca8fa1d7029dffffffff01287d0200000000001976a91436a5ee46338acf885538ebd709a810b361c93a4388ac00000000", "0418fb71c9c7fc1fb1d383149dc0c01bdc6894d867535b2758ceae57e83ab805"}, {"0100000001ab8ead1a89e7959d1aa325b1b619ccb164bc9b77cc6d2decfb064f120951af5b000000006a47304402200ad6ba00c17d78095e1e46203e438d02179345b87a4f9af2eed985ddf7b7432a0220738e94e64ba6a576166cec83dbcdc7e827c1479eab1df50f8cf323fa71db4b89012103bb6e200caa87be8296d5b4398684729f27c7d44f9b29ab96640793fdd23a864affffffff1437020000000000001976a914425245544852454e0a0a6168696d73612d64657688ac37020000000000001976a91412cd026060604265666f72652049206c6566742088ac37020000000000001976a914536f757468204166726963612c2061206c616e6488ac37020000000000001976a9142049206c6f76652070617373696f6e6174656c7988ac37020000000000001976a9142c2077652068616420616e20656d657267656e6388ac37020000000000001976a91479206d656574696e67206f66207468652045786588ac37020000000000001976a91463757469766520436f6d6d6974746565206f662088ac37020000000000001976a91474686520536f757468204166726963616e20436f88ac37020000000000001976a914756e63696c206f6620436875726368657320776988ac37020000000000001976a914746820746865206c656164657273206f66206f7588ac37020000000000001976a91472206d656d6265722063687572636865732e205788ac37020000000000001976a914652063616c6c656420746865206d656574696e6788ac37020000000000001976a9142062656361757365206f6620746865206465657088ac37020000000000001976a914656e696e672063726973697320696e206f75722088ac37020000000000001976a9146c616e642c2077686963682068617320636c616988ac37020000000000001976a9146d6564206e6561726c7920323030206c6976657388ac37020000000000001976a9142074686973207965617220616c6f6e652e60606088ac37020000000000001976a9140a0a2d2d4465736d6f6e64205475747518e88ffa88ac37020000000000001976a914ac0500000000000000000000000000000000000088ac237c4400000000001976a9148fe22047956d1510f84018a3f3ab91686b82f2ea88ac00000000", "cac99ea9fc912ef42b4059add3d853c722d32be8b903fef24e7fd08f05960eab"}, - //this one has op_return data + // this one has op_return data {"01000000018dc21dfe0dae9c213b015c496da276fd090ad4ba22386f53b28985f374e50b28020000006a47304402207ac812172733436bd0ee318aa3064da7e49e212f59a3e62f7a6f3b6f11220b5f0220690b7174a607e64eed5e2ae3622f5d5fcffc7f947523d23bd428ade7897f55220121030229d577f4d7b45d50b55dd93e5024561baa6ddf3ba29188d43b9b357618e896ffffffff03c8190000000000001976a914c4a0be51e3280054bcfc7471182ddbaf3bb3c58e88ac0000000000000000396a374f4101000101303030303030303030303030303031333130326574597668696c646c6d4762746a54694c3648494f776a4b64756e6f4d559082b302000000001976a914c4a0be51e3280054bcfc7471182ddbaf3bb3c58e88ac00000000", "af5575e0a1ae1ca1bbca55f74f7504ef9bc50280a7da9bd5ce210d8a4392ea33"}, // op_return and 4 outputs {"0100000001b9e93d75c8bb80716709ff41d6a89585c9408b50cf4f5c6f6404a7e8f23d3b7006000000fb00473044022036f79054547c3696b87abc30bbfd4815f49199c8d3adbacfe798ce2c91775264022036dfd5a59ef722c568580f818cee19cf4da9d9be638833573fd811d7888d9291014630430220239b77e69f536f5f9e22bf6286d3f7bddb9493e087583563e090dfaeab1dbe29021f2dd263ca25643469652bba0cf1cc2c753318acc4599e275d163408943a3d07014c69522102081bc3fe67cf4fe2397c9c232993aaff3ddbad39982253d3e09ef8f6655d958721037d8ab0e3bc36818067d042b9a714363ee36a6e4e3c5c3c35b785377a43cef0d22103b1a264f3fd81af6bd775aaae218444302945c78a711e05679107ffc713be12fc53aeffffffff0500000000000000000b6a095349474e4154555245aee353000000000017a914715b26c59e87d9247fb0b0171e85c32f5f0a6f7787fb750e000000000017a914ff718c1a44a41fe1decc73d601cb3b5f0c189377871b5b03000000000017a9144a456da09638ebb610364742f51713d379908257877c3613000000000017a914887fee10bad2a610796eefec5aeddcb607045a618700000000", "4ad274333d08cd55981b217017fa209d3c435364c94a42f666c83a551d67961b"}, @@ -39,21 +40,20 @@ func TestBtcTransactionParsing(t *testing.T) { txBytes, _ := hex.DecodeString(test.bitcoinTransactionHex) hashBytes, _ := chainhash.NewHashFromStr(test.txHash) - tx, e := btcctypes.ParseTransaction(txBytes) - - if e != nil { + tx, err := btcctypes.ParseTransaction(txBytes) + if err != nil { t.Errorf("Failed to parse valid bitcoin transaction %d", i) } if !tx.Hash().IsEqual(hashBytes) { t.Errorf("Hash of decoded transaction does not match provided hash %d", i) } - } } // All data here is taken from btc testnet func TestParsingCorrectBtcProofs(t *testing.T) { + t.Parallel() tests := []struct { header string transactions []string @@ -132,9 +132,7 @@ func TestParsingCorrectBtcProofs(t *testing.T) { } for i, test := range tests { - headerBytes, _ := bbn.NewBTCHeaderBytesFromHex(test.header) - var transactionBytes [][]byte for _, tx := range test.transactions { @@ -181,6 +179,7 @@ func buildOpReturnOutput(t *testing.T, r *rand.Rand, dataLen int) *wire.TxOut { } func TestExtractingOpReturn(t *testing.T) { + t.Parallel() tests := []struct { name string buildTxFn func(t *testing.T, r *rand.Rand) *btcutil.Tx @@ -260,6 +259,7 @@ func TestExtractingOpReturn(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) tx := tt.buildTxFn(t, r) data, err := btcctypes.ExtractStandardOpReturnData(tx) diff --git a/x/btccheckpoint/types/genesis_test.go b/x/btccheckpoint/types/genesis_test.go index aa5c98b5d..18b84f79a 100644 --- a/x/btccheckpoint/types/genesis_test.go +++ b/x/btccheckpoint/types/genesis_test.go @@ -8,6 +8,8 @@ import ( ) func TestGenesisState_Validate(t *testing.T) { + t.Parallel() + for _, tc := range []struct { desc string genState *types.GenesisState @@ -31,6 +33,7 @@ func TestGenesisState_Validate(t *testing.T) { }, } { t.Run(tc.desc, func(t *testing.T) { + t.Parallel() err := tc.genState.Validate() if tc.valid { require.NoError(t, err) diff --git a/x/btccheckpoint/types/mock_keepers.go b/x/btccheckpoint/types/mock_keepers.go index bc4e809d6..6e41877d0 100644 --- a/x/btccheckpoint/types/mock_keepers.go +++ b/x/btccheckpoint/types/mock_keepers.go @@ -38,29 +38,29 @@ func NewMockIncentiveKeeper() *MockIncentiveKeeper { return &MockIncentiveKeeper{} } -func (mc *MockCheckpointingKeeper) ReturnError() { - mc.returnError = true +func (m *MockCheckpointingKeeper) ReturnError() { + m.returnError = true } -func (mc *MockCheckpointingKeeper) ReturnSuccess() { - mc.returnError = false +func (m *MockCheckpointingKeeper) ReturnSuccess() { + m.returnError = false } -func (mc *MockBTCLightClientKeeper) SetDepth(header *bbn.BTCHeaderHashBytes, dd uint32) { - mc.headers[header.String()] = dd +func (m *MockBTCLightClientKeeper) SetDepth(header *bbn.BTCHeaderHashBytes, dd uint32) { + m.headers[header.String()] = dd } -func (mc *MockBTCLightClientKeeper) DeleteHeader(header *bbn.BTCHeaderHashBytes) { - delete(mc.headers, header.String()) +func (m *MockBTCLightClientKeeper) DeleteHeader(header *bbn.BTCHeaderHashBytes) { + delete(m.headers, header.String()) } -func (mb MockBTCLightClientKeeper) BlockHeight(ctx context.Context, header *bbn.BTCHeaderHashBytes) (uint32, error) { +func (m MockBTCLightClientKeeper) BlockHeight(ctx context.Context, header *bbn.BTCHeaderHashBytes) (uint32, error) { // todo not used return uint32(10), nil } -func (ck MockBTCLightClientKeeper) MainChainDepth(ctx context.Context, headerBytes *bbn.BTCHeaderHashBytes) (uint32, error) { - depth, ok := ck.headers[headerBytes.String()] +func (m MockBTCLightClientKeeper) MainChainDepth(ctx context.Context, headerBytes *bbn.BTCHeaderHashBytes) (uint32, error) { + depth, ok := m.headers[headerBytes.String()] if ok { return depth, nil } else { @@ -68,8 +68,8 @@ func (ck MockBTCLightClientKeeper) MainChainDepth(ctx context.Context, headerByt } } -func (ck MockCheckpointingKeeper) VerifyCheckpoint(ctx context.Context, checkpoint txformat.RawBtcCheckpoint) error { - if ck.returnError { +func (m MockCheckpointingKeeper) VerifyCheckpoint(ctx context.Context, checkpoint txformat.RawBtcCheckpoint) error { + if m.returnError { return errors.New("bad checkpoints") } @@ -78,26 +78,26 @@ func (ck MockCheckpointingKeeper) VerifyCheckpoint(ctx context.Context, checkpoi // SetCheckpointSubmitted Informs checkpointing module that checkpoint was // successfully submitted on btc chain. -func (ck MockCheckpointingKeeper) SetCheckpointSubmitted(ctx context.Context, epoch uint64) { +func (m MockCheckpointingKeeper) SetCheckpointSubmitted(ctx context.Context, epoch uint64) { } // SetCheckpointConfirmed Informs checkpointing module that checkpoint was // successfully submitted on btc chain, and it is at least K-deep on the main chain -func (ck MockCheckpointingKeeper) SetCheckpointConfirmed(ctx context.Context, epoch uint64) { +func (m MockCheckpointingKeeper) SetCheckpointConfirmed(ctx context.Context, epoch uint64) { } // SetCheckpointFinalized Informs checkpointing module that checkpoint was // successfully submitted on btc chain, and it is at least W-deep on the main chain -func (ck MockCheckpointingKeeper) SetCheckpointFinalized(ctx context.Context, epoch uint64) { +func (m MockCheckpointingKeeper) SetCheckpointFinalized(ctx context.Context, epoch uint64) { } // SetCheckpointForgotten Informs checkpointing module that was in submitted state // lost all its checkpoints and is checkpoint empty -func (ck MockCheckpointingKeeper) SetCheckpointForgotten(ctx context.Context, epoch uint64) { +func (m MockCheckpointingKeeper) SetCheckpointForgotten(ctx context.Context, epoch uint64) { } -func (ik *MockIncentiveKeeper) RewardBTCTimestamping(ctx context.Context, epoch uint64, rewardDistInfo *RewardDistInfo) { +func (m *MockIncentiveKeeper) RewardBTCTimestamping(ctx context.Context, epoch uint64, rewardDistInfo *RewardDistInfo) { } -func (ik *MockIncentiveKeeper) IndexRefundableMsg(ctx context.Context, msg sdk.Msg) { +func (m *MockIncentiveKeeper) IndexRefundableMsg(ctx context.Context, msg sdk.Msg) { } diff --git a/x/btccheckpoint/types/params_test.go b/x/btccheckpoint/types/params_test.go index a534b9a0a..bd52d2244 100644 --- a/x/btccheckpoint/types/params_test.go +++ b/x/btccheckpoint/types/params_test.go @@ -8,6 +8,7 @@ import ( ) func TestParamsEqual(t *testing.T) { + t.Parallel() p1 := types.DefaultParams() p2 := types.DefaultParams() From 9a0b226aa2d050fe8e8768edcb4268ce44cc5b37 Mon Sep 17 00:00:00 2001 From: RafilxTenfen Date: Wed, 20 Nov 2024 21:23:21 -0300 Subject: [PATCH 6/8] fix: lint --- x/btccheckpoint/types/types.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/btccheckpoint/types/types.go b/x/btccheckpoint/types/types.go index 7a55899d2..4c1c78fb8 100644 --- a/x/btccheckpoint/types/types.go +++ b/x/btccheckpoint/types/types.go @@ -140,19 +140,19 @@ func (submission *SubmissionBtcInfo) SubmissionDepth() uint32 { return submission.YoungestBlockDepth } -func (newSubmission *SubmissionBtcInfo) IsBetterThan(currentBestSubmission *SubmissionBtcInfo) bool { - if newSubmission.SubmissionDepth() > currentBestSubmission.SubmissionDepth() { +func (submission *SubmissionBtcInfo) IsBetterThan(currentBestSubmission *SubmissionBtcInfo) bool { + if submission.SubmissionDepth() > currentBestSubmission.SubmissionDepth() { return true } - if newSubmission.SubmissionDepth() < currentBestSubmission.SubmissionDepth() { + if submission.SubmissionDepth() < currentBestSubmission.SubmissionDepth() { return false } // at this point we know that both submissions youngest part happens to be in // the same block. To resolve the tie we need to take into account index of // latest transaction of the submissions - return newSubmission.YoungestBlockLowestTxIdx < currentBestSubmission.YoungestBlockLowestTxIdx + return submission.YoungestBlockLowestTxIdx < currentBestSubmission.YoungestBlockLowestTxIdx } func NewTransactionInfo(txKey *TransactionKey, txBytes []byte, proof []byte) *TransactionInfo { From 5bbbbc57ae8e741bdd8d3e311fb607c420351617 Mon Sep 17 00:00:00 2001 From: KonradStaniec Date: Tue, 3 Dec 2024 11:23:46 +0100 Subject: [PATCH 7/8] Bunch of fixes --- app/ante/ante_btc_validation_decorator.go | 1 - app/app.go | 8 +++---- app/keepers/utils.go | 4 ++-- btcstaking/btcstaking_test.go | 3 +-- btcstaking/staking_test.go | 1 - btcstaking/types.go | 4 ++-- cmd/babylond/cmd/genesis.go | 2 -- cmd/babylond/cmd/root.go | 1 - cmd/babylond/cmd/testnet.go | 4 ---- crypto/bls12381/bls_test.go | 5 ++++ crypto/schnorr-adaptor-signature/keys_test.go | 4 ++-- test/e2e/configurer/upgrade_test.go | 2 +- test/e2e/initialization/config.go | 10 ++++---- testutil/datagen/btc_blockchain.go | 2 +- testutil/datagen/btc_header_info.go | 1 - testutil/datagen/btc_transaction.go | 3 --- testutil/datagen/btcstaking.go | 4 +--- testutil/datagen/genesiskey.go | 3 +-- wasmbinding/test/custom_query_test.go | 2 -- x/btccheckpoint/keeper/submissions.go | 2 -- x/btccheckpoint/types/genesis.go | 1 - x/btccheckpoint/types/mock_keepers.go | 18 +++++++------- x/btclightclient/keeper/grpc_query_test.go | 4 ++-- x/btclightclient/keeper/msg_server_test.go | 2 +- x/btclightclient/keeper/utils_test.go | 1 - x/btclightclient/types/msgs_test.go | 3 +-- x/btcstaking/keeper/grpc_query_test.go | 1 - x/btcstaking/keeper/inclusion_proof.go | 2 +- x/btcstaking/keeper/msg_server_test.go | 4 ++-- x/btcstaking/types/btc_delegation.go | 24 +++++++++---------- x/btcstaking/types/btc_slashing_tx.go | 2 +- x/btcstaking/types/btc_undelegation_test.go | 2 +- .../types/create_delegation_parser.go | 20 ++++++++-------- x/btcstaking/types/genesis.go | 1 - x/btcstaking/types/msg.go | 8 +++---- x/btcstaking/types/msg_test.go | 2 +- .../types/validate_parsed_message_test.go | 3 +-- x/checkpointing/proposal.go | 4 ++-- x/epoching/keeper/hooks.go | 20 ++++++++-------- x/finality/genesis_test.go | 1 - x/finality/keeper/genesis_test.go | 2 +- x/finality/keeper/tallying_bench_test.go | 2 +- x/finality/keeper/tallying_test.go | 2 -- x/monitor/module.go | 11 +++++---- 44 files changed, 90 insertions(+), 116 deletions(-) diff --git a/app/ante/ante_btc_validation_decorator.go b/app/ante/ante_btc_validation_decorator.go index ffe7d21cc..3440b9e47 100644 --- a/app/ante/ante_btc_validation_decorator.go +++ b/app/ante/ante_btc_validation_decorator.go @@ -24,7 +24,6 @@ func NewBtcValidationDecorator( } func (bvd BtcValidationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { - // only do this validation when handling mempool addition. During DeliverTx they // should be performed by btclightclient and btccheckpoint modules if ctx.IsCheckTx() || ctx.IsReCheckTx() { diff --git a/app/app.go b/app/app.go index 924cde78e..ce139428e 100644 --- a/app/app.go +++ b/app/app.go @@ -528,14 +528,14 @@ func NewBabylonApp( wasmkeeper.NewWasmSnapshotter(app.CommitMultiStore(), &app.WasmKeeper), ) if err != nil { - panic(fmt.Errorf("failed to register snapshot extension: %s", err)) + panic(fmt.Errorf("failed to register snapshot extension: %w", err)) } err = manager.RegisterExtensions( ibcwasmkeeper.NewWasmSnapshotter(app.CommitMultiStore(), &app.IBCWasmKeeper), ) if err != nil { - panic(fmt.Errorf("failed to register snapshot extension: %s", err)) + panic(fmt.Errorf("failed to register snapshot extension: %w", err)) } } @@ -722,8 +722,8 @@ func (app *BabylonApp) RegisterNodeService(clientCtx client.Context, cfg config. } // DefaultGenesis returns a default genesis from the registered AppModuleBasic's. -func (a *BabylonApp) DefaultGenesis() map[string]json.RawMessage { - return a.BasicModuleManager.DefaultGenesis(a.appCodec) +func (app *BabylonApp) DefaultGenesis() map[string]json.RawMessage { + return app.BasicModuleManager.DefaultGenesis(app.appCodec) } func (app *BabylonApp) TxConfig() client.TxConfig { diff --git a/app/keepers/utils.go b/app/keepers/utils.go index 7efe4b78a..033b5656c 100644 --- a/app/keepers/utils.go +++ b/app/keepers/utils.go @@ -77,11 +77,11 @@ func saveClientConfig(homePath string, cliConf *config.ClientConfig) error { configPath := filepath.Join(homePath, "config") configFilePath := filepath.Join(configPath, "client.toml") if err = ensureConfigPath(configPath); err != nil { - return fmt.Errorf("couldn't make client config: %v", err) + return fmt.Errorf("couldn't make client config: %w", err) } if err = writeConfigToFile(configFilePath, cliConf); err != nil { - return fmt.Errorf("could not write client config to the file: %v", err) + return fmt.Errorf("could not write client config to the file: %w", err) } return nil diff --git a/btcstaking/btcstaking_test.go b/btcstaking/btcstaking_test.go index 940a4aace..287aa6686 100644 --- a/btcstaking/btcstaking_test.go +++ b/btcstaking/btcstaking_test.go @@ -194,7 +194,6 @@ func GenerateSignatures( stakingOutput *wire.TxOut, leaf txscript.TapLeaf, ) []*schnorr.Signature { - var si []*SignatureInfo for _, key := range keys { @@ -216,7 +215,7 @@ func GenerateSignatures( // sort signatures by public key sortedSigInfo := sortSignatureInfo(si) - var sigs []*schnorr.Signature = make([]*schnorr.Signature, len(sortedSigInfo)) + sigs := make([]*schnorr.Signature, len(sortedSigInfo)) for i, sigInfo := range sortedSigInfo { sig := sigInfo diff --git a/btcstaking/staking_test.go b/btcstaking/staking_test.go index 0f596915a..da28aaf64 100644 --- a/btcstaking/staking_test.go +++ b/btcstaking/staking_test.go @@ -34,7 +34,6 @@ func NewStakingScriptData( fpKey, covenantKey *btcec.PublicKey, stakingTime uint16) (*StakingScriptData, error) { - if stakerKey == nil || fpKey == nil || covenantKey == nil { return nil, fmt.Errorf("staker, finality provider and covenant keys cannot be nil") } diff --git a/btcstaking/types.go b/btcstaking/types.go index c19649361..5c6c72673 100644 --- a/btcstaking/types.go +++ b/btcstaking/types.go @@ -75,7 +75,7 @@ func DeriveTaprootAddress( schnorr.SerializePubKey(outputKey), net) if err != nil { - return nil, fmt.Errorf("error encoding Taproot address: %v", err) + return nil, fmt.Errorf("error encoding Taproot address: %w", err) } return address, nil @@ -400,7 +400,7 @@ func BuildStakingInfo( ) if err != nil { - return nil, fmt.Errorf("%s: %w", errBuildingStakingInfo, err) + return nil, fmt.Errorf("%w: %w", errBuildingStakingInfo, err) } var unbondingPaths [][]byte diff --git a/cmd/babylond/cmd/genesis.go b/cmd/babylond/cmd/genesis.go index 6a992a54c..b546aedd8 100644 --- a/cmd/babylond/cmd/genesis.go +++ b/cmd/babylond/cmd/genesis.go @@ -154,7 +154,6 @@ func PrepareGenesis( if genesis.Consensus == nil { genesis.Consensus = genutiltypes.NewConsensusGenesis(comettypes.DefaultConsensusParams().ToProto(), nil) - } // Set gas limit @@ -305,7 +304,6 @@ func TestnetGenesisParams( jailDuration time.Duration, finalityActivationBlockHeight uint64, ) GenesisParams { - genParams := GenesisParams{} genParams.GenesisTime = genesisTime diff --git a/cmd/babylond/cmd/root.go b/cmd/babylond/cmd/root.go index e5979db3a..2228d2223 100644 --- a/cmd/babylond/cmd/root.go +++ b/cmd/babylond/cmd/root.go @@ -293,7 +293,6 @@ func appExport( appOpts servertypes.AppOptions, modulesToExport []string, ) (servertypes.ExportedApp, error) { - var babylonApp *app.BabylonApp homePath, ok := appOpts.Get(flags.FlagHome).(string) if !ok || homePath == "" { diff --git a/cmd/babylond/cmd/testnet.go b/cmd/babylond/cmd/testnet.go index bae46a5e6..c05b9c94a 100644 --- a/cmd/babylond/cmd/testnet.go +++ b/cmd/babylond/cmd/testnet.go @@ -178,7 +178,6 @@ func InitTestnet( valAddrCodec runtime.ValidatorAddressCodec, genesisParams GenesisParams, ) error { - nodeIDs := make([]string, numValidators) valKeys := make([]*privval.ValidatorKeys, numValidators) @@ -398,7 +397,6 @@ func InitTestnet( genBalances = append(genBalances, banktypes.Balance{Address: addr.String(), Coins: coins.Sort()}) genAccounts = append(genAccounts, authtypes.NewBaseAccount(addr, nil, 0, 0)) - } } @@ -424,7 +422,6 @@ func initGenFiles( genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string, genKeys []*checkpointingtypes.GenesisKey, numValidators int, genesisParams GenesisParams, ) error { - appGenState := mbm.DefaultGenesis(clientCtx.Codec) // set the accounts in the genesis state @@ -465,7 +462,6 @@ func collectGenFiles( nodeIDs []string, genKeys []*checkpointingtypes.GenesisKey, numValidators int, outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator, ) error { - var appState json.RawMessage genTime := cmttime.Now() diff --git a/crypto/bls12381/bls_test.go b/crypto/bls12381/bls_test.go index d433e9499..8dc588cad 100644 --- a/crypto/bls12381/bls_test.go +++ b/crypto/bls12381/bls_test.go @@ -8,6 +8,7 @@ import ( // Tests single BLS sig verification func TestVerifyBlsSig(t *testing.T) { + t.Parallel() msga := []byte("aaaaaaaa") msgb := []byte("bbbbbbbb") sk, pk := GenKeyPair() @@ -26,6 +27,7 @@ func TestVerifyBlsSig(t *testing.T) { // Tests BLS multi sig verification func TestVerifyBlsMultiSig(t *testing.T) { + t.Parallel() msga := []byte("aaaaaaaa") msgb := []byte("bbbbbbbb") n := 100 @@ -47,6 +49,7 @@ func TestVerifyBlsMultiSig(t *testing.T) { // Tests BLS multi sig verification // insert an invalid BLS sig in aggregation func TestVerifyBlsMultiSig2(t *testing.T) { + t.Parallel() msga := []byte("aaaaaaaa") msgb := []byte("bbbbbbbb") n := 100 @@ -67,6 +70,7 @@ func TestVerifyBlsMultiSig2(t *testing.T) { } func TestAccumulativeAggregation(t *testing.T) { + t.Parallel() msga := []byte("aaaaaaaa") msgb := []byte("bbbbbbbb") n := 100 @@ -96,6 +100,7 @@ func TestAccumulativeAggregation(t *testing.T) { } func TestSKToPK(t *testing.T) { + t.Parallel() n := 100 sks, pks := generateBatchTestKeyPairs(n) for i := 0; i < n; i++ { diff --git a/crypto/schnorr-adaptor-signature/keys_test.go b/crypto/schnorr-adaptor-signature/keys_test.go index 92b8aee7b..240ed892c 100644 --- a/crypto/schnorr-adaptor-signature/keys_test.go +++ b/crypto/schnorr-adaptor-signature/keys_test.go @@ -15,7 +15,7 @@ func FuzzKeyGen(f *testing.F) { f.Add([]byte("1234567892!@#$%^&*()")) f.Add([]byte("1234567893!@#$%^&*()")) - f.Fuzz(func(t *testing.T, seed []byte) { + f.Fuzz(func(t *testing.T, _ []byte) { encKey, decKey, err := asig.GenKeyPair() require.NoError(t, err) @@ -49,7 +49,7 @@ func FuzzKeySerialization(f *testing.F) { f.Add([]byte("1234567892!@#$%^&*()")) f.Add([]byte("1234567893!@#$%^&*()")) - f.Fuzz(func(t *testing.T, seed []byte) { + f.Fuzz(func(t *testing.T, _ []byte) { encKey, decKey, err := asig.GenKeyPair() require.NoError(t, err) diff --git a/test/e2e/configurer/upgrade_test.go b/test/e2e/configurer/upgrade_test.go index fb992c761..2c5cc58c4 100644 --- a/test/e2e/configurer/upgrade_test.go +++ b/test/e2e/configurer/upgrade_test.go @@ -37,7 +37,7 @@ func TestWriteGovPropToFile(t *testing.T) { require.NoError(t, err) r := rand.New(rand.NewSource(time.Now().Unix())) - newPropHeight := int64(r.Int63()) + newPropHeight := r.Int63() msgProp.Plan.Height = newPropHeight tempFilePath := filepath.Join(t.TempDir(), filepath.Base(config.UpgradeSignetLaunchFilePath)) diff --git a/test/e2e/initialization/config.go b/test/e2e/initialization/config.go index 2bcba9c63..876ae7cda 100644 --- a/test/e2e/initialization/config.go +++ b/test/e2e/initialization/config.go @@ -26,7 +26,6 @@ import ( "github.com/babylonlabs-io/babylon/privval" bbn "github.com/babylonlabs-io/babylon/types" btccheckpointtypes "github.com/babylonlabs-io/babylon/x/btccheckpoint/types" - blctypes "github.com/babylonlabs-io/babylon/x/btclightclient/types" btclighttypes "github.com/babylonlabs-io/babylon/x/btclightclient/types" checkpointingtypes "github.com/babylonlabs-io/babylon/x/checkpointing/types" finalitytypes "github.com/babylonlabs-io/babylon/x/finality/types" @@ -255,7 +254,7 @@ func initGenesis( return err } - err = updateModuleGenesis(appGenState, blctypes.ModuleName, blctypes.DefaultGenesis(), updateBtcLightClientGenesis(btcHeaders)) + err = updateModuleGenesis(appGenState, btclighttypes.ModuleName, btclighttypes.DefaultGenesis(), updateBtcLightClientGenesis(btcHeaders)) if err != nil { return err } @@ -286,7 +285,6 @@ func initGenesis( if err = genutil.ExportGenesisFile(genDoc, path); err != nil { return fmt.Errorf("failed to export app genesis state: %w", err) } - } return nil } @@ -334,7 +332,7 @@ func updateCrisisGenesis(crisisGenState *crisistypes.GenesisState) { crisisGenState.ConstantFee.Denom = BabylonDenom } -func updateBtcLightClientGenesis(btcHeaders []*btclighttypes.BTCHeaderInfo) func(blcGenState *blctypes.GenesisState) { +func updateBtcLightClientGenesis(btcHeaders []*btclighttypes.BTCHeaderInfo) func(blcGenState *btclighttypes.GenesisState) { return func(blcGenState *btclighttypes.GenesisState) { if len(btcHeaders) > 0 { blcGenState.BtcHeaders = btcHeaders @@ -346,8 +344,8 @@ func updateBtcLightClientGenesis(btcHeaders []*btclighttypes.BTCHeaderInfo) func if err != nil { panic(err) } - work := blctypes.CalcWork(&baseBtcHeader) - blcGenState.BtcHeaders = []*blctypes.BTCHeaderInfo{blctypes.NewBTCHeaderInfo(&baseBtcHeader, baseBtcHeader.Hash(), 0, &work)} + work := btclighttypes.CalcWork(&baseBtcHeader) + blcGenState.BtcHeaders = []*btclighttypes.BTCHeaderInfo{btclighttypes.NewBTCHeaderInfo(&baseBtcHeader, baseBtcHeader.Hash(), 0, &work)} } } diff --git a/testutil/datagen/btc_blockchain.go b/testutil/datagen/btc_blockchain.go index 3e3ee42ec..beb3e1488 100644 --- a/testutil/datagen/btc_blockchain.go +++ b/testutil/datagen/btc_blockchain.go @@ -19,7 +19,7 @@ import ( // When numBabylonTxs == 2, the function will return the BTC raw checkpoint as well. func GenRandomBtcdBlock(r *rand.Rand, numBabylonTxs int, prevHash *chainhash.Hash) (*wire.MsgBlock, *btctxformatter.RawBtcCheckpoint) { var ( - randomTxs []*wire.MsgTx = []*wire.MsgTx{GenRandomTx(r), GenRandomTx(r)} + randomTxs = []*wire.MsgTx{GenRandomTx(r), GenRandomTx(r)} rawCkpt *btctxformatter.RawBtcCheckpoint = nil ) diff --git a/testutil/datagen/btc_header_info.go b/testutil/datagen/btc_header_info.go index 796e0182e..0cc7d8881 100644 --- a/testutil/datagen/btc_header_info.go +++ b/testutil/datagen/btc_header_info.go @@ -33,7 +33,6 @@ func calculateAdjustedDifficulty( lastRetargetHeader *wire.BlockHeader, currentHeaderTimestamp time.Time, params *chaincfg.Params) uint32 { - targetTimespan := int64(params.TargetTimespan / time.Second) adjustmentFactor := params.RetargetAdjustmentFactor minRetargetTimespan := targetTimespan / adjustmentFactor diff --git a/testutil/datagen/btc_transaction.go b/testutil/datagen/btc_transaction.go index ea5277e5a..51fc81295 100644 --- a/testutil/datagen/btc_transaction.go +++ b/testutil/datagen/btc_transaction.go @@ -95,7 +95,6 @@ func SolveBlock(header *wire.BlockHeader) bool { hash := hdr.BlockHash() if blockchain.HashToBig(&hash).Cmp( targetDifficulty) <= 0 { - results <- sbResult{true, i} return } @@ -245,7 +244,6 @@ func CreateBlock( babylonOpReturnIdx uint32, babylonData []byte, ) *BlockCreationResult { - if babylonOpReturnIdx > numTx { panic("babylon tx index should be less than number of transasactions and greater than 0") } @@ -305,7 +303,6 @@ func CreateBlockWithTransaction( ph *wire.BlockHeader, tx *wire.MsgTx, ) *BtcHeaderWithProof { - var transactions []*wire.MsgTx // height does not matter here, as it is used only for calculation of reward transactions = append(transactions, createCoinbaseTx(int32(889), &chaincfg.SimNetParams)) diff --git a/testutil/datagen/btcstaking.go b/testutil/datagen/btcstaking.go index 21efdc766..bd2eef8ff 100644 --- a/testutil/datagen/btcstaking.go +++ b/testutil/datagen/btcstaking.go @@ -154,7 +154,7 @@ func GenRandomBTCDelegation( BtcPk: delBTCPK, Pop: pop, FpBtcPkList: fpBTCPKs, - StakingTime: uint32(stakingTime), + StakingTime: stakingTime, StartHeight: startHeight, EndHeight: endHeight, TotalSat: totalSat, @@ -248,7 +248,6 @@ func GenBTCStakingSlashingInfoWithOutPoint( slashingRate sdkmath.LegacyDec, slashingChangeLockTime uint16, ) *TestStakingSlashingInfo { - stakingInfo, err := btcstaking.BuildStakingInfo( stakerSK.PubKey(), fpPKs, @@ -342,7 +341,6 @@ func GenBTCUnbondingSlashingInfo( slashingRate sdkmath.LegacyDec, slashingChangeLockTime uint16, ) *TestUnbondingSlashingInfo { - unbondingInfo, err := btcstaking.BuildUnbondingInfo( stakerSK.PubKey(), fpPKs, diff --git a/testutil/datagen/genesiskey.go b/testutil/datagen/genesiskey.go index 77bffb8af..1fb3bdbc3 100644 --- a/testutil/datagen/genesiskey.go +++ b/testutil/datagen/genesiskey.go @@ -9,7 +9,6 @@ import ( cmtcrypto "github.com/cometbft/cometbft/crypto" cmted25519 "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cosmos/cosmos-sdk/crypto/codec" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" cosmosed "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" @@ -63,7 +62,7 @@ func GenesisValidatorSet(numVals int) (*GenesisValidators, error) { if err != nil { return nil, err } - valPubkey, err := cryptocodec.FromCmtPubKeyInterface(valKeys.ValPubkey) + valPubkey, err := codec.FromCmtPubKeyInterface(valKeys.ValPubkey) if err != nil { return nil, err } diff --git a/wasmbinding/test/custom_query_test.go b/wasmbinding/test/custom_query_test.go index a5a68527c..afa10352a 100644 --- a/wasmbinding/test/custom_query_test.go +++ b/wasmbinding/test/custom_query_test.go @@ -238,7 +238,6 @@ func fundAccount( ctx sdk.Context, bbn *app.BabylonApp, acc sdk.AccAddress) { - err := mintCoinsTo(bbn.BankKeeper, ctx, acc, sdk.NewCoins( sdk.NewCoin("ubbn", math.NewInt(10000000000)), )) @@ -282,7 +281,6 @@ func deployTestContract( deployer sdk.AccAddress, codePath string, ) sdk.AccAddress { - codeId, _ := storeTestCodeCode(t, ctx, bbn, deployer, codePath) contractAddr := instantiateExampleContract(t, ctx, bbn, deployer, codeId) diff --git a/x/btccheckpoint/keeper/submissions.go b/x/btccheckpoint/keeper/submissions.go index 50f284600..31d6251d6 100644 --- a/x/btccheckpoint/keeper/submissions.go +++ b/x/btccheckpoint/keeper/submissions.go @@ -50,7 +50,6 @@ func (k Keeper) addEpochSubmission( sk types.SubmissionKey, sd types.SubmissionData, ) error { - ed := k.GetEpochData(ctx, epochNum) // TODO: SaveEpochData and SaveSubmission should be done in one transaction. @@ -132,7 +131,6 @@ func (k Keeper) checkSubmissionStatus(ctx context.Context, info *types.Submissio } func (k Keeper) GetSubmissionBtcInfo(ctx context.Context, sk types.SubmissionKey) (*types.SubmissionBtcInfo, error) { - var youngestBlockDepth uint32 = math.MaxUint32 var youngestBlockHash *bbn.BTCHeaderHashBytes diff --git a/x/btccheckpoint/types/genesis.go b/x/btccheckpoint/types/genesis.go index 2fb67af14..ffd96d1aa 100644 --- a/x/btccheckpoint/types/genesis.go +++ b/x/btccheckpoint/types/genesis.go @@ -10,6 +10,5 @@ func DefaultGenesis() *GenesisState { // Validate performs basic genesis state validation returning an error upon any // failure. func (gs GenesisState) Validate() error { - return gs.Params.Validate() } diff --git a/x/btccheckpoint/types/mock_keepers.go b/x/btccheckpoint/types/mock_keepers.go index 6e41877d0..604ce3dbd 100644 --- a/x/btccheckpoint/types/mock_keepers.go +++ b/x/btccheckpoint/types/mock_keepers.go @@ -54,12 +54,12 @@ func (m *MockBTCLightClientKeeper) DeleteHeader(header *bbn.BTCHeaderHashBytes) delete(m.headers, header.String()) } -func (m MockBTCLightClientKeeper) BlockHeight(ctx context.Context, header *bbn.BTCHeaderHashBytes) (uint32, error) { +func (m MockBTCLightClientKeeper) BlockHeight(_ context.Context, _ *bbn.BTCHeaderHashBytes) (uint32, error) { // todo not used return uint32(10), nil } -func (m MockBTCLightClientKeeper) MainChainDepth(ctx context.Context, headerBytes *bbn.BTCHeaderHashBytes) (uint32, error) { +func (m MockBTCLightClientKeeper) MainChainDepth(_ context.Context, headerBytes *bbn.BTCHeaderHashBytes) (uint32, error) { depth, ok := m.headers[headerBytes.String()] if ok { return depth, nil @@ -68,7 +68,7 @@ func (m MockBTCLightClientKeeper) MainChainDepth(ctx context.Context, headerByte } } -func (m MockCheckpointingKeeper) VerifyCheckpoint(ctx context.Context, checkpoint txformat.RawBtcCheckpoint) error { +func (m MockCheckpointingKeeper) VerifyCheckpoint(_ context.Context, _ txformat.RawBtcCheckpoint) error { if m.returnError { return errors.New("bad checkpoints") } @@ -78,26 +78,26 @@ func (m MockCheckpointingKeeper) VerifyCheckpoint(ctx context.Context, checkpoin // SetCheckpointSubmitted Informs checkpointing module that checkpoint was // successfully submitted on btc chain. -func (m MockCheckpointingKeeper) SetCheckpointSubmitted(ctx context.Context, epoch uint64) { +func (m MockCheckpointingKeeper) SetCheckpointSubmitted(_ context.Context, _ uint64) { } // SetCheckpointConfirmed Informs checkpointing module that checkpoint was // successfully submitted on btc chain, and it is at least K-deep on the main chain -func (m MockCheckpointingKeeper) SetCheckpointConfirmed(ctx context.Context, epoch uint64) { +func (m MockCheckpointingKeeper) SetCheckpointConfirmed(_ context.Context, _ uint64) { } // SetCheckpointFinalized Informs checkpointing module that checkpoint was // successfully submitted on btc chain, and it is at least W-deep on the main chain -func (m MockCheckpointingKeeper) SetCheckpointFinalized(ctx context.Context, epoch uint64) { +func (m MockCheckpointingKeeper) SetCheckpointFinalized(_ context.Context, _ uint64) { } // SetCheckpointForgotten Informs checkpointing module that was in submitted state // lost all its checkpoints and is checkpoint empty -func (m MockCheckpointingKeeper) SetCheckpointForgotten(ctx context.Context, epoch uint64) { +func (m MockCheckpointingKeeper) SetCheckpointForgotten(_ context.Context, _ uint64) { } -func (m *MockIncentiveKeeper) RewardBTCTimestamping(ctx context.Context, epoch uint64, rewardDistInfo *RewardDistInfo) { +func (m *MockIncentiveKeeper) RewardBTCTimestamping(_ context.Context, _ uint64, _ *RewardDistInfo) { } -func (m *MockIncentiveKeeper) IndexRefundableMsg(ctx context.Context, msg sdk.Msg) { +func (m *MockIncentiveKeeper) IndexRefundableMsg(_ context.Context, _ sdk.Msg) { } diff --git a/x/btclightclient/keeper/grpc_query_test.go b/x/btclightclient/keeper/grpc_query_test.go index 4e97f58c5..7252ba921 100644 --- a/x/btclightclient/keeper/grpc_query_test.go +++ b/x/btclightclient/keeper/grpc_query_test.go @@ -93,11 +93,11 @@ func FuzzHashesQuery(f *testing.F) { t.Fatalf("Valid request led to a nil response") } // If we are on the last page the elements retrieved should be equal to the remaining ones - if headersRetrieved+uint32(limit) >= chainSize && uint32(len(resp.Hashes)) != chainSize-headersRetrieved { + if headersRetrieved+limit >= chainSize && uint32(len(resp.Hashes)) != chainSize-headersRetrieved { t.Fatalf("On the last page expected %d elements but got %d", chainSize-headersRetrieved, len(resp.Hashes)) } // Otherwise, the elements retrieved should be equal to the limit - if headersRetrieved+uint32(limit) < chainSize && uint32(len(resp.Hashes)) != limit { + if headersRetrieved+limit < chainSize && uint32(len(resp.Hashes)) != limit { t.Fatalf("On an intermediate page expected %d elements but got %d", limit, len(resp.Hashes)) } diff --git a/x/btclightclient/keeper/msg_server_test.go b/x/btclightclient/keeper/msg_server_test.go index 26eaac2aa..4f0b91365 100644 --- a/x/btclightclient/keeper/msg_server_test.go +++ b/x/btclightclient/keeper/msg_server_test.go @@ -129,7 +129,7 @@ func FuzzMsgServerReorgChain(f *testing.F) { r, forkHeader.Header.ToBlockHeader(), nil, - uint32(forkChainLen), + forkChainLen, ) chainExtensionWork := chainWork(chainExtension) msg := &types.MsgInsertHeaders{Signer: address.String(), Headers: keepertest.NewBTCHeaderBytesList(chainExtension)} diff --git a/x/btclightclient/keeper/utils_test.go b/x/btclightclient/keeper/utils_test.go index 9efbf1e18..b0c266b30 100644 --- a/x/btclightclient/keeper/utils_test.go +++ b/x/btclightclient/keeper/utils_test.go @@ -58,7 +58,6 @@ func checkTip( expectedWork sdkmath.Uint, expectedHeight uint32, expectedTipHeader *wire.BlockHeader) { - currentTip := blcKeeper.GetTipInfo(ctx) blockByHeight := blcKeeper.GetHeaderByHeight(ctx, currentTip.Height) blockByHash, err := blcKeeper.GetHeaderByHash(ctx, currentTip.Hash) diff --git a/x/btclightclient/types/msgs_test.go b/x/btclightclient/types/msgs_test.go index 9a4766fd8..ddf78119d 100644 --- a/x/btclightclient/types/msgs_test.go +++ b/x/btclightclient/types/msgs_test.go @@ -21,7 +21,6 @@ func FuzzMsgInsertHeader(f *testing.F) { f.Fuzz(func(t *testing.T, seed int64) { r := rand.New(rand.NewSource(seed)) - errorKind := 0 addressBytes := datagen.GenRandomByteArray(r, 1+uint64(r.Intn(255))) headerBytes := datagen.GenRandomBTCHeaderInfo(r).Header @@ -33,7 +32,7 @@ func FuzzMsgInsertHeader(f *testing.F) { require.NoError(t, err) // Perform modifications on the header - errorKind = r.Intn(2) + errorKind := r.Intn(2) var bitsBig sdkmath.Uint switch errorKind { case 0: diff --git a/x/btcstaking/keeper/grpc_query_test.go b/x/btcstaking/keeper/grpc_query_test.go index c250b8383..3a3a3a41f 100644 --- a/x/btcstaking/keeper/grpc_query_test.go +++ b/x/btcstaking/keeper/grpc_query_test.go @@ -258,7 +258,6 @@ func FuzzFinalityProviderDelegations(f *testing.F) { } } require.Equal(t, len(btcDelsFound), len(expectedBtcDelsMap)) - }) } diff --git a/x/btcstaking/keeper/inclusion_proof.go b/x/btcstaking/keeper/inclusion_proof.go index 5a8e51dae..803d42442 100644 --- a/x/btcstaking/keeper/inclusion_proof.go +++ b/x/btcstaking/keeper/inclusion_proof.go @@ -33,7 +33,7 @@ func (k Keeper) VerifyInclusionProofAndGetHeight( // - staking tx inclusion proof stakingTxHeader, err := k.btclcKeeper.GetHeaderByHash(ctx, inclusionProof.HeaderHash) if err != nil { - return nil, fmt.Errorf("staking tx inclusion proof header %s is not found in BTC light client state: %v", inclusionProof.HeaderHash.MarshalHex(), err) + return nil, fmt.Errorf("staking tx inclusion proof header %s is not found in BTC light client state: %w", inclusionProof.HeaderHash.MarshalHex(), err) } // no need to do more validations to the btc header as it was already diff --git a/x/btcstaking/keeper/msg_server_test.go b/x/btcstaking/keeper/msg_server_test.go index cb8b79bd8..76b0ce1d9 100644 --- a/x/btcstaking/keeper/msg_server_test.go +++ b/x/btcstaking/keeper/msg_server_test.go @@ -894,14 +894,14 @@ func TestDoNotAllowDelegationWithoutFinalityProvider(t *testing.T) { FpBtcPkList: []bbn.BIP340PubKey{*fp.BtcPk}, BtcPk: bbn.NewBIP340PubKeyFromBTCPK(delSK.PubKey()), Pop: pop, - StakingTime: uint32(stakingTimeBlocks), + StakingTime: stakingTimeBlocks, StakingValue: stakingValue, StakingTx: serializedStakingTx, StakingTxInclusionProof: txInclusionProof, SlashingTx: testStakingInfo.SlashingTx, DelegatorSlashingSig: delegatorSig, UnbondingTx: unbondingTx, - UnbondingTime: uint32(unbondingTime), + UnbondingTime: unbondingTime, UnbondingValue: unbondingValue, UnbondingSlashingTx: testUnbondingInfo.SlashingTx, DelegatorUnbondingSlashingSig: delUnbondingSlashingSig, diff --git a/x/btcstaking/types/btc_delegation.go b/x/btcstaking/types/btc_delegation.go index e9a877a26..e24dace58 100644 --- a/x/btcstaking/types/btc_delegation.go +++ b/x/btcstaking/types/btc_delegation.go @@ -254,11 +254,11 @@ func (d *BTCDelegation) AddCovenantSigs( func (d *BTCDelegation) GetStakingInfo(bsParams *Params, btcNet *chaincfg.Params) (*btcstaking.StakingInfo, error) { fpBtcPkList, err := bbn.NewBTCPKsFromBIP340PKs(d.FpBtcPkList) if err != nil { - return nil, fmt.Errorf("failed to convert finality provider pks to BTC pks %v", err) + return nil, fmt.Errorf("failed to convert finality provider pks to BTC pks %w", err) } covenantBtcPkList, err := bbn.NewBTCPKsFromBIP340PKs(bsParams.CovenantPks) if err != nil { - return nil, fmt.Errorf("failed to convert covenant pks to BTC pks %v", err) + return nil, fmt.Errorf("failed to convert covenant pks to BTC pks %w", err) } stakingInfo, err := btcstaking.BuildStakingInfo( d.BtcPk.MustToBTCPK(), @@ -270,7 +270,7 @@ func (d *BTCDelegation) GetStakingInfo(bsParams *Params, btcNet *chaincfg.Params btcNet, ) if err != nil { - return nil, fmt.Errorf("could not create BTC staking info: %v", err) + return nil, fmt.Errorf("could not create BTC staking info: %w", err) } return stakingInfo, nil } @@ -278,11 +278,11 @@ func (d *BTCDelegation) GetStakingInfo(bsParams *Params, btcNet *chaincfg.Params func (d *BTCDelegation) SignUnbondingTx(bsParams *Params, btcNet *chaincfg.Params, sk *btcec.PrivateKey) (*schnorr.Signature, error) { stakingTx, err := bbn.NewBTCTxFromBytes(d.StakingTx) if err != nil { - return nil, fmt.Errorf("failed to parse staking transaction: %v", err) + return nil, fmt.Errorf("failed to parse staking transaction: %w", err) } unbondingTx, err := bbn.NewBTCTxFromBytes(d.BtcUndelegation.UnbondingTx) if err != nil { - return nil, fmt.Errorf("failed to parse unbonding transaction: %v", err) + return nil, fmt.Errorf("failed to parse unbonding transaction: %w", err) } stakingInfo, err := d.GetStakingInfo(bsParams, btcNet) if err != nil { @@ -312,16 +312,16 @@ func (d *BTCDelegation) SignUnbondingTx(bsParams *Params, btcNet *chaincfg.Param func (d *BTCDelegation) GetUnbondingInfo(bsParams *Params, btcNet *chaincfg.Params) (*btcstaking.UnbondingInfo, error) { fpBtcPkList, err := bbn.NewBTCPKsFromBIP340PKs(d.FpBtcPkList) if err != nil { - return nil, fmt.Errorf("failed to convert finality provider pks to BTC pks: %v", err) + return nil, fmt.Errorf("failed to convert finality provider pks to BTC pks: %w", err) } covenantBtcPkList, err := bbn.NewBTCPKsFromBIP340PKs(bsParams.CovenantPks) if err != nil { - return nil, fmt.Errorf("failed to convert covenant pks to BTC pks: %v", err) + return nil, fmt.Errorf("failed to convert covenant pks to BTC pks: %w", err) } unbondingTx, err := bbn.NewBTCTxFromBytes(d.BtcUndelegation.UnbondingTx) if err != nil { - return nil, fmt.Errorf("failed to parse unbonding transaction: %v", err) + return nil, fmt.Errorf("failed to parse unbonding transaction: %w", err) } unbondingInfo, err := btcstaking.BuildUnbondingInfo( @@ -334,7 +334,7 @@ func (d *BTCDelegation) GetUnbondingInfo(bsParams *Params, btcNet *chaincfg.Para btcNet, ) if err != nil { - return nil, fmt.Errorf("could not create BTC staking info: %v", err) + return nil, fmt.Errorf("could not create BTC staking info: %w", err) } return unbondingInfo, nil @@ -366,11 +366,11 @@ func (d *BTCDelegation) BuildSlashingTxWithWitness(bsParams *Params, btcNet *cha // get staking info stakingInfo, err := d.GetStakingInfo(bsParams, btcNet) if err != nil { - return nil, fmt.Errorf("could not create BTC staking info: %v", err) + return nil, fmt.Errorf("could not create BTC staking info: %w", err) } slashingSpendInfo, err := stakingInfo.SlashingPathSpendInfo() if err != nil { - return nil, fmt.Errorf("could not get slashing spend info: %v", err) + return nil, fmt.Errorf("could not get slashing spend info: %w", err) } // get the list of covenant signatures encrypted by the given finality provider's PK @@ -449,7 +449,7 @@ func (d *BTCDelegation) BuildUnbondingSlashingTxWithWitness(bsParams *Params, bt ) if err != nil { return nil, fmt.Errorf( - "failed to build witness for unbonding BTC delegation %s under finality provider %s: %v", + "failed to build witness for unbonding BTC delegation %s under finality provider %s: %w", d.BtcPk.MarshalHex(), bbn.NewBIP340PubKeyFromBTCPK(fpSK.PubKey()).MarshalHex(), err, diff --git a/x/btcstaking/types/btc_slashing_tx.go b/x/btcstaking/types/btc_slashing_tx.go index d420a3bf0..cb594519e 100644 --- a/x/btcstaking/types/btc_slashing_tx.go +++ b/x/btcstaking/types/btc_slashing_tx.go @@ -200,7 +200,7 @@ func (tx *BTCSlashingTx) ParseEncVerifyAdaptorSignatures( valPKs []bbn.BIP340PubKey, sigs [][]byte, ) ([]asig.AdaptorSignature, error) { - var adaptorSigs []asig.AdaptorSignature = make([]asig.AdaptorSignature, len(sigs)) + adaptorSigs := make([]asig.AdaptorSignature, len(sigs)) for i := range sigs { sig := sigs[i] adaptorSig, err := asig.NewAdaptorSignatureFromBytes(sig) diff --git a/x/btcstaking/types/btc_undelegation_test.go b/x/btcstaking/types/btc_undelegation_test.go index 7cfaecdba..005a554a1 100644 --- a/x/btcstaking/types/btc_undelegation_test.go +++ b/x/btcstaking/types/btc_undelegation_test.go @@ -75,7 +75,7 @@ func FuzzBTCUndelegation_SlashingTx(f *testing.F) { slashingPkScript, stakingTimeBlocks, 1000, - uint32(stakingTimeBlocks)+1000, + stakingTimeBlocks+1000, uint64(stakingValue), slashingRate, slashingChangeLockTime, diff --git a/x/btcstaking/types/create_delegation_parser.go b/x/btcstaking/types/create_delegation_parser.go index 23a775aaf..f25e8e17c 100644 --- a/x/btcstaking/types/create_delegation_parser.go +++ b/x/btcstaking/types/create_delegation_parser.go @@ -154,32 +154,32 @@ func ParseCreateDelegationMessage(msg *MsgCreateBTCDelegation) (*ParsedCreateDel stakingTxProofOfInclusion, err := NewParsedProofOfInclusion(msg.StakingTxInclusionProof) if err != nil { - return nil, fmt.Errorf("failed to parse staking tx proof of inclusion: %v", err) + return nil, fmt.Errorf("failed to parse staking tx proof of inclusion: %w", err) } // 1. Parse all transactions stakingTx, err := NewBtcTransaction(msg.StakingTx) if err != nil { - return nil, fmt.Errorf("failed to deserialize staking tx: %v", err) + return nil, fmt.Errorf("failed to deserialize staking tx: %w", err) } stakingSlashingTx, err := NewBtcTransaction(msg.SlashingTx.MustMarshal()) if err != nil { - return nil, fmt.Errorf("failed to deserialize staking slashing tx: %v", err) + return nil, fmt.Errorf("failed to deserialize staking slashing tx: %w", err) } unbondingTx, err := NewBtcTransaction(msg.UnbondingTx) if err != nil { - return nil, fmt.Errorf("failed to deserialize unbonding tx: %v", err) + return nil, fmt.Errorf("failed to deserialize unbonding tx: %w", err) } unbondingSlashingTx, err := NewBtcTransaction(msg.UnbondingSlashingTx.MustMarshal()) if err != nil { - return nil, fmt.Errorf("failed to deserialize unbonding slashing tx: %v", err) + return nil, fmt.Errorf("failed to deserialize unbonding slashing tx: %w", err) } // 2. Check all timelocks @@ -195,7 +195,7 @@ func ParseCreateDelegationMessage(msg *MsgCreateBTCDelegation) (*ParsedCreateDel stakerAddr, err := sdk.AccAddressFromBech32(msg.StakerAddr) if err != nil { - return nil, fmt.Errorf("invalid staker address %s: %v", msg.StakerAddr, err) + return nil, fmt.Errorf("invalid staker address %s: %w", msg.StakerAddr, err) } // 4. Parse proof of possession @@ -211,20 +211,20 @@ func ParseCreateDelegationMessage(msg *MsgCreateBTCDelegation) (*ParsedCreateDel stakerStakingSlashingTxSig, err := NewParsedBIP340Signature(msg.DelegatorSlashingSig) if err != nil { - return nil, fmt.Errorf("failed to parse staker staking slashing signature: %v", err) + return nil, fmt.Errorf("failed to parse staker staking slashing signature: %w", err) } stakerUnbondingSlashingSig, err := NewParsedBIP340Signature(msg.DelegatorUnbondingSlashingSig) if err != nil { - return nil, fmt.Errorf("failed to parse staker unbonding slashing signature: %v", err) + return nil, fmt.Errorf("failed to parse staker unbonding slashing signature: %w", err) } // 6. Parse finality provider public keys and check for duplicates fpPKs, err := NewParsedPublicKeyList(msg.FpBtcPkList) if err != nil { - return nil, fmt.Errorf("failed to parse finality provider public keys: %v", err) + return nil, fmt.Errorf("failed to parse finality provider public keys: %w", err) } if ExistsDup(fpPKs.PublicKeysBbnFormat) { @@ -239,7 +239,7 @@ func ParseCreateDelegationMessage(msg *MsgCreateBTCDelegation) (*ParsedCreateDel stakerPK, err := NewParsedPublicKey(msg.BtcPk) if err != nil { - return nil, fmt.Errorf("failed to parse staker public key: %v", err) + return nil, fmt.Errorf("failed to parse staker public key: %w", err) } // 8. Parse staking and unbonding value diff --git a/x/btcstaking/types/genesis.go b/x/btcstaking/types/genesis.go index 9746fb6b6..7747d8d7e 100644 --- a/x/btcstaking/types/genesis.go +++ b/x/btcstaking/types/genesis.go @@ -34,7 +34,6 @@ func (gs GenesisState) Validate() error { if err != nil { return err } - } return nil } diff --git a/x/btcstaking/types/msg.go b/x/btcstaking/types/msg.go index 9603f91e6..c1d4fb533 100644 --- a/x/btcstaking/types/msg.go +++ b/x/btcstaking/types/msg.go @@ -38,13 +38,13 @@ func (m *MsgCreateFinalityProvider) ValidateBasic() error { return fmt.Errorf("empty BTC public key") } if _, err := m.BtcPk.ToBTCPK(); err != nil { - return fmt.Errorf("invalid BTC public key: %v", err) + return fmt.Errorf("invalid BTC public key: %w", err) } if m.Pop == nil { return fmt.Errorf("empty proof of possession") } if _, err := sdk.AccAddressFromBech32(m.Addr); err != nil { - return fmt.Errorf("invalid FP addr: %s - %v", m.Addr, err) + return fmt.Errorf("invalid FP addr: %s - %w", m.Addr, err) } return m.Pop.ValidateBasic() } @@ -85,7 +85,7 @@ func (m *MsgAddCovenantSigs) ValidateBasic() error { return fmt.Errorf("empty BTC covenant public key") } if _, err := m.Pk.ToBTCPK(); err != nil { - return fmt.Errorf("invalid BTC public key: %v", err) + return fmt.Errorf("invalid BTC public key: %w", err) } if m.SlashingTxSigs == nil { return fmt.Errorf("empty covenant signatures on slashing tx") @@ -158,7 +158,7 @@ func (m *MsgAddBTCDelegationInclusionProof) ValidateBasic() error { } if _, err := sdk.AccAddressFromBech32(m.Signer); err != nil { - return fmt.Errorf("invalid signer addr: %s - %v", m.Signer, err) + return fmt.Errorf("invalid signer addr: %s - %w", m.Signer, err) } return nil diff --git a/x/btcstaking/types/msg_test.go b/x/btcstaking/types/msg_test.go index ba69fd302..a93d9bea1 100644 --- a/x/btcstaking/types/msg_test.go +++ b/x/btcstaking/types/msg_test.go @@ -117,7 +117,7 @@ func TestMsgCreateFinalityProviderValidateBasic(t *testing.T) { BtcPk: (*bbntypes.BIP340PubKey)(&bigBtcPK), Pop: fp.Pop, }, - fmt.Errorf("invalid BTC public key: %v", fmt.Errorf("bad pubkey byte string size (want %v, have %v)", 32, len(bigBtcPK))), + fmt.Errorf("invalid BTC public key: %w", fmt.Errorf("bad pubkey byte string size (want %v, have %v)", 32, len(bigBtcPK))), }, { "invalid: empty PoP", diff --git a/x/btcstaking/types/validate_parsed_message_test.go b/x/btcstaking/types/validate_parsed_message_test.go index 93515e826..028001e1f 100644 --- a/x/btcstaking/types/validate_parsed_message_test.go +++ b/x/btcstaking/types/validate_parsed_message_test.go @@ -88,7 +88,6 @@ func generateUnbondingInfo( unbondingValue int64, p *types.Params, ) *unbondingInfo { - covPKs, err := bbn.NewBTCPKsFromBIP340PKs(p.CovenantPks) require.NoError(t, err) @@ -222,7 +221,7 @@ func createMsgDelegationForParams( SlashingTx: testStakingInfo.SlashingTx, DelegatorSlashingSig: delegatorSig, UnbondingTx: unbondingInfo.serializedUnbondingTx, - UnbondingTime: uint32(unbondingTime), + UnbondingTime: unbondingTime, UnbondingValue: unbondingValue, UnbondingSlashingTx: unbondingInfo.unbondingSlashingTx, DelegatorUnbondingSlashingSig: unbondingInfo.unbondingSlashinSig, diff --git a/x/checkpointing/proposal.go b/x/checkpointing/proposal.go index de0662345..ef8550e6c 100644 --- a/x/checkpointing/proposal.go +++ b/x/checkpointing/proposal.go @@ -215,7 +215,7 @@ func (h *ProposalHandler) findLastBlockHash(extendedVotes []abci.ExtendedVoteInf blockHashes := make(map[string]int64, 0) // Iterate over vote extensions and if they have a valid structure // increase the voting power of the block hash they commit to - var totalPower int64 = 0 + var totalPower int64 for _, vote := range extendedVotes { // accumulate voting power from all the votes totalPower += vote.Validator.Power @@ -237,7 +237,7 @@ func (h *ProposalHandler) findLastBlockHash(extendedVotes []abci.ExtendedVoteInf blockHashes[hex.EncodeToString(bHash)] += vote.Validator.Power } var ( - maxPower int64 = 0 + maxPower int64 resBlockHash string ) // Find the block hash that has the maximum voting power committed to it diff --git a/x/epoching/keeper/hooks.go b/x/epoching/keeper/hooks.go index 525e26640..a174d67b5 100644 --- a/x/epoching/keeper/hooks.go +++ b/x/epoching/keeper/hooks.go @@ -108,21 +108,21 @@ func (h Hooks) BeforeDelegationRemoved(ctx context.Context, delAddr sdk.AccAddre return h.k.RecordNewDelegationState(sdk.UnwrapSDKContext(ctx), delAddr, valAddr, nil, types.BondState_REMOVED) } -func (h Hooks) AfterUnbondingInitiated(ctx context.Context, id uint64) error { +func (h Hooks) AfterUnbondingInitiated(_ context.Context, _ uint64) error { return nil } // Other hooks that are not used in the epoching module -func (h Hooks) BeforeValidatorModified(ctx context.Context, valAddr sdk.ValAddress) error { +func (h Hooks) BeforeValidatorModified(_ context.Context, _ sdk.ValAddress) error { return nil } -func (h Hooks) BeforeDelegationCreated(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { +func (h Hooks) BeforeDelegationCreated(_ context.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } -func (h Hooks) BeforeDelegationSharesModified(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { +func (h Hooks) BeforeDelegationSharesModified(_ context.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } -func (h Hooks) AfterDelegationModified(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { +func (h Hooks) AfterDelegationModified(_ context.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } @@ -133,14 +133,14 @@ func (h Hooks) AfterRawCheckpointFinalized(ctx context.Context, epoch uint64) er return nil } -func (h Hooks) AfterBlsKeyRegistered(ctx context.Context, valAddr sdk.ValAddress) error { return nil } +func (h Hooks) AfterBlsKeyRegistered(_ context.Context, _ sdk.ValAddress) error { return nil } -func (h Hooks) AfterRawCheckpointSealed(ctx context.Context, epoch uint64) error { return nil } -func (h Hooks) AfterRawCheckpointConfirmed(ctx context.Context, epoch uint64) error { return nil } -func (h Hooks) AfterRawCheckpointForgotten(ctx context.Context, ckpt *checkpointingtypes.RawCheckpoint) error { +func (h Hooks) AfterRawCheckpointSealed(_ context.Context, _ uint64) error { return nil } +func (h Hooks) AfterRawCheckpointConfirmed(_ context.Context, _ uint64) error { return nil } +func (h Hooks) AfterRawCheckpointForgotten(_ context.Context, _ *checkpointingtypes.RawCheckpoint) error { return nil } -func (h Hooks) AfterRawCheckpointBlsSigVerified(ctx context.Context, ckpt *checkpointingtypes.RawCheckpoint) error { +func (h Hooks) AfterRawCheckpointBlsSigVerified(_ context.Context, _ *checkpointingtypes.RawCheckpoint) error { return nil } diff --git a/x/finality/genesis_test.go b/x/finality/genesis_test.go index 3e7b821f7..c083dcff5 100644 --- a/x/finality/genesis_test.go +++ b/x/finality/genesis_test.go @@ -23,5 +23,4 @@ func TestGenesis(t *testing.T) { nullify.Fill(&genesisState) nullify.Fill(got) - } diff --git a/x/finality/keeper/genesis_test.go b/x/finality/keeper/genesis_test.go index df9286152..2db1a2f0f 100644 --- a/x/finality/keeper/genesis_test.go +++ b/x/finality/keeper/genesis_test.go @@ -114,7 +114,7 @@ func FuzzTestExportGenesis(f *testing.F) { fps := datagen.CreateNFinalityProviders(r, t, int(numFps)) vpFps := make(map[string]*types.VotingPowerFP, 0) for _, fp := range fps { - vp := uint64(datagen.RandomInt(r, 1000000)) + vp := datagen.RandomInt(r, 1000000) // sets voting power k.SetVotingPower(ctx, *fp.BtcPk, blkHeight, vp) vpFps[fp.BtcPk.MarshalHex()] = &types.VotingPowerFP{ diff --git a/x/finality/keeper/tallying_bench_test.go b/x/finality/keeper/tallying_bench_test.go index 9e1d5f998..c621bc7cf 100644 --- a/x/finality/keeper/tallying_bench_test.go +++ b/x/finality/keeper/tallying_bench_test.go @@ -30,7 +30,7 @@ func benchmarkTallyBlocks(b *testing.B, numFPs int) { // activate BTC staking protocol at a random height activatedHeight := uint64(1) // add mock queries to GetBTCStakingActivatedHeight - ctx = datagen.WithCtxHeight(ctx, uint64(activatedHeight)) + ctx = datagen.WithCtxHeight(ctx, activatedHeight) // simulate fp set fpSet := map[string]uint64{} diff --git a/x/finality/keeper/tallying_test.go b/x/finality/keeper/tallying_test.go index 24b4c13e3..f4dde934b 100644 --- a/x/finality/keeper/tallying_test.go +++ b/x/finality/keeper/tallying_test.go @@ -55,7 +55,6 @@ func FuzzTallying_FinalizingNoBlock(f *testing.F) { require.False(t, ib.Finalized) } }) - } func FuzzTallying_FinalizingSomeBlocks(f *testing.F) { @@ -109,7 +108,6 @@ func FuzzTallying_FinalizingSomeBlocks(f *testing.F) { } } }) - } func giveQCToHeight(r *rand.Rand, ctx sdk.Context, fKeeper *keeper.Keeper, height uint64) error { diff --git a/x/monitor/module.go b/x/monitor/module.go index 0c1c95864..08e2ed00d 100644 --- a/x/monitor/module.go +++ b/x/monitor/module.go @@ -2,10 +2,11 @@ package monitor import ( "context" - "cosmossdk.io/core/appmodule" "encoding/json" "fmt" + "cosmossdk.io/core/appmodule" + "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" @@ -47,17 +48,17 @@ func (AppModuleBasic) Name() string { return types.ModuleName } -func (AppModuleBasic) RegisterCodec(cdc *codec.LegacyAmino) { +func (AppModuleBasic) RegisterCodec(_ *codec.LegacyAmino) { // types.RegisterCodec(cdc) } -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModuleBasic) RegisterLegacyAminoCodec(_ *codec.LegacyAmino) { // types.RegisterCodec(cdc) } // RegisterInterfaces registers the module's interface types -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { +func (a AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) { // types.RegisterInterfaces(reg) } @@ -76,7 +77,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod } // RegisterRESTRoutes registers the capability module's REST service handlers. -func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) { } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. From 8645bba2b87b9466c38ad767c779a8ba035a195c Mon Sep 17 00:00:00 2001 From: KonradStaniec Date: Tue, 3 Dec 2024 11:45:57 +0100 Subject: [PATCH 8/8] more fixes --- app/app_test.go | 3 +++ btcstaking/btcstaking_test.go | 1 - btcstaking/staking_test.go | 1 + btcstaking/types.go | 10 ++++----- client/client/keys.go | 2 +- crypto/eots/eots.go | 4 ++-- .../schnorr-adaptor-signature/sign_utils.go | 6 ++--- test/e2e/configurer/upgrade_test.go | 2 ++ test/e2e/containers/containers.go | 20 ++++++++--------- testutil/keeper/btclightclient.go | 2 +- types/btcutils_test.go | 7 +++--- wasmbinding/test/custom_query_test.go | 7 ++++++ x/btcstaking/keeper/inclusion_proof_test.go | 2 +- x/btcstaking/keeper/msg_server_test.go | 4 ++-- x/btcstaking/types/btc_delegation.go | 2 +- x/btcstaking/types/msg_test.go | 2 +- .../types/validate_parsed_message_test.go | 22 +++++++++---------- x/epoching/keeper/hooks.go | 8 +++---- x/epoching/keeper/modified_staking.go | 2 +- x/mint/types/minter_test.go | 3 +++ x/monitor/keeper/hooks.go | 12 +++++----- x/monitor/module.go | 2 +- 22 files changed, 70 insertions(+), 54 deletions(-) diff --git a/app/app_test.go b/app/app_test.go index 47599538d..d2639589d 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -13,6 +13,7 @@ import ( ) func TestBabylonBlockedAddrs(t *testing.T) { + t.Parallel() db := dbm.NewMemDB() signer, _ := SetupTestPrivSigner() logger := log.NewTestLogger(t) @@ -65,11 +66,13 @@ func TestBabylonBlockedAddrs(t *testing.T) { } func TestGetMaccPerms(t *testing.T) { + t.Parallel() dup := GetMaccPerms() require.Equal(t, maccPerms, dup, "duplicated module account permissions differed from actual module account permissions") } func TestUpgradeStateOnGenesis(t *testing.T) { + t.Parallel() db := dbm.NewMemDB() privSigner, err := SetupTestPrivSigner() require.NoError(t, err) diff --git a/btcstaking/btcstaking_test.go b/btcstaking/btcstaking_test.go index 287aa6686..f80df8b74 100644 --- a/btcstaking/btcstaking_test.go +++ b/btcstaking/btcstaking_test.go @@ -292,7 +292,6 @@ func TestSpendingUnbondingPathCovenant35MultiSig(t *testing.T) { ) } btctest.AssertEngineExecution(t, 0, true, newEngine) - } func TestSpendingUnbondingPathSingleKeyCovenant(t *testing.T) { diff --git a/btcstaking/staking_test.go b/btcstaking/staking_test.go index da28aaf64..718f086cd 100644 --- a/btcstaking/staking_test.go +++ b/btcstaking/staking_test.go @@ -252,6 +252,7 @@ func FuzzGeneratingSignatureValidation(f *testing.F) { } func TestSlashingTxWithOverflowMustNotAccepted(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) // we do not care for inputs in staking tx stakingTx := wire.NewMsgTx(2) diff --git a/btcstaking/types.go b/btcstaking/types.go index 5c6c72673..d3e7d1413 100644 --- a/btcstaking/types.go +++ b/btcstaking/types.go @@ -418,13 +418,13 @@ func BuildStakingInfo( ) if err != nil { - return nil, fmt.Errorf("%s: %w", errBuildingStakingInfo, err) + return nil, fmt.Errorf("%w: %w", errBuildingStakingInfo, err) } taprootPkScript, err := sh.taprootPkScript(net) if err != nil { - return nil, fmt.Errorf("%s: %w", errBuildingStakingInfo, err) + return nil, fmt.Errorf("%w: %w", errBuildingStakingInfo, err) } stakingOutput := wire.NewTxOut(int64(stakingAmount), taprootPkScript) @@ -486,7 +486,7 @@ func BuildUnbondingInfo( ) if err != nil { - return nil, fmt.Errorf("%s: %w", errBuildingUnbondingInfo, err) + return nil, fmt.Errorf("%w: %w", errBuildingUnbondingInfo, err) } var unbondingPaths [][]byte @@ -502,13 +502,13 @@ func BuildUnbondingInfo( ) if err != nil { - return nil, fmt.Errorf("%s: %w", errBuildingUnbondingInfo, err) + return nil, fmt.Errorf("%w: %w", errBuildingUnbondingInfo, err) } taprootPkScript, err := sh.taprootPkScript(net) if err != nil { - return nil, fmt.Errorf("%s: %w", errBuildingUnbondingInfo, err) + return nil, fmt.Errorf("%w: %w", errBuildingUnbondingInfo, err) } unbondingOutput := wire.NewTxOut(int64(unbondingAmount), taprootPkScript) diff --git a/client/client/keys.go b/client/client/keys.go index 2974ccbde..ca0360eec 100644 --- a/client/client/keys.go +++ b/client/client/keys.go @@ -15,7 +15,7 @@ func (c *Client) GetAddr() (string, error) { func (c *Client) MustGetAddr() string { addr, err := c.provider.Address() if err != nil { - panic(fmt.Errorf("failed to get signer: %v", err)) + panic(fmt.Errorf("failed to get signer: %w", err)) } return addr } diff --git a/crypto/eots/eots.go b/crypto/eots/eots.go index 5bb288980..eec1c6059 100644 --- a/crypto/eots/eots.go +++ b/crypto/eots/eots.go @@ -207,7 +207,7 @@ func extractFromHashes(pubKey *PublicKey, r *PublicRand, hash1 [32]byte, sig1 *S pBytes := pubKey.SerializeCompressed()[1:] if sig1.Equals(sig2) { - return nil, errors.New("The two signatures need to be different in order to extract") + return nil, errors.New("the two signatures need to be different in order to extract") } commitment1 := chainhash.TaggedHash(chainhash.TagBIP0340Challenge, rBytes[:], pBytes, hash1[:]) @@ -238,6 +238,6 @@ func extractFromHashes(pubKey *PublicKey, r *PublicRand, hash1 [32]byte, sig1 *S if privKey.PubKey().IsEqual(pubKey) { return privKey, nil } else { - return privKey, errors.New("Extracted private key does not match public key") + return privKey, errors.New("extracted private key does not match public key") } } diff --git a/crypto/schnorr-adaptor-signature/sign_utils.go b/crypto/schnorr-adaptor-signature/sign_utils.go index e45dc4caf..50d5a3ee2 100644 --- a/crypto/schnorr-adaptor-signature/sign_utils.go +++ b/crypto/schnorr-adaptor-signature/sign_utils.go @@ -15,7 +15,7 @@ const ( AdaptorSignatureSize = JacobianPointSize + ModNScalarSize + 1 ) -func encSign(privKey, nonce *btcec.ModNScalar, pubKey *btcec.PublicKey, m []byte, T *btcec.JacobianPoint) (*AdaptorSignature, error) { +func encSign(privKey, nonce *btcec.ModNScalar, pubKey *btcec.PublicKey, m []byte, t *btcec.JacobianPoint) (*AdaptorSignature, error) { // R' = kG var RHat btcec.JacobianPoint k := *nonce @@ -23,7 +23,7 @@ func encSign(privKey, nonce *btcec.ModNScalar, pubKey *btcec.PublicKey, m []byte // get R = R'+T var R btcec.JacobianPoint - btcec.AddNonConst(&RHat, T, &R) + btcec.AddNonConst(&RHat, t, &R) // negate k and R if R.y is odd affineRWithEvenY, needNegation := intoPointWithEvenY(&R) R = *affineRWithEvenY @@ -52,7 +52,7 @@ func encSign(privKey, nonce *btcec.ModNScalar, pubKey *btcec.PublicKey, m []byte // can only be because of bad nonces. The caller function `EncSign` will // keep trying `encSign` until finding a nonce that generates correct // signature - if err := encVerify(sig, m, pBytes, T); err != nil { + if err := encVerify(sig, m, pBytes, t); err != nil { return nil, fmt.Errorf("the provided nonce does not work: %w", err) } diff --git a/test/e2e/configurer/upgrade_test.go b/test/e2e/configurer/upgrade_test.go index 2c5cc58c4..8d36e9af6 100644 --- a/test/e2e/configurer/upgrade_test.go +++ b/test/e2e/configurer/upgrade_test.go @@ -14,6 +14,7 @@ import ( ) func TestParseGovPropFromFile(t *testing.T) { + t.Parallel() cdc := app.NewTmpBabylonApp().AppCodec() pwd, err := os.Getwd() @@ -27,6 +28,7 @@ func TestParseGovPropFromFile(t *testing.T) { } func TestWriteGovPropToFile(t *testing.T) { + t.Parallel() cdc := app.NewTmpBabylonApp().AppCodec() pwd, err := os.Getwd() diff --git a/test/e2e/containers/containers.go b/test/e2e/containers/containers.go index f2977256f..d24d01237 100644 --- a/test/e2e/containers/containers.go +++ b/test/e2e/containers/containers.go @@ -61,8 +61,8 @@ func NewManager(identifier string, isDebugLogEnabled bool, isCosmosRelayer, isUp } // ExecTxCmd Runs ExecTxCmdWithSuccessString searching for `code: 0` -func (m *Manager) ExecTxCmd(t *testing.T, chainId string, nodeName string, command []string) (bytes.Buffer, bytes.Buffer, error) { - return m.ExecTxCmdWithSuccessString(t, chainId, nodeName, command, "code: 0") +func (m *Manager) ExecTxCmd(t *testing.T, chainID string, nodeName string, command []string) (bytes.Buffer, bytes.Buffer, error) { + return m.ExecTxCmdWithSuccessString(t, chainID, nodeName, command, "code: 0") } // ExecTxCmdWithSuccessString Runs ExecCmd, with flags for txs added. @@ -88,7 +88,7 @@ func (m *Manager) ExecCmd(t *testing.T, fullContainerName string, command []stri if _, ok := m.resources[fullContainerName]; !ok { return bytes.Buffer{}, bytes.Buffer{}, fmt.Errorf("no resource %s found", fullContainerName) } - containerId := m.resources[fullContainerName].Container.ID + containerID := m.resources[fullContainerName].Container.ID var ( outBuf bytes.Buffer @@ -112,7 +112,7 @@ func (m *Manager) ExecCmd(t *testing.T, fullContainerName string, command []stri Context: ctx, AttachStdout: true, AttachStderr: true, - Container: containerId, + Container: containerID, User: "root", Cmd: command, }) @@ -251,7 +251,7 @@ func (m *Manager) RunRlyResource(chainAID, osmoARelayerNodeName, osmoAValMnemoni // RunNodeResource runs a node container. Assigns containerName to the container. // Mounts the container on valConfigDir volume on the running host. Returns the container resource and error if any. -func (m *Manager) RunNodeResource(chainId string, containerName, valCondifDir string) (*dockertest.Resource, error) { +func (m *Manager) RunNodeResource(chainID string, containerName, valCondifDir string) (*dockertest.Resource, error) { pwd, err := os.Getwd() if err != nil { return nil, err @@ -304,12 +304,12 @@ func (m *Manager) GetNodeResource(containerName string) (*dockertest.Resource, e // necessary to connect to the portId exposed inside the container. // The container is determined by containerName. // Returns the host-port or error if any. -func (m *Manager) GetHostPort(nodeName string, portId string) (string, error) { +func (m *Manager) GetHostPort(nodeName string, portID string) (string, error) { resource, err := m.GetNodeResource(nodeName) if err != nil { return "", err } - return resource.GetHostPort(portId), nil + return resource.GetHostPort(portID), nil } // RemoveNodeResource removes a node container specified by containerName. @@ -362,7 +362,7 @@ func noRestart(config *docker.HostConfig) { // Returns the container resource and error if any. This method does not Purge the container. The caller // must deal with removing the resource. func (m *Manager) RunChainInitResource( - chainId string, + chainID string, chainVotingPeriod, chainExpeditedVotingPeriod int, validatorConfigBytes []byte, mountDir string, @@ -374,12 +374,12 @@ func (m *Manager) RunChainInitResource( initResource, err := m.pool.RunWithOptions( &dockertest.RunOptions{ - Name: chainId, + Name: chainID, Repository: InitChainContainerE2E, NetworkID: m.network.Network.ID, Cmd: []string{ fmt.Sprintf("--data-dir=%s", mountDir), - fmt.Sprintf("--chain-id=%s", chainId), + fmt.Sprintf("--chain-id=%s", chainID), fmt.Sprintf("--config=%s", validatorConfigBytes), fmt.Sprintf("--voting-period=%v", votingPeriodDuration), fmt.Sprintf("--expedited-voting-period=%v", expeditedVotingPeriodDuration), diff --git a/testutil/keeper/btclightclient.go b/testutil/keeper/btclightclient.go index 711308755..29aef9b0a 100644 --- a/testutil/keeper/btclightclient.go +++ b/testutil/keeper/btclightclient.go @@ -29,7 +29,7 @@ import ( type MockIncentiveKeeper struct{} -func (mik MockIncentiveKeeper) IndexRefundableMsg(ctx context.Context, msg sdk.Msg) {} +func (mik MockIncentiveKeeper) IndexRefundableMsg(_ context.Context, _ sdk.Msg) {} func BTCLightClientKeeper(t testing.TB) (*btclightclientk.Keeper, sdk.Context) { k, ctx, _ := BTCLightClientKeeperWithCustomParams(t, btclightclientt.DefaultParams()) diff --git a/types/btcutils_test.go b/types/btcutils_test.go index 7bd100a53..26f821e55 100644 --- a/types/btcutils_test.go +++ b/types/btcutils_test.go @@ -1,13 +1,14 @@ package types_test import ( + "math/big" + "testing" + "time" + "github.com/babylonlabs-io/babylon/types" btcchaincfg "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/wire" "github.com/stretchr/testify/suite" - "math/big" - "testing" - "time" ) type btcutilsTestSuite struct { diff --git a/wasmbinding/test/custom_query_test.go b/wasmbinding/test/custom_query_test.go index afa10352a..89fbfcd47 100644 --- a/wasmbinding/test/custom_query_test.go +++ b/wasmbinding/test/custom_query_test.go @@ -40,6 +40,7 @@ func getArtifactPath() string { var pathToContract = getArtifactPath() func TestQueryEpoch(t *testing.T) { + t.Parallel() acc := randomAccountAddress() babylonApp, ctx := setupAppWithContext(t) fundAccount(t, ctx, babylonApp, acc) @@ -61,6 +62,7 @@ func TestQueryEpoch(t *testing.T) { } func TestFinalizedEpoch(t *testing.T) { + t.Parallel() acc := randomAccountAddress() babylonApp, ctx := setupAppWithContext(t) fundAccount(t, ctx, babylonApp, acc) @@ -88,6 +90,7 @@ func TestFinalizedEpoch(t *testing.T) { } func TestQueryBtcTip(t *testing.T) { + t.Parallel() acc := randomAccountAddress() babylonApp, ctx := setupAppWithContext(t) fundAccount(t, ctx, babylonApp, acc) @@ -109,6 +112,7 @@ func TestQueryBtcTip(t *testing.T) { } func TestQueryBtcBase(t *testing.T) { + t.Parallel() acc := randomAccountAddress() babylonApp, ctx := setupAppWithContext(t) fundAccount(t, ctx, babylonApp, acc) @@ -129,6 +133,7 @@ func TestQueryBtcBase(t *testing.T) { } func TestQueryBtcByHash(t *testing.T) { + t.Parallel() acc := randomAccountAddress() babylonApp, ctx := setupAppWithContext(t) fundAccount(t, ctx, babylonApp, acc) @@ -150,6 +155,7 @@ func TestQueryBtcByHash(t *testing.T) { } func TestQueryBtcByNumber(t *testing.T) { + t.Parallel() acc := randomAccountAddress() babylonApp, ctx := setupAppWithContext(t) fundAccount(t, ctx, babylonApp, acc) @@ -171,6 +177,7 @@ func TestQueryBtcByNumber(t *testing.T) { } func TestQueryNonExistingHeader(t *testing.T) { + t.Parallel() acc := randomAccountAddress() babylonApp, ctx := setupAppWithContext(t) fundAccount(t, ctx, babylonApp, acc) diff --git a/x/btcstaking/keeper/inclusion_proof_test.go b/x/btcstaking/keeper/inclusion_proof_test.go index 924c36960..6d961aea8 100644 --- a/x/btcstaking/keeper/inclusion_proof_test.go +++ b/x/btcstaking/keeper/inclusion_proof_test.go @@ -101,7 +101,7 @@ func FuzzVerifyInclusionProofAndGetHeight(f *testing.F) { proof, ) - expErr := fmt.Errorf("staking tx inclusion proof header %s is not found in BTC light client state: %v", proof.HeaderHash.MarshalHex(), btclctypes.ErrHeaderDoesNotExist.Wrap("no header with provided hash")) + expErr := fmt.Errorf("staking tx inclusion proof header %s is not found in BTC light client state: %w", proof.HeaderHash.MarshalHex(), btclctypes.ErrHeaderDoesNotExist.Wrap("no header with provided hash")) require.EqualError(t, err, expErr.Error()) }) diff --git a/x/btcstaking/keeper/msg_server_test.go b/x/btcstaking/keeper/msg_server_test.go index 76b0ce1d9..93b544004 100644 --- a/x/btcstaking/keeper/msg_server_test.go +++ b/x/btcstaking/keeper/msg_server_test.go @@ -49,7 +49,7 @@ func FuzzMsgServer_UpdateParams(f *testing.F) { params := h.BTCStakingKeeper.GetParams(h.Ctx) ckptFinalizationTimeout := btccKeeper.GetParams(h.Ctx).CheckpointFinalizationTimeout params.MinUnbondingTimeBlocks = uint32(r.Intn(int(ckptFinalizationTimeout))) + 1 - params.BtcActivationHeight = params.BtcActivationHeight + 1 + params.BtcActivationHeight++ // Try to update params with minUnbondingTime less than or equal to checkpointFinalizationTimeout msg := &types.MsgUpdateParams{ @@ -361,7 +361,7 @@ func TestProperVersionInDelegation(t *testing.T) { customMinUnbondingTime := uint32(2000) currentParams := h.BTCStakingKeeper.GetParams(h.Ctx) currentParams.MinUnbondingTimeBlocks = 2000 - currentParams.BtcActivationHeight = currentParams.BtcActivationHeight + 1 + currentParams.BtcActivationHeight++ // Update new params err = h.BTCStakingKeeper.SetParams(h.Ctx, currentParams) require.NoError(t, err) diff --git a/x/btcstaking/types/btc_delegation.go b/x/btcstaking/types/btc_delegation.go index e24dace58..355377321 100644 --- a/x/btcstaking/types/btc_delegation.go +++ b/x/btcstaking/types/btc_delegation.go @@ -397,7 +397,7 @@ func (d *BTCDelegation) BuildSlashingTxWithWitness(bsParams *Params, btcNet *cha ) if err != nil { return nil, fmt.Errorf( - "failed to build witness for BTC delegation of %s under finality provider %s: %v", + "failed to build witness for BTC delegation of %s under finality provider %s: %w", d.BtcPk.MarshalHex(), bbn.NewBIP340PubKeyFromBTCPK(fpSK.PubKey()).MarshalHex(), err, diff --git a/x/btcstaking/types/msg_test.go b/x/btcstaking/types/msg_test.go index a93d9bea1..96fe10704 100644 --- a/x/btcstaking/types/msg_test.go +++ b/x/btcstaking/types/msg_test.go @@ -150,7 +150,7 @@ func TestMsgCreateFinalityProviderValidateBasic(t *testing.T) { BtcPk: fp.BtcPk, Pop: fp.Pop, }, - fmt.Errorf("invalid FP addr: %s - %v", invalidAddr, fmt.Errorf("decoding bech32 failed: invalid separator index -1")), + fmt.Errorf("invalid FP addr: %s - %w", invalidAddr, fmt.Errorf("decoding bech32 failed: invalid separator index -1")), }, { "invalid: bad PoP empty sig", diff --git a/x/btcstaking/types/validate_parsed_message_test.go b/x/btcstaking/types/validate_parsed_message_test.go index 028001e1f..8e5d6ee55 100644 --- a/x/btcstaking/types/validate_parsed_message_test.go +++ b/x/btcstaking/types/validate_parsed_message_test.go @@ -317,7 +317,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { checkpointParams := testCheckpointParams() msg, _ := createMsgDelegationForParams(r, t, params, checkpointParams) - msg.StakingTime = msg.StakingTime + 1 + msg.StakingTime++ return msg, params, checkpointParams }, @@ -331,7 +331,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { checkpointParams := testCheckpointParams() msg, _ := createMsgDelegationForParams(r, t, params, checkpointParams) - msg.StakingValue = msg.StakingValue + 1 + msg.StakingValue++ return msg, params, checkpointParams }, @@ -515,7 +515,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { invalidSlashingPkScript := make([]byte, len(params.SlashingPkScript)) copy(invalidSlashingPkScript, params.SlashingPkScript) // change one byte in the pk script - invalidSlashingPkScript[0] = invalidSlashingPkScript[0] + 1 + invalidSlashingPkScript[0]++ // slashing output must always be first output currentSlashingTx.TxOut[0].PkScript = invalidSlashingPkScript @@ -541,7 +541,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { invalidHashBytes := currentSlashingTx.TxIn[0].PreviousOutPoint.Hash.CloneBytes() // change one byte in the hash - invalidHashBytes[0] = invalidHashBytes[0] + 1 + invalidHashBytes[0]++ invalidHash, err := chainhash.NewHash(invalidHashBytes) require.NoError(t, err) @@ -590,7 +590,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { invalidSlashingSig := make([]byte, len(sigInMessage)) copy(invalidSlashingSig, sigInMessage) // change last byte is sig - invalidSlashingSig[63] = invalidSlashingSig[63] + 1 + invalidSlashingSig[63]++ newSig, err := bbn.NewBIP340Signature(invalidSlashingSig) require.NoError(t, err) @@ -614,7 +614,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { invalidHashBytes := currentSlashingTx.TxIn[0].PreviousOutPoint.Hash.CloneBytes() // change one byte in the hash - invalidHashBytes[0] = invalidHashBytes[0] + 1 + invalidHashBytes[0]++ invalidHash, err := chainhash.NewHash(invalidHashBytes) require.NoError(t, err) @@ -664,7 +664,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { invalidSlashingPkScript := make([]byte, len(params.SlashingPkScript)) copy(invalidSlashingPkScript, params.SlashingPkScript) // change one byte in the pk script - invalidSlashingPkScript[0] = invalidSlashingPkScript[0] + 1 + invalidSlashingPkScript[0]++ // slashing output must always be first output currentUnbondingSlashingTx.TxOut[0].PkScript = invalidSlashingPkScript @@ -690,7 +690,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { invalidSlashingSig := make([]byte, len(sigInMessage)) copy(invalidSlashingSig, sigInMessage) // change last byte is sig - invalidSlashingSig[63] = invalidSlashingSig[63] + 1 + invalidSlashingSig[63]++ newSig, err := bbn.NewBIP340Signature(invalidSlashingSig) require.NoError(t, err) @@ -714,7 +714,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { invalidHashBytes := currentUnbondingTx.TxIn[0].PreviousOutPoint.Hash.CloneBytes() // change one byte in the hash - invalidHashBytes[0] = invalidHashBytes[0] + 1 + invalidHashBytes[0]++ invalidHash, err := chainhash.NewHash(invalidHashBytes) require.NoError(t, err) @@ -798,7 +798,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { params, ) - msg.UnbondingValue = msg.UnbondingValue + 1 + msg.UnbondingValue++ msg.UnbondingTx = newUnbondingInfdo.serializedUnbondingTx msg.UnbondingSlashingTx = newUnbondingInfdo.unbondingSlashingTx msg.DelegatorUnbondingSlashingSig = newUnbondingInfdo.unbondingSlashinSig @@ -855,7 +855,7 @@ func TestValidateParsedMessageAgainstTheParams(t *testing.T) { ) // to cause the unbonding value mismatch with the unbonding tx output value - msg.UnbondingValue = msg.UnbondingValue + 1 + msg.UnbondingValue++ msg.UnbondingTx = newUnbondingInfdo.serializedUnbondingTx msg.UnbondingSlashingTx = newUnbondingInfdo.unbondingSlashingTx msg.DelegatorUnbondingSlashingSig = newUnbondingInfdo.unbondingSlashinSig diff --git a/x/epoching/keeper/hooks.go b/x/epoching/keeper/hooks.go index a174d67b5..06d37bfde 100644 --- a/x/epoching/keeper/hooks.go +++ b/x/epoching/keeper/hooks.go @@ -47,7 +47,7 @@ var _ checkpointingtypes.CheckpointingHooks = Hooks{} func (k Keeper) Hooks() Hooks { return Hooks{k} } // BeforeValidatorSlashed records the slash event -func (h Hooks) BeforeValidatorSlashed(ctx context.Context, valAddr sdk.ValAddress, fraction math.LegacyDec) error { +func (h Hooks) BeforeValidatorSlashed(ctx context.Context, valAddr sdk.ValAddress, _ math.LegacyDec) error { sdkCtx := sdk.UnwrapSDKContext(ctx) thresholds := []float64{float64(1) / float64(3), float64(2) / float64(3)} @@ -92,15 +92,15 @@ func (h Hooks) AfterValidatorCreated(ctx context.Context, valAddr sdk.ValAddress return h.k.RecordNewValState(sdk.UnwrapSDKContext(ctx), valAddr, types.BondState_CREATED) } -func (h Hooks) AfterValidatorRemoved(ctx context.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { +func (h Hooks) AfterValidatorRemoved(ctx context.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) error { return h.k.RecordNewValState(sdk.UnwrapSDKContext(ctx), valAddr, types.BondState_REMOVED) } -func (h Hooks) AfterValidatorBonded(ctx context.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { +func (h Hooks) AfterValidatorBonded(ctx context.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) error { return h.k.RecordNewValState(sdk.UnwrapSDKContext(ctx), valAddr, types.BondState_BONDED) } -func (h Hooks) AfterValidatorBeginUnbonding(ctx context.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { +func (h Hooks) AfterValidatorBeginUnbonding(ctx context.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) error { return h.k.RecordNewValState(sdk.UnwrapSDKContext(ctx), valAddr, types.BondState_UNBONDING) } diff --git a/x/epoching/keeper/modified_staking.go b/x/epoching/keeper/modified_staking.go index d0b122c11..c5ea4cb3a 100644 --- a/x/epoching/keeper/modified_staking.go +++ b/x/epoching/keeper/modified_staking.go @@ -179,7 +179,7 @@ func (k Keeper) getAllMatureValidators(ctx sdk.Context) []sdk.ValAddress { // over are not ready to unbond, so an explicit check is required. unbondingValIterator, err := k.stk.ValidatorQueueIterator(ctx, blockTime, blockHeight) if err != nil { - panic(fmt.Errorf("could not get iterator to validator's queue: %s", err)) + panic(fmt.Errorf("could not get iterator to validator's queue: %w", err)) } defer unbondingValIterator.Close() diff --git a/x/mint/types/minter_test.go b/x/mint/types/minter_test.go index a2a066912..e1eee2653 100644 --- a/x/mint/types/minter_test.go +++ b/x/mint/types/minter_test.go @@ -14,6 +14,7 @@ import ( ) func TestCalculateInflationRate(t *testing.T) { + t.Parallel() minter := DefaultMinter() genesisTime := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC) @@ -78,6 +79,7 @@ func TestCalculateInflationRate(t *testing.T) { } func TestCalculateBlockProvision(t *testing.T) { + t.Parallel() minter := DefaultMinter() current := time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC) blockInterval := 15 * time.Second @@ -133,6 +135,7 @@ func TestCalculateBlockProvision(t *testing.T) { // TestCalculateBlockProvisionError verifies that the error for total block // provisions in a year is less than .01 func TestCalculateBlockProvisionError(t *testing.T) { + t.Parallel() minter := DefaultMinter() current := time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC) oneYear := time.Duration(NanosecondsPerYear) diff --git a/x/monitor/keeper/hooks.go b/x/monitor/keeper/hooks.go index 8a0a3d492..f6ed6c358 100644 --- a/x/monitor/keeper/hooks.go +++ b/x/monitor/keeper/hooks.go @@ -21,21 +21,21 @@ type Hooks struct { // Hooks Create new distribution hooks func (k Keeper) Hooks() Hooks { return Hooks{k} } -func (h Hooks) AfterEpochBegins(ctx context.Context, epoch uint64) {} +func (h Hooks) AfterEpochBegins(_ context.Context, _ uint64) {} func (h Hooks) AfterEpochEnds(ctx context.Context, epoch uint64) { h.k.updateBtcLightClientHeightForEpoch(ctx, epoch) } -func (h Hooks) BeforeSlashThreshold(ctx context.Context, valSet etypes.ValidatorSet) {} +func (h Hooks) BeforeSlashThreshold(_ context.Context, _ etypes.ValidatorSet) {} -func (h Hooks) AfterBlsKeyRegistered(ctx context.Context, valAddr sdk.ValAddress) error { +func (h Hooks) AfterBlsKeyRegistered(_ context.Context, _ sdk.ValAddress) error { return nil } -func (h Hooks) AfterRawCheckpointSealed(ctx context.Context, epoch uint64) error { +func (h Hooks) AfterRawCheckpointSealed(_ context.Context, _ uint64) error { return nil } -func (h Hooks) AfterRawCheckpointConfirmed(ctx context.Context, epoch uint64) error { +func (h Hooks) AfterRawCheckpointConfirmed(_ context.Context, _ uint64) error { return nil } @@ -43,7 +43,7 @@ func (h Hooks) AfterRawCheckpointForgotten(ctx context.Context, ckpt *checkpoint return h.k.removeCheckpointRecord(ctx, ckpt) } -func (h Hooks) AfterRawCheckpointFinalized(ctx context.Context, epoch uint64) error { +func (h Hooks) AfterRawCheckpointFinalized(_ context.Context, _ uint64) error { return nil } diff --git a/x/monitor/module.go b/x/monitor/module.go index 08e2ed00d..6c1a31192 100644 --- a/x/monitor/module.go +++ b/x/monitor/module.go @@ -68,7 +68,7 @@ func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { } // ValidateGenesis performs genesis state validation for the capability module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { var genState types.GenesisState if err := cdc.UnmarshalJSON(bz, &genState); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)