diff --git a/.golangci.yml b/.golangci.yml index b8c7d682f24f..ffece2cc4ab7 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -63,10 +63,139 @@ linters-settings: # Default: false extra-rules: true dogsled: - max-blank-identifiers: 3 - maligned: - # print struct with more effective memory layout or not, false by default - suggest-new: true + max-blank-identifiers: 5 + + gosec: + # To select a subset of rules to run. + # Available rules: https://github.com/securego/gosec#available-rules + # Default: [] - means include all rules + includes: + # - G101 # Look for hard coded credentials + - G102 # Bind to all interfaces + - G103 # Audit the use of unsafe block + - G104 # Audit errors not checked + - G106 # Audit the use of ssh.InsecureIgnoreHostKey + - G107 # Url provided to HTTP request as taint input + - G108 # Profiling endpoint automatically exposed on /debug/pprof + - G109 # Potential Integer overflow made by strconv.Atoi result conversion to int16/32 + - G110 # Potential DoS vulnerability via decompression bomb + - G111 # Potential directory traversal + - G112 # Potential slowloris attack + - G113 # Usage of Rat.SetString in math/big with an overflow (CVE-2022-23772) + - G114 # Use of net/http serve function that has no support for setting timeouts + - G201 # SQL query construction using format string + - G202 # SQL query construction using string concatenation + - G203 # Use of unescaped data in HTML templates + - G204 # Audit use of command execution + - G301 # Poor file permissions used when creating a directory + - G302 # Poor file permissions used with chmod + - G303 # Creating tempfile using a predictable path + - G304 # File path provided as taint input + - G305 # File traversal when extracting zip/tar archive + - G306 # Poor file permissions used when writing to a new file + - G307 # Deferring a method which returns an error + - G401 # Detect the usage of DES, RC4, MD5 or SHA1 + - G402 # Look for bad TLS connection settings + - G403 # Ensure minimum RSA key length of 2048 bits + - G404 # Insecure random number source (rand) + - G501 # Import blocklist: crypto/md5 + - G502 # Import blocklist: crypto/des + - G503 # Import blocklist: crypto/rc4 + - G504 # Import blocklist: net/http/cgi + - G505 # Import blocklist: crypto/sha1 + - G601 # Implicit memory aliasing of items from a range statement + # To specify a set of rules to explicitly exclude. + # Available rules: https://github.com/securego/gosec#available-rules + # Default: [] + # Exclude generated files + # Default: false + exclude-generated: false + # Filter out the issues with a lower severity than the given value. + # Valid options are: low, medium, high. + # Default: low + severity: low + # Filter out the issues with a lower confidence than the given value. + # Valid options are: low, medium, high. + # Default: low + confidence: low + # Concurrency value. + # Default: the number of logical CPUs usable by the current process. + concurrency: 12 + # To specify the configuration of rules. + config: + # Globals are applicable to all rules. + global: + # If true, ignore #nosec in comments (and an alternative as well). + # Default: false + nosec: false + # Add an alternative comment prefix to #nosec (both will work at the same time). + # Default: "" + "#nosec": "#my-custom-nosec" + # Define whether nosec issues are counted as finding or not. + # Default: false + show-ignored: true + # Audit mode enables addition checks that for normal code analysis might be too nosy. + # Default: false + audit: false + # G101: + # Regexp pattern for variables and constants to find. + # Default: "(?i)passwd|pass|password|pwd|secret|token|pw|apiKey|bearer|cred" + # pattern: "(?i)example" + # If true, complain about all cases (even with low entropy). + # Default: false + # ignore_entropy: false + # Maximum allowed entropy of the string. + # Default: "80.0" + # entropy_threshold: "80.0" + # Maximum allowed value of entropy/string length. + # Is taken into account if entropy >= entropy_threshold/2. + # Default: "3.0" + # per_char_threshold: "3.0" + # Calculate entropy for first N chars of the string. + # Default: "16" + # truncate: "16" + # Additional functions to ignore while checking unhandled errors. + # Following functions always ignored: + # bytes.Buffer: + # - Write + # - WriteByte + # - WriteRune + # - WriteString + # fmt: + # - Print + # - Printf + # - Println + # - Fprint + # - Fprintf + # - Fprintln + # strings.Builder: + # - Write + # - WriteByte + # - WriteRune + # - WriteString + # io.PipeWriter: + # - CloseWithError + # hash.Hash: + # - Write + # os: + # - Unsetenv + # Default: {} + G104: + fmt: + - Fscanf + G111: + # Regexp pattern to find potential directory traversal. + # Default: "http\\.Dir\\(\"\\/\"\\)|http\\.Dir\\('\\/'\\)" + pattern: "custom\\.Dir\\(\\)" + # Maximum allowed permissions mode for os.Mkdir and os.MkdirAll + # Default: "0750" + G301: "0750" + # Maximum allowed permissions mode for os.OpenFile and os.Chmod + # Default: "0600" + G302: "0600" + # Maximum allowed permissions mode for os.WriteFile and ioutil.WriteFile + # Default: "0600" + G306: "0600" nolintlint: allow-unused: false allow-leading-space: true diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index cba39a846944..4d803df0783c 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -48,7 +48,7 @@ const ( var _ abci.Application = (*BaseApp)(nil) // BaseApp reflects the ABCI application implementation. -type BaseApp struct { //nolint: maligned +type BaseApp struct { // initialized on creation logger log.Logger name string // application name from abci.Info @@ -861,7 +861,7 @@ func (app *BaseApp) PrepareProposalVerifyTx(tx sdk.Tx) ([]byte, error) { return nil, err } - _, _, _, _, err = app.runTx(runTxPrepareProposal, bz) //nolint:dogsled + _, _, _, _, err = app.runTx(runTxPrepareProposal, bz) if err != nil { return nil, err } @@ -880,7 +880,7 @@ func (app *BaseApp) ProcessProposalVerifyTx(txBz []byte) (sdk.Tx, error) { return nil, err } - _, _, _, _, err = app.runTx(runTxProcessProposal, txBz) //nolint:dogsled + _, _, _, _, err = app.runTx(runTxProcessProposal, txBz) if err != nil { return nil, err } diff --git a/baseapp/block_gas_test.go b/baseapp/block_gas_test.go index 5c79772d2c8c..c1f4ff2f5c63 100644 --- a/baseapp/block_gas_test.go +++ b/baseapp/block_gas_test.go @@ -221,7 +221,7 @@ func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs [] Sequence: accSeqs[i], } sigV2, err := tx.SignWithPrivKey( - nil, txConfig.SignModeHandler().DefaultMode(), signerData, //nolint:staticcheck + context.TODO(), txConfig.SignModeHandler().DefaultMode(), signerData, txBuilder, priv, txConfig, accSeqs[i]) if err != nil { return nil, nil, err diff --git a/client/config/config_test.go b/client/config/config_test.go index 64e28ccc3d76..c5630f22a378 100644 --- a/client/config/config_test.go +++ b/client/config/config_test.go @@ -24,12 +24,12 @@ const ( // initClientContext initiates client Context for tests func initClientContext(t *testing.T, envVar string) (client.Context, func()) { home := t.TempDir() - chainId := "test-chain" //nolint:revive + chainID := "test-chain" clientCtx := client.Context{}. WithHomeDir(home). WithViper(""). WithCodec(codec.NewProtoCodec(codectypes.NewInterfaceRegistry())). - WithChainID(chainId) + WithChainID(chainID) require.NoError(t, clientCtx.Viper.BindEnv(nodeEnv)) if envVar != "" { @@ -38,7 +38,7 @@ func initClientContext(t *testing.T, envVar string) (client.Context, func()) { clientCtx, err := config.ReadFromClientConfig(clientCtx) require.NoError(t, err) - require.Equal(t, clientCtx.ChainID, chainId) + require.Equal(t, clientCtx.ChainID, chainID) return clientCtx, func() { _ = os.RemoveAll(home) } } diff --git a/client/context_test.go b/client/context_test.go index bc531042188a..7145dada0092 100644 --- a/client/context_test.go +++ b/client/context_test.go @@ -20,6 +20,11 @@ import ( "github.com/cosmos/cosmos-sdk/types/module/testutil" ) +const ( + text = "text" + jsonText = "json" +) + func TestMain(m *testing.M) { viper.Set(flags.FlagKeyringBackend, keyring.BackendMemory) os.Exit(m.Run()) @@ -46,7 +51,7 @@ func TestContext_PrintProto(t *testing.T) { // json buf := &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "json" //nolint:goconst + ctx.OutputFormat = jsonText err = ctx.PrintProto(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -56,7 +61,7 @@ func TestContext_PrintProto(t *testing.T) { // yaml buf = &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "text" //nolint:goconst + ctx.OutputFormat = text err = ctx.PrintProto(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -89,7 +94,7 @@ func TestContext_PrintObjectLegacy(t *testing.T) { // json buf := &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "json" + ctx.OutputFormat = jsonText err = ctx.PrintObjectLegacy(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -99,7 +104,7 @@ func TestContext_PrintObjectLegacy(t *testing.T) { // yaml buf = &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "text" + ctx.OutputFormat = text err = ctx.PrintObjectLegacy(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -121,7 +126,7 @@ func TestContext_PrintRaw(t *testing.T) { // json buf := &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "json" + ctx.OutputFormat = jsonText err := ctx.PrintRaw(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -131,7 +136,7 @@ func TestContext_PrintRaw(t *testing.T) { // yaml buf = &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "text" + ctx.OutputFormat = text err = ctx.PrintRaw(hasAnimal) require.NoError(t, err) require.Equal(t, diff --git a/client/keys/import_test.go b/client/keys/import_test.go index 59cdf044d9cf..d9b9d0fee79f 100644 --- a/client/keys/import_test.go +++ b/client/keys/import_test.go @@ -94,7 +94,7 @@ HbP+c6JmeJy9JXe2rbbF1QtCX1gLqGcDQPBXiCtFvP7/8wTZtVOPj8vREzhZ9ElO t.Cleanup(cleanupKeys(t, kb, "keyname1")) keyfile := filepath.Join(kbHome, "key.asc") - require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o644)) //nolint:gosec + require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o600)) defer func() { _ = os.RemoveAll(kbHome) diff --git a/client/keys/output.go b/client/keys/output.go index 893233498185..1ec5eed6a62c 100644 --- a/client/keys/output.go +++ b/client/keys/output.go @@ -21,7 +21,7 @@ type KeyOutput struct { } // NewKeyOutput creates a default KeyOutput instance without Mnemonic, Threshold and PubKeys -func NewKeyOutput(name string, keyType keyring.KeyType, a sdk.Address, pk cryptotypes.PubKey) (KeyOutput, error) { //nolint:interfacer +func NewKeyOutput(name string, keyType keyring.KeyType, a sdk.Address, pk cryptotypes.PubKey) (KeyOutput, error) { apk, err := codectypes.NewAnyWithValue(pk) if err != nil { return KeyOutput{}, err diff --git a/client/tx/tx.go b/client/tx/tx.go index 86c0caaa06ac..5fbc83eb1319 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -107,11 +107,11 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { buf := bufio.NewReader(os.Stdin) ok, err := input.GetConfirmation("confirm transaction before signing and broadcasting", buf, os.Stderr) if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "error: %v\ncancelled transaction\n", err) + _, _ = fmt.Fprintf(os.Stderr, "error: %v\ncanceled transaction\n", err) return err } if !ok { - _, _ = fmt.Fprintln(os.Stderr, "cancelled transaction") + _, _ = fmt.Fprintln(os.Stderr, "canceled transaction") return nil } } diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index 788b96c2f2f3..6c0d3a7eb2b5 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -1,7 +1,7 @@ package tx_test import ( - gocontext "context" + "context" "fmt" "strings" "testing" @@ -40,7 +40,7 @@ type mockContext struct { wantErr bool } -func (m mockContext) Invoke(grpcCtx gocontext.Context, method string, req, reply interface{}, opts ...grpc.CallOption) (err error) { +func (m mockContext) Invoke(grpcCtx context.Context, method string, req, reply interface{}, opts ...grpc.CallOption) (err error) { if m.wantErr { return fmt.Errorf("mock err") } @@ -53,7 +53,7 @@ func (m mockContext) Invoke(grpcCtx gocontext.Context, method string, req, reply return nil } -func (mockContext) NewStream(gocontext.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) { +func (mockContext) NewStream(context.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) { panic("not implemented") } @@ -347,7 +347,7 @@ func TestSign(t *testing.T) { var prevSigs []signingtypes.SignatureV2 for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - err = tx.Sign(nil, tc.txf, tc.from, tc.txb, tc.overwrite) //nolint:staticcheck + err = tx.Sign(context.TODO(), tc.txf, tc.from, tc.txb, tc.overwrite) if len(tc.expectedPKs) == 0 { requireT.Error(err) } else { @@ -418,7 +418,7 @@ func TestPreprocessHook(t *testing.T) { txb, err := txfDirect.BuildUnsignedTx(msg1, msg2) requireT.NoError(err) - err = tx.Sign(nil, txfDirect, from, txb, false) //nolint:staticcheck + err = tx.Sign(context.TODO(), txfDirect, from, txb, false) requireT.NoError(err) // Run preprocessing diff --git a/codec/proto_codec.go b/codec/proto_codec.go index ed71b8f897a3..32560b617ced 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -137,8 +137,6 @@ func (pc *ProtoCodec) MustUnmarshalLengthPrefixed(bz []byte, ptr gogoproto.Messa // it marshals to JSON using proto codec. // NOTE: this function must be used with a concrete type which // implements proto.Message. For interface please use the codec.MarshalInterfaceJSON -// -//nolint:stdmethods func (pc *ProtoCodec) MarshalJSON(o gogoproto.Message) ([]byte, error) { if o == nil { return nil, fmt.Errorf("cannot protobuf JSON encode nil") @@ -186,7 +184,7 @@ func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr gogoproto.Message) { } } -// MarshalInterface is a convenience function for proto marshalling interfaces. It packs +// MarshalInterface is a convenience function for proto marshaling interfaces. It packs // the provided value, which must be an interface, in an Any and then marshals it to bytes. // NOTE: to marshal a concrete type, you should use Marshal instead func (pc *ProtoCodec) MarshalInterface(i gogoproto.Message) ([]byte, error) { @@ -224,7 +222,7 @@ func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { return pc.UnpackAny(any, ptr) } -// MarshalInterfaceJSON is a convenience function for proto marshalling interfaces. It +// MarshalInterfaceJSON is a convenience function for proto marshaling interfaces. It // packs the provided value in an Any and then marshals it to bytes. // NOTE: to marshal a concrete type, you should use MarshalJSON instead func (pc *ProtoCodec) MarshalInterfaceJSON(x gogoproto.Message) ([]byte, error) { diff --git a/codec/types/any.go b/codec/types/any.go index 5ecc297f8e6b..c08b08d855be 100644 --- a/codec/types/any.go +++ b/codec/types/any.go @@ -1,4 +1,3 @@ -// nolint package types import ( diff --git a/codec/types/any_internal_test.go b/codec/types/any_internal_test.go index b2b12b123bdb..9adab2946653 100644 --- a/codec/types/any_internal_test.go +++ b/codec/types/any_internal_test.go @@ -17,7 +17,7 @@ func (d Dog) Greet() string { return d.Name } func (d *Dog) Reset() { d.Name = "" } func (d *Dog) String() string { return d.Name } func (d *Dog) ProtoMessage() {} -func (d *Dog) XXX_MessageName() string { return "tests/dog" } //nolint:revive +func (d *Dog) XXX_MessageName() string { return "tests/dog" } type Animal interface { Greet() string diff --git a/codec/types/any_test.go b/codec/types/any_test.go index 656344414a7e..5e2b29fcca22 100644 --- a/codec/types/any_test.go +++ b/codec/types/any_test.go @@ -19,7 +19,7 @@ var _ proto.Message = (*errOnMarshal)(nil) var errAlways = fmt.Errorf("always erroring") -func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { //nolint:revive +func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return nil, errAlways } diff --git a/codec/types/types_test.go b/codec/types/types_test.go index 2c24a87ce0c7..dddacfe18b0f 100644 --- a/codec/types/types_test.go +++ b/codec/types/types_test.go @@ -44,7 +44,7 @@ var ( func (dog FakeDog) Reset() {} func (dog FakeDog) String() string { return "fakedog" } func (dog FakeDog) ProtoMessage() {} -func (dog FakeDog) XXX_MessageName() string { return proto.MessageName(&testdata.Dog{}) } //nolint:revive +func (dog FakeDog) XXX_MessageName() string { return proto.MessageName(&testdata.Dog{}) } func (dog FakeDog) Greet() string { return "fakedog" } func TestRegister(t *testing.T) { diff --git a/codec/unknownproto/unknown_fields_test.go b/codec/unknownproto/unknown_fields_test.go index 7e0af479adbe..1a8fd0affd7e 100644 --- a/codec/unknownproto/unknown_fields_test.go +++ b/codec/unknownproto/unknown_fields_test.go @@ -656,11 +656,11 @@ func TestRejectUnknownFieldsFlat(t *testing.T) { func TestPackedEncoding(t *testing.T) { data := testdata.TestRepeatedUints{Nums: []uint64{12, 13}} - marshalled, err := data.Marshal() + marshaled, err := data.Marshal() require.NoError(t, err) unmarshalled := &testdata.TestRepeatedUints{} - _, err = RejectUnknownFields(marshalled, unmarshalled, false, DefaultAnyResolver{}) + _, err = RejectUnknownFields(marshaled, unmarshalled, false, DefaultAnyResolver{}) require.NoError(t, err) } diff --git a/core/coins/format_test.go b/core/coins/format_test.go index ded6a8760bbb..ba487e220465 100644 --- a/core/coins/format_test.go +++ b/core/coins/format_test.go @@ -12,15 +12,15 @@ import ( ) // coinsJsonTest is the type of test cases in the coin.json file. -type coinJsonTest struct { +type coinJSONTest struct { Proto *basev1beta1.Coin Metadata *bankv1beta1.Metadata Text string Error bool } -// coinsJsonTest is the type of test cases in the coins.json file. -type coinsJsonTest struct { +// coinsJSONTest is the type of test cases in the coins.json file. +type coinsJSONTest struct { Proto []*basev1beta1.Coin Metadata map[string]*bankv1beta1.Metadata Text string @@ -28,7 +28,7 @@ type coinsJsonTest struct { } func TestFormatCoin(t *testing.T) { - var testcases []coinJsonTest + var testcases []coinJSONTest raw, err := os.ReadFile("../../x/tx/signing/textual/internal/testdata/coin.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) @@ -52,7 +52,7 @@ func TestFormatCoin(t *testing.T) { } func TestFormatCoins(t *testing.T) { - var testcases []coinsJsonTest + var testcases []coinsJSONTest raw, err := os.ReadFile("../../x/tx/signing/textual/internal/testdata/coins.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) diff --git a/crypto/codec/amino.go b/crypto/codec/amino.go index 27bb10ce46b4..988c17ba1976 100644 --- a/crypto/codec/amino.go +++ b/crypto/codec/amino.go @@ -26,7 +26,7 @@ func RegisterCrypto(cdc *codec.LegacyAmino) { cdc.RegisterInterface((*cryptotypes.PrivKey)(nil), nil) cdc.RegisterConcrete(sr25519.PrivKey{}, sr25519.PrivKeyName, nil) - cdc.RegisterConcrete(&ed25519.PrivKey{}, //nolint:staticcheck + cdc.RegisterConcrete(&ed25519.PrivKey{}, ed25519.PrivKeyName, nil) cdc.RegisterConcrete(&secp256k1.PrivKey{}, secp256k1.PrivKeyName, nil) diff --git a/crypto/codec/proto.go b/crypto/codec/proto.go index 1340dab03de5..45cd5b4c35df 100644 --- a/crypto/codec/proto.go +++ b/crypto/codec/proto.go @@ -20,6 +20,6 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { var priv *cryptotypes.PrivKey registry.RegisterInterface("cosmos.crypto.PrivKey", priv) registry.RegisterImplementations(priv, &secp256k1.PrivKey{}) - registry.RegisterImplementations(priv, &ed25519.PrivKey{}) //nolint + registry.RegisterImplementations(priv, &ed25519.PrivKey{}) secp256r1.RegisterInterfaces(registry) } diff --git a/crypto/hd/hdpath_test.go b/crypto/hd/hdpath_test.go index 126a2a24f0ef..797a013f16ce 100644 --- a/crypto/hd/hdpath_test.go +++ b/crypto/hd/hdpath_test.go @@ -185,7 +185,7 @@ func TestDeriveHDPathRange(t *testing.T) { } } -func ExampleStringifyPathParams() { //nolint:govet +func ExampleStringifyPathParams() { path := hd.NewParams(44, 0, 0, false, 0) fmt.Println(path.String()) path = hd.NewParams(44, 33, 7, true, 9) @@ -195,7 +195,7 @@ func ExampleStringifyPathParams() { //nolint:govet // m/44'/33'/7'/1/9 } -func ExampleSomeBIP32TestVecs() { //nolint:govet +func ExampleSomeBIP32TestVecs() { seed := mnemonicToSeed("barrel original fuel morning among eternal " + "filter ball stove pluck matrix mechanic") master, ch := hd.ComputeMastersFromSeed(seed) diff --git a/crypto/keys/ed25519/ed25519.go b/crypto/keys/ed25519/ed25519.go index 37603f20f4d6..122be97cb254 100644 --- a/crypto/keys/ed25519/ed25519.go +++ b/crypto/keys/ed25519/ed25519.go @@ -94,12 +94,12 @@ func (privKey *PrivKey) Type() string { return keyType } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (privKey PrivKey) MarshalAmino() ([]byte, error) { return privKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { if len(bz) != PrivKeySize { return fmt.Errorf("invalid privkey size") @@ -109,14 +109,14 @@ func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return privKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { return privKey.UnmarshalAmino(bz) } @@ -203,12 +203,12 @@ func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { return subtle.ConstantTimeCompare(pubKey.Bytes(), other.Bytes()) == 1 } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (pubKey PubKey) MarshalAmino() ([]byte, error) { return pubKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { if len(bz) != PubKeySize { return errorsmod.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size") @@ -218,14 +218,14 @@ func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return pubKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { return pubKey.UnmarshalAmino(bz) } diff --git a/crypto/keys/ed25519/keys.pb.go b/crypto/keys/ed25519/keys.pb.go index 1280647df3ec..e24a1b3b35fb 100644 --- a/crypto/keys/ed25519/keys.pb.go +++ b/crypto/keys/ed25519/keys.pb.go @@ -73,7 +73,7 @@ func (m *PubKey) GetKey() crypto_ed25519.PublicKey { return nil } -// Deprecated: PrivKey defines a ed25519 private key. +// PrivKey defines a ed25519 private key. // NOTE: ed25519 keys must not be used in SDK apps except in a tendermint validator context. type PrivKey struct { Key crypto_ed25519.PrivateKey `protobuf:"bytes,1,opt,name=key,proto3,casttype=crypto/ed25519.PrivateKey" json:"key,omitempty"` diff --git a/crypto/keys/multisig/amino.go b/crypto/keys/multisig/amino.go index 8c83b27021f1..459c4fc05d93 100644 --- a/crypto/keys/multisig/amino.go +++ b/crypto/keys/multisig/amino.go @@ -66,7 +66,7 @@ func tmToProto(tmPk tmMultisig) (*LegacyAminoPubKey, error) { } // MarshalAminoJSON overrides amino JSON unmarshaling. -func (m LegacyAminoPubKey) MarshalAminoJSON() (tmMultisig, error) { //nolint:golint,revive +func (m LegacyAminoPubKey) MarshalAminoJSON() (tmMultisig, error) { return protoToTm(&m) } diff --git a/crypto/keys/secp256k1/secp256k1.go b/crypto/keys/secp256k1/secp256k1.go index 68208f859aef..380f16420d1a 100644 --- a/crypto/keys/secp256k1/secp256k1.go +++ b/crypto/keys/secp256k1/secp256k1.go @@ -53,12 +53,12 @@ func (privKey *PrivKey) Type() string { return keyType } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (privKey PrivKey) MarshalAmino() ([]byte, error) { return privKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { if len(bz) != PrivKeySize { return fmt.Errorf("invalid privkey size") @@ -68,14 +68,14 @@ func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return privKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { return privKey.UnmarshalAmino(bz) } @@ -179,12 +179,12 @@ func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes()) } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (pubKey PubKey) MarshalAmino() ([]byte, error) { return pubKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { if len(bz) != PubKeySize { return errorsmod.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size") @@ -194,14 +194,14 @@ func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return pubKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { return pubKey.UnmarshalAmino(bz) } diff --git a/crypto/keys/secp256r1/privkey_internal_test.go b/crypto/keys/secp256r1/privkey_internal_test.go index 771582d6a413..902ee6dafbf8 100644 --- a/crypto/keys/secp256r1/privkey_internal_test.go +++ b/crypto/keys/secp256r1/privkey_internal_test.go @@ -51,7 +51,7 @@ func (suite *SKSuite) TestBytes() { func (suite *SKSuite) TestMarshalProto() { require := suite.Require() - /**** test structure marshalling ****/ + /**** test structure marshaling ****/ var sk PrivKey bz, err := proto.Marshal(suite.sk) @@ -59,7 +59,7 @@ func (suite *SKSuite) TestMarshalProto() { require.NoError(proto.Unmarshal(bz, &sk)) require.True(sk.Equals(suite.sk)) - /**** test structure marshalling with codec ****/ + /**** test structure marshaling with codec ****/ sk = PrivKey{} registry := types.NewInterfaceRegistry() diff --git a/crypto/keys/secp256r1/pubkey_internal_test.go b/crypto/keys/secp256r1/pubkey_internal_test.go index 2015b32cb307..d3d2ed3823eb 100644 --- a/crypto/keys/secp256r1/pubkey_internal_test.go +++ b/crypto/keys/secp256r1/pubkey_internal_test.go @@ -68,7 +68,7 @@ func (suite *PKSuite) TestEquals() { func (suite *PKSuite) TestMarshalProto() { require := suite.Require() - /**** test structure marshalling ****/ + /**** test structure marshaling ****/ var pk PubKey bz, err := proto.Marshal(suite.pk) @@ -76,7 +76,7 @@ func (suite *PKSuite) TestMarshalProto() { require.NoError(proto.Unmarshal(bz, &pk)) require.True(pk.Equals(suite.pk)) - /**** test structure marshalling with codec ****/ + /**** test structure marshaling with codec ****/ pk = PubKey{} emptyRegistry := types.NewInterfaceRegistry() @@ -104,7 +104,7 @@ func (suite *PKSuite) TestMarshalProto() { require.Len(bz2, bufSize) require.Equal(bz, bz2[(bufSize-pk.Size()):]) - /**** test interface marshalling ****/ + /**** test interface marshaling ****/ bz, err = pubkeyCodec.MarshalInterface(suite.pk) require.NoError(err) var pkI cryptotypes.PubKey diff --git a/crypto/ledger/encode_test.go b/crypto/ledger/encode_test.go index f9ce2418fd8b..099c8e91a38e 100644 --- a/crypto/ledger/encode_test.go +++ b/crypto/ledger/encode_test.go @@ -24,7 +24,7 @@ func checkAminoJSON(t *testing.T, src, dst interface{}, isNil bool) { require.Nil(t, err, "%+v", err) } -func ExamplePrintRegisteredTypes() { //nolint:govet +func ExamplePrintRegisteredTypes() { _ = cdc.PrintTypes(os.Stdout) // | Type | Name | Prefix | Length | Notes | // | ---- | ---- | ------ | ----- | ------ | diff --git a/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go b/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go index 9428c514d6e5..6923cc9416c6 100644 --- a/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go +++ b/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go @@ -1,9 +1,8 @@ package main import ( - "google.golang.org/protobuf/compiler/protogen" - "github.com/cosmos/cosmos-sdk/orm/internal/codegen" + "google.golang.org/protobuf/compiler/protogen" ) func main() { diff --git a/orm/cmd/protoc-gen-go-cosmos-orm/main.go b/orm/cmd/protoc-gen-go-cosmos-orm/main.go index 9c06f9ac8b7c..ce75b2f39dc1 100644 --- a/orm/cmd/protoc-gen-go-cosmos-orm/main.go +++ b/orm/cmd/protoc-gen-go-cosmos-orm/main.go @@ -1,9 +1,8 @@ package main import ( - "google.golang.org/protobuf/compiler/protogen" - "github.com/cosmos/cosmos-sdk/orm/internal/codegen" + "google.golang.org/protobuf/compiler/protogen" ) func main() { diff --git a/orm/encoding/encodeutil/util.go b/orm/encoding/encodeutil/util.go index d8fe8a1c2ed3..b126c834ea57 100644 --- a/orm/encoding/encodeutil/util.go +++ b/orm/encoding/encodeutil/util.go @@ -14,9 +14,10 @@ import ( func SkipPrefix(r *bytes.Reader, prefix []byte) error { n := len(prefix) if n > 0 { - // we skip checking the prefix for performance reasons because we assume - // that it was checked by the caller + // We skip checking the prefix for performance reasons because we assume + // that it was checked by the caller. _, err := r.Seek(int64(n), io.SeekCurrent) + return err } return nil @@ -33,12 +34,12 @@ func AppendVarUInt32(prefix []byte, x uint32) []byte { } // ValuesOf takes the arguments and converts them to protoreflect.Value's. -func ValuesOf(values ...interface{}) []protoreflect.Value { +func ValuesOf(values ...any) []protoreflect.Value { n := len(values) res := make([]protoreflect.Value, n) for i := 0; i < n; i++ { - // we catch the case of proto messages here and call ProtoReflect. - // this allows us to use imported messages, such as timestamppb.Timestamp + // We catch the case of proto messages here and call ProtoReflect. + // This allows us to use imported messages, such as timestamppb.Timestamp // in iterators. value := values[i] switch value.(type) { diff --git a/orm/encoding/ormfield/bool.go b/orm/encoding/ormfield/bool.go index 8fac99becb4c..faf9080f5fe5 100644 --- a/orm/encoding/ormfield/bool.go +++ b/orm/encoding/ormfield/bool.go @@ -9,7 +9,7 @@ import ( // BoolCodec encodes a bool value as a single byte 0 or 1. type BoolCodec struct{} -func (b BoolCodec) Decode(r Reader) (protoreflect.Value, error) { +func (BoolCodec) Decode(r Reader) (protoreflect.Value, error) { x, err := r.ReadByte() return protoreflect.ValueOfBool(x != 0), err } @@ -19,7 +19,7 @@ var ( oneBz = []byte{1} ) -func (b BoolCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (BoolCodec) Encode(value protoreflect.Value, w io.Writer) error { var err error if !value.IsValid() || !value.Bool() { _, err = w.Write(zeroBz) @@ -29,7 +29,7 @@ func (b BoolCodec) Encode(value protoreflect.Value, w io.Writer) error { return err } -func (b BoolCodec) Compare(v1, v2 protoreflect.Value) int { +func (BoolCodec) Compare(v1, v2 protoreflect.Value) int { var b1, b2 bool if v1.IsValid() { b1 = v1.Bool() @@ -46,11 +46,11 @@ func (b BoolCodec) Compare(v1, v2 protoreflect.Value) int { } } -func (b BoolCodec) IsOrdered() bool { +func (BoolCodec) IsOrdered() bool { return false } -func (b BoolCodec) FixedBufferSize() int { +func (BoolCodec) FixedBufferSize() int { return 1 } diff --git a/orm/encoding/ormfield/bytes.go b/orm/encoding/ormfield/bytes.go index 0eea476b8a47..e91aafa68416 100644 --- a/orm/encoding/ormfield/bytes.go +++ b/orm/encoding/ormfield/bytes.go @@ -12,12 +12,12 @@ import ( // than 255 bytes. type BytesCodec struct{} -func (b BytesCodec) FixedBufferSize() int { +func (BytesCodec) FixedBufferSize() int { return -1 } // ComputeBufferSize returns the bytes size of the value. -func (b BytesCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { +func (BytesCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { return bytesSize(value), nil } @@ -28,16 +28,16 @@ func bytesSize(value protoreflect.Value) int { return len(value.Bytes()) } -func (b BytesCodec) IsOrdered() bool { +func (BytesCodec) IsOrdered() bool { return false } -func (b BytesCodec) Decode(r Reader) (protoreflect.Value, error) { +func (BytesCodec) Decode(r Reader) (protoreflect.Value, error) { bz, err := io.ReadAll(r) return protoreflect.ValueOfBytes(bz), err } -func (b BytesCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (BytesCodec) Encode(value protoreflect.Value, w io.Writer) error { if !value.IsValid() { return nil } @@ -45,7 +45,7 @@ func (b BytesCodec) Encode(value protoreflect.Value, w io.Writer) error { return err } -func (b BytesCodec) Compare(v1, v2 protoreflect.Value) int { +func (BytesCodec) Compare(v1, v2 protoreflect.Value) int { return compareBytes(v1, v2) } @@ -53,16 +53,16 @@ func (b BytesCodec) Compare(v1, v2 protoreflect.Value) int { // byte. It errors if the byte array is longer than 255 bytes. type NonTerminalBytesCodec struct{} -func (b NonTerminalBytesCodec) FixedBufferSize() int { +func (NonTerminalBytesCodec) FixedBufferSize() int { return -1 } // ComputeBufferSize returns the bytes size of the value plus the length of the // varint length-prefix. -func (b NonTerminalBytesCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { +func (NonTerminalBytesCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { n := bytesSize(value) prefixLen := 1 - // we use varint, if the first bit of a byte is 1 then we need to signal continuation + // We use varint, if the first bit of a byte is 1 then we need to signal continuation. for n >= 0x80 { prefixLen++ n >>= 7 @@ -70,15 +70,15 @@ func (b NonTerminalBytesCodec) ComputeBufferSize(value protoreflect.Value) (int, return n + prefixLen, nil } -func (b NonTerminalBytesCodec) IsOrdered() bool { +func (NonTerminalBytesCodec) IsOrdered() bool { return false } -func (b NonTerminalBytesCodec) Compare(v1, v2 protoreflect.Value) int { +func (NonTerminalBytesCodec) Compare(v1, v2 protoreflect.Value) int { return compareBytes(v1, v2) } -func (b NonTerminalBytesCodec) Decode(r Reader) (protoreflect.Value, error) { +func (NonTerminalBytesCodec) Decode(r Reader) (protoreflect.Value, error) { n, err := binary.ReadUvarint(r) if err != nil { return protoreflect.Value{}, err @@ -93,7 +93,7 @@ func (b NonTerminalBytesCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfBytes(bz), err } -func (b NonTerminalBytesCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (NonTerminalBytesCodec) Encode(value protoreflect.Value, w io.Writer) error { var bz []byte if value.IsValid() { bz = value.Bytes() diff --git a/orm/encoding/ormfield/codec.go b/orm/encoding/ormfield/codec.go index 14a1d4804c71..1626058ddc7d 100644 --- a/orm/encoding/ormfield/codec.go +++ b/orm/encoding/ormfield/codec.go @@ -4,11 +4,9 @@ import ( "io" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - + "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" - - "google.golang.org/protobuf/reflect/protoreflect" ) // Codec defines an interface for decoding and encoding values in ORM index keys. @@ -50,37 +48,37 @@ var ( ) // GetCodec returns the Codec for the provided field if one is defined. -// nonTerminal should be set to true if this value is being encoded as a +// NonTerminal should be set to true if this value is being encoded as a // non-terminal segment of a multi-part key. func GetCodec(field protoreflect.FieldDescriptor, nonTerminal bool) (Codec, error) { if field == nil { - return nil, ormerrors.InvalidKeyField.Wrap("nil field") + return nil, ormerrors.ErrInvalidKeyField.Wrap("nil field") } if field.IsList() { - return nil, ormerrors.InvalidKeyField.Wrapf("repeated field %s", field.FullName()) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("repeated field %s", field.FullName()) } if field.ContainingOneof() != nil { - return nil, ormerrors.InvalidKeyField.Wrapf("oneof field %s", field.FullName()) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("oneof field %s", field.FullName()) } if field.HasOptionalKeyword() { - return nil, ormerrors.InvalidKeyField.Wrapf("optional field %s", field.FullName()) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("optional field %s", field.FullName()) } switch field.Kind() { case protoreflect.BytesKind: if nonTerminal { return NonTerminalBytesCodec{}, nil - } else { - return BytesCodec{}, nil } + return BytesCodec{}, nil + case protoreflect.StringKind: if nonTerminal { return NonTerminalStringCodec{}, nil - } else { - return StringCodec{}, nil } + return StringCodec{}, nil + case protoreflect.Uint32Kind: return CompactUint32Codec{}, nil case protoreflect.Fixed32Kind: @@ -105,9 +103,9 @@ func GetCodec(field protoreflect.FieldDescriptor, nonTerminal bool) (Codec, erro case durationFullName: return DurationCodec{}, nil default: - return nil, ormerrors.InvalidKeyField.Wrapf("%s of type %s", field.FullName(), msgName) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("%s of type %s", field.FullName(), msgName) } default: - return nil, ormerrors.InvalidKeyField.Wrapf("%s of kind %s", field.FullName(), field.Kind()) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("%s of kind %s", field.FullName(), field.Kind()) } } diff --git a/orm/encoding/ormfield/codec_test.go b/orm/encoding/ormfield/codec_test.go index abab4d2d5a9b..5a5db3598c94 100644 --- a/orm/encoding/ormfield/codec_test.go +++ b/orm/encoding/ormfield/codec_test.go @@ -6,26 +6,23 @@ import ( "testing" "time" - "google.golang.org/protobuf/types/known/timestamppb" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" - + "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/known/timestamppb" "gotest.tools/v3/assert" "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" ) func TestCodec(t *testing.T) { for _, ks := range testutil.TestFieldSpecs { - testCodec(t, ks) + doTestCodec(t, ks) } } -func testCodec(t *testing.T, spec testutil.TestFieldSpec) { +func doTestCodec(t *testing.T, spec testutil.TestFieldSpec) { + t.Helper() t.Run(fmt.Sprintf("%s %v", spec.FieldName, false), func(t *testing.T) { testCodecNT(t, spec.FieldName, spec.Gen, false) }) @@ -35,6 +32,7 @@ func testCodec(t *testing.T, spec testutil.TestFieldSpec) { } func testCodecNT(t *testing.T, fname protoreflect.Name, generator *rapid.Generator[any], nonTerminal bool) { + t.Helper() cdc, err := testutil.MakeTestCodec(fname, nonTerminal) assert.NilError(t, err) rapid.Check(t, func(t *rapid.T) { @@ -68,15 +66,15 @@ func checkEncodeDecodeSize(t *rapid.T, x protoreflect.Value, cdc ormfield.Codec) func TestUnsupportedFields(t *testing.T) { _, err := ormfield.GetCodec(nil, false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) _, err = ormfield.GetCodec(testutil.GetTestField("repeated"), false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) _, err = ormfield.GetCodec(testutil.GetTestField("map"), false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) _, err = ormfield.GetCodec(testutil.GetTestField("msg"), false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) _, err = ormfield.GetCodec(testutil.GetTestField("oneof"), false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) } func TestCompactUInt32(t *testing.T) { @@ -99,7 +97,7 @@ func TestCompactUInt32(t *testing.T) { testEncodeDecode(1073741823, 4) testEncodeDecode(1073741824, 5) - // randomized tests + // Randomized tests. rapid.Check(t, func(t *rapid.T) { x := rapid.Uint32().Draw(t, "x") y := rapid.Uint32().Draw(t, "y") @@ -147,7 +145,7 @@ func TestCompactUInt64(t *testing.T) { testEncodeDecode(70368744177663, 6) testEncodeDecode(70368744177664, 9) - // randomized tests + // Randomized tests. rapid.Check(t, func(t *rapid.T) { x := rapid.Uint64().Draw(t, "x") y := rapid.Uint64().Draw(t, "y") @@ -176,7 +174,7 @@ func TestCompactUInt64(t *testing.T) { func TestTimestamp(t *testing.T) { cdc := ormfield.TimestampCodec{} - // nil value + // Nil value. buf := &bytes.Buffer{} assert.NilError(t, cdc.Encode(protoreflect.Value{}, buf)) assert.Equal(t, 1, len(buf.Bytes())) @@ -184,7 +182,7 @@ func TestTimestamp(t *testing.T) { assert.NilError(t, err) assert.Assert(t, !val.IsValid()) - // no nanos + // No nanos. ts := timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 0, time.UTC)) val = protoreflect.ValueOfMessage(ts.ProtoReflect()) buf = &bytes.Buffer{} @@ -194,7 +192,7 @@ func TestTimestamp(t *testing.T) { assert.NilError(t, err) assert.Equal(t, 0, cdc.Compare(val, val2)) - // nanos + // Nanos. ts = timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 235809753, time.UTC)) val = protoreflect.ValueOfMessage(ts.ProtoReflect()) buf = &bytes.Buffer{} diff --git a/orm/encoding/ormfield/duration.go b/orm/encoding/ormfield/duration.go index f01e2a60e235..9b0d6cbd9ab8 100644 --- a/orm/encoding/ormfield/duration.go +++ b/orm/encoding/ormfield/duration.go @@ -21,7 +21,7 @@ func getDurationSecondsAndNanos(value protoreflect.Value) (protoreflect.Value, p // sorted iteration. type DurationCodec struct{} -func (d DurationCodec) Decode(r Reader) (protoreflect.Value, error) { +func (DurationCodec) Decode(r Reader) (protoreflect.Value, error) { seconds, err := int64Codec.Decode(r) if err != nil { return protoreflect.Value{}, err @@ -36,7 +36,7 @@ func (d DurationCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfMessage(msg), nil } -func (d DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { seconds, nanos := getDurationSecondsAndNanos(value) err := int64Codec.Encode(seconds, w) if err != nil { @@ -45,22 +45,21 @@ func (d DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { return int32Codec.Encode(nanos, w) } -func (d DurationCodec) Compare(v1, v2 protoreflect.Value) int { +func (DurationCodec) Compare(v1, v2 protoreflect.Value) int { s1, n1 := getDurationSecondsAndNanos(v1) s2, n2 := getDurationSecondsAndNanos(v2) c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + return compareInt(n1, n2) } -func (d DurationCodec) IsOrdered() bool { +func (DurationCodec) IsOrdered() bool { return true } -func (d DurationCodec) FixedBufferSize() int { +func (DurationCodec) FixedBufferSize() int { return 12 } diff --git a/orm/encoding/ormfield/enum.go b/orm/encoding/ormfield/enum.go index 106ac311a8ff..397490877257 100644 --- a/orm/encoding/ormfield/enum.go +++ b/orm/encoding/ormfield/enum.go @@ -10,12 +10,12 @@ import ( // EnumCodec encodes enum values as varints. type EnumCodec struct{} -func (e EnumCodec) Decode(r Reader) (protoreflect.Value, error) { +func (EnumCodec) Decode(r Reader) (protoreflect.Value, error) { x, err := binary.ReadVarint(r) return protoreflect.ValueOfEnum(protoreflect.EnumNumber(x)), err } -func (e EnumCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (EnumCodec) Encode(value protoreflect.Value, w io.Writer) error { var x protoreflect.EnumNumber if value.IsValid() { x = value.Enum() @@ -26,7 +26,7 @@ func (e EnumCodec) Encode(value protoreflect.Value, w io.Writer) error { return err } -func (e EnumCodec) Compare(v1, v2 protoreflect.Value) int { +func (EnumCodec) Compare(v1, v2 protoreflect.Value) int { var x, y protoreflect.EnumNumber if v1.IsValid() { x = v1.Enum() @@ -43,11 +43,11 @@ func (e EnumCodec) Compare(v1, v2 protoreflect.Value) int { } } -func (e EnumCodec) IsOrdered() bool { +func (EnumCodec) IsOrdered() bool { return false } -func (e EnumCodec) FixedBufferSize() int { +func (EnumCodec) FixedBufferSize() int { return binary.MaxVarintLen32 } diff --git a/orm/encoding/ormfield/int32.go b/orm/encoding/ormfield/int32.go index 8b2dd9331af8..9d2cccb9c748 100644 --- a/orm/encoding/ormfield/int32.go +++ b/orm/encoding/ormfield/int32.go @@ -19,14 +19,14 @@ const ( int32Offset = int32Max + 1 ) -func (i Int32Codec) Decode(r Reader) (protoreflect.Value, error) { +func (Int32Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint32 err := binary.Read(r, binary.BigEndian, &x) y := int64(x) - int32Offset return protoreflect.ValueOfInt32(int32(y)), err } -func (i Int32Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (Int32Codec) Encode(value protoreflect.Value, w io.Writer) error { var x int64 if value.IsValid() { x = value.Int() @@ -35,15 +35,15 @@ func (i Int32Codec) Encode(value protoreflect.Value, w io.Writer) error { return binary.Write(w, binary.BigEndian, uint32(x)) } -func (i Int32Codec) Compare(v1, v2 protoreflect.Value) int { +func (Int32Codec) Compare(v1, v2 protoreflect.Value) int { return compareInt(v1, v2) } -func (i Int32Codec) IsOrdered() bool { +func (Int32Codec) IsOrdered() bool { return true } -func (i Int32Codec) FixedBufferSize() int { +func (Int32Codec) FixedBufferSize() int { return 4 } diff --git a/orm/encoding/ormfield/int64.go b/orm/encoding/ormfield/int64.go index cbe13420d7d5..58d754d01d99 100644 --- a/orm/encoding/ormfield/int64.go +++ b/orm/encoding/ormfield/int64.go @@ -16,19 +16,18 @@ var int64Codec = Int64Codec{} const int64Max = 9223372036854775807 -func (i Int64Codec) Decode(r Reader) (protoreflect.Value, error) { +func (Int64Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint64 err := binary.Read(r, binary.BigEndian, &x) if x >= int64Max { x = x - int64Max - 1 return protoreflect.ValueOfInt64(int64(x)), err - } else { - y := int64(x) - int64Max - 1 - return protoreflect.ValueOfInt64(y), err } + y := int64(x) - int64Max - 1 + return protoreflect.ValueOfInt64(y), err } -func (i Int64Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (Int64Codec) Encode(value protoreflect.Value, w io.Writer) error { var x int64 if value.IsValid() { x = value.Int() @@ -36,22 +35,21 @@ func (i Int64Codec) Encode(value protoreflect.Value, w io.Writer) error { if x >= -1 { y := uint64(x) + int64Max + 1 return binary.Write(w, binary.BigEndian, y) - } else { - x += int64Max - x += 1 - return binary.Write(w, binary.BigEndian, uint64(x)) } + x += int64Max + x++ + return binary.Write(w, binary.BigEndian, uint64(x)) } -func (i Int64Codec) Compare(v1, v2 protoreflect.Value) int { +func (Int64Codec) Compare(v1, v2 protoreflect.Value) int { return compareInt(v1, v2) } -func (i Int64Codec) IsOrdered() bool { +func (Int64Codec) IsOrdered() bool { return true } -func (i Int64Codec) FixedBufferSize() int { +func (Int64Codec) FixedBufferSize() int { return 8 } diff --git a/orm/encoding/ormfield/string.go b/orm/encoding/ormfield/string.go index e052efab31d4..b15bb93509f4 100644 --- a/orm/encoding/ormfield/string.go +++ b/orm/encoding/ormfield/string.go @@ -11,11 +11,11 @@ import ( // StringCodec encodes strings as raw bytes. type StringCodec struct{} -func (s StringCodec) FixedBufferSize() int { +func (StringCodec) FixedBufferSize() int { return -1 } -func (s StringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { +func (StringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { if !value.IsValid() { return 0, nil } @@ -23,20 +23,20 @@ func (s StringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { return len(value.String()), nil } -func (s StringCodec) IsOrdered() bool { +func (StringCodec) IsOrdered() bool { return true } -func (s StringCodec) Compare(v1, v2 protoreflect.Value) int { +func (StringCodec) Compare(v1, v2 protoreflect.Value) int { return compareStrings(v1, v2) } -func (s StringCodec) Decode(r Reader) (protoreflect.Value, error) { +func (StringCodec) Decode(r Reader) (protoreflect.Value, error) { bz, err := io.ReadAll(r) return protoreflect.ValueOfString(string(bz)), err } -func (s StringCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (StringCodec) Encode(value protoreflect.Value, w io.Writer) error { var x string if value.IsValid() { x = value.String() @@ -49,23 +49,23 @@ func (s StringCodec) Encode(value protoreflect.Value, w io.Writer) error { // values within strings will produce an error. type NonTerminalStringCodec struct{} -func (s NonTerminalStringCodec) FixedBufferSize() int { +func (NonTerminalStringCodec) FixedBufferSize() int { return -1 } -func (s NonTerminalStringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { +func (NonTerminalStringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { return len(value.String()) + 1, nil } -func (s NonTerminalStringCodec) IsOrdered() bool { +func (NonTerminalStringCodec) IsOrdered() bool { return true } -func (s NonTerminalStringCodec) Compare(v1, v2 protoreflect.Value) int { +func (NonTerminalStringCodec) Compare(v1, v2 protoreflect.Value) int { return compareStrings(v1, v2) } -func (s NonTerminalStringCodec) Decode(r Reader) (protoreflect.Value, error) { +func (NonTerminalStringCodec) Decode(r Reader) (protoreflect.Value, error) { var bz []byte for { b, err := r.ReadByte() @@ -76,7 +76,7 @@ func (s NonTerminalStringCodec) Decode(r Reader) (protoreflect.Value, error) { } } -func (s NonTerminalStringCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (NonTerminalStringCodec) Encode(value protoreflect.Value, w io.Writer) error { var str string if value.IsValid() { str = value.String() diff --git a/orm/encoding/ormfield/timestamp.go b/orm/encoding/ormfield/timestamp.go index eb13c3de74b0..7b59195b8988 100644 --- a/orm/encoding/ormfield/timestamp.go +++ b/orm/encoding/ormfield/timestamp.go @@ -33,8 +33,8 @@ var ( timestampZeroNanosBz = []byte{timestampZeroNanosValue} ) -func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { - // nil case +func (TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { + // Nil case. if !value.IsValid() { _, err := w.Write(timestampNilBz) return err @@ -47,7 +47,7 @@ func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { } secondsInt -= timestampSecondsMin var secondsBz [5]byte - // write the seconds buffer from the end to the front + // Write the seconds buffer from the end to the front. for i := 4; i >= 0; i-- { secondsBz[i] = byte(secondsInt) secondsInt >>= 8 @@ -72,12 +72,12 @@ func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { nanosBz[i] = byte(nanosInt) nanosInt >>= 8 } - nanosBz[0] = nanosBz[0] | 0xC0 + nanosBz[0] |= 0xC0 _, err = w.Write(nanosBz[:]) return err } -func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { +func (TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { b0, err := r.ReadByte() if err != nil { return protoreflect.Value{}, err @@ -124,7 +124,7 @@ func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.Value{}, io.EOF } - nanos := int32(b0) & 0x3F // clear first two bits + nanos := int32(b0) & 0x3F // Clear first two bits. for i := 0; i < 3; i++ { nanos <<= 8 nanos |= int32(nanosBz[i]) @@ -134,7 +134,7 @@ func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfMessage(msg), nil } -func (t TimestampCodec) Compare(v1, v2 protoreflect.Value) int { +func (TimestampCodec) Compare(v1, v2 protoreflect.Value) int { if !v1.IsValid() { if !v2.IsValid() { return 0 @@ -151,20 +151,19 @@ func (t TimestampCodec) Compare(v1, v2 protoreflect.Value) int { c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + return compareInt(n1, n2) } -func (t TimestampCodec) IsOrdered() bool { +func (TimestampCodec) IsOrdered() bool { return true } -func (t TimestampCodec) FixedBufferSize() int { +func (TimestampCodec) FixedBufferSize() int { return 9 } -func (t TimestampCodec) ComputeBufferSize(protoreflect.Value) (int, error) { +func (TimestampCodec) ComputeBufferSize(protoreflect.Value) (int, error) { return 9, nil } @@ -185,7 +184,7 @@ func getTimestampSecondsAndNanos(value protoreflect.Value) (protoreflect.Value, return msg.Get(timestampSecondsField), msg.Get(timestampNanosField) } -func (t TimestampV0Codec) Decode(r Reader) (protoreflect.Value, error) { +func (TimestampV0Codec) Decode(r Reader) (protoreflect.Value, error) { seconds, err := int64Codec.Decode(r) if err != nil { return protoreflect.Value{}, err @@ -200,7 +199,7 @@ func (t TimestampV0Codec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfMessage(msg), nil } -func (t TimestampV0Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (TimestampV0Codec) Encode(value protoreflect.Value, w io.Writer) error { seconds, nanos := getTimestampSecondsAndNanos(value) err := int64Codec.Encode(seconds, w) if err != nil { @@ -209,22 +208,21 @@ func (t TimestampV0Codec) Encode(value protoreflect.Value, w io.Writer) error { return int32Codec.Encode(nanos, w) } -func (t TimestampV0Codec) Compare(v1, v2 protoreflect.Value) int { +func (TimestampV0Codec) Compare(v1, v2 protoreflect.Value) int { s1, n1 := getTimestampSecondsAndNanos(v1) s2, n2 := getTimestampSecondsAndNanos(v2) c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + return compareInt(n1, n2) } -func (t TimestampV0Codec) IsOrdered() bool { +func (TimestampV0Codec) IsOrdered() bool { return true } -func (t TimestampV0Codec) FixedBufferSize() int { +func (TimestampV0Codec) FixedBufferSize() int { return 12 } diff --git a/orm/encoding/ormfield/uint32.go b/orm/encoding/ormfield/uint32.go index 0e770ad6b482..1ec6b147a026 100644 --- a/orm/encoding/ormfield/uint32.go +++ b/orm/encoding/ormfield/uint32.go @@ -11,7 +11,7 @@ import ( // FixedUint32Codec encodes uint32 values as 4-byte big-endian integers. type FixedUint32Codec struct{} -func (u FixedUint32Codec) FixedBufferSize() int { +func (FixedUint32Codec) FixedBufferSize() int { return 4 } @@ -19,21 +19,21 @@ func (u FixedUint32Codec) ComputeBufferSize(protoreflect.Value) (int, error) { return u.FixedBufferSize(), nil } -func (u FixedUint32Codec) IsOrdered() bool { +func (FixedUint32Codec) IsOrdered() bool { return true } -func (u FixedUint32Codec) Compare(v1, v2 protoreflect.Value) int { +func (FixedUint32Codec) Compare(v1, v2 protoreflect.Value) int { return compareUint(v1, v2) } -func (u FixedUint32Codec) Decode(r Reader) (protoreflect.Value, error) { +func (FixedUint32Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint32 err := binary.Read(r, binary.BigEndian, &x) return protoreflect.ValueOfUint32(x), err } -func (u FixedUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (FixedUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { var x uint64 if value.IsValid() { x = value.Uint() @@ -44,12 +44,12 @@ func (u FixedUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { // CompactUint32Codec encodes uint32 values using EncodeCompactUint32. type CompactUint32Codec struct{} -func (c CompactUint32Codec) Decode(r Reader) (protoreflect.Value, error) { +func (CompactUint32Codec) Decode(r Reader) (protoreflect.Value, error) { x, err := DecodeCompactUint32(r) return protoreflect.ValueOfUint32(x), err } -func (c CompactUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (CompactUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { var x uint64 if value.IsValid() { x = value.Uint() @@ -58,15 +58,15 @@ func (c CompactUint32Codec) Encode(value protoreflect.Value, w io.Writer) error return err } -func (c CompactUint32Codec) Compare(v1, v2 protoreflect.Value) int { +func (CompactUint32Codec) Compare(v1, v2 protoreflect.Value) int { return compareUint(v1, v2) } -func (c CompactUint32Codec) IsOrdered() bool { +func (CompactUint32Codec) IsOrdered() bool { return true } -func (c CompactUint32Codec) FixedBufferSize() int { +func (CompactUint32Codec) FixedBufferSize() int { return 5 } @@ -83,19 +83,19 @@ func (c CompactUint32Codec) ComputeBufferSize(protoreflect.Value) (int, error) { // fit in 3, and values less than 2^30 will fit in 4. func EncodeCompactUint32(x uint32) []byte { switch { - case x < 16384: // 2^14 + case x < 16384: // 2^14. buf := make([]byte, 2) buf[0] = byte(x >> 8) buf[1] = byte(x) return buf - case x < 4194304: // 2^22 + case x < 4194304: // 2^22. buf := make([]byte, 3) buf[0] = 0x40 buf[0] |= byte(x >> 16) buf[1] = byte(x >> 8) buf[2] = byte(x) return buf - case x < 1073741824: // 2^30 + case x < 1073741824: // 2^30. buf := make([]byte, 4) buf[0] = 0x80 buf[0] |= byte(x >> 24) diff --git a/orm/encoding/ormfield/uint64.go b/orm/encoding/ormfield/uint64.go index e4f654239905..7573ad584245 100644 --- a/orm/encoding/ormfield/uint64.go +++ b/orm/encoding/ormfield/uint64.go @@ -11,7 +11,7 @@ import ( // FixedUint64Codec encodes uint64 values as 8-byte big-endian integers. type FixedUint64Codec struct{} -func (u FixedUint64Codec) FixedBufferSize() int { +func (FixedUint64Codec) FixedBufferSize() int { return 8 } @@ -19,21 +19,21 @@ func (u FixedUint64Codec) ComputeBufferSize(protoreflect.Value) (int, error) { return u.FixedBufferSize(), nil } -func (u FixedUint64Codec) IsOrdered() bool { +func (FixedUint64Codec) IsOrdered() bool { return true } -func (u FixedUint64Codec) Compare(v1, v2 protoreflect.Value) int { +func (FixedUint64Codec) Compare(v1, v2 protoreflect.Value) int { return compareUint(v1, v2) } -func (u FixedUint64Codec) Decode(r Reader) (protoreflect.Value, error) { +func (FixedUint64Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint64 err := binary.Read(r, binary.BigEndian, &x) return protoreflect.ValueOfUint64(x), err } -func (u FixedUint64Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (FixedUint64Codec) Encode(value protoreflect.Value, w io.Writer) error { var x uint64 if value.IsValid() { x = value.Uint() @@ -61,12 +61,12 @@ func compareUint(v1, v2 protoreflect.Value) int { // CompactUint64Codec encodes uint64 values using EncodeCompactUint64. type CompactUint64Codec struct{} -func (c CompactUint64Codec) Decode(r Reader) (protoreflect.Value, error) { +func (CompactUint64Codec) Decode(r Reader) (protoreflect.Value, error) { x, err := DecodeCompactUint64(r) return protoreflect.ValueOfUint64(x), err } -func (c CompactUint64Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (CompactUint64Codec) Encode(value protoreflect.Value, w io.Writer) error { var x uint64 if value.IsValid() { x = value.Uint() @@ -75,15 +75,15 @@ func (c CompactUint64Codec) Encode(value protoreflect.Value, w io.Writer) error return err } -func (c CompactUint64Codec) Compare(v1, v2 protoreflect.Value) int { +func (CompactUint64Codec) Compare(v1, v2 protoreflect.Value) int { return compareUint(v1, v2) } -func (c CompactUint64Codec) IsOrdered() bool { +func (CompactUint64Codec) IsOrdered() bool { return true } -func (c CompactUint64Codec) FixedBufferSize() int { +func (CompactUint64Codec) FixedBufferSize() int { return 9 } @@ -100,12 +100,12 @@ func (c CompactUint64Codec) ComputeBufferSize(protoreflect.Value) (int, error) { // fit in 4, and values less than 2^46 will fit in 6. func EncodeCompactUint64(x uint64) []byte { switch { - case x < 16384: // 2^14 + case x < 16384: // 2^14. buf := make([]byte, 2) buf[0] = byte(x >> 8) buf[1] = byte(x) return buf - case x < 1073741824: // 2^30 + case x < 1073741824: // 2^30. buf := make([]byte, 4) buf[0] = 0x40 buf[0] |= byte(x >> 24) @@ -113,7 +113,7 @@ func EncodeCompactUint64(x uint64) []byte { buf[2] = byte(x >> 8) buf[3] = byte(x) return buf - case x < 70368744177664: // 2^46 + case x < 70368744177664: // 2^46. buf := make([]byte, 6) buf[0] = 0x80 buf[0] |= byte(x >> 40) diff --git a/orm/encoding/ormkv/entry.go b/orm/encoding/ormkv/entry.go index 2098afbac6a9..7105b514b7c6 100644 --- a/orm/encoding/ormkv/entry.go +++ b/orm/encoding/ormkv/entry.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" ) @@ -18,7 +17,7 @@ type Entry interface { // proto message name) this entry corresponds to. GetTableName() protoreflect.FullName - // to allow new methods to be added without breakage, this interface + // To allow new methods to be added without breakage, this interface // shouldn't be implemented outside this package, // see https://go.dev/blog/module-compatibility doNotImplement() @@ -43,14 +42,13 @@ func (p *PrimaryKeyEntry) GetTableName() protoreflect.FullName { func (p *PrimaryKeyEntry) String() string { if p.Value == nil { return fmt.Sprintf("PK %s %s -> _", p.TableName, fmtValues(p.Key)) - } else { - valBz, err := stablejson.Marshal(p.Value) - valStr := string(valBz) - if err != nil { - valStr = fmt.Sprintf("ERR %v", err) - } - return fmt.Sprintf("PK %s %s -> %s", p.TableName, fmtValues(p.Key), valStr) } + valBz, err := stablejson.Marshal(p.Value) + valStr := string(valBz) + if err != nil { + valStr = fmt.Sprintf("ERR %v", err) + } + return fmt.Sprintf("PK %s %s -> %s", p.TableName, fmtValues(p.Key), valStr) } func fmtValues(values []protoreflect.Value) string { @@ -66,7 +64,7 @@ func fmtValues(values []protoreflect.Value) string { return strings.Join(parts, "/") } -func (p *PrimaryKeyEntry) doNotImplement() {} +func (*PrimaryKeyEntry) doNotImplement() {} // IndexKeyEntry represents a logically decoded index entry. type IndexKeyEntry struct { @@ -83,7 +81,7 @@ type IndexKeyEntry struct { IndexValues []protoreflect.Value // PrimaryKey represents the primary key values, it is empty if this is a - // prefix key + // prefix key. PrimaryKey []protoreflect.Value } @@ -91,9 +89,9 @@ func (i *IndexKeyEntry) GetTableName() protoreflect.FullName { return i.TableName } -func (i *IndexKeyEntry) doNotImplement() {} +func (*IndexKeyEntry) doNotImplement() {} -func (i *IndexKeyEntry) string() string { +func (i *IndexKeyEntry) returnString() string { return fmt.Sprintf("%s %s : %s -> %s", i.TableName, fmtFields(i.Fields), fmtValues(i.IndexValues), fmtValues(i.PrimaryKey)) } @@ -107,10 +105,9 @@ func fmtFields(fields []protoreflect.Name) string { func (i *IndexKeyEntry) String() string { if i.IsUnique { - return fmt.Sprintf("UNIQ %s", i.string()) - } else { - return fmt.Sprintf("IDX %s", i.string()) + return fmt.Sprintf("UNIQ %s", i.returnString()) } + return fmt.Sprintf("IDX %s", i.returnString()) } // SeqEntry represents a sequence for tables with auto-incrementing primary keys. @@ -126,7 +123,7 @@ func (s *SeqEntry) GetTableName() protoreflect.FullName { return s.TableName } -func (s *SeqEntry) doNotImplement() {} +func (*SeqEntry) doNotImplement() {} func (s *SeqEntry) String() string { return fmt.Sprintf("SEQ %s %d", s.TableName, s.Value) diff --git a/orm/encoding/ormkv/entry_test.go b/orm/encoding/ormkv/entry_test.go index 9a78d60825ac..3f23703e1e9d 100644 --- a/orm/encoding/ormkv/entry_test.go +++ b/orm/encoding/ormkv/entry_test.go @@ -3,12 +3,11 @@ package ormkv_test import ( "testing" - "google.golang.org/protobuf/reflect/protoreflect" - "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" + "google.golang.org/protobuf/reflect/protoreflect" + "gotest.tools/v3/assert" ) var aFullName = (&testpb.ExampleTable{}).ProtoReflect().Descriptor().FullName() @@ -22,7 +21,7 @@ func TestPrimaryKeyEntry(t *testing.T) { assert.Equal(t, `PK testpb.ExampleTable 1/abc -> {"i32":-1}`, entry.String()) assert.Equal(t, aFullName, entry.GetTableName()) - // prefix key + // Prefix key. entry = &ormkv.PrimaryKeyEntry{ TableName: aFullName, Key: encodeutil.ValuesOf(uint32(1), "abc"), @@ -53,7 +52,7 @@ func TestIndexKeyEntry(t *testing.T) { assert.Equal(t, `UNIQ testpb.ExampleTable u32 : 10 -> abc/-1`, entry.String()) assert.Equal(t, aFullName, entry.GetTableName()) - // prefix key + // Prefix key. entry = &ormkv.IndexKeyEntry{ TableName: aFullName, Fields: []protoreflect.Name{"u32", "i32", "str"}, @@ -63,7 +62,7 @@ func TestIndexKeyEntry(t *testing.T) { assert.Equal(t, `IDX testpb.ExampleTable u32/i32/str : 10/-1 -> _`, entry.String()) assert.Equal(t, aFullName, entry.GetTableName()) - // prefix key + // Prefix key. entry = &ormkv.IndexKeyEntry{ TableName: aFullName, Fields: []protoreflect.Name{"str", "i32"}, diff --git a/orm/encoding/ormkv/index_key.go b/orm/encoding/ormkv/index_key.go index 55284f220636..50b023d0bb68 100644 --- a/orm/encoding/ormkv/index_key.go +++ b/orm/encoding/ormkv/index_key.go @@ -5,7 +5,6 @@ import ( "io" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" ) @@ -21,11 +20,11 @@ var _ IndexCodec = &IndexKeyCodec{} // provided message descriptor, index and primary key fields. func NewIndexKeyCodec(prefix []byte, messageType protoreflect.MessageType, indexFields, primaryKeyFields []protoreflect.Name) (*IndexKeyCodec, error) { if len(indexFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("index fields are empty") + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("index fields are empty") } if len(primaryKeyFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("primary key fields are empty") + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("primary key fields are empty") } indexFieldMap := map[protoreflect.Name]int{} @@ -63,14 +62,14 @@ func NewIndexKeyCodec(prefix []byte, messageType protoreflect.MessageType, index func (cdc IndexKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey []protoreflect.Value, err error) { values, err := cdc.DecodeKey(bytes.NewReader(k)) - // got prefix key + // Got prefix key. if err == io.EOF { return values, nil, nil } else if err != nil { return nil, nil, err } - // got prefix key + // Got prefix key. if len(values) < len(cdc.fieldCodecs) { return values, nil, nil } @@ -102,11 +101,11 @@ func (cdc IndexKeyCodec) DecodeEntry(k, v []byte) (Entry, error) { func (cdc IndexKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { indexEntry, ok := entry.(*IndexKeyEntry) if !ok { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } if indexEntry.TableName != cdc.messageType.Descriptor().FullName() { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } bz, err := cdc.KeyCodec.EncodeKey(indexEntry.IndexValues) diff --git a/orm/encoding/ormkv/index_key_test.go b/orm/encoding/ormkv/index_key_test.go index 9625641bf1c6..0146011370b1 100644 --- a/orm/encoding/ormkv/index_key_test.go +++ b/orm/encoding/ormkv/index_key_test.go @@ -5,12 +5,11 @@ import ( "fmt" "testing" - "gotest.tools/v3/assert" - "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "gotest.tools/v3/assert" + "pgregory.net/rapid" ) func TestIndexKeyCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/key_codec.go b/orm/encoding/ormkv/key_codec.go index 4d16a7bb9b8c..13eb1537443d 100644 --- a/orm/encoding/ormkv/key_codec.go +++ b/orm/encoding/ormkv/key_codec.go @@ -4,12 +4,10 @@ import ( "bytes" "io" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - - "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "google.golang.org/protobuf/reflect/protoreflect" ) type KeyCodec struct { @@ -43,7 +41,7 @@ func NewKeyCodec(prefix []byte, messageType protoreflect.MessageType, fieldNames nonTerminal := i != n-1 field := messageFields.ByName(fieldNames[i]) if field == nil { - return nil, ormerrors.FieldNotFound.Wrapf("field %s on %s", fieldNames[i], messageType.Descriptor().FullName()) + return nil, ormerrors.ErrFieldNotFound.Wrapf("field %s on %s", fieldNames[i], messageType.Descriptor().FullName()) } cdc, err := ormfield.GetCodec(field, nonTerminal) if err != nil { @@ -89,11 +87,11 @@ func (cdc *KeyCodec) EncodeKey(values []protoreflect.Value) ([]byte, error) { n := len(values) if n > len(cdc.fieldCodecs) { - return nil, ormerrors.IndexOutOfBounds.Wrapf("cannot encode %d values into %d fields", n, len(cdc.fieldCodecs)) + return nil, ormerrors.ErrIndexOutOfBounds.Wrapf("cannot encode %d values into %d fields", n, len(cdc.fieldCodecs)) } for i := 0; i < n; i++ { - if err = cdc.fieldCodecs[i].Encode(values[i], w); err != nil { + if err := cdc.fieldCodecs[i].Encode(values[i], w); err != nil { return nil, err } } @@ -170,13 +168,13 @@ func (cdc *KeyCodec) CompareKeys(values1, values2 []protoreflect.Value) int { var cmp int for i := 0; i < n; i++ { cmp = cdc.fieldCodecs[i].Compare(values1[i], values2[i]) - // any non-equal parts determine our ordering + // Any non-equal parts determine our ordering. if cmp != 0 { return cmp } } - // values are equal but arrays of different length + // Values are equal but arrays of different length. if j == k { return 0 } else if j < k { @@ -192,7 +190,7 @@ func (cdc KeyCodec) ComputeKeyBufferSize(values []protoreflect.Value) (int, erro size := cdc.fixedSize n := len(values) for _, sz := range cdc.variableSizers { - // handle prefix key encoding case where don't need all the sizers + // Handle prefix key encoding case where don't need all the sizers. if sz.i >= n { return size, nil } @@ -235,7 +233,7 @@ func (cdc KeyCodec) CheckValidRangeIterationKeys(start, end []protoreflect.Value } if longest > len(cdc.fieldCodecs) { - return ormerrors.IndexOutOfBounds + return ormerrors.ErrIndexOutOfBounds } i := 0 @@ -248,13 +246,13 @@ func (cdc KeyCodec) CheckValidRangeIterationKeys(start, end []protoreflect.Value cmp = fieldCdc.Compare(x, y) if cmp > 0 { - return ormerrors.InvalidRangeIterationKeys.Wrapf( + return ormerrors.ErrInvalidRangeIterationKeys.Wrapf( "start must be before end for field %s", cdc.fieldDescriptors[i].FullName(), ) } else if !fieldCdc.IsOrdered() && cmp != 0 { descriptor := cdc.fieldDescriptors[i] - return ormerrors.InvalidRangeIterationKeys.Wrapf( + return ormerrors.ErrInvalidRangeIterationKeys.Wrapf( "field %s of kind %s doesn't support ordered range iteration", descriptor.FullName(), descriptor.Kind(), @@ -264,16 +262,16 @@ func (cdc KeyCodec) CheckValidRangeIterationKeys(start, end []protoreflect.Value } } - // the last prefix value must not be equal if the key lengths are the same + // The last prefix value must not be equal if the key lengths are the same. if lenStart == lenEnd { if cmp == 0 { - return ormerrors.InvalidRangeIterationKeys + return ormerrors.ErrInvalidRangeIterationKeys } } else { - // check any remaining values in start or end + // Check any remaining values in start or end. for j := i; j < longest; j++ { if !cdc.fieldCodecs[j].IsOrdered() { - return ormerrors.InvalidRangeIterationKeys.Wrapf( + return ormerrors.ErrInvalidRangeIterationKeys.Wrapf( "field %s of kind %s doesn't support ordered range iteration", cdc.fieldDescriptors[j].FullName(), cdc.fieldDescriptors[j].Kind(), diff --git a/orm/encoding/ormkv/key_codec_test.go b/orm/encoding/ormkv/key_codec_test.go index 2b5ae8e7d7d6..1eef903bd2c9 100644 --- a/orm/encoding/ormkv/key_codec_test.go +++ b/orm/encoding/ormkv/key_codec_test.go @@ -5,14 +5,13 @@ import ( "io" "testing" - "google.golang.org/protobuf/reflect/protoreflect" - "gotest.tools/v3/assert" - "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "google.golang.org/protobuf/reflect/protoreflect" + "gotest.tools/v3/assert" + "pgregory.net/rapid" ) func TestKeyCodec(t *testing.T) { @@ -24,10 +23,10 @@ func TestKeyCodec(t *testing.T) { bz1 := assertEncDecKey(t, key, keyValues) if key.Codec.IsFullyOrdered() { - // check if ordered keys have ordered encodings + // Check if ordered keys have ordered encodings. keyValues2 := key.Draw(t, "values2") bz2 := assertEncDecKey(t, key, keyValues2) - // bytes comparison should equal comparison of values + // Bytes comparison should equal comparison of values. assert.Equal(t, key.Codec.CompareKeys(keyValues, keyValues2), bytes.Compare(bz1, bz2)) } } @@ -170,12 +169,13 @@ func TestCompareValues(t *testing.T) { }, } for _, test := range tests { + test := test t.Run(test.name, func(t *testing.T) { assert.Equal( t, test.expect, cdc.CompareKeys(test.values1, test.values2), ) - // CheckValidRangeIterationKeys should give comparable results + // CheckValidRangeIterationKeys should give comparable results. err := cdc.CheckValidRangeIterationKeys(test.values1, test.values2) if test.validRange { assert.NilError(t, err) @@ -202,6 +202,7 @@ func TestDecodePrefixKey(t *testing.T) { }, } for _, test := range tests { + test := test t.Run(test.name, func(t *testing.T) { bz, err := cdc.EncodeKey(test.values) assert.NilError(t, err) @@ -286,6 +287,7 @@ func TestValidRangeIterationKeys(t *testing.T) { }, } for _, test := range tests { + test := test t.Run(test.name, func(t *testing.T) { err := cdc.CheckValidRangeIterationKeys(test.values1, test.values2) if test.expectErr { diff --git a/orm/encoding/ormkv/primary_key.go b/orm/encoding/ormkv/primary_key.go index ff4509cb562e..7c6589622b9a 100644 --- a/orm/encoding/ormkv/primary_key.go +++ b/orm/encoding/ormkv/primary_key.go @@ -5,9 +5,7 @@ import ( "io" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" ) @@ -38,7 +36,7 @@ var _ IndexCodec = PrimaryKeyCodec{} func (p PrimaryKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey []protoreflect.Value, err error) { indexFields, err = p.DecodeKey(bytes.NewReader(k)) - // got prefix key + // Got prefix key. if err == io.EOF { return indexFields, nil, nil } else if err != nil { @@ -46,8 +44,8 @@ func (p PrimaryKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey [] } if len(indexFields) == len(p.fieldCodecs) { - // for primary keys the index fields are the primary key - // but only if we don't have a prefix key + // For primary keys the index fields are the primary key + // but only if we don't have a prefix key. primaryKey = indexFields } return indexFields, primaryKey, nil @@ -77,11 +75,11 @@ func (p PrimaryKeyCodec) DecodeEntry(k, v []byte) (Entry, error) { func (p PrimaryKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { pkEntry, ok := entry.(*PrimaryKeyEntry) if !ok { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("expected %T, got %T", &PrimaryKeyEntry{}, entry) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("expected %T, got %T", &PrimaryKeyEntry{}, entry) } if pkEntry.TableName != p.messageType.Descriptor().FullName() { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf( + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf( "wrong table name, got %s, expected %s", pkEntry.TableName, p.messageType.Descriptor().FullName(), @@ -98,8 +96,8 @@ func (p PrimaryKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { } func (p PrimaryKeyCodec) marshal(key []protoreflect.Value, message proto.Message) (v []byte, err error) { - // first clear the priamry key values because these are already stored in - // the key so we don't need to store them again in the value + // First clear the priamry key values because these are already stored in + // the key so we don't need to store them again in the value. p.ClearValues(message.ProtoReflect()) v, err = proto.MarshalOptions{Deterministic: true}.Marshal(message) @@ -107,7 +105,7 @@ func (p PrimaryKeyCodec) marshal(key []protoreflect.Value, message proto.Message return nil, err } - // set the primary key values again returning the message to its original state + // Set the primary key values again returning the message to its original state. p.SetKeyValues(message.ProtoReflect(), key) return v, nil @@ -125,7 +123,7 @@ func (p *PrimaryKeyCodec) Unmarshal(key []protoreflect.Value, value []byte, mess return err } - // rehydrate primary key + // Rehydrate primary key. p.SetKeyValues(message.ProtoReflect(), key) return nil } diff --git a/orm/encoding/ormkv/primary_key_test.go b/orm/encoding/ormkv/primary_key_test.go index ece72754a7ec..22bf3b0de8eb 100644 --- a/orm/encoding/ormkv/primary_key_test.go +++ b/orm/encoding/ormkv/primary_key_test.go @@ -5,14 +5,13 @@ import ( "fmt" "testing" + "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" + "github.com/cosmos/cosmos-sdk/orm/internal/testpb" + "github.com/cosmos/cosmos-sdk/orm/internal/testutil" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/testing/protocmp" "gotest.tools/v3/assert" "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" ) func TestPrimaryKeyCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/seq.go b/orm/encoding/ormkv/seq.go index 59e38dc0e67f..2f958203fe6b 100644 --- a/orm/encoding/ormkv/seq.go +++ b/orm/encoding/ormkv/seq.go @@ -5,7 +5,6 @@ import ( "encoding/binary" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" ) @@ -24,7 +23,7 @@ var _ EntryCodec = &SeqCodec{} func (s SeqCodec) DecodeEntry(k, v []byte) (Entry, error) { if !bytes.Equal(k, s.prefix) { - return nil, ormerrors.UnexpectedDecodePrefix + return nil, ormerrors.ErrUnexpectedDecodePrefix } x, err := s.DecodeValue(v) @@ -41,11 +40,11 @@ func (s SeqCodec) DecodeEntry(k, v []byte) (Entry, error) { func (s SeqCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { seqEntry, ok := entry.(*SeqEntry) if !ok { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } if seqEntry.TableName != s.messageType { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } return s.prefix, s.EncodeValue(seqEntry.Value), nil @@ -55,13 +54,13 @@ func (s SeqCodec) Prefix() []byte { return s.prefix } -func (s SeqCodec) EncodeValue(seq uint64) (v []byte) { +func (SeqCodec) EncodeValue(seq uint64) (v []byte) { bz := make([]byte, binary.MaxVarintLen64) n := binary.PutUvarint(bz, seq) return bz[:n] } -func (s SeqCodec) DecodeValue(v []byte) (uint64, error) { +func (SeqCodec) DecodeValue(v []byte) (uint64, error) { if len(v) == 0 { return 0, nil } diff --git a/orm/encoding/ormkv/seq_test.go b/orm/encoding/ormkv/seq_test.go index 90a3c2b8c201..d22fd0f62af5 100644 --- a/orm/encoding/ormkv/seq_test.go +++ b/orm/encoding/ormkv/seq_test.go @@ -5,11 +5,9 @@ import ( "testing" "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - + "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "gotest.tools/v3/assert" "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" ) func TestSeqCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/unique_key.go b/orm/encoding/ormkv/unique_key.go index e9d36cb5ae6f..39c671b9d6d7 100644 --- a/orm/encoding/ormkv/unique_key.go +++ b/orm/encoding/ormkv/unique_key.go @@ -5,7 +5,6 @@ import ( "io" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" ) @@ -25,11 +24,11 @@ var _ IndexCodec = &UniqueKeyCodec{} // provided message descriptor, index and primary key fields. func NewUniqueKeyCodec(prefix []byte, messageType protoreflect.MessageType, indexFields, primaryKeyFields []protoreflect.Name) (*UniqueKeyCodec, error) { if len(indexFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("index fields are empty") + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("index fields are empty") } if len(primaryKeyFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("primary key fields are empty") + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("primary key fields are empty") } keyCodec, err := NewKeyCodec(prefix, messageType, indexFields) @@ -64,10 +63,10 @@ func NewUniqueKeyCodec(prefix []byte, messageType protoreflect.MessageType, inde } } - // if there is nothing in the value we have a trivial unique index - // which shouldn't actually be a unique index at all + // If there is nothing in the value we have a trivial unique index + // which shouldn't actually be a unique index at all. if len(valueFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("unique index %s on table %s introduces no new uniqueness constraint not already in the primary key and should not be marked as unique", + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("unique index %s on table %s introduces no new uniqueness constraint not already in the primary key and should not be marked as unique", indexFields, messageType.Descriptor().FullName()) } @@ -86,14 +85,14 @@ func NewUniqueKeyCodec(prefix []byte, messageType protoreflect.MessageType, inde func (u UniqueKeyCodec) DecodeIndexKey(k, v []byte) (indexFields, primaryKey []protoreflect.Value, err error) { ks, err := u.keyCodec.DecodeKey(bytes.NewReader(k)) - // got prefix key + // Got prefix key. if err == io.EOF { return ks, nil, err } else if err != nil { return nil, nil, err } - // got prefix key + // Got prefix key. if len(ks) < len(u.keyCodec.fieldCodecs) { return ks, nil, err } @@ -107,12 +106,12 @@ func (u UniqueKeyCodec) DecodeIndexKey(k, v []byte) (indexFields, primaryKey []p return ks, pk, nil } -func (cdc UniqueKeyCodec) extractPrimaryKey(keyValues, valueValues []protoreflect.Value) []protoreflect.Value { - numPkFields := len(cdc.pkFieldOrder) +func (u UniqueKeyCodec) extractPrimaryKey(keyValues, valueValues []protoreflect.Value) []protoreflect.Value { + numPkFields := len(u.pkFieldOrder) pkValues := make([]protoreflect.Value, numPkFields) for i := 0; i < numPkFields; i++ { - fo := cdc.pkFieldOrder[i] + fo := u.pkFieldOrder[i] if fo.inKey { pkValues[i] = keyValues[fo.i] } else { @@ -141,7 +140,7 @@ func (u UniqueKeyCodec) DecodeEntry(k, v []byte) (Entry, error) { func (u UniqueKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { indexEntry, ok := entry.(*IndexKeyEntry) if !ok { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } k, err = u.keyCodec.EncodeKey(indexEntry.IndexValues) if err != nil { @@ -150,7 +149,7 @@ func (u UniqueKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { n := len(indexEntry.PrimaryKey) if n != len(u.pkFieldOrder) { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("wrong primary key length") + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("wrong primary key length") } var values []protoreflect.Value @@ -158,13 +157,11 @@ func (u UniqueKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { value := indexEntry.PrimaryKey[i] fieldOrder := u.pkFieldOrder[i] if !fieldOrder.inKey { - // goes in values because it is not present in the index key otherwise + // Goes in values because it is not present in the index key otherwise. values = append(values, value) - } else { - // does not go in values, but we need to verify that the value in index values matches the primary key value - if u.keyCodec.fieldCodecs[fieldOrder.i].Compare(value, indexEntry.IndexValues[fieldOrder.i]) != 0 { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("value in primary key does not match corresponding value in index key") - } + // Does not go in values, but we need to verify that the value in index values matches the primary key value. + } else if u.keyCodec.fieldCodecs[fieldOrder.i].Compare(value, indexEntry.IndexValues[fieldOrder.i]) != 0 { + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("value in primary key does not match corresponding value in index key") } } diff --git a/orm/encoding/ormkv/unique_key_test.go b/orm/encoding/ormkv/unique_key_test.go index c015e671e397..f30c343a4e0c 100644 --- a/orm/encoding/ormkv/unique_key_test.go +++ b/orm/encoding/ormkv/unique_key_test.go @@ -5,14 +5,13 @@ import ( "fmt" "testing" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - "gotest.tools/v3/assert" - "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/internal/testutil" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + "gotest.tools/v3/assert" + "pgregory.net/rapid" ) func TestUniqueKeyCodec(t *testing.T) { @@ -20,9 +19,9 @@ func TestUniqueKeyCodec(t *testing.T) { keyCodec := testutil.TestKeyCodecGen(1, 5).Draw(t, "keyCodec") pkCodec := testutil.TestKeyCodecGen(1, 5).Draw(t, "primaryKeyCodec") - // check if we have a trivial unique index where all of the fields + // Check if we have a trivial unique index where all of the fields // in the primary key are in the unique key, we should expect an - // error in this case + // error in this case. isInPk := map[protoreflect.Name]bool{} for _, spec := range pkCodec.KeySpecs { isInPk[spec.FieldName] = true @@ -46,9 +45,8 @@ func TestUniqueKeyCodec(t *testing.T) { if isTrivialUniqueKey { assert.ErrorContains(t, err, "no new uniqueness constraint") return - } else { - assert.NilError(t, err) } + assert.NilError(t, err) for i := 0; i < 100; i++ { a := testutil.GenA.Draw(t, fmt.Sprintf("a%d", i)) @@ -89,5 +87,5 @@ func TestUniqueKeyCodec(t *testing.T) { func TestTrivialUnique(t *testing.T) { _, err := ormkv.NewUniqueKeyCodec(nil, (&testpb.ExampleTable{}).ProtoReflect().Type(), []protoreflect.Name{"u32", "str"}, []protoreflect.Name{"str", "u32"}) - assert.ErrorIs(t, err, ormerrors.InvalidTableDefinition) + assert.ErrorIs(t, err, ormerrors.ErrInvalidTableDefinition) } diff --git a/orm/internal/codegen/codegen.go b/orm/internal/codegen/codegen.go index b895d9909cfc..bd58330805cc 100644 --- a/orm/internal/codegen/codegen.go +++ b/orm/internal/codegen/codegen.go @@ -4,12 +4,11 @@ import ( "fmt" "os" + ormv1 "cosmossdk.io/api/cosmos/orm/v1" + "github.com/cosmos/cosmos-proto/generator" "google.golang.org/protobuf/compiler/protogen" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/pluginpb" - - ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-proto/generator" ) const ( diff --git a/orm/internal/codegen/file.go b/orm/internal/codegen/file.go index 681e49cf89e2..28b8255d68cc 100644 --- a/orm/internal/codegen/file.go +++ b/orm/internal/codegen/file.go @@ -33,7 +33,7 @@ func (f fileGen) gen() error { } singletonDesc := proto.GetExtension(msg.Desc.Options(), ormv1.E_Singleton).(*ormv1.SingletonDescriptor) if singletonDesc != nil { - // do some singleton magic + // Do some singleton magic. singletonGen, err := newSingletonGen(f, msg, singletonDesc) if err != nil { return err @@ -41,7 +41,7 @@ func (f fileGen) gen() error { singletonGen.gen() } - if tableDesc != nil || singletonDesc != nil { // message is one of the tables, + if tableDesc != nil || singletonDesc != nil { // Message is one of the tables,. stores = append(stores, msg) } } @@ -66,7 +66,7 @@ func (f fileGen) genStoreInterface(stores []*protogen.Message) { } func (f fileGen) genStoreStruct(stores []*protogen.Message) { - // struct + // Struct. f.P("type ", f.storeStructName(), " struct {") for _, message := range stores { f.P(f.param(message.GoIdent.GoName), " ", f.messageTableInterfaceName(message)) @@ -74,10 +74,6 @@ func (f fileGen) genStoreStruct(stores []*protogen.Message) { f.P("}") } -func (f fileGen) storeAccessorName() string { - return f.storeInterfaceName() -} - func (f fileGen) storeInterfaceName() string { return strcase.ToCamel(f.fileShortName()) + "Store" } @@ -100,19 +96,11 @@ func fileShortName(file *protogen.File) string { return strcase.ToCamel(shortName) } -func (f fileGen) messageTableInterfaceName(m *protogen.Message) string { +func (fileGen) messageTableInterfaceName(m *protogen.Message) string { return m.GoIdent.GoName + "Table" } -func (f fileGen) messageReaderInterfaceName(m *protogen.Message) string { - return m.GoIdent.GoName + "Reader" -} - -func (f fileGen) messageTableVar(m *protogen.Message) string { - return f.param(m.GoIdent.GoName + "Table") -} - -func (f fileGen) param(name string) string { +func (fileGen) param(name string) string { return strcase.ToLowerCamel(name) } @@ -125,7 +113,7 @@ func (f fileGen) messageConstructorName(m *protogen.Message) string { } func (f fileGen) genStoreMethods(stores []*protogen.Message) { - // getters + // Getters. for _, msg := range stores { name := f.messageTableInterfaceName(msg) f.P("func(x ", f.storeStructName(), ") ", name, "() ", name, "{") diff --git a/orm/internal/codegen/index.go b/orm/internal/codegen/index.go index 9b889d431e46..ce64b2ec50af 100644 --- a/orm/internal/codegen/index.go +++ b/orm/internal/codegen/index.go @@ -5,19 +5,18 @@ import ( "strings" "github.com/iancoleman/strcase" - "google.golang.org/protobuf/reflect/protoreflect" ) func (t tableGen) genIndexKeys() { - // interface that all keys must adhere to + // Interface that all keys must adhere to. t.P("type ", t.indexKeyInterfaceName(), " interface {") t.P("id() uint32") - t.P("values() []interface{}") + t.P("values() []any") t.P(t.param(t.indexKeyInterfaceName()), "()") t.P("}") t.P() - // start with primary key.. + // Start with primary key.. t.P("// primary key starting index..") t.genIndex(t.table.PrimaryKey.Fields, 0, true) for _, idx := range t.table.Index { @@ -43,47 +42,10 @@ func (t tableGen) genValueFunc() { t.P("}") } -func (t tableGen) genIndexMethods(idxKeyName string) { - receiverFunc := fmt.Sprintf("func (x %s) ", idxKeyName) - t.P(receiverFunc, "id() uint32 { return ", t.table.Id, " /* primary key */ }") - t.P(receiverFunc, "values() []interface{} { return x.vs }") - t.P(receiverFunc, t.param(t.indexKeyInterfaceName()), "() {}") - t.P() -} - -func (t tableGen) genIndexInterfaceGuard(idxKeyName string) { - t.P("var _ ", t.indexKeyInterfaceName(), " = ", idxKeyName, "{}") - t.P() -} - func (t tableGen) indexKeyInterfaceName() string { return t.msg.GoIdent.GoName + "IndexKey" } -func (t tableGen) genIndexKey(idxKeyName string) { - t.P("type ", idxKeyName, " struct {") - t.P("vs []interface{}") - t.P("}") - t.P() -} - -func (t tableGen) indexKeyParts(names []protoreflect.Name) string { - cnames := make([]string, len(names)) - for i, name := range names { - cnames[i] = strcase.ToCamel(string(name)) - } - return strings.Join(cnames, "") -} - -func (t tableGen) indexKeyName(names []protoreflect.Name) string { - cnames := make([]string, len(names)) - for i, name := range names { - cnames[i] = strcase.ToCamel(string(name)) - } - joinedNames := strings.Join(cnames, "") - return t.msg.GoIdent.GoName + joinedNames + "IndexKey" -} - func (t tableGen) indexStructName(fields []string) string { names := make([]string, len(fields)) for i, field := range fields { @@ -103,7 +65,7 @@ func (t tableGen) genIndex(fields string, id uint32, isPrimaryKey bool) { } t.P("type ", idxKeyName, " struct {") - t.P("vs []interface{}") + t.P("vs []any") t.P("}") t.genIndexInterfaceMethods(id, idxKeyName) @@ -116,7 +78,7 @@ func (t tableGen) genIndex(fields string, id uint32, isPrimaryKey bool) { func (t tableGen) genIndexInterfaceMethods(id uint32, indexStructName string) { funPrefix := fmt.Sprintf("func (x %s) ", indexStructName) t.P(funPrefix, "id() uint32 {return ", id, "}") - t.P(funPrefix, "values() []interface{} {return x.vs}") + t.P(funPrefix, "values() []any {return x.vs}") t.P(funPrefix, t.param(t.indexKeyInterfaceName()), "() {}") t.P() } @@ -130,7 +92,7 @@ func (t tableGen) genWithMethods(indexStructName string, parts []string) { funcName := "With" + strings.Join(camelParts, "") t.P(funcPrefix, funcName, "(", t.fieldArgsFromStringSlice(parts), ") ", indexStructName, "{") - t.P("this.vs = []interface{}{", strings.Join(parts, ","), "}") + t.P("this.vs = []any{", strings.Join(parts, ","), "}") t.P("return this") t.P("}") t.P() diff --git a/orm/internal/codegen/query.go b/orm/internal/codegen/query.go index 974a6b40c24c..e799c9b396a0 100644 --- a/orm/internal/codegen/query.go +++ b/orm/internal/codegen/query.go @@ -84,7 +84,7 @@ func (g queryProtoGen) gen() error { func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.TableDescriptor) error { name := msg.Desc.Name() g.svc.F("// Get queries the %s table by its primary key.", name) - g.svc.F("rpc Get%s(Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway + g.svc.F("rpc Get%s(Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway. g.startRequestType("Get%sRequest", name) g.msgs.Indent() @@ -118,7 +118,7 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab fieldsCamel := fieldsToCamelCase(idx.Fields) methodName := fmt.Sprintf("Get%sBy%s", name, fieldsCamel) g.svc.F("// %s queries the %s table by its %s index", methodName, name, fieldsCamel) - g.svc.F("rpc %s(%sRequest) returns (%sResponse) {}", methodName, methodName, methodName) // TODO grpc gateway + g.svc.F("rpc %s(%sRequest) returns (%sResponse) {}", methodName, methodName, methodName) // TODO grpc gateway. g.startRequestType("%sRequest", methodName) g.msgs.Indent() @@ -144,7 +144,7 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab g.imports["cosmos/base/query/v1beta1/pagination.proto"] = true g.svc.F("// List%s queries the %s table using prefix and range queries against defined indexes.", name, name) - g.svc.F("rpc List%s(List%sRequest) returns (List%sResponse) {}", name, name, name) // TODO grpc gateway + g.svc.F("rpc List%s(List%sRequest) returns (List%sResponse) {}", name, name, name) // TODO grpc gateway. g.startRequestType("List%sRequest", name) g.msgs.Indent() g.msgs.F("// IndexKey specifies the value of an index key to use in prefix and range queries.") @@ -152,11 +152,11 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab g.msgs.Indent() indexFields := []string{desc.PrimaryKey.Fields} - // the primary key has field number 1 + // The primary key has field number 1. fieldNums := []uint32{1} for _, index := range desc.Index { indexFields = append(indexFields, index.Fields) - // index field numbers are their id + 1 + // Index field numbers are their id + 1. fieldNums = append(fieldNums, index.Id+1) } @@ -231,7 +231,7 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab func (g queryProtoGen) genSingletonRPCMethods(msg *protogen.Message) error { name := msg.Desc.Name() g.svc.F("// Get%s queries the %s singleton.", name, name) - g.svc.F("rpc Get%s (Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway + g.svc.F("rpc Get%s (Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway. g.startRequestType("Get%sRequest", name) g.msgs.F("}") g.msgs.F("") @@ -284,8 +284,8 @@ func newWriter() *writer { } } -func (w *writer) F(format string, args ...interface{}) { - _, err := w.Write([]byte(w.indentStr)) +func (w *writer) F(format string, args ...any) { + _, err := w.WriteString(w.indentStr) if err != nil { panic(err) } @@ -302,7 +302,7 @@ func (w *writer) F(format string, args ...interface{}) { } func (w *writer) Indent() { - w.indent += 1 + w.indent++ w.updateIndent() } @@ -314,6 +314,6 @@ func (w *writer) updateIndent() { } func (w *writer) Dedent() { - w.indent -= 1 + w.indent-- w.updateIndent() } diff --git a/orm/internal/codegen/singleton.go b/orm/internal/codegen/singleton.go index 40a265235c04..84422c8183b1 100644 --- a/orm/internal/codegen/singleton.go +++ b/orm/internal/codegen/singleton.go @@ -3,12 +3,10 @@ package codegen import ( "fmt" - "google.golang.org/protobuf/compiler/protogen" - "google.golang.org/protobuf/types/dynamicpb" - ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/types/dynamicpb" ) type singletonGen struct { @@ -59,7 +57,7 @@ func (s singletonGen) genInterfaceGuard() { func (s singletonGen) genMethods() { receiver := fmt.Sprintf("func (x %s) ", s.messageTableReceiverName(s.msg)) varName := s.param(s.msg.GoIdent.GoName) - // Get + // Get. s.P(receiver, "Get(ctx ", contextPkg.Ident("Context"), ") (*", s.msg.GoIdent.GoName, ", error) {") s.P(varName, " := &", s.msg.GoIdent.GoName, "{}") s.P("_, err := x.table.Get(ctx, ", varName, ")") @@ -67,7 +65,7 @@ func (s singletonGen) genMethods() { s.P("}") s.P() - // Save + // Save. s.P(receiver, "Save(ctx ", contextPkg.Ident("Context"), ", ", varName, " *", s.msg.GoIdent.GoName, ") error {") s.P("return x.table.Save(ctx, ", varName, ")") s.P("}") diff --git a/orm/internal/codegen/table.go b/orm/internal/codegen/table.go index d629b0c29802..c2a64b99dce3 100644 --- a/orm/internal/codegen/table.go +++ b/orm/internal/codegen/table.go @@ -4,14 +4,12 @@ import ( "fmt" "strings" - "google.golang.org/protobuf/compiler/protogen" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/types/dynamicpb" - ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/dynamicpb" ) type tableGen struct { @@ -48,7 +46,7 @@ func newTableGen(fileGen fileGen, msg *protogen.Message, table *ormv1.TableDescr } func (t tableGen) gen() { - t.getTableInterface() + t.tableInterface() t.genIterator() t.genIndexKeys() t.genStruct() @@ -57,7 +55,7 @@ func (t tableGen) gen() { t.genConstructor() } -func (t tableGen) getTableInterface() { +func (t tableGen) tableInterface() { t.P("type ", t.messageTableInterfaceName(t.msg), " interface {") t.P("Insert(ctx ", contextPkg.Ident("Context"), ", ", t.param(t.msg.GoIdent.GoName), " *", t.QualifiedGoIdent(t.msg.GoIdent), ") error") if t.table.PrimaryKey.AutoIncrement { @@ -85,16 +83,16 @@ func (t tableGen) getTableInterface() { } // returns the has and get (in that order) function signature for unique indexes. -func (t tableGen) uniqueIndexSig(idxFields string) (string, string, string) { +func (t tableGen) uniqueIndexSig(idxFields string) (hasFuncSig, getFuncSig, getFuncName string) { fieldsSlc := strings.Split(idxFields, ",") camelFields := fieldsToCamelCase(idxFields) hasFuncName := "HasBy" + camelFields - getFuncName := "GetBy" + camelFields + getFuncName = "GetBy" + camelFields args := t.fieldArgsFromStringSlice(fieldsSlc) - hasFuncSig := fmt.Sprintf("%s (ctx context.Context, %s) (found bool, err error)", hasFuncName, args) - getFuncSig := fmt.Sprintf("%s (ctx context.Context, %s) (*%s, error)", getFuncName, args, t.msg.GoIdent.GoName) + hasFuncSig = fmt.Sprintf("%s (ctx context.Context, %s) (found bool, err error)", hasFuncName, args) + getFuncSig = fmt.Sprintf("%s (ctx context.Context, %s) (*%s, error)", getFuncName, args, t.msg.GoIdent.GoName) return hasFuncSig, getFuncSig, getFuncName } @@ -109,27 +107,6 @@ func (t tableGen) iteratorName() string { return t.msg.GoIdent.GoName + "Iterator" } -func (t tableGen) getSig() string { - res := "Get" + t.msg.GoIdent.GoName + "(" - res += t.fieldsArgs(t.primaryKeyFields.Names()) - res += ") (*" + t.QualifiedGoIdent(t.msg.GoIdent) + ", error)" - return res -} - -func (t tableGen) hasSig() string { - t.P("Has(ctx ", contextPkg.Ident("Context"), ", ", t.fieldsArgs(t.primaryKeyFields.Names()), ") (found bool, err error)") - return "" -} - -func (t tableGen) listSig() string { - res := "List" + t.msg.GoIdent.GoName + "(" - res += t.indexKeyInterfaceName() - res += ") (" - res += t.iteratorName() - res += ", error)" - return res -} - func (t tableGen) fieldArgsFromStringSlice(names []string) string { args := make([]string, len(names)) for i, name := range names { @@ -171,7 +148,7 @@ func (t tableGen) genTableImpl() { varName := t.param(t.msg.GoIdent.GoName) varTypeName := t.QualifiedGoIdent(t.msg.GoIdent) - // these methods all have the same impl sans their names. so we can just loop and replace. + // These methods all have the same impl sans their names. So we can just loop and replace. methods := []string{"Insert", "Update", "Save", "Delete"} for _, method := range methods { t.P(receiver, method, "(ctx ", contextPkg.Ident("Context"), ", ", varName, " *", varTypeName, ") error {") @@ -192,13 +169,13 @@ func (t tableGen) genTableImpl() { t.P() } - // Has + // Has. t.P(receiver, "Has(ctx ", contextPkg.Ident("Context"), ", ", t.fieldsArgs(t.primaryKeyFields.Names()), ") (found bool, err error) {") t.P("return ", receiverVar, ".table.PrimaryKey().Has(ctx, ", t.primaryKeyFields.String(), ")") t.P("}") t.P() - // Get + // Get. t.P(receiver, "Get(ctx ", contextPkg.Ident("Context"), ", ", t.fieldsArgs(t.primaryKeyFields.Names()), ") (*", varTypeName, ", error) {") t.P("var ", varName, " ", varTypeName) t.P("found, err := ", receiverVar, ".table.PrimaryKey().Get(ctx, &", varName, ", ", t.primaryKeyFields.String(), ")") @@ -216,7 +193,7 @@ func (t tableGen) genTableImpl() { fields := strings.Split(idx.Fields, ",") hasName, getName, _ := t.uniqueIndexSig(idx.Fields) - // has + // Has. t.P("func (", receiverVar, " ", t.messageTableReceiverName(t.msg), ") ", hasName, "{") t.P("return ", receiverVar, ".table.GetIndexByID(", idx.Id, ").(", ormTablePkg.Ident("UniqueIndex"), ").Has(ctx,") @@ -227,7 +204,7 @@ func (t tableGen) genTableImpl() { t.P("}") t.P() - // get + // Get. varName := t.param(t.msg.GoIdent.GoName) varTypeName := t.msg.GoIdent.GoName t.P("func (", receiverVar, " ", t.messageTableReceiverName(t.msg), ") ", getName, "{") @@ -249,28 +226,28 @@ func (t tableGen) genTableImpl() { t.P() } - // List + // List. t.P(receiver, "List(ctx ", contextPkg.Ident("Context"), ", prefixKey ", t.indexKeyInterfaceName(), ", opts ...", ormListPkg.Ident("Option"), ") (", t.iteratorName(), ", error) {") t.P("it, err := ", receiverVar, ".table.GetIndexByID(prefixKey.id()).List(ctx, prefixKey.values(), opts...)") t.P("return ", t.iteratorName(), "{it}, err") t.P("}") t.P() - // ListRange + // ListRange. t.P(receiver, "ListRange(ctx ", contextPkg.Ident("Context"), ", from, to ", t.indexKeyInterfaceName(), ", opts ...", ormListPkg.Ident("Option"), ") (", t.iteratorName(), ", error) {") t.P("it, err := ", receiverVar, ".table.GetIndexByID(from.id()).ListRange(ctx, from.values(), to.values(), opts...)") t.P("return ", t.iteratorName(), "{it}, err") t.P("}") t.P() - // DeleteBy + // DeleteBy. t.P(receiver, "DeleteBy(ctx ", contextPkg.Ident("Context"), ", prefixKey ", t.indexKeyInterfaceName(), ") error {") t.P("return ", receiverVar, ".table.GetIndexByID(prefixKey.id()).DeleteBy(ctx, prefixKey.values()...)") t.P("}") t.P() t.P() - // DeleteRange + // DeleteRange. t.P(receiver, "DeleteRange(ctx ", contextPkg.Ident("Context"), ", from, to ", t.indexKeyInterfaceName(), ") error {") t.P("return ", receiverVar, ".table.GetIndexByID(from.id()).DeleteRange(ctx, from.values(), to.values())") t.P("}") diff --git a/orm/internal/fieldnames/fieldnames.go b/orm/internal/fieldnames/fieldnames.go index e348e3a1971b..2ecdde2f6cac 100644 --- a/orm/internal/fieldnames/fieldnames.go +++ b/orm/internal/fieldnames/fieldnames.go @@ -15,7 +15,7 @@ type FieldNames struct { // CommaSeparatedFieldNames creates a FieldNames instance from a list of comma-separated // fields. func CommaSeparatedFieldNames(fields string) FieldNames { - // normalize cases where there are spaces + // Normalize cases where there are spaces. if strings.IndexByte(fields, ' ') >= 0 { parts := strings.Split(fields, ",") for i, part := range parts { diff --git a/orm/internal/fieldnames/fieldnames_test.go b/orm/internal/fieldnames/fieldnames_test.go index f341fd7e3fe4..379221752374 100644 --- a/orm/internal/fieldnames/fieldnames_test.go +++ b/orm/internal/fieldnames/fieldnames_test.go @@ -4,7 +4,6 @@ import ( "testing" "google.golang.org/protobuf/reflect/protoreflect" - "gotest.tools/v3/assert" ) @@ -22,7 +21,7 @@ func TestFieldNames(t *testing.T) { assert.DeepEqual(t, names, f.Names()) assert.Equal(t, abc, f.String()) - // empty okay + // Empty okay. f = CommaSeparatedFieldNames("") assert.Equal(t, FieldNames{""}, f) assert.Equal(t, 0, len(f.Names())) @@ -33,7 +32,7 @@ func TestFieldNames(t *testing.T) { assert.DeepEqual(t, names, f.Names()) assert.Equal(t, abc, f.String()) - // empty okay + // Empty okay. f = FieldsFromNames([]protoreflect.Name{}) assert.Equal(t, FieldNames{""}, f) f = FieldsFromNames(nil) diff --git a/orm/internal/stablejson/encode.go b/orm/internal/stablejson/encode.go index e9dd143773d0..4e1281420548 100644 --- a/orm/internal/stablejson/encode.go +++ b/orm/internal/stablejson/encode.go @@ -34,9 +34,9 @@ func Marshal(message proto.Message) ([]byte, error) { fd = last.Step.FieldDescriptor() _, _ = fmt.Fprintf(buf, "%q:", fd.Name()) case protopath.ListIndexStep: - fd = beforeLast.Step.FieldDescriptor() // lists always appear in the context of a repeated field + fd = beforeLast.Step.FieldDescriptor() // Lists always appear in the context of a repeated field. case protopath.MapIndexStep: - fd = beforeLast.Step.FieldDescriptor() // maps always appear in the context of a repeated field + fd = beforeLast.Step.FieldDescriptor() // Maps always appear in the context of a repeated field. _, _ = fmt.Fprintf(buf, "%v:", last.Step.MapIndex().Interface()) case protopath.AnyExpandStep: _, _ = fmt.Fprintf(buf, `"@type":%q`, last.Value.Message().Descriptor().FullName()) diff --git a/orm/internal/stablejson/encode_test.go b/orm/internal/stablejson/encode_test.go index 85d8acd57920..87b11f8f9b4e 100644 --- a/orm/internal/stablejson/encode_test.go +++ b/orm/internal/stablejson/encode_test.go @@ -3,15 +3,13 @@ package stablejson_test import ( "testing" - "github.com/stretchr/testify/require" - - "google.golang.org/protobuf/types/known/anypb" - bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" "github.com/cosmos/cosmos-proto/anyutil" "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/anypb" ) func TestStableJSON(t *testing.T) { diff --git a/orm/internal/testkv/compare.go b/orm/internal/testkv/compare.go index 8b3878f4738f..a5f9a9dd66fc 100644 --- a/orm/internal/testkv/compare.go +++ b/orm/internal/testkv/compare.go @@ -3,10 +3,9 @@ package testkv import ( "bytes" - "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "github.com/cosmos/cosmos-sdk/orm/types/kv" + "gotest.tools/v3/assert" ) func AssertBackendsEqual(t assert.TestingT, b1, b2 ormtable.Backend) { diff --git a/orm/internal/testkv/debug.go b/orm/internal/testkv/debug.go index 5891528942b1..b5626bc42cb1 100644 --- a/orm/internal/testkv/debug.go +++ b/orm/internal/testkv/debug.go @@ -4,12 +4,11 @@ import ( "context" "fmt" - "google.golang.org/protobuf/proto" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "github.com/cosmos/cosmos-sdk/orm/types/kv" + "google.golang.org/protobuf/proto" ) // Debugger is an interface that handles debug info from the debug store wrapper. @@ -217,42 +216,42 @@ type debugHooks struct { writeHooks ormtable.WriteHooks } -func (d debugHooks) ValidateInsert(context context.Context, message proto.Message) error { - jsonBz, err := stablejson.Marshal(message) +func (d debugHooks) ValidateInsert(ctx context.Context, insertMessage proto.Message) error { + jsonBz, err := stablejson.Marshal(insertMessage) if err != nil { return err } d.debugger.Log(fmt.Sprintf( "ORM BEFORE INSERT %s %s", - message.ProtoReflect().Descriptor().FullName(), + insertMessage.ProtoReflect().Descriptor().FullName(), jsonBz, )) if d.validateHooks != nil { - return d.validateHooks.ValidateInsert(context, message) + return d.validateHooks.ValidateInsert(ctx, insertMessage) } return nil } -func (d debugHooks) ValidateUpdate(ctx context.Context, existing, new proto.Message) error { - existingJson, err := stablejson.Marshal(existing) +func (d debugHooks) ValidateUpdate(ctx context.Context, existingMsg, newMsg proto.Message) error { + existingJSON, err := stablejson.Marshal(existingMsg) if err != nil { return err } - newJson, err := stablejson.Marshal(new) + newJSON, err := stablejson.Marshal(newMsg) if err != nil { return err } d.debugger.Log(fmt.Sprintf( "ORM BEFORE UPDATE %s %s -> %s", - existing.ProtoReflect().Descriptor().FullName(), - existingJson, - newJson, + existingMsg.ProtoReflect().Descriptor().FullName(), + existingJSON, + newJSON, )) if d.validateHooks != nil { - return d.validateHooks.ValidateUpdate(ctx, existing, new) + return d.validateHooks.ValidateUpdate(ctx, existingMsg, newMsg) } return nil } @@ -290,25 +289,25 @@ func (d debugHooks) OnInsert(ctx context.Context, message proto.Message) { } } -func (d debugHooks) OnUpdate(ctx context.Context, existing, new proto.Message) { - existingJson, err := stablejson.Marshal(existing) +func (d debugHooks) OnUpdate(ctx context.Context, existingMsg, newMsg proto.Message) { + existingJSON, err := stablejson.Marshal(existingMsg) if err != nil { panic(err) } - newJson, err := stablejson.Marshal(new) + newJSON, err := stablejson.Marshal(newMsg) if err != nil { panic(err) } d.debugger.Log(fmt.Sprintf( "ORM AFTER UPDATE %s %s -> %s", - existing.ProtoReflect().Descriptor().FullName(), - existingJson, - newJson, + existingMsg.ProtoReflect().Descriptor().FullName(), + existingJSON, + newJSON, )) if d.writeHooks != nil { - d.writeHooks.OnUpdate(ctx, existing, new) + d.writeHooks.OnUpdate(ctx, existingMsg, newMsg) } } diff --git a/orm/internal/testkv/leveldb.go b/orm/internal/testkv/leveldb.go index 4e03f3642138..2ee777fff91d 100644 --- a/orm/internal/testkv/leveldb.go +++ b/orm/internal/testkv/leveldb.go @@ -4,14 +4,14 @@ import ( "testing" dbm "github.com/cosmos/cosmos-db" - "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "gotest.tools/v3/assert" ) -func NewGoLevelDBBackend(t testing.TB) ormtable.Backend { - db, err := dbm.NewGoLevelDB("test", t.TempDir(), nil) - assert.NilError(t, err) +func NewGoLevelDBBackend(tb testing.TB) ormtable.Backend { + tb.Helper() + db, err := dbm.NewGoLevelDB("test", tb.TempDir(), nil) + assert.NilError(tb, err) return ormtable.NewBackend(ormtable.BackendOptions{ CommitmentStore: db, }) diff --git a/orm/internal/testkv/mem.go b/orm/internal/testkv/mem.go index d2c89a2e8db4..26d6ba4fdda9 100644 --- a/orm/internal/testkv/mem.go +++ b/orm/internal/testkv/mem.go @@ -2,7 +2,6 @@ package testkv import ( dbm "github.com/cosmos/cosmos-db" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" ) @@ -22,6 +21,6 @@ func NewSplitMemBackend() ormtable.Backend { func NewSharedMemBackend() ormtable.Backend { return ormtable.NewBackend(ormtable.BackendOptions{ CommitmentStore: dbm.NewMemDB(), - // commit store is automatically used as the index store + // Commit store is automatically used as the index store. }) } diff --git a/orm/internal/testpb/bank.cosmos_orm.go b/orm/internal/testpb/bank.cosmos_orm.go index 0635179c20e8..4fac9828d4d5 100644 --- a/orm/internal/testpb/bank.cosmos_orm.go +++ b/orm/internal/testpb/bank.cosmos_orm.go @@ -37,7 +37,7 @@ func (i BalanceIterator) Value() (*Balance, error) { type BalanceIndexKey interface { id() uint32 - values() []interface{} + values() []any balanceIndexKey() } @@ -45,33 +45,33 @@ type BalanceIndexKey interface { type BalancePrimaryKey = BalanceAddressDenomIndexKey type BalanceAddressDenomIndexKey struct { - vs []interface{} + vs []any } func (x BalanceAddressDenomIndexKey) id() uint32 { return 0 } -func (x BalanceAddressDenomIndexKey) values() []interface{} { return x.vs } +func (x BalanceAddressDenomIndexKey) values() []any { return x.vs } func (x BalanceAddressDenomIndexKey) balanceIndexKey() {} func (this BalanceAddressDenomIndexKey) WithAddress(address string) BalanceAddressDenomIndexKey { - this.vs = []interface{}{address} + this.vs = []any{address} return this } func (this BalanceAddressDenomIndexKey) WithAddressDenom(address string, denom string) BalanceAddressDenomIndexKey { - this.vs = []interface{}{address, denom} + this.vs = []any{address, denom} return this } type BalanceDenomIndexKey struct { - vs []interface{} + vs []any } func (x BalanceDenomIndexKey) id() uint32 { return 1 } -func (x BalanceDenomIndexKey) values() []interface{} { return x.vs } +func (x BalanceDenomIndexKey) values() []any { return x.vs } func (x BalanceDenomIndexKey) balanceIndexKey() {} func (this BalanceDenomIndexKey) WithDenom(denom string) BalanceDenomIndexKey { - this.vs = []interface{}{denom} + this.vs = []any{denom} return this } @@ -106,7 +106,7 @@ func (this balanceTable) Get(ctx context.Context, address string, denom string) return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &balance, nil } @@ -136,7 +136,7 @@ var _ BalanceTable = balanceTable{} func NewBalanceTable(db ormtable.Schema) (BalanceTable, error) { table := db.GetTable(&Balance{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&Balance{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&Balance{}).ProtoReflect().Descriptor().FullName())) } return balanceTable{table}, nil } @@ -169,7 +169,7 @@ func (i SupplyIterator) Value() (*Supply, error) { type SupplyIndexKey interface { id() uint32 - values() []interface{} + values() []any supplyIndexKey() } @@ -177,15 +177,15 @@ type SupplyIndexKey interface { type SupplyPrimaryKey = SupplyDenomIndexKey type SupplyDenomIndexKey struct { - vs []interface{} + vs []any } func (x SupplyDenomIndexKey) id() uint32 { return 0 } -func (x SupplyDenomIndexKey) values() []interface{} { return x.vs } +func (x SupplyDenomIndexKey) values() []any { return x.vs } func (x SupplyDenomIndexKey) supplyIndexKey() {} func (this SupplyDenomIndexKey) WithDenom(denom string) SupplyDenomIndexKey { - this.vs = []interface{}{denom} + this.vs = []any{denom} return this } @@ -220,7 +220,7 @@ func (this supplyTable) Get(ctx context.Context, denom string) (*Supply, error) return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &supply, nil } @@ -250,7 +250,7 @@ var _ SupplyTable = supplyTable{} func NewSupplyTable(db ormtable.Schema) (SupplyTable, error) { table := db.GetTable(&Supply{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&Supply{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&Supply{}).ProtoReflect().Descriptor().FullName())) } return supplyTable{table}, nil } diff --git a/orm/internal/testpb/test_schema.cosmos_orm.go b/orm/internal/testpb/test_schema.cosmos_orm.go index 93ce0cda021f..5eb4c5398b72 100644 --- a/orm/internal/testpb/test_schema.cosmos_orm.go +++ b/orm/internal/testpb/test_schema.cosmos_orm.go @@ -41,7 +41,7 @@ func (i ExampleTableIterator) Value() (*ExampleTable, error) { type ExampleTableIndexKey interface { id() uint32 - values() []interface{} + values() []any exampleTableIndexKey() } @@ -49,79 +49,79 @@ type ExampleTableIndexKey interface { type ExampleTablePrimaryKey = ExampleTableU32I64StrIndexKey type ExampleTableU32I64StrIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTableU32I64StrIndexKey) id() uint32 { return 0 } -func (x ExampleTableU32I64StrIndexKey) values() []interface{} { return x.vs } +func (x ExampleTableU32I64StrIndexKey) values() []any { return x.vs } func (x ExampleTableU32I64StrIndexKey) exampleTableIndexKey() {} func (this ExampleTableU32I64StrIndexKey) WithU32(u32 uint32) ExampleTableU32I64StrIndexKey { - this.vs = []interface{}{u32} + this.vs = []any{u32} return this } func (this ExampleTableU32I64StrIndexKey) WithU32I64(u32 uint32, i64 int64) ExampleTableU32I64StrIndexKey { - this.vs = []interface{}{u32, i64} + this.vs = []any{u32, i64} return this } func (this ExampleTableU32I64StrIndexKey) WithU32I64Str(u32 uint32, i64 int64, str string) ExampleTableU32I64StrIndexKey { - this.vs = []interface{}{u32, i64, str} + this.vs = []any{u32, i64, str} return this } type ExampleTableU64StrIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTableU64StrIndexKey) id() uint32 { return 1 } -func (x ExampleTableU64StrIndexKey) values() []interface{} { return x.vs } +func (x ExampleTableU64StrIndexKey) values() []any { return x.vs } func (x ExampleTableU64StrIndexKey) exampleTableIndexKey() {} func (this ExampleTableU64StrIndexKey) WithU64(u64 uint64) ExampleTableU64StrIndexKey { - this.vs = []interface{}{u64} + this.vs = []any{u64} return this } func (this ExampleTableU64StrIndexKey) WithU64Str(u64 uint64, str string) ExampleTableU64StrIndexKey { - this.vs = []interface{}{u64, str} + this.vs = []any{u64, str} return this } type ExampleTableStrU32IndexKey struct { - vs []interface{} + vs []any } func (x ExampleTableStrU32IndexKey) id() uint32 { return 2 } -func (x ExampleTableStrU32IndexKey) values() []interface{} { return x.vs } +func (x ExampleTableStrU32IndexKey) values() []any { return x.vs } func (x ExampleTableStrU32IndexKey) exampleTableIndexKey() {} func (this ExampleTableStrU32IndexKey) WithStr(str string) ExampleTableStrU32IndexKey { - this.vs = []interface{}{str} + this.vs = []any{str} return this } func (this ExampleTableStrU32IndexKey) WithStrU32(str string, u32 uint32) ExampleTableStrU32IndexKey { - this.vs = []interface{}{str, u32} + this.vs = []any{str, u32} return this } type ExampleTableBzStrIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTableBzStrIndexKey) id() uint32 { return 3 } -func (x ExampleTableBzStrIndexKey) values() []interface{} { return x.vs } +func (x ExampleTableBzStrIndexKey) values() []any { return x.vs } func (x ExampleTableBzStrIndexKey) exampleTableIndexKey() {} func (this ExampleTableBzStrIndexKey) WithBz(bz []byte) ExampleTableBzStrIndexKey { - this.vs = []interface{}{bz} + this.vs = []any{bz} return this } func (this ExampleTableBzStrIndexKey) WithBzStr(bz []byte, str string) ExampleTableBzStrIndexKey { - this.vs = []interface{}{bz, str} + this.vs = []any{bz, str} return this } @@ -156,7 +156,7 @@ func (this exampleTableTable) Get(ctx context.Context, u32 uint32, i64 int64, st return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleTable, nil } @@ -178,7 +178,7 @@ func (this exampleTableTable) GetByU64Str(ctx context.Context, u64 uint64, str s return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleTable, nil } @@ -208,7 +208,7 @@ var _ ExampleTableTable = exampleTableTable{} func NewExampleTableTable(db ormtable.Schema) (ExampleTableTable, error) { table := db.GetTable(&ExampleTable{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleTable{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleTable{}).ProtoReflect().Descriptor().FullName())) } return exampleTableTable{table}, nil } @@ -246,7 +246,7 @@ func (i ExampleAutoIncrementTableIterator) Value() (*ExampleAutoIncrementTable, type ExampleAutoIncrementTableIndexKey interface { id() uint32 - values() []interface{} + values() []any exampleAutoIncrementTableIndexKey() } @@ -254,28 +254,28 @@ type ExampleAutoIncrementTableIndexKey interface { type ExampleAutoIncrementTablePrimaryKey = ExampleAutoIncrementTableIdIndexKey type ExampleAutoIncrementTableIdIndexKey struct { - vs []interface{} + vs []any } func (x ExampleAutoIncrementTableIdIndexKey) id() uint32 { return 0 } -func (x ExampleAutoIncrementTableIdIndexKey) values() []interface{} { return x.vs } +func (x ExampleAutoIncrementTableIdIndexKey) values() []any { return x.vs } func (x ExampleAutoIncrementTableIdIndexKey) exampleAutoIncrementTableIndexKey() {} func (this ExampleAutoIncrementTableIdIndexKey) WithId(id uint64) ExampleAutoIncrementTableIdIndexKey { - this.vs = []interface{}{id} + this.vs = []any{id} return this } type ExampleAutoIncrementTableXIndexKey struct { - vs []interface{} + vs []any } func (x ExampleAutoIncrementTableXIndexKey) id() uint32 { return 1 } -func (x ExampleAutoIncrementTableXIndexKey) values() []interface{} { return x.vs } +func (x ExampleAutoIncrementTableXIndexKey) values() []any { return x.vs } func (x ExampleAutoIncrementTableXIndexKey) exampleAutoIncrementTableIndexKey() {} func (this ExampleAutoIncrementTableXIndexKey) WithX(x string) ExampleAutoIncrementTableXIndexKey { - this.vs = []interface{}{x} + this.vs = []any{x} return this } @@ -318,7 +318,7 @@ func (this exampleAutoIncrementTableTable) Get(ctx context.Context, id uint64) ( return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleAutoIncrementTable, nil } @@ -338,7 +338,7 @@ func (this exampleAutoIncrementTableTable) GetByX(ctx context.Context, x string) return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleAutoIncrementTable, nil } @@ -368,7 +368,7 @@ var _ ExampleAutoIncrementTableTable = exampleAutoIncrementTableTable{} func NewExampleAutoIncrementTableTable(db ormtable.Schema) (ExampleAutoIncrementTableTable, error) { table := db.GetTable(&ExampleAutoIncrementTable{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleAutoIncrementTable{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleAutoIncrementTable{}).ProtoReflect().Descriptor().FullName())) } return exampleAutoIncrementTableTable{table.(ormtable.AutoIncrementTable)}, nil } @@ -398,7 +398,7 @@ func (x exampleSingletonTable) Save(ctx context.Context, exampleSingleton *Examp func NewExampleSingletonTable(db ormtable.Schema) (ExampleSingletonTable, error) { table := db.GetTable(&ExampleSingleton{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleSingleton{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleSingleton{}).ProtoReflect().Descriptor().FullName())) } return &exampleSingletonTable{table}, nil } @@ -433,7 +433,7 @@ func (i ExampleTimestampIterator) Value() (*ExampleTimestamp, error) { type ExampleTimestampIndexKey interface { id() uint32 - values() []interface{} + values() []any exampleTimestampIndexKey() } @@ -441,28 +441,28 @@ type ExampleTimestampIndexKey interface { type ExampleTimestampPrimaryKey = ExampleTimestampIdIndexKey type ExampleTimestampIdIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTimestampIdIndexKey) id() uint32 { return 0 } -func (x ExampleTimestampIdIndexKey) values() []interface{} { return x.vs } +func (x ExampleTimestampIdIndexKey) values() []any { return x.vs } func (x ExampleTimestampIdIndexKey) exampleTimestampIndexKey() {} func (this ExampleTimestampIdIndexKey) WithId(id uint64) ExampleTimestampIdIndexKey { - this.vs = []interface{}{id} + this.vs = []any{id} return this } type ExampleTimestampTsIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTimestampTsIndexKey) id() uint32 { return 1 } -func (x ExampleTimestampTsIndexKey) values() []interface{} { return x.vs } +func (x ExampleTimestampTsIndexKey) values() []any { return x.vs } func (x ExampleTimestampTsIndexKey) exampleTimestampIndexKey() {} func (this ExampleTimestampTsIndexKey) WithTs(ts *timestamppb.Timestamp) ExampleTimestampTsIndexKey { - this.vs = []interface{}{ts} + this.vs = []any{ts} return this } @@ -505,7 +505,7 @@ func (this exampleTimestampTable) Get(ctx context.Context, id uint64) (*ExampleT return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleTimestamp, nil } @@ -535,7 +535,7 @@ var _ ExampleTimestampTable = exampleTimestampTable{} func NewExampleTimestampTable(db ormtable.Schema) (ExampleTimestampTable, error) { table := db.GetTable(&ExampleTimestamp{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleTimestamp{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleTimestamp{}).ProtoReflect().Descriptor().FullName())) } return exampleTimestampTable{table.(ormtable.AutoIncrementTable)}, nil } @@ -571,7 +571,7 @@ func (i SimpleExampleIterator) Value() (*SimpleExample, error) { type SimpleExampleIndexKey interface { id() uint32 - values() []interface{} + values() []any simpleExampleIndexKey() } @@ -579,28 +579,28 @@ type SimpleExampleIndexKey interface { type SimpleExamplePrimaryKey = SimpleExampleNameIndexKey type SimpleExampleNameIndexKey struct { - vs []interface{} + vs []any } func (x SimpleExampleNameIndexKey) id() uint32 { return 0 } -func (x SimpleExampleNameIndexKey) values() []interface{} { return x.vs } +func (x SimpleExampleNameIndexKey) values() []any { return x.vs } func (x SimpleExampleNameIndexKey) simpleExampleIndexKey() {} func (this SimpleExampleNameIndexKey) WithName(name string) SimpleExampleNameIndexKey { - this.vs = []interface{}{name} + this.vs = []any{name} return this } type SimpleExampleUniqueIndexKey struct { - vs []interface{} + vs []any } func (x SimpleExampleUniqueIndexKey) id() uint32 { return 1 } -func (x SimpleExampleUniqueIndexKey) values() []interface{} { return x.vs } +func (x SimpleExampleUniqueIndexKey) values() []any { return x.vs } func (x SimpleExampleUniqueIndexKey) simpleExampleIndexKey() {} func (this SimpleExampleUniqueIndexKey) WithUnique(unique string) SimpleExampleUniqueIndexKey { - this.vs = []interface{}{unique} + this.vs = []any{unique} return this } @@ -635,7 +635,7 @@ func (this simpleExampleTable) Get(ctx context.Context, name string) (*SimpleExa return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &simpleExample, nil } @@ -655,7 +655,7 @@ func (this simpleExampleTable) GetByUnique(ctx context.Context, unique string) ( return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &simpleExample, nil } @@ -685,7 +685,7 @@ var _ SimpleExampleTable = simpleExampleTable{} func NewSimpleExampleTable(db ormtable.Schema) (SimpleExampleTable, error) { table := db.GetTable(&SimpleExample{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&SimpleExample{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&SimpleExample{}).ProtoReflect().Descriptor().FullName())) } return simpleExampleTable{table}, nil } @@ -720,7 +720,7 @@ func (i ExampleAutoIncFieldNameIterator) Value() (*ExampleAutoIncFieldName, erro type ExampleAutoIncFieldNameIndexKey interface { id() uint32 - values() []interface{} + values() []any exampleAutoIncFieldNameIndexKey() } @@ -728,15 +728,15 @@ type ExampleAutoIncFieldNameIndexKey interface { type ExampleAutoIncFieldNamePrimaryKey = ExampleAutoIncFieldNameFooIndexKey type ExampleAutoIncFieldNameFooIndexKey struct { - vs []interface{} + vs []any } func (x ExampleAutoIncFieldNameFooIndexKey) id() uint32 { return 0 } -func (x ExampleAutoIncFieldNameFooIndexKey) values() []interface{} { return x.vs } +func (x ExampleAutoIncFieldNameFooIndexKey) values() []any { return x.vs } func (x ExampleAutoIncFieldNameFooIndexKey) exampleAutoIncFieldNameIndexKey() {} func (this ExampleAutoIncFieldNameFooIndexKey) WithFoo(foo uint64) ExampleAutoIncFieldNameFooIndexKey { - this.vs = []interface{}{foo} + this.vs = []any{foo} return this } @@ -779,7 +779,7 @@ func (this exampleAutoIncFieldNameTable) Get(ctx context.Context, foo uint64) (* return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleAutoIncFieldName, nil } @@ -809,7 +809,7 @@ var _ ExampleAutoIncFieldNameTable = exampleAutoIncFieldNameTable{} func NewExampleAutoIncFieldNameTable(db ormtable.Schema) (ExampleAutoIncFieldNameTable, error) { table := db.GetTable(&ExampleAutoIncFieldName{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleAutoIncFieldName{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleAutoIncFieldName{}).ProtoReflect().Descriptor().FullName())) } return exampleAutoIncFieldNameTable{table.(ormtable.AutoIncrementTable)}, nil } diff --git a/orm/internal/testutil/testutil.go b/orm/internal/testutil/testutil.go index ce27964812f9..f6daf5a0307b 100644 --- a/orm/internal/testutil/testutil.go +++ b/orm/internal/testutil/testutil.go @@ -5,14 +5,13 @@ import ( "math" "strings" + "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" + "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" + "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" ) // TestFieldSpec defines a test field against the testpb.ExampleTable message. @@ -33,7 +32,7 @@ var TestFieldSpecs = []TestFieldSpec{ { "str", rapid.String().Filter(func(x string) bool { - // filter out null terminators + // Filter out null terminators. return strings.IndexByte(x, 0) < 0 }).AsAny(), }, @@ -81,7 +80,7 @@ var TestFieldSpecs = []TestFieldSpec{ "ts", rapid.Custom(func(t *rapid.T) protoreflect.Message { isNil := rapid.Float32().Draw(t, "isNil") - if isNil >= 0.95 { // draw a nil 5% of the time + if isNil >= 0.95 { // Draw a nil 5% of the time. return nil } seconds := rapid.Int64Range(-9999999999, 9999999999).Draw(t, "seconds") diff --git a/orm/model/ormdb/file.go b/orm/model/ormdb/file.go index 37c01bcb1f29..8820b83b5295 100644 --- a/orm/model/ormdb/file.go +++ b/orm/model/ormdb/file.go @@ -30,7 +30,7 @@ type fileDescriptorDBOptions struct { type fileDescriptorDB struct { id uint32 prefix []byte - tablesById map[uint32]ormtable.Table + tablesByID map[uint32]ormtable.Table tablesByName map[protoreflect.FullName]ormtable.Table fileDescriptor protoreflect.FileDescriptor } @@ -41,7 +41,7 @@ func newFileDescriptorDB(fileDescriptor protoreflect.FileDescriptor, options fil schema := &fileDescriptorDB{ id: options.ID, prefix: prefix, - tablesById: map[uint32]ormtable.Table{}, + tablesByID: map[uint32]ormtable.Table{}, tablesByName: map[protoreflect.FullName]ormtable.Table{}, fileDescriptor: fileDescriptor, } @@ -68,7 +68,7 @@ func newFileDescriptorDB(fileDescriptor protoreflect.FileDescriptor, options fil JSONValidator: options.JSONValidator, BackendResolver: options.BackendResolver, }) - if errors.Is(err, ormerrors.NoTableDescriptor) { + if errors.Is(err, ormerrors.ErrNoTableDescriptor) { continue } if err != nil { @@ -76,13 +76,13 @@ func newFileDescriptorDB(fileDescriptor protoreflect.FileDescriptor, options fil } id := table.ID() - if _, ok := schema.tablesById[id]; ok { - return nil, ormerrors.InvalidTableId.Wrapf("duplicate ID %d for %s", id, tableName) + if _, ok := schema.tablesByID[id]; ok { + return nil, ormerrors.ErrInvalidTableID.Wrapf("duplicate ID %d for %s", id, tableName) } - schema.tablesById[id] = table + schema.tablesByID[id] = table if _, ok := schema.tablesByName[tableName]; ok { - return nil, ormerrors.InvalidTableDefinition.Wrapf("duplicate table %s", tableName) + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("duplicate table %s", tableName) } schema.tablesByName[tableName] = table } @@ -103,12 +103,12 @@ func (f fileDescriptorDB) DecodeEntry(k, v []byte) (ormkv.Entry, error) { } if id > math.MaxUint32 { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - table, ok := f.tablesById[uint32(id)] + table, ok := f.tablesByID[uint32(id)] if !ok { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find table with id %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("can't find table with id %d", id) } return table.DecodeEntry(k, v) @@ -117,7 +117,7 @@ func (f fileDescriptorDB) DecodeEntry(k, v []byte) (ormkv.Entry, error) { func (f fileDescriptorDB) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { table, ok := f.tablesByName[entry.GetTableName()] if !ok { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("can't find table %s", entry.GetTableName()) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("can't find table %s", entry.GetTableName()) } return table.EncodeEntry(entry) diff --git a/orm/model/ormdb/genesis.go b/orm/model/ormdb/genesis.go index 1f983704e164..e7479f2e30a0 100644 --- a/orm/model/ormdb/genesis.go +++ b/orm/model/ormdb/genesis.go @@ -18,9 +18,9 @@ type appModuleGenesisWrapper struct { moduleDB } -func (m appModuleGenesisWrapper) IsOnePerModuleType() {} +func (appModuleGenesisWrapper) IsOnePerModuleType() {} -func (m appModuleGenesisWrapper) IsAppModule() {} +func (appModuleGenesisWrapper) IsAppModule() {} func (m appModuleGenesisWrapper) DefaultGenesis(target appmodule.GenesisTarget) error { tableNames := maps.Keys(m.tablesByName) @@ -83,7 +83,7 @@ func (m appModuleGenesisWrapper) ValidateGenesis(source appmodule.GenesisSource) for name, err := range errMap { allErrors += fmt.Sprintf("Error in JSON for table %s: %v\n", name, err) } - return ormerrors.JSONValidationError.Wrap(allErrors) + return ormerrors.ErrJSONValidationError.Wrap(allErrors) } return nil diff --git a/orm/model/ormdb/module.go b/orm/model/ormdb/module.go index ff0c0ccf1afe..c54f579501a8 100644 --- a/orm/model/ormdb/module.go +++ b/orm/model/ormdb/module.go @@ -47,7 +47,7 @@ type ModuleDB interface { type moduleDB struct { prefix []byte - filesById map[uint32]*fileDescriptorDB + filesByID map[uint32]*fileDescriptorDB tablesByName map[protoreflect.FullName]ormtable.Table } @@ -83,7 +83,7 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt prefix := schema.Prefix db := &moduleDB{ prefix: prefix, - filesById: map[uint32]*fileDescriptorDB{}, + filesByID: map[uint32]*fileDescriptorDB{}, tablesByName: map[protoreflect.FullName]ormtable.Table{}, } @@ -146,7 +146,7 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt } if id == 0 { - return nil, ormerrors.InvalidFileDescriptorID.Wrapf("for %s", fileDescriptor.Path()) + return nil, ormerrors.ErrInvalidFileDescriptorID.Wrapf("for %s", fileDescriptor.Path()) } opts := fileDescriptorDBOptions{ @@ -162,10 +162,10 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt return nil, err } - db.filesById[id] = fdSchema + db.filesByID[id] = fdSchema for name, table := range fdSchema.tablesByName { if _, ok := db.tablesByName[name]; ok { - return nil, ormerrors.UnexpectedError.Wrapf("duplicate table %s", name) + return nil, ormerrors.ErrUnexpectedError.Wrapf("duplicate table %s", name) } db.tablesByName[name] = table @@ -188,12 +188,12 @@ func (m moduleDB) DecodeEntry(k, v []byte) (ormkv.Entry, error) { } if id > math.MaxUint32 { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - fileSchema, ok := m.filesById[uint32(id)] + fileSchema, ok := m.filesByID[uint32(id)] if !ok { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find FileDescriptor schema with id %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("can't find FileDescriptor schema with id %d", id) } return fileSchema.DecodeEntry(k, v) @@ -203,7 +203,7 @@ func (m moduleDB) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { tableName := entry.GetTableName() table, ok := m.tablesByName[tableName] if !ok { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("can't find table %s", tableName) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("can't find table %s", tableName) } return table.EncodeEntry(entry) diff --git a/orm/model/ormdb/module_test.go b/orm/model/ormdb/module_test.go index 71ca0a167f49..8825f4fd5a66 100644 --- a/orm/model/ormdb/module_test.go +++ b/orm/model/ormdb/module_test.go @@ -89,7 +89,7 @@ func (k keeper) Mint(ctx context.Context, acct, denom string, amount uint64) err if supply == nil { supply = &testpb.Supply{Denom: denom, Amount: amount} } else { - supply.Amount = supply.Amount + amount + supply.Amount += amount } err = k.store.SupplyTable().Save(ctx, supply) @@ -111,7 +111,7 @@ func (k keeper) Burn(ctx context.Context, acct, denom string, amount uint64) err return fmt.Errorf("insufficient supply") } - supply.Amount = supply.Amount - amount + supply.Amount -= amount if supply.Amount == 0 { err = supplyStore.Delete(ctx, supply) @@ -162,7 +162,7 @@ func (k keeper) addBalance(ctx context.Context, acct, denom string, amount uint6 Amount: amount, } } else { - balance.Amount = balance.Amount + amount + balance.Amount += amount } return k.store.BalanceTable().Save(ctx, balance) @@ -179,13 +179,12 @@ func (k keeper) safeSubBalance(ctx context.Context, acct, denom string, amount u return fmt.Errorf("insufficient funds") } - balance.Amount = balance.Amount - amount + balance.Amount -= amount if balance.Amount == 0 { return balanceStore.Delete(ctx, balance) - } else { - return balanceStore.Save(ctx, balance) } + return balanceStore.Save(ctx, balance) } func TestModuleDB(t *testing.T) { @@ -198,7 +197,7 @@ func TestModuleDB(t *testing.T) { backend, &testkv.EntryCodecDebugger{ EntryCodec: db, - Print: func(s string) { debugBuf.WriteString(s + "\n") }, + Print: func(s string) { debugBuf.WriteString(s + "\n") }, //nolint:errcheck,revive // ignore error }, )) @@ -206,7 +205,7 @@ func TestModuleDB(t *testing.T) { k, err := NewKeeper(db) assert.NilError(t, err) - runSimpleBankTests(t, k, ctx) + runSimpleBankTests(ctx, t, k) // check debug output golden.Assert(t, debugBuf.String(), "bank_scenario.golden") @@ -227,13 +226,13 @@ func TestModuleDB(t *testing.T) { // check JSON target := genesis.RawJSONTarget{} assert.NilError(t, db.GenesisHandler().DefaultGenesis(target.Target())) - rawJson, err := target.JSON() + rawJSON, err := target.JSON() assert.NilError(t, err) - golden.Assert(t, string(rawJson), "default_json.golden") + golden.Assert(t, string(rawJSON), "default_json.golden") target = genesis.RawJSONTarget{} assert.NilError(t, db.GenesisHandler().ExportGenesis(ctx, target.Target())) - rawJson, err = target.JSON() + rawJSON, err = target.JSON() assert.NilError(t, err) goodJSON := `{ @@ -251,18 +250,19 @@ func TestModuleDB(t *testing.T) { ` source, err = genesis.SourceFromRawJSON(json.RawMessage(badJSON)) assert.NilError(t, err) - assert.ErrorIs(t, db.GenesisHandler().ValidateGenesis(source), ormerrors.JSONValidationError) + assert.ErrorIs(t, db.GenesisHandler().ValidateGenesis(source), ormerrors.ErrJSONValidationError) backend2 := ormtest.NewMemoryBackend() ctx2 := ormtable.WrapContextDefault(backend2) - source, err = genesis.SourceFromRawJSON(rawJson) + source, err = genesis.SourceFromRawJSON(rawJSON) assert.NilError(t, err) assert.NilError(t, db.GenesisHandler().ValidateGenesis(source)) assert.NilError(t, db.GenesisHandler().InitGenesis(ctx2, source)) testkv.AssertBackendsEqual(t, backend, backend2) } -func runSimpleBankTests(t *testing.T, k Keeper, ctx context.Context) { +func runSimpleBankTests(ctx context.Context, t *testing.T, k Keeper) { + t.Helper() // mint coins denom := "foo" acct1 := "bob" @@ -415,5 +415,5 @@ func TestAppConfigModule(t *testing.T) { ), &k) assert.NilError(t, err) - runSimpleBankTests(t, k, context.Background()) + runSimpleBankTests(context.Background(), t, k) } diff --git a/orm/model/ormtable/auto_increment.go b/orm/model/ormtable/auto_increment.go index 982ce7987248..0e79c8e6e05e 100644 --- a/orm/model/ormtable/auto_increment.go +++ b/orm/model/ormtable/auto_increment.go @@ -28,7 +28,7 @@ func (t autoIncrementTable) InsertReturningPKey(ctx context.Context, message pro return 0, err } - return t.save(ctx, backend, message, saveModeInsert) + return t.saveAutoIncrement(ctx, backend, message, saveModeInsert) } func (t autoIncrementTable) Save(ctx context.Context, message proto.Message) error { @@ -37,7 +37,7 @@ func (t autoIncrementTable) Save(ctx context.Context, message proto.Message) err return err } - _, err = t.save(ctx, backend, message, saveModeDefault) + _, err = t.saveAutoIncrement(ctx, backend, message, saveModeDefault) return err } @@ -47,7 +47,7 @@ func (t autoIncrementTable) Insert(ctx context.Context, message proto.Message) e return err } - _, err = t.save(ctx, backend, message, saveModeInsert) + _, err = t.saveAutoIncrement(ctx, backend, message, saveModeInsert) return err } @@ -57,7 +57,7 @@ func (t autoIncrementTable) Update(ctx context.Context, message proto.Message) e return err } - _, err = t.save(ctx, backend, message, saveModeUpdate) + _, err = t.saveAutoIncrement(ctx, backend, message, saveModeUpdate) return err } @@ -70,7 +70,7 @@ func (t autoIncrementTable) LastInsertedSequence(ctx context.Context) (uint64, e return t.curSeqValue(backend.IndexStoreReader()) } -func (t *autoIncrementTable) save(ctx context.Context, backend Backend, message proto.Message, mode saveMode) (newPK uint64, err error) { +func (t *autoIncrementTable) saveAutoIncrement(ctx context.Context, backend Backend, message proto.Message, mode saveMode) (newPK uint64, err error) { messageRef := message.ProtoReflect() val := messageRef.Get(t.autoIncField).Uint() writer := newBatchIndexCommitmentWriter(backend) @@ -78,7 +78,7 @@ func (t *autoIncrementTable) save(ctx context.Context, backend Backend, message if val == 0 { if mode == saveModeUpdate { - return 0, ormerrors.PrimaryKeyInvalidOnUpdate + return 0, ormerrors.ErrPrimaryKeyInvalidOnUpdate } mode = saveModeInsert @@ -90,7 +90,7 @@ func (t *autoIncrementTable) save(ctx context.Context, backend Backend, message messageRef.Set(t.autoIncField, protoreflect.ValueOfUint64(newPK)) } else { if mode == saveModeInsert { - return 0, ormerrors.AutoIncrementKeyAlreadySet + return 0, ormerrors.ErrAutoIncrementKeyAlreadySet } mode = saveModeUpdate @@ -99,8 +99,8 @@ func (t *autoIncrementTable) save(ctx context.Context, backend Backend, message return newPK, t.tableImpl.doSave(ctx, writer, message, mode) } -func (t *autoIncrementTable) curSeqValue(kv kv.ReadonlyStore) (uint64, error) { - bz, err := kv.Get(t.seqCodec.Prefix()) +func (t *autoIncrementTable) curSeqValue(kvro kv.ReadonlyStore) (uint64, error) { + bz, err := kvro.Get(t.seqCodec.Prefix()) if err != nil { return 0, err } @@ -108,18 +108,18 @@ func (t *autoIncrementTable) curSeqValue(kv kv.ReadonlyStore) (uint64, error) { return t.seqCodec.DecodeValue(bz) } -func (t *autoIncrementTable) nextSeqValue(kv kv.Store) (uint64, error) { - seq, err := t.curSeqValue(kv) +func (t *autoIncrementTable) nextSeqValue(kvstore kv.Store) (uint64, error) { + seq, err := t.curSeqValue(kvstore) if err != nil { return 0, err } seq++ - return seq, t.setSeqValue(kv, seq) + return seq, t.setSeqValue(kvstore, seq) } -func (t *autoIncrementTable) setSeqValue(kv kv.Store, seq uint64) error { - return kv.Set(t.seqCodec.Prefix(), t.seqCodec.EncodeValue(seq)) +func (t *autoIncrementTable) setSeqValue(kvstore kv.Store, seq uint64) error { + return kvstore.Set(t.seqCodec.Prefix(), t.seqCodec.EncodeValue(seq)) } func (t autoIncrementTable) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { @@ -130,7 +130,7 @@ func (t autoIncrementTable) EncodeEntry(entry ormkv.Entry) (k, v []byte, err err } func (t autoIncrementTable) ValidateJSON(reader io.Reader) error { - return t.decodeAutoIncJson(nil, reader, func(message proto.Message, maxSeq uint64) error { + return t.decodeAutoIncJSON(nil, reader, func(message proto.Message, maxSeq uint64) error { messageRef := message.ProtoReflect() pkey := messageRef.Get(t.autoIncField).Uint() if pkey > maxSeq { @@ -140,9 +140,8 @@ func (t autoIncrementTable) ValidateJSON(reader io.Reader) error { if t.customJSONValidator != nil { return t.customJSONValidator(message) - } else { - return DefaultJSONValidator(message) } + return DefaultJSONValidator(message) }) } @@ -152,37 +151,36 @@ func (t autoIncrementTable) ImportJSON(ctx context.Context, reader io.Reader) er return err } - return t.decodeAutoIncJson(backend, reader, func(message proto.Message, maxSeq uint64) error { + return t.decodeAutoIncJSON(backend, reader, func(message proto.Message, maxSeq uint64) error { messageRef := message.ProtoReflect() pkey := messageRef.Get(t.autoIncField).Uint() if pkey == 0 { // we don't have a primary key in the JSON, so we call Save to insert and // generate one - _, err = t.save(ctx, backend, message, saveModeInsert) + _, err = t.saveAutoIncrement(ctx, backend, message, saveModeInsert) return err - } else { - if pkey > maxSeq { - return fmt.Errorf("invalid auto increment primary key %d, expected a value <= %d, the highest "+ - "sequence number", pkey, maxSeq) - } - // we do have a primary key and calling Save will fail because it expects - // either no primary key or SAVE_MODE_UPDATE. So instead we drop one level - // down and insert using tableImpl which doesn't know about - // auto-incrementing primary keys. - return t.tableImpl.save(ctx, backend, message, saveModeInsert) } + if pkey > maxSeq { + return fmt.Errorf("invalid auto increment primary key %d, expected a value <= %d, the highest "+ + "sequence number", pkey, maxSeq) + } + // we do have a primary key and calling Save will fail because it expects + // either no primary key or SAVE_MODE_UPDATE. So instead we drop one level + // down and insert using tableImpl which doesn't know about + // auto-incrementing primary keys. + return t.tableImpl.write(ctx, backend, message, saveModeInsert) }) } -func (t autoIncrementTable) decodeAutoIncJson(backend Backend, reader io.Reader, onMsg func(message proto.Message, maxID uint64) error) error { - decoder, err := t.startDecodeJson(reader) +func (t autoIncrementTable) decodeAutoIncJSON(backend Backend, reader io.Reader, onMsg func(message proto.Message, maxID uint64) error) error { + decoder, err := t.startDecodeJSON(reader) if err != nil { return err } var seq uint64 - return t.doDecodeJson(decoder, + return t.doDecodeJSON(decoder, func(message json.RawMessage) bool { err = json.Unmarshal(message, &seq) if err == nil { diff --git a/orm/model/ormtable/auto_increment_test.go b/orm/model/ormtable/auto_increment_test.go index 5ba1fa4ed05a..175c61f5ed45 100644 --- a/orm/model/ormtable/auto_increment_test.go +++ b/orm/model/ormtable/auto_increment_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/orm/model/ormtable" ) +// TestAutoIncrementScenario runs a scenario with a table that has an auto-incrementing primary key. func TestAutoIncrementScenario(t *testing.T) { table, err := ormtable.Build(ormtable.Options{ MessageType: (&testpb.ExampleAutoIncrementTable{}).ProtoReflect().Type(), @@ -25,7 +26,7 @@ func TestAutoIncrementScenario(t *testing.T) { assert.Assert(t, ok) // first run tests with a split index-commitment store - runAutoIncrementScenario(t, autoTable, ormtable.WrapContextDefault(testkv.NewSplitMemBackend())) + runAutoIncrementScenario(ormtable.WrapContextDefault(testkv.NewSplitMemBackend()), t, autoTable) // now run with shared store and debugging debugBuf := &strings.Builder{} @@ -33,16 +34,18 @@ func TestAutoIncrementScenario(t *testing.T) { testkv.NewSharedMemBackend(), &testkv.EntryCodecDebugger{ EntryCodec: table, - Print: func(s string) { debugBuf.WriteString(s + "\n") }, + Print: func(s string) { debugBuf.WriteString(s + "\n") }, //nolint:errcheck,revive // ignore errors }, ) - runAutoIncrementScenario(t, autoTable, ormtable.WrapContextDefault(store)) + runAutoIncrementScenario(ormtable.WrapContextDefault(store), t, autoTable) golden.Assert(t, debugBuf.String(), "test_auto_inc.golden") checkEncodeDecodeEntries(t, table, store.IndexStoreReader()) } -func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, ctx context.Context) { +// runAutoIncrementScenario runs a simple scenario with an auto-increment table. +func runAutoIncrementScenario(ctx context.Context, t *testing.T, table ormtable.AutoIncrementTable) { + t.Helper() store, err := testpb.NewExampleAutoIncrementTableTable(table) assert.NilError(t, err) @@ -57,10 +60,10 @@ func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, c assert.Equal(t, curSeq, uint64(1)) ex2 := &testpb.ExampleAutoIncrementTable{X: "bar", Y: 10} - newId, err := table.InsertReturningPKey(ctx, ex2) + newID, err := table.InsertReturningPKey(ctx, ex2) assert.NilError(t, err) assert.Equal(t, uint64(2), ex2.Id) - assert.Equal(t, newId, ex2.Id) + assert.Equal(t, newID, ex2.Id) curSeq, err = table.LastInsertedSequence(ctx) assert.NilError(t, err) assert.Equal(t, curSeq, uint64(2)) @@ -70,7 +73,7 @@ func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, c assert.NilError(t, table.ValidateJSON(bytes.NewReader(buf.Bytes()))) store2 := ormtable.WrapContextDefault(testkv.NewSplitMemBackend()) assert.NilError(t, table.ImportJSON(store2, bytes.NewReader(buf.Bytes()))) - assertTablesEqual(t, table, ctx, store2) + assertTablesEqual(ctx, store2, t, table) // test edge case where we have deleted all entities but we're still exporting the sequence number assert.NilError(t, table.Delete(ctx, ex1)) @@ -89,6 +92,7 @@ func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, c assert.Equal(t, curSeq, uint64(3)) } +// TestBadJSON tests that we get an error when importing bad JSON. func TestBadJSON(t *testing.T) { table, err := ormtable.Build(ormtable.Options{ MessageType: (&testpb.ExampleAutoIncrementTable{}).ProtoReflect().Type(), diff --git a/orm/model/ormtable/bench_test.go b/orm/model/ormtable/bench_test.go index 48d2621e84d6..d34ca44b5cae 100644 --- a/orm/model/ormtable/bench_test.go +++ b/orm/model/ormtable/bench_test.go @@ -18,20 +18,22 @@ import ( "github.com/cosmos/cosmos-sdk/orm/types/kv" ) -func initBalanceTable(t testing.TB) testpb.BalanceTable { +func initBalanceTable(tb testing.TB) testpb.BalanceTable { + tb.Helper() table, err := ormtable.Build(ormtable.Options{ MessageType: (&testpb.Balance{}).ProtoReflect().Type(), }) - assert.NilError(t, err) + assert.NilError(tb, err) balanceTable, err := testpb.NewBalanceTable(table) - assert.NilError(t, err) + assert.NilError(tb, err) return balanceTable } func BenchmarkMemory(b *testing.B) { bench(b, func(tb testing.TB) ormtable.Backend { + tb.Helper() return ormtest.NewMemoryBackend() }) } @@ -41,36 +43,38 @@ func BenchmarkLevelDB(b *testing.B) { } func bench(b *testing.B, newBackend func(testing.TB) ormtable.Backend) { + b.Helper() b.Run("insert", func(b *testing.B) { b.StopTimer() ctx := ormtable.WrapContextDefault(newBackend(b)) b.StartTimer() - benchInsert(b, ctx) + benchInsert(ctx, b) }) b.Run("update", func(b *testing.B) { b.StopTimer() ctx := ormtable.WrapContextDefault(newBackend(b)) - benchInsert(b, ctx) + benchInsert(ctx, b) b.StartTimer() - benchUpdate(b, ctx) + benchUpdate(ctx, b) }) b.Run("get", func(b *testing.B) { b.StopTimer() ctx := ormtable.WrapContextDefault(newBackend(b)) - benchInsert(b, ctx) + benchInsert(ctx, b) b.StartTimer() - benchGet(b, ctx) + benchGet(ctx, b) }) b.Run("delete", func(b *testing.B) { b.StopTimer() ctx := ormtable.WrapContextDefault(newBackend(b)) - benchInsert(b, ctx) + benchInsert(ctx, b) b.StartTimer() - benchDelete(b, ctx) + benchDelete(ctx, b) }) } -func benchInsert(b *testing.B, ctx context.Context) { +func benchInsert(ctx context.Context, b *testing.B) { + b.Helper() balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Insert(ctx, &testpb.Balance{ @@ -81,7 +85,8 @@ func benchInsert(b *testing.B, ctx context.Context) { } } -func benchUpdate(b *testing.B, ctx context.Context) { +func benchUpdate(ctx context.Context, b *testing.B) { + b.Helper() balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Update(ctx, &testpb.Balance{ @@ -92,7 +97,8 @@ func benchUpdate(b *testing.B, ctx context.Context) { } } -func benchGet(b *testing.B, ctx context.Context) { +func benchGet(ctx context.Context, b *testing.B) { + b.Helper() balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { balance, err := balanceTable.Get(ctx, fmt.Sprintf("acct%d", i), "bar") @@ -101,7 +107,8 @@ func benchGet(b *testing.B, ctx context.Context) { } } -func benchDelete(b *testing.B, ctx context.Context) { +func benchDelete(ctx context.Context, b *testing.B) { + b.Helper() balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Delete(ctx, &testpb.Balance{ @@ -244,6 +251,7 @@ func BenchmarkManualInsertLevelDB(b *testing.B) { } func benchManual(b *testing.B, newStore func() (dbm.DB, error)) { + b.Helper() b.Run("insert", func(b *testing.B) { b.StopTimer() store, err := newStore() @@ -278,6 +286,7 @@ func benchManual(b *testing.B, newStore func() (dbm.DB, error)) { } func benchManualInsert(b *testing.B, store kv.Store) { + b.Helper() for i := 0; i < b.N; i++ { assert.NilError(b, insertBalance(store, &testpb.Balance{ Address: fmt.Sprintf("acct%d", i), @@ -288,6 +297,7 @@ func benchManualInsert(b *testing.B, store kv.Store) { } func benchManualUpdate(b *testing.B, store kv.Store) { + b.Helper() for i := 0; i < b.N; i++ { assert.NilError(b, updateBalance(store, &testpb.Balance{ Address: fmt.Sprintf("acct%d", i), @@ -298,6 +308,7 @@ func benchManualUpdate(b *testing.B, store kv.Store) { } func benchManualDelete(b *testing.B, store kv.Store) { + b.Helper() for i := 0; i < b.N; i++ { assert.NilError(b, deleteBalance(store, &testpb.Balance{ Address: fmt.Sprintf("acct%d", i), @@ -307,6 +318,7 @@ func benchManualDelete(b *testing.B, store kv.Store) { } func benchManualGet(b *testing.B, store kv.Store) { + b.Helper() for i := 0; i < b.N; i++ { balance, err := getBalance(store, fmt.Sprintf("acct%d", i), "bar") assert.NilError(b, err) diff --git a/orm/model/ormtable/build.go b/orm/model/ormtable/build.go index 3e9137665d0a..590fb8d11b1d 100644 --- a/orm/model/ormtable/build.go +++ b/orm/model/ormtable/build.go @@ -16,9 +16,9 @@ import ( ) const ( - primaryKeyId uint32 = 0 - indexIdLimit uint32 = 32768 - seqId = indexIdLimit + primaryKeyID uint32 = 0 + indexIDLimit uint32 = 32768 + seqID = indexIDLimit ) // Options are options for building a Table. @@ -84,8 +84,8 @@ func Build(options Options) (Table, error) { indexes: []Index{}, indexesByFields: map[fieldnames.FieldNames]concreteIndex{}, uniqueIndexesByFields: map[fieldnames.FieldNames]UniqueIndex{}, - entryCodecsById: map[uint32]ormkv.EntryCodec{}, - indexesById: map[uint32]Index{}, + entryCodecsByID: map[uint32]ormkv.EntryCodec{}, + indexesByID: map[uint32]Index{}, typeResolver: options.TypeResolver, customJSONValidator: options.JSONValidator, } @@ -105,11 +105,11 @@ func Build(options Options) (Table, error) { switch { case tableDesc != nil: if singletonDesc != nil { - return nil, ormerrors.InvalidTableDefinition.Wrapf("message %s cannot be declared as both a table and a singleton", messageDescriptor.FullName()) + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("message %s cannot be declared as both a table and a singleton", messageDescriptor.FullName()) } case singletonDesc != nil: if singletonDesc.Id == 0 { - return nil, ormerrors.InvalidTableId.Wrapf("%s", messageDescriptor.FullName()) + return nil, ormerrors.ErrInvalidTableID.Wrapf("%s", messageDescriptor.FullName()) } prefix := encodeutil.AppendVarUInt32(options.Prefix, singletonDesc.Id) @@ -125,35 +125,35 @@ func Build(options Options) (Table, error) { pkIndex.PrimaryKeyCodec = pkCodec table.tablePrefix = prefix - table.tableId = singletonDesc.Id + table.tableID = singletonDesc.Id return &singleton{table}, nil default: - return nil, ormerrors.NoTableDescriptor.Wrapf("missing table descriptor for %s", messageDescriptor.FullName()) + return nil, ormerrors.ErrNoTableDescriptor.Wrapf("missing table descriptor for %s", messageDescriptor.FullName()) } - tableId := tableDesc.Id - if tableId == 0 { - return nil, ormerrors.InvalidTableId.Wrapf("table %s", messageDescriptor.FullName()) + tableID := tableDesc.Id + if tableID == 0 { + return nil, ormerrors.ErrInvalidTableID.Wrapf("table %s", messageDescriptor.FullName()) } prefix := options.Prefix - prefix = encodeutil.AppendVarUInt32(prefix, tableId) + prefix = encodeutil.AppendVarUInt32(prefix, tableID) table.tablePrefix = prefix - table.tableId = tableId + table.tableID = tableID if tableDesc.PrimaryKey == nil { - return nil, ormerrors.MissingPrimaryKey.Wrap(string(messageDescriptor.FullName())) + return nil, ormerrors.ErrMissingPrimaryKey.Wrap(string(messageDescriptor.FullName())) } pkFields := fieldnames.CommaSeparatedFieldNames(tableDesc.PrimaryKey.Fields) table.primaryKeyIndex.fields = pkFields pkFieldNames := pkFields.Names() if len(pkFieldNames) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("empty primary key fields for %s", messageDescriptor.FullName()) + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("empty primary key fields for %s", messageDescriptor.FullName()) } - pkPrefix := encodeutil.AppendVarUInt32(prefix, primaryKeyId) + pkPrefix := encodeutil.AppendVarUInt32(prefix, primaryKeyID) pkCodec, err := ormkv.NewPrimaryKeyCodec( pkPrefix, options.MessageType, @@ -167,18 +167,18 @@ func Build(options Options) (Table, error) { pkIndex.PrimaryKeyCodec = pkCodec table.indexesByFields[pkFields] = pkIndex table.uniqueIndexesByFields[pkFields] = pkIndex - table.entryCodecsById[primaryKeyId] = pkIndex - table.indexesById[primaryKeyId] = pkIndex + table.entryCodecsByID[primaryKeyID] = pkIndex + table.indexesByID[primaryKeyID] = pkIndex table.indexes = append(table.indexes, pkIndex) for _, idxDesc := range tableDesc.Index { id := idxDesc.Id - if id == 0 || id >= indexIdLimit { - return nil, ormerrors.InvalidIndexId.Wrapf("index on table %s with fields %s, invalid id %d", messageDescriptor.FullName(), idxDesc.Fields, id) + if id == 0 || id >= indexIDLimit { + return nil, ormerrors.ErrInvalidIndexID.Wrapf("index on table %s with fields %s, invalid id %d", messageDescriptor.FullName(), idxDesc.Fields, id) } - if _, ok := table.entryCodecsById[id]; ok { - return nil, ormerrors.DuplicateIndexId.Wrapf("id %d on table %s", id, messageDescriptor.FullName()) + if _, ok := table.entryCodecsByID[id]; ok { + return nil, ormerrors.ErrDuplicateIndexID.Wrapf("id %d on table %s", id, messageDescriptor.FullName()) } idxFields := fieldnames.CommaSeparatedFieldNames(idxDesc.Fields) @@ -264,8 +264,8 @@ func Build(options Options) (Table, error) { table.indexesByFields[name] = index } - table.entryCodecsById[id] = index - table.indexesById[id] = index + table.entryCodecsByID[id] = index + table.indexesByID[id] = index table.indexes = append(table.indexes, index) table.indexers = append(table.indexers, index.(indexer)) } @@ -273,12 +273,12 @@ func Build(options Options) (Table, error) { if tableDesc.PrimaryKey.AutoIncrement { autoIncField := pkCodec.GetFieldDescriptors()[0] if len(pkFieldNames) != 1 && autoIncField.Kind() != protoreflect.Uint64Kind { - return nil, ormerrors.InvalidAutoIncrementKey.Wrapf("field %s", autoIncField.FullName()) + return nil, ormerrors.ErrInvalidAutoIncrementKey.Wrapf("field %s", autoIncField.FullName()) } - seqPrefix := encodeutil.AppendVarUInt32(prefix, seqId) + seqPrefix := encodeutil.AppendVarUInt32(prefix, seqID) seqCodec := ormkv.NewSeqCodec(options.MessageType, seqPrefix) - table.entryCodecsById[seqId] = seqCodec + table.entryCodecsByID[seqID] = seqCodec return &autoIncrementTable{ tableImpl: table, autoIncField: autoIncField, diff --git a/orm/model/ormtable/index.go b/orm/model/ormtable/index.go index 903c19348505..1276833f9c09 100644 --- a/orm/model/ormtable/index.go +++ b/orm/model/ormtable/index.go @@ -20,7 +20,7 @@ type Index interface { // Prefix key values must correspond in type to the index's fields and the // number of values provided cannot exceed the number of fields in the index, // although fewer values can be provided. - List(ctx context.Context, prefixKey []interface{}, options ...ormlist.Option) (Iterator, error) + List(ctx context.Context, prefixKey []any, options ...ormlist.Option) (Iterator, error) // ListRange does range iteration over the index with the provided from and to // values and options. @@ -36,13 +36,13 @@ type Index interface { // value for bytes. // // Range iteration is inclusive at both ends. - ListRange(ctx context.Context, from, to []interface{}, options ...ormlist.Option) (Iterator, error) + ListRange(ctx context.Context, from, to []any, options ...ormlist.Option) (Iterator, error) // DeleteBy deletes any entries which match the provided prefix key. - DeleteBy(context context.Context, prefixKey ...interface{}) error + DeleteBy(context context.Context, prefixKey ...any) error // DeleteRange deletes any entries between the provided range keys. - DeleteRange(context context.Context, from, to []interface{}) error + DeleteRange(context context.Context, from, to []any) error // MessageType returns the protobuf message type of the index. MessageType() protoreflect.MessageType @@ -66,10 +66,10 @@ type UniqueIndex interface { Index // Has returns true if the key values are present in the store for this index. - Has(context context.Context, keyValues ...interface{}) (found bool, err error) + Has(context context.Context, keyValues ...any) (found bool, err error) // Get retrieves the message if one exists for the provided key values. - Get(context context.Context, message proto.Message, keyValues ...interface{}) (found bool, err error) + Get(context context.Context, message proto.Message, keyValues ...any) (found bool, err error) } type indexer interface { diff --git a/orm/model/ormtable/index_impl.go b/orm/model/ormtable/index_impl.go index 7289efc40af4..a51318ae12ca 100644 --- a/orm/model/ormtable/index_impl.go +++ b/orm/model/ormtable/index_impl.go @@ -25,7 +25,7 @@ type indexKeyIndex struct { getReadBackend func(context.Context) (ReadBackend, error) } -func (i indexKeyIndex) DeleteBy(ctx context.Context, keyValues ...interface{}) error { +func (i indexKeyIndex) DeleteBy(ctx context.Context, keyValues ...any) error { it, err := i.List(ctx, keyValues) if err != nil { return err @@ -34,7 +34,7 @@ func (i indexKeyIndex) DeleteBy(ctx context.Context, keyValues ...interface{}) e return i.primaryKey.deleteByIterator(ctx, it) } -func (i indexKeyIndex) DeleteRange(ctx context.Context, from, to []interface{}) error { +func (i indexKeyIndex) DeleteRange(ctx context.Context, from, to []any) error { it, err := i.ListRange(ctx, from, to) if err != nil { return err @@ -43,7 +43,7 @@ func (i indexKeyIndex) DeleteRange(ctx context.Context, from, to []interface{}) return i.primaryKey.deleteByIterator(ctx, it) } -func (i indexKeyIndex) List(ctx context.Context, prefixKey []interface{}, options ...ormlist.Option) (Iterator, error) { +func (i indexKeyIndex) List(ctx context.Context, prefixKey []any, options ...ormlist.Option) (Iterator, error) { backend, err := i.getReadBackend(ctx) if err != nil { return nil, err @@ -52,7 +52,7 @@ func (i indexKeyIndex) List(ctx context.Context, prefixKey []interface{}, option return prefixIterator(backend.IndexStoreReader(), backend, i, i.KeyCodec, prefixKey, options) } -func (i indexKeyIndex) ListRange(ctx context.Context, from, to []interface{}, options ...ormlist.Option) (Iterator, error) { +func (i indexKeyIndex) ListRange(ctx context.Context, from, to []any, options ...ormlist.Option) (Iterator, error) { backend, err := i.getReadBackend(ctx) if err != nil { return nil, err @@ -66,7 +66,7 @@ var ( _ Index = &indexKeyIndex{} ) -func (i indexKeyIndex) doNotImplement() {} +func (indexKeyIndex) doNotImplement() {} func (i indexKeyIndex) onInsert(store kv.Store, message protoreflect.Message) error { k, v, err := i.EncodeKVFromMessage(message) @@ -76,9 +76,9 @@ func (i indexKeyIndex) onInsert(store kv.Store, message protoreflect.Message) er return store.Set(k, v) } -func (i indexKeyIndex) onUpdate(store kv.Store, new, existing protoreflect.Message) error { - newValues := i.GetKeyValues(new) - existingValues := i.GetKeyValues(existing) +func (i indexKeyIndex) onUpdate(store kv.Store, newMsg, existingMsg protoreflect.Message) error { + newValues := i.GetKeyValues(newMsg) + existingValues := i.GetKeyValues(existingMsg) if i.CompareKeys(newValues, existingValues) == 0 { return nil } @@ -108,18 +108,18 @@ func (i indexKeyIndex) onDelete(store kv.Store, message protoreflect.Message) er } func (i indexKeyIndex) readValueFromIndexKey(backend ReadBackend, primaryKey []protoreflect.Value, _ []byte, message proto.Message) error { - found, err := i.primaryKey.get(backend, message, primaryKey) + found, err := i.primaryKey.doGet(backend, message, primaryKey) if err != nil { return err } if !found { - return ormerrors.UnexpectedError.Wrapf("can't find primary key") + return ormerrors.ErrUnexpectedError.Wrapf("can't find primary key") } return nil } -func (p indexKeyIndex) Fields() string { - return p.fields.String() +func (i indexKeyIndex) Fields() string { + return i.fields.String() } diff --git a/orm/model/ormtable/iterator.go b/orm/model/ormtable/iterator.go index 848396cb96c6..2f47ac10a876 100644 --- a/orm/model/ormtable/iterator.go +++ b/orm/model/ormtable/iterator.go @@ -49,7 +49,7 @@ type Iterator interface { doNotImplement() } -func prefixIterator(iteratorStore kv.ReadonlyStore, backend ReadBackend, index concreteIndex, codec *ormkv.KeyCodec, prefix []interface{}, opts []listinternal.Option) (Iterator, error) { +func prefixIterator(iteratorStore kv.ReadonlyStore, backend ReadBackend, index concreteIndex, codec *ormkv.KeyCodec, prefix []any, opts []listinternal.Option) (Iterator, error) { options := &listinternal.Options{} listinternal.ApplyOptions(options, opts) if err := options.Validate(); err != nil { @@ -106,7 +106,7 @@ func prefixIterator(iteratorStore kv.ReadonlyStore, backend ReadBackend, index c return applyCommonIteratorOptions(res, options) } -func rangeIterator(iteratorStore kv.ReadonlyStore, reader ReadBackend, index concreteIndex, codec *ormkv.KeyCodec, start, end []interface{}, opts []listinternal.Option) (Iterator, error) { +func rangeIterator(iteratorStore kv.ReadonlyStore, reader ReadBackend, index concreteIndex, codec *ormkv.KeyCodec, start, end []any, opts []listinternal.Option) (Iterator, error) { options := &listinternal.Options{} listinternal.ApplyOptions(options, opts) if err := options.Validate(); err != nil { @@ -205,7 +205,7 @@ type indexIterator struct { started bool } -func (i *indexIterator) PageResponse() *queryv1beta1.PageResponse { +func (*indexIterator) PageResponse() *queryv1beta1.PageResponse { return nil } diff --git a/orm/model/ormtable/paginate.go b/orm/model/ormtable/paginate.go index f30d9c02583d..0bf27ba2d433 100644 --- a/orm/model/ormtable/paginate.go +++ b/orm/model/ormtable/paginate.go @@ -84,12 +84,11 @@ func (it *paginationIterator) Next() bool { if ok { it.i++ return true - } else { - it.pageRes = &queryv1beta1.PageResponse{ - Total: uint64(it.i), - } - return false } + it.pageRes = &queryv1beta1.PageResponse{ + Total: uint64(it.i), + } + return false } func (it paginationIterator) PageResponse() *queryv1beta1.PageResponse { diff --git a/orm/model/ormtable/primary_key.go b/orm/model/ormtable/primary_key.go index 0ce62852895b..9bff13afd7a7 100644 --- a/orm/model/ormtable/primary_key.go +++ b/orm/model/ormtable/primary_key.go @@ -25,7 +25,7 @@ type primaryKeyIndex struct { getBackend func(context.Context) (ReadBackend, error) } -func (p primaryKeyIndex) List(ctx context.Context, prefixKey []interface{}, options ...ormlist.Option) (Iterator, error) { +func (p primaryKeyIndex) List(ctx context.Context, prefixKey []any, options ...ormlist.Option) (Iterator, error) { backend, err := p.getBackend(ctx) if err != nil { return nil, err @@ -34,7 +34,7 @@ func (p primaryKeyIndex) List(ctx context.Context, prefixKey []interface{}, opti return prefixIterator(backend.CommitmentStoreReader(), backend, p, p.KeyCodec, prefixKey, options) } -func (p primaryKeyIndex) ListRange(ctx context.Context, from, to []interface{}, options ...ormlist.Option) (Iterator, error) { +func (p primaryKeyIndex) ListRange(ctx context.Context, from, to []any, options ...ormlist.Option) (Iterator, error) { backend, err := p.getBackend(ctx) if err != nil { return nil, err @@ -43,18 +43,18 @@ func (p primaryKeyIndex) ListRange(ctx context.Context, from, to []interface{}, return rangeIterator(backend.CommitmentStoreReader(), backend, p, p.KeyCodec, from, to, options) } -func (p primaryKeyIndex) doNotImplement() {} +func (primaryKeyIndex) doNotImplement() {} -func (p primaryKeyIndex) Has(ctx context.Context, key ...interface{}) (found bool, err error) { +func (p primaryKeyIndex) Has(ctx context.Context, key ...any) (found bool, err error) { backend, err := p.getBackend(ctx) if err != nil { return false, err } - return p.has(backend, encodeutil.ValuesOf(key...)) + return p.checkHas(backend, encodeutil.ValuesOf(key...)) } -func (p primaryKeyIndex) has(backend ReadBackend, values []protoreflect.Value) (found bool, err error) { +func (p primaryKeyIndex) checkHas(backend ReadBackend, values []protoreflect.Value) (found bool, err error) { keyBz, err := p.EncodeKey(values) if err != nil { return false, err @@ -63,16 +63,16 @@ func (p primaryKeyIndex) has(backend ReadBackend, values []protoreflect.Value) ( return backend.CommitmentStoreReader().Has(keyBz) } -func (p primaryKeyIndex) Get(ctx context.Context, message proto.Message, values ...interface{}) (found bool, err error) { +func (p primaryKeyIndex) Get(ctx context.Context, message proto.Message, values ...any) (found bool, err error) { backend, err := p.getBackend(ctx) if err != nil { return false, err } - return p.get(backend, message, encodeutil.ValuesOf(values...)) + return p.doGet(backend, message, encodeutil.ValuesOf(values...)) } -func (p primaryKeyIndex) get(backend ReadBackend, message proto.Message, values []protoreflect.Value) (found bool, err error) { +func (p primaryKeyIndex) doGet(backend ReadBackend, message proto.Message, values []protoreflect.Value) (found bool, err error) { key, err := p.EncodeKey(values) if err != nil { return false, err @@ -81,7 +81,7 @@ func (p primaryKeyIndex) get(backend ReadBackend, message proto.Message, values return p.getByKeyBytes(backend, key, values, message) } -func (p primaryKeyIndex) DeleteBy(ctx context.Context, primaryKeyValues ...interface{}) error { +func (p primaryKeyIndex) DeleteBy(ctx context.Context, primaryKeyValues ...any) error { if len(primaryKeyValues) == len(p.GetFieldNames()) { return p.doDelete(ctx, encodeutil.ValuesOf(primaryKeyValues...)) } @@ -94,7 +94,7 @@ func (p primaryKeyIndex) DeleteBy(ctx context.Context, primaryKeyValues ...inter return p.deleteByIterator(ctx, it) } -func (p primaryKeyIndex) DeleteRange(ctx context.Context, from, to []interface{}) error { +func (p primaryKeyIndex) DeleteRange(ctx context.Context, from, to []any) error { it, err := p.ListRange(ctx, from, to) if err != nil { return err @@ -113,7 +113,7 @@ func (p primaryKeyIndex) getWriteBackend(ctx context.Context) (Backend, error) { return writeBackend, nil } - return nil, ormerrors.ReadOnly + return nil, ormerrors.ErrReadOnly } func (p primaryKeyIndex) doDelete(ctx context.Context, primaryKeyValues []protoreflect.Value) error { diff --git a/orm/model/ormtable/singleton.go b/orm/model/ormtable/singleton.go index 1a7017662579..db494d26f0ba 100644 --- a/orm/model/ormtable/singleton.go +++ b/orm/model/ormtable/singleton.go @@ -37,9 +37,8 @@ func (t singleton) ValidateJSON(reader io.Reader) error { if t.customJSONValidator != nil { return t.customJSONValidator(msg) - } else { - return DefaultJSONValidator(msg) } + return DefaultJSONValidator(msg) } func (t singleton) ImportJSON(ctx context.Context, reader io.Reader) error { @@ -59,7 +58,7 @@ func (t singleton) ImportJSON(ctx context.Context, reader io.Reader) error { return err } - return t.save(ctx, backend, msg, saveModeDefault) + return t.write(ctx, backend, msg, saveModeDefault) } func (t singleton) ExportJSON(ctx context.Context, writer io.Writer) error { diff --git a/orm/model/ormtable/table_impl.go b/orm/model/ormtable/table_impl.go index bbcebb3a96ad..e99ba2b6dcff 100644 --- a/orm/model/ormtable/table_impl.go +++ b/orm/model/ormtable/table_impl.go @@ -24,10 +24,10 @@ type tableImpl struct { indexes []Index indexesByFields map[fieldnames.FieldNames]concreteIndex uniqueIndexesByFields map[fieldnames.FieldNames]UniqueIndex - indexesById map[uint32]Index - entryCodecsById map[uint32]ormkv.EntryCodec + indexesByID map[uint32]Index + entryCodecsByID map[uint32]ormkv.EntryCodec tablePrefix []byte - tableId uint32 + tableID uint32 typeResolver TypeResolver customJSONValidator func(message proto.Message) error } @@ -44,7 +44,7 @@ func (t tableImpl) PrimaryKey() UniqueIndex { } func (t tableImpl) GetIndexByID(id uint32) Index { - return t.indexesById[id] + return t.indexesByID[id] } func (t tableImpl) Save(ctx context.Context, message proto.Message) error { @@ -53,7 +53,7 @@ func (t tableImpl) Save(ctx context.Context, message proto.Message) error { return err } - return t.save(ctx, backend, message, saveModeDefault) + return t.write(ctx, backend, message, saveModeDefault) } func (t tableImpl) Insert(ctx context.Context, message proto.Message) error { @@ -62,7 +62,7 @@ func (t tableImpl) Insert(ctx context.Context, message proto.Message) error { return err } - return t.save(ctx, backend, message, saveModeInsert) + return t.write(ctx, backend, message, saveModeInsert) } func (t tableImpl) Update(ctx context.Context, message proto.Message) error { @@ -71,10 +71,10 @@ func (t tableImpl) Update(ctx context.Context, message proto.Message) error { return err } - return t.save(ctx, backend, message, saveModeUpdate) + return t.write(ctx, backend, message, saveModeUpdate) } -func (t tableImpl) save(ctx context.Context, backend Backend, message proto.Message, mode saveMode) error { +func (t tableImpl) write(ctx context.Context, backend Backend, message proto.Message, mode saveMode) error { writer := newBatchIndexCommitmentWriter(backend) defer writer.Close() return t.doSave(ctx, writer, message, mode) @@ -95,7 +95,7 @@ func (t tableImpl) doSave(ctx context.Context, writer *batchIndexCommitmentWrite if haveExisting { if mode == saveModeInsert { - return ormerrors.AlreadyExists.Wrapf("%q:%+v", mref.Descriptor().FullName(), pkValues) + return ormerrors.ErrOrmAlreadyExists.Wrapf("%q:%+v", mref.Descriptor().FullName(), pkValues) } if validateHooks := writer.ValidateHooks(); validateHooks != nil { @@ -106,7 +106,7 @@ func (t tableImpl) doSave(ctx context.Context, writer *batchIndexCommitmentWrite } } else { if mode == saveModeUpdate { - return ormerrors.NotFound.Wrapf("%q", mref.Descriptor().FullName()) + return ormerrors.ErrNotFound.Wrapf("%q", mref.Descriptor().FullName()) } if validateHooks := writer.ValidateHooks(); validateHooks != nil { @@ -141,7 +141,6 @@ func (t tableImpl) doSave(ctx context.Context, writer *batchIndexCommitmentWrite if err != nil { return err } - } if writeHooks := writer.WriteHooks(); writeHooks != nil { writer.enqueueHook(func() { @@ -183,20 +182,20 @@ func (t tableImpl) Indexes() []Index { return t.indexes } -func (t tableImpl) DefaultJSON() json.RawMessage { +func (tableImpl) DefaultJSON() json.RawMessage { return json.RawMessage("[]") } -func (t tableImpl) decodeJson(reader io.Reader, onMsg func(message proto.Message) error) error { - decoder, err := t.startDecodeJson(reader) +func (t tableImpl) decodeJSON(reader io.Reader, onMsg func(message proto.Message) error) error { + decoder, err := t.startDecodeJSON(reader) if err != nil { return err } - return t.doDecodeJson(decoder, nil, onMsg) + return t.doDecodeJSON(decoder, nil, onMsg) } -func (t tableImpl) startDecodeJson(reader io.Reader) (*json.Decoder, error) { +func (tableImpl) startDecodeJSON(reader io.Reader) (*json.Decoder, error) { decoder := json.NewDecoder(reader) token, err := decoder.Token() if err != nil { @@ -204,7 +203,7 @@ func (t tableImpl) startDecodeJson(reader io.Reader) (*json.Decoder, error) { } if token != json.Delim('[') { - return nil, ormerrors.JSONImportError.Wrapf("expected [ got %s", token) + return nil, ormerrors.ErrJSONImportError.Wrapf("expected [ got %s", token) } return decoder, nil @@ -213,21 +212,21 @@ func (t tableImpl) startDecodeJson(reader io.Reader) (*json.Decoder, error) { // onFirst is called on the first RawMessage and used for auto-increment tables // to decode the sequence in which case it should return true. // onMsg is called on every decoded message -func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json.RawMessage) bool, onMsg func(message proto.Message) error) error { +func (t tableImpl) doDecodeJSON(decoder *json.Decoder, onFirst func(message json.RawMessage) bool, onMsg func(message proto.Message) error) error { unmarshalOptions := protojson.UnmarshalOptions{Resolver: t.typeResolver} first := true for decoder.More() { - var rawJson json.RawMessage - err := decoder.Decode(&rawJson) + var rawJSON json.RawMessage + err := decoder.Decode(&rawJSON) if err != nil { - return ormerrors.JSONImportError.Wrapf("%s", err) + return ormerrors.ErrJSONImportError.Wrapf("%s", err) } if first { first = false if onFirst != nil { - if onFirst(rawJson) { + if onFirst(rawJSON) { // if onFirst handled this, skip decoding into a proto message continue } @@ -235,7 +234,7 @@ func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json } msg := t.MessageType().New().Interface() - err = unmarshalOptions.Unmarshal(rawJson, msg) + err = unmarshalOptions.Unmarshal(rawJSON, msg) if err != nil { return err } @@ -252,7 +251,7 @@ func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json } if token != json.Delim(']') { - return ormerrors.JSONImportError.Wrapf("expected ] got %s", token) + return ormerrors.ErrJSONImportError.Wrapf("expected ] got %s", token) } return nil @@ -280,12 +279,11 @@ func DefaultJSONValidator(message proto.Message) error { } func (t tableImpl) ValidateJSON(reader io.Reader) error { - return t.decodeJson(reader, func(message proto.Message) error { + return t.decodeJSON(reader, func(message proto.Message) error { if t.customJSONValidator != nil { return t.customJSONValidator(message) - } else { - return DefaultJSONValidator(message) } + return DefaultJSONValidator(message) }) } @@ -295,18 +293,18 @@ func (t tableImpl) ImportJSON(ctx context.Context, reader io.Reader) error { return err } - return t.decodeJson(reader, func(message proto.Message) error { - return t.save(ctx, backend, message, saveModeDefault) + return t.decodeJSON(reader, func(message proto.Message) error { + return t.write(ctx, backend, message, saveModeDefault) }) } -func (t tableImpl) ExportJSON(context context.Context, writer io.Writer) error { +func (t tableImpl) ExportJSON(ctx context.Context, writer io.Writer) error { _, err := writer.Write([]byte("[")) if err != nil { return err } - return t.doExportJSON(context, writer, true) + return t.doExportJSON(ctx, writer, true) } func (t tableImpl) doExportJSON(ctx context.Context, writer io.Writer, start bool) error { @@ -346,7 +344,6 @@ func (t tableImpl) doExportJSON(ctx context.Context, writer io.Writer, start boo if err != nil { return err } - } } @@ -363,12 +360,12 @@ func (t tableImpl) DecodeEntry(k, v []byte) (ormkv.Entry, error) { } if id > math.MaxUint32 { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - idx, ok := t.entryCodecsById[uint32(id)] + idx, ok := t.entryCodecsByID[uint32(id)] if !ok { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find field with id %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("can't find field with id %d", id) } return idx.DecodeEntry(k, v) @@ -381,17 +378,17 @@ func (t tableImpl) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { case *ormkv.IndexKeyEntry: idx, ok := t.indexesByFields[fieldnames.FieldsFromNames(entry.Fields)] if !ok { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("can't find index with fields %s", entry.Fields) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("can't find index with fields %s", entry.Fields) } return idx.EncodeEntry(entry) default: - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("%s", entry) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("%s", entry) } } func (t tableImpl) ID() uint32 { - return t.tableId + return t.tableID } func (t tableImpl) Has(ctx context.Context, message proto.Message) (found bool, err error) { @@ -401,7 +398,7 @@ func (t tableImpl) Has(ctx context.Context, message proto.Message) (found bool, } keyValues := t.primaryKeyIndex.PrimaryKeyCodec.GetKeyValues(message.ProtoReflect()) - return t.primaryKeyIndex.has(backend, keyValues) + return t.primaryKeyIndex.checkHas(backend, keyValues) } // Get retrieves the message if one exists for the primary key fields @@ -414,7 +411,7 @@ func (t tableImpl) Get(ctx context.Context, message proto.Message) (found bool, } keyValues := t.primaryKeyIndex.PrimaryKeyCodec.GetKeyValues(message.ProtoReflect()) - return t.primaryKeyIndex.get(backend, message, keyValues) + return t.primaryKeyIndex.doGet(backend, message, keyValues) } var ( diff --git a/orm/model/ormtable/table_test.go b/orm/model/ormtable/table_test.go index 8e62cf814359..aa1575179f32 100644 --- a/orm/model/ormtable/table_test.go +++ b/orm/model/ormtable/table_test.go @@ -9,29 +9,24 @@ import ( "testing" "time" - "google.golang.org/protobuf/types/known/timestamppb" - - dbm "github.com/cosmos/cosmos-db" - - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/testing/protocmp" - "gotest.tools/v3/assert" - "gotest.tools/v3/golden" - "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/types/kv" - queryv1beta1 "cosmossdk.io/api/cosmos/base/query/v1beta1" sdkerrors "cosmossdk.io/errors" - + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/internal/testutil" "github.com/cosmos/cosmos-sdk/orm/model/ormlist" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "github.com/cosmos/cosmos-sdk/orm/types/kv" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/testing/protocmp" + "google.golang.org/protobuf/types/known/timestamppb" + "gotest.tools/v3/assert" + "gotest.tools/v3/golden" + "pgregory.net/rapid" ) func TestScenario(t *testing.T) { @@ -40,30 +35,32 @@ func TestScenario(t *testing.T) { }) assert.NilError(t, err) - // first run tests with a split index-commitment store + // First run tests with a split index-commitment store. runTestScenario(t, table, testkv.NewSplitMemBackend()) - // now run tests with a shared index-commitment store + // Now run tests with a shared index-commitment store. - // we're going to wrap this test in a debug store and save the decoded debug + // We're going to wrap this test in a debug store and save the decoded debug // messages, these will be checked against a golden file at the end of the - // test. the golden file can be used for fine-grained debugging of kv-store - // layout + // test. The golden file can be used for fine-grained debugging of kv-store + // layout. debugBuf := &strings.Builder{} store := testkv.NewDebugBackend( testkv.NewSharedMemBackend(), &testkv.EntryCodecDebugger{ EntryCodec: table, - Print: func(s string) { debugBuf.WriteString(s + "\n") }, + Print: func(s string) { + debugBuf.WriteString(s + "\n") //nolint:errcheck,revive // we're going to pass the whole function + }, }, ) runTestScenario(t, table, store) - // we're going to store debug data in a golden file to make sure that + // We're going to store debug data in a golden file to make sure that // logical decoding works successfully // run `go test pkgname -test.update-golden` to update the golden file - // see https://pkg.go.dev/gotest.tools/v3/golden for docs + // see https://pkg.go.dev/gotest.tools/v3/golden for docs. golden.Assert(t, debugBuf.String(), "test_scenario.golden") checkEncodeDecodeEntries(t, table, store.IndexStoreReader()) @@ -94,7 +91,7 @@ func TestPaginationLimitCountTotal(t *testing.T) { it, err = store.List(ctx, &testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{Limit: 1, CountTotal: true})) assert.NilError(t, err) - for it.Next() { + for it.Next() { //nolint:revive // we need this empty block here } pr := it.PageResponse() assert.Check(t, pr != nil) @@ -151,7 +148,7 @@ func TestTimestampIndex(t *testing.T) { i++ } - // insert a nil entry + // Insert a nil entry. id, err := store.InsertReturningId(ctx, &testpb.ExampleTimestamp{ Name: "nil", Ts: nil, @@ -165,7 +162,7 @@ func TestTimestampIndex(t *testing.T) { it, err = store.List(ctx, testpb.ExampleTimestampTsIndexKey{}) assert.NilError(t, err) - // make sure nils are ordered last + // Make sure nils are ordered last. timeOrder = append(timeOrder, nil) i = 0 for it.Next() { @@ -182,7 +179,7 @@ func TestTimestampIndex(t *testing.T) { } it.Close() - // try iterating over just nil timestamps + // Try iterating over just nil timestamps. it, err = store.List(ctx, testpb.ExampleTimestampTsIndexKey{}.WithTs(nil)) assert.NilError(t, err) assert.Assert(t, it.Next()) @@ -193,8 +190,9 @@ func TestTimestampIndex(t *testing.T) { it.Close() } -// check that the ormkv.Entry's decode and encode to the same bytes +// check that the ormkv.Entry's decode and encode to the same bytes. func checkEncodeDecodeEntries(t *testing.T, table ormtable.Table, store kv.ReadonlyStore) { + t.Helper() it, err := store.Iterator(nil, nil) assert.NilError(t, err) for it.Valid() { @@ -211,73 +209,74 @@ func checkEncodeDecodeEntries(t *testing.T, table ormtable.Table, store kv.Reado } func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backend) { + t.Helper() ctx := ormtable.WrapContextDefault(backend) store, err := testpb.NewExampleTableTable(table) assert.NilError(t, err) - // let's create 10 data items we'll use later and give them indexes + // Let's create 10 data items we'll use later and give them indexes. data := []*testpb.ExampleTable{ - {U32: 4, I64: -2, Str: "abc", U64: 7}, // 0 - {U32: 4, I64: -2, Str: "abd", U64: 7}, // 1 - {U32: 4, I64: -1, Str: "abc", U64: 8}, // 2 - {U32: 5, I64: -2, Str: "abd", U64: 8}, // 3 - {U32: 5, I64: -2, Str: "abe", U64: 9}, // 4 - {U32: 7, I64: -2, Str: "abe", U64: 10}, // 5 - {U32: 7, I64: -1, Str: "abe", U64: 11}, // 6 - {U32: 8, I64: -4, Str: "abc", U64: 11}, // 7 - {U32: 8, I64: 1, Str: "abc", U64: 12}, // 8 - {U32: 8, I64: 1, Str: "abd", U64: 10}, // 9 + {U32: 4, I64: -2, Str: "abc", U64: 7}, // 0. + {U32: 4, I64: -2, Str: "abd", U64: 7}, // 1. + {U32: 4, I64: -1, Str: "abc", U64: 8}, // 2. + {U32: 5, I64: -2, Str: "abd", U64: 8}, // 3. + {U32: 5, I64: -2, Str: "abe", U64: 9}, // 4. + {U32: 7, I64: -2, Str: "abe", U64: 10}, // 5. + {U32: 7, I64: -1, Str: "abe", U64: 11}, // 6. + {U32: 8, I64: -4, Str: "abc", U64: 11}, // 7. + {U32: 8., I64: 1, Str: "abc", U64: 12}, // 8 + {U32: 8, I64: 1, Str: "abd", U64: 10}, // 9. } - // let's make a function to match what's in our iterator with what we - // expect using indexes in the data array above + // Let's make a function to match what's in our iterator with what we + // expect using indexes in the data array above. assertIteratorItems := func(it ormtable.Iterator, xs ...int) { for _, i := range xs { assert.Assert(t, it.Next()) msg, err := it.GetMessage() assert.NilError(t, err) - // t.Logf("data[%d] %v == %v", i, data[i], msg) + // T.Logf("data[%d] %v == %v", i, data[i], msg). assert.DeepEqual(t, data[i], msg, protocmp.Transform()) } - // make sure the iterator is done + // Make sure the iterator is done. assert.Assert(t, !it.Next()) } - // insert one record + // Insert one record. err = store.Insert(ctx, data[0]) assert.NilError(t, err) - // trivial prefix query has one record + // Trivial prefix query has one record. it, err := store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0) - // insert one record + // Insert one record. err = store.Insert(ctx, data[1]) assert.NilError(t, err) - // trivial prefix query has two records + // Trivial prefix query has two records. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0, 1) - // insert the other records + // Insert the other records. assert.NilError(t, err) for i := 2; i < len(data); i++ { err = store.Insert(ctx, data[i]) assert.NilError(t, err) } - // let's do a prefix query on the primary key + // Let's do a prefix query on the primary key. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}.WithU32(8)) assert.NilError(t, err) assertIteratorItems(it, 7, 8, 9) - // let's try a reverse prefix query + // Let's try a reverse prefix query. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}.WithU32(4), ormlist.Reverse()) assert.NilError(t, err) defer it.Close() assertIteratorItems(it, 2, 1, 0) - // let's try a range query + // Let's try a range query. it, err = store.ListRange(ctx, testpb.ExampleTablePrimaryKey{}.WithU32I64(4, -1), testpb.ExampleTablePrimaryKey{}.WithU32(7), @@ -286,7 +285,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen defer it.Close() assertIteratorItems(it, 2, 3, 4, 5, 6) - // and another range query + // And another range query. it, err = store.ListRange(ctx, testpb.ExampleTablePrimaryKey{}.WithU32I64(5, -3), testpb.ExampleTablePrimaryKey{}.WithU32I64Str(8, 1, "abc"), @@ -295,7 +294,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen defer it.Close() assertIteratorItems(it, 3, 4, 5, 6, 7, 8) - // now a reverse range query on a different index + // Now a reverse range query on a different index. strU32Index := table.GetIndex("str,u32") assert.Assert(t, strU32Index != nil) it, err = store.ListRange(ctx, @@ -306,14 +305,14 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 9, 3, 1, 8, 7, 2, 0) - // another prefix query forwards + // Another prefix query forwards. it, err = store.List(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStrU32("abe", 7), ) assert.NilError(t, err) assertIteratorItems(it, 5, 6) - // and backwards + // And backwards. it, err = store.List(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStrU32("abc", 4), ormlist.Reverse(), @@ -321,7 +320,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 2, 0) - // try filtering + // Try filtering. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Filter(func(message proto.Message) bool { ex := message.(*testpb.ExampleTable) return ex.U64 != 10 @@ -329,7 +328,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 0, 1, 2, 3, 4, 6, 7, 8) - // try a cursor + // Try a cursor. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assert.Assert(t, it.Next()) @@ -338,7 +337,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 2, 3, 4, 5, 6, 7, 8, 9) - // try an unique index + // Try an unique index. found, err := store.HasByU64Str(ctx, 12, "abc") assert.NilError(t, err) assert.Assert(t, found) @@ -346,7 +345,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assert.DeepEqual(t, data[8], a, protocmp.Transform()) - // let's try paginating some stuff + // Let's try paginating some stuff. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 4, CountTotal: true, @@ -358,7 +357,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Equal(t, uint64(10), res.Total) assert.Assert(t, res.NextKey != nil) - // let's use a default limit + // Let's use a default limit. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.DefaultLimit(4), ormlist.Paginate(&queryv1beta1.PageRequest{ @@ -371,7 +370,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Equal(t, uint64(10), res.Total) assert.Assert(t, res.NextKey != nil) - // read another page + // Read another page. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Key: res.NextKey, Limit: 4, @@ -382,7 +381,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res != nil) assert.Assert(t, res.NextKey != nil) - // and the last page + // And the last page. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Key: res.NextKey, Limit: 4, @@ -393,7 +392,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res != nil) assert.Assert(t, res.NextKey == nil) - // let's go backwards + // Let's go backwards. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 2, CountTotal: true, @@ -406,7 +405,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res.NextKey != nil) assert.Equal(t, uint64(10), res.Total) - // a bit more + // A bit more. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Key: res.NextKey, Limit: 2, @@ -418,7 +417,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res != nil) assert.Assert(t, res.NextKey != nil) - // range query + // Range query. it, err = store.ListRange(ctx, testpb.ExampleTablePrimaryKey{}.WithU32I64Str(4, -1, "abc"), testpb.ExampleTablePrimaryKey{}.WithU32I64Str(7, -2, "abe"), @@ -431,7 +430,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res != nil) assert.Assert(t, res.NextKey == nil) - // let's try an offset + // Let's try an offset. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 2, CountTotal: true, @@ -444,7 +443,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res.NextKey != nil) assert.Equal(t, uint64(10), res.Total) - // and reverse + // And reverse. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 3, CountTotal: true, @@ -458,7 +457,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res.NextKey != nil) assert.Equal(t, uint64(10), res.Total) - // now an offset that's slightly too big + // Now an offset that's slightly too big. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 1, CountTotal: true, @@ -471,19 +470,19 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res.NextKey == nil) assert.Equal(t, uint64(10), res.Total) - // now let's update some things + // Now let's update some things. for i := 0; i < 5; i++ { - data[i].U64 = data[i].U64 * 2 + data[i].U64 *= 2 data[i].Bz = []byte(data[i].Str) err = store.Update(ctx, data[i]) assert.NilError(t, err) } it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) - // we should still get everything in the same order + // We should still get everything in the same order. assertIteratorItems(it, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - // let's use SAVE_MODE_DEFAULT and add something + // Let's use SAVE_MODE_DEFAULT and add something. data = append(data, &testpb.ExampleTable{U32: 9}) err = store.Save(ctx, data[10]) assert.NilError(t, err) @@ -491,19 +490,19 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assert.Assert(t, a != nil) assert.DeepEqual(t, data[10], a, protocmp.Transform()) - // and update it + // And update it. data[10].B = true assert.NilError(t, table.Save(ctx, data[10])) a, err = store.Get(ctx, 9, 0, "") assert.NilError(t, err) assert.Assert(t, a != nil) assert.DeepEqual(t, data[10], a, protocmp.Transform()) - // and iterate + // And iterate. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - // let's export and import JSON and use a read-only backend + // Let's export and import JSON and use a read-only backend. buf := &bytes.Buffer{} readBackend := ormtable.NewReadBackend(ormtable.ReadBackendOptions{ CommitmentStoreReader: backend.CommitmentStoreReader(), @@ -513,32 +512,32 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, table.ValidateJSON(bytes.NewReader(buf.Bytes()))) store2 := ormtable.WrapContextDefault(testkv.NewSplitMemBackend()) assert.NilError(t, table.ImportJSON(store2, bytes.NewReader(buf.Bytes()))) - assertTablesEqual(t, table, ctx, store2) + assertTablesEqual(ctx, store2, t, table) - // let's delete item 5 + // Let's delete item 5. err = store.DeleteBy(ctx, testpb.ExampleTableU32I64StrIndexKey{}.WithU32I64Str(7, -2, "abe")) assert.NilError(t, err) - // it should be gone + // It should be gone. found, err = store.Has(ctx, 7, -2, "abe") assert.NilError(t, err) assert.Assert(t, !found) - // and missing from the iterator + // And missing from the iterator. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0, 1, 2, 3, 4, 6, 7, 8, 9, 10) - // let's do a batch delete - // first iterate over the items we'll delete to check that iterator + // Let's do a batch delete + // first iterate over the items we'll delete to check that iterator. it, err = store.List(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStr("abd")) assert.NilError(t, err) assertIteratorItems(it, 1, 3, 9) - // now delete them + // Now delete them. assert.NilError(t, store.DeleteBy(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStr("abd"))) it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0, 2, 4, 6, 7, 8, 10) - // Let's do a range delete + // Let's do a range delete. assert.NilError(t, store.DeleteRange(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStrU32("abc", 8), testpb.ExampleTableStrU32IndexKey{}.WithStrU32("abe", 5), @@ -547,7 +546,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 0, 2, 6, 10) - // Let's delete something directly + // Let's delete something directly. assert.NilError(t, store.Delete(ctx, data[0])) it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) @@ -559,6 +558,7 @@ func TestRandomTableData(t *testing.T) { } func testTable(t *testing.T, tableData *TableData) { + t.Helper() for _, index := range tableData.table.Indexes() { indexModel := &IndexModel{ TableData: tableData, @@ -573,6 +573,7 @@ func testTable(t *testing.T, tableData *TableData) { } func testUniqueIndex(t *testing.T, model *IndexModel) { + t.Helper() index := model.index.(ormtable.UniqueIndex) t.Logf("testing unique index %T %s", index, index.Fields()) for i := 0; i < len(model.data); i++ { @@ -595,6 +596,7 @@ func testUniqueIndex(t *testing.T, model *IndexModel) { } func testIndex(t *testing.T, model *IndexModel) { + t.Helper() index := model.index if index.IsFullyOrdered() { t.Logf("testing index %T %s", index, index.Fields()) @@ -630,7 +632,7 @@ func testIndex(t *testing.T, model *IndexModel) { } else { t.Logf("testing unordered index %T %s", index, index.Fields()) - // get all the data + // Get all the data. it, err := model.index.List(model.context, nil) assert.NilError(t, err) var data2 []proto.Message @@ -641,7 +643,7 @@ func testIndex(t *testing.T, model *IndexModel) { } assert.Equal(t, len(model.data), len(data2)) - // sort it + // Sort it. model2 := &IndexModel{ TableData: &TableData{ table: model.table, @@ -652,7 +654,7 @@ func testIndex(t *testing.T, model *IndexModel) { } sort.Sort(model2) - // compare + // Compare. for i := 0; i < len(data2); i++ { assert.DeepEqual(t, model.data[i], data2[i], protocmp.Transform()) } @@ -703,7 +705,7 @@ func TableDataGen[T proto.Message](elemGen *rapid.Generator[T], n int) *rapid.Ge for i := 0; i < n; { message = elemGen.Draw(t, fmt.Sprintf("message[%d]", i)) err := table.Insert(store, message) - if sdkerrors.IsOf(err, ormerrors.PrimaryKeyConstraintViolation, ormerrors.UniqueKeyViolation) { + if sdkerrors.IsOf(err, ormerrors.ErrPrimaryKeyConstraintViolation, ormerrors.ErrUniqueKeyViolation) { continue } else if err != nil { panic(err) @@ -763,9 +765,7 @@ func (m *IndexModel) Less(i, j int) bool { } func (m *IndexModel) Swap(i, j int) { - x := m.data[i] - m.data[i] = m.data[j] - m.data[j] = x + m.data[i], m.data[j] = m.data[j], m.data[i] } var _ sort.Interface = &IndexModel{} @@ -780,11 +780,11 @@ func TestJSONExportImport(t *testing.T) { for i := 0; i < 100; { x := testutil.GenA.Example() err = table.Insert(store, x) - if sdkerrors.IsOf(err, ormerrors.PrimaryKeyConstraintViolation, ormerrors.UniqueKeyViolation) { + if sdkerrors.IsOf(err, ormerrors.ErrPrimaryKeyConstraintViolation, ormerrors.ErrUniqueKeyViolation) { continue - } else { - assert.NilError(t, err) } + assert.NilError(t, err) + i++ } @@ -796,10 +796,10 @@ func TestJSONExportImport(t *testing.T) { store2 := ormtable.WrapContextDefault(testkv.NewSplitMemBackend()) assert.NilError(t, table.ImportJSON(store2, bytes.NewReader(buf.Bytes()))) - assertTablesEqual(t, table, store, store2) + assertTablesEqual(store, store2, t, table) } -func assertTablesEqual(t assert.TestingT, table ormtable.Table, ctx, ctx2 context.Context) { +func assertTablesEqual(ctx, ctx2 context.Context, t assert.TestingT, table ormtable.Table) { it, err := table.List(ctx, nil) assert.NilError(t, err) it2, err := table.List(ctx2, nil) @@ -822,8 +822,8 @@ func assertTablesEqual(t assert.TestingT, table ormtable.Table, ctx, ctx2 contex } } -func protoValuesToInterfaces(ks []protoreflect.Value) []interface{} { - values := make([]interface{}, len(ks)) +func protoValuesToInterfaces(ks []protoreflect.Value) []any { + values := make([]any, len(ks)) for i := 0; i < len(ks); i++ { values[i] = ks[i].Interface() } @@ -841,7 +841,7 @@ func TestReadonly(t *testing.T) { IndexStoreReader: dbm.NewMemDB(), }) ctx := ormtable.WrapContextDefault(readBackend) - assert.ErrorIs(t, ormerrors.ReadOnly, table.Insert(ctx, &testpb.ExampleTable{})) + assert.ErrorIs(t, ormerrors.ErrReadOnly, table.Insert(ctx, &testpb.ExampleTable{})) } func TestInsertReturningFieldName(t *testing.T) { diff --git a/orm/model/ormtable/unique.go b/orm/model/ormtable/unique.go index 13127da04c43..232cfa64eeeb 100644 --- a/orm/model/ormtable/unique.go +++ b/orm/model/ormtable/unique.go @@ -3,19 +3,14 @@ package ormtable import ( "context" - "github.com/cosmos/cosmos-sdk/orm/types/kv" - + "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" + "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - + "github.com/cosmos/cosmos-sdk/orm/types/kv" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" ) type uniqueKeyIndex struct { @@ -25,7 +20,7 @@ type uniqueKeyIndex struct { getReadBackend func(context.Context) (ReadBackend, error) } -func (u uniqueKeyIndex) List(ctx context.Context, prefixKey []interface{}, options ...ormlist.Option) (Iterator, error) { +func (u uniqueKeyIndex) List(ctx context.Context, prefixKey []any, options ...ormlist.Option) (Iterator, error) { backend, err := u.getReadBackend(ctx) if err != nil { return nil, err @@ -34,7 +29,7 @@ func (u uniqueKeyIndex) List(ctx context.Context, prefixKey []interface{}, optio return prefixIterator(backend.IndexStoreReader(), backend, u, u.GetKeyCodec(), prefixKey, options) } -func (u uniqueKeyIndex) ListRange(ctx context.Context, from, to []interface{}, options ...ormlist.Option) (Iterator, error) { +func (u uniqueKeyIndex) ListRange(ctx context.Context, from, to []any, options ...ormlist.Option) (Iterator, error) { backend, err := u.getReadBackend(ctx) if err != nil { return nil, err @@ -43,9 +38,9 @@ func (u uniqueKeyIndex) ListRange(ctx context.Context, from, to []interface{}, o return rangeIterator(backend.IndexStoreReader(), backend, u, u.GetKeyCodec(), from, to, options) } -func (u uniqueKeyIndex) doNotImplement() {} +func (uniqueKeyIndex) doNotImplement() {} -func (u uniqueKeyIndex) Has(ctx context.Context, values ...interface{}) (found bool, err error) { +func (u uniqueKeyIndex) Has(ctx context.Context, values ...any) (found bool, err error) { backend, err := u.getReadBackend(ctx) if err != nil { return false, err @@ -59,7 +54,7 @@ func (u uniqueKeyIndex) Has(ctx context.Context, values ...interface{}) (found b return backend.IndexStoreReader().Has(key) } -func (u uniqueKeyIndex) Get(ctx context.Context, message proto.Message, keyValues ...interface{}) (found bool, err error) { +func (u uniqueKeyIndex) Get(ctx context.Context, message proto.Message, keyValues ...any) (found bool, err error) { backend, err := u.getReadBackend(ctx) if err != nil { return false, err @@ -75,7 +70,7 @@ func (u uniqueKeyIndex) Get(ctx context.Context, message proto.Message, keyValue return false, err } - // for unique keys, value can be empty and the entry still exists + // For unique keys, value can be empty and the entry still exists. if value == nil { return false, nil } @@ -85,10 +80,10 @@ func (u uniqueKeyIndex) Get(ctx context.Context, message proto.Message, keyValue return true, err } - return u.primaryKey.get(backend, message, pk) + return u.primaryKey.doGet(backend, message, pk) } -func (u uniqueKeyIndex) DeleteBy(ctx context.Context, keyValues ...interface{}) error { +func (u uniqueKeyIndex) DeleteBy(ctx context.Context, keyValues ...any) error { it, err := u.List(ctx, keyValues) if err != nil { return err @@ -97,7 +92,7 @@ func (u uniqueKeyIndex) DeleteBy(ctx context.Context, keyValues ...interface{}) return u.primaryKey.deleteByIterator(ctx, it) } -func (u uniqueKeyIndex) DeleteRange(ctx context.Context, from, to []interface{}) error { +func (u uniqueKeyIndex) DeleteRange(ctx context.Context, from, to []any) error { it, err := u.ListRange(ctx, from, to) if err != nil { return err @@ -118,16 +113,16 @@ func (u uniqueKeyIndex) onInsert(store kv.Store, message protoreflect.Message) e } if has { - return ormerrors.UniqueKeyViolation.Wrapf("%q", u.fields) + return ormerrors.ErrUniqueKeyViolation.Wrapf("%q", u.fields) } return store.Set(k, v) } -func (u uniqueKeyIndex) onUpdate(store kv.Store, new, existing protoreflect.Message) error { +func (u uniqueKeyIndex) onUpdate(store kv.Store, newMsg, existingMsg protoreflect.Message) error { keyCodec := u.GetKeyCodec() - newValues := keyCodec.GetKeyValues(new) - existingValues := keyCodec.GetKeyValues(existing) + newValues := keyCodec.GetKeyValues(newMsg) + existingValues := keyCodec.GetKeyValues(existingMsg) if keyCodec.CompareKeys(newValues, existingValues) == 0 { return nil } @@ -143,7 +138,7 @@ func (u uniqueKeyIndex) onUpdate(store kv.Store, new, existing protoreflect.Mess } if has { - return ormerrors.UniqueKeyViolation.Wrapf("%q", u.fields) + return ormerrors.ErrUniqueKeyViolation.Wrapf("%q", u.fields) } existingKey, err := keyCodec.EncodeKey(existingValues) @@ -156,7 +151,7 @@ func (u uniqueKeyIndex) onUpdate(store kv.Store, new, existing protoreflect.Mess return err } - _, value, err := u.GetValueCodec().EncodeKeyFromMessage(new) + _, value, err := u.GetValueCodec().EncodeKeyFromMessage(newMsg) if err != nil { return err } @@ -174,13 +169,13 @@ func (u uniqueKeyIndex) onDelete(store kv.Store, message protoreflect.Message) e } func (u uniqueKeyIndex) readValueFromIndexKey(store ReadBackend, primaryKey []protoreflect.Value, _ []byte, message proto.Message) error { - found, err := u.primaryKey.get(store, message, primaryKey) + found, err := u.primaryKey.doGet(store, message, primaryKey) if err != nil { return err } if !found { - return ormerrors.UnexpectedError.Wrapf("can't find primary key") + return ormerrors.ErrUnexpectedError.Wrapf("can't find primary key") } return nil diff --git a/orm/orm.go b/orm/orm.go index 558a061c7460..0467e8f35707 100644 --- a/orm/orm.go +++ b/orm/orm.go @@ -8,14 +8,12 @@ import ( ormv1alpha1 "cosmossdk.io/api/cosmos/orm/v1alpha1" "cosmossdk.io/core/appmodule" "cosmossdk.io/core/store" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protodesc" - "google.golang.org/protobuf/reflect/protoregistry" - "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoregistry" ) func init() { diff --git a/orm/testing/ormmocks/hooks.go b/orm/testing/ormmocks/hooks.go index c5ad0e6f0b17..cf4471a8548b 100644 --- a/orm/testing/ormmocks/hooks.go +++ b/orm/testing/ormmocks/hooks.go @@ -44,7 +44,7 @@ func (m *MockValidateHooks) ValidateDelete(arg0 context.Context, arg1 proto.Mess } // ValidateDelete indicates an expected call of ValidateDelete. -func (mr *MockValidateHooksMockRecorder) ValidateDelete(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockValidateHooksMockRecorder) ValidateDelete(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateDelete", reflect.TypeOf((*MockValidateHooks)(nil).ValidateDelete), arg0, arg1) } @@ -58,7 +58,7 @@ func (m *MockValidateHooks) ValidateInsert(arg0 context.Context, arg1 proto.Mess } // ValidateInsert indicates an expected call of ValidateInsert. -func (mr *MockValidateHooksMockRecorder) ValidateInsert(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockValidateHooksMockRecorder) ValidateInsert(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateInsert", reflect.TypeOf((*MockValidateHooks)(nil).ValidateInsert), arg0, arg1) } @@ -72,7 +72,7 @@ func (m *MockValidateHooks) ValidateUpdate(ctx context.Context, existing, new pr } // ValidateUpdate indicates an expected call of ValidateUpdate. -func (mr *MockValidateHooksMockRecorder) ValidateUpdate(ctx, existing, new interface{}) *gomock.Call { +func (mr *MockValidateHooksMockRecorder) ValidateUpdate(ctx, existing, new any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateUpdate", reflect.TypeOf((*MockValidateHooks)(nil).ValidateUpdate), ctx, existing, new) } @@ -107,7 +107,7 @@ func (m *MockWriteHooks) OnDelete(arg0 context.Context, arg1 proto.Message) { } // OnDelete indicates an expected call of OnDelete. -func (mr *MockWriteHooksMockRecorder) OnDelete(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockWriteHooksMockRecorder) OnDelete(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnDelete", reflect.TypeOf((*MockWriteHooks)(nil).OnDelete), arg0, arg1) } @@ -119,7 +119,7 @@ func (m *MockWriteHooks) OnInsert(arg0 context.Context, arg1 proto.Message) { } // OnInsert indicates an expected call of OnInsert. -func (mr *MockWriteHooksMockRecorder) OnInsert(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockWriteHooksMockRecorder) OnInsert(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnInsert", reflect.TypeOf((*MockWriteHooks)(nil).OnInsert), arg0, arg1) } @@ -131,7 +131,7 @@ func (m *MockWriteHooks) OnUpdate(ctx context.Context, existing, new proto.Messa } // OnUpdate indicates an expected call of OnUpdate. -func (mr *MockWriteHooksMockRecorder) OnUpdate(ctx, existing, new interface{}) *gomock.Call { +func (mr *MockWriteHooksMockRecorder) OnUpdate(ctx, existing, new any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnUpdate", reflect.TypeOf((*MockWriteHooks)(nil).OnUpdate), ctx, existing, new) } diff --git a/orm/testing/ormmocks/match.go b/orm/testing/ormmocks/match.go index 8c1da2c022f0..fa5936e20370 100644 --- a/orm/testing/ormmocks/match.go +++ b/orm/testing/ormmocks/match.go @@ -15,13 +15,13 @@ func Eq(message proto.Message) gomock.Matcher { } type protoEq struct { - message interface{} + message any diff string } -func (p protoEq) Matches(x interface{}) bool { +func (p protoEq) Matches(x any) bool { p.diff = cmp.Diff(x, p.message, protocmp.Transform()) - return len(p.diff) == 0 + return p.diff == "" } func (p protoEq) String() string { diff --git a/orm/types/kv/store.go b/orm/types/kv/store.go index f1281b356a0a..66e4c830fa6f 100644 --- a/orm/types/kv/store.go +++ b/orm/types/kv/store.go @@ -9,11 +9,11 @@ import ( // ReadonlyStore is an interface for readonly access to a kv-store. type ReadonlyStore interface { // Get fetches the value of the given key, or nil if it does not exist. - // CONTRACT: key, value readonly []byte + // CONTRACT: key, value readonly []byte. Get(key []byte) ([]byte, error) // Has checks if a key exists. - // CONTRACT: key, value readonly []byte + // CONTRACT: key, value readonly []byte. Has(key []byte) (bool, error) // Iterator returns an iterator over a domain of keys, in ascending order. The caller must call @@ -21,7 +21,7 @@ type ReadonlyStore interface { // from the first key, and a nil end iterates to the last key (inclusive). Empty keys are not // valid. // CONTRACT: No writes may happen within a domain while an iterator exists over it. - // CONTRACT: start, end readonly []byte + // CONTRACT: start, end readonly []byte. Iterator(start, end []byte) (Iterator, error) // ReverseIterator returns an iterator over a domain of keys, in descending order. The caller @@ -29,7 +29,7 @@ type ReadonlyStore interface { // iterates from the last key (inclusive), and a nil start iterates to the first key (inclusive). // Empty keys are not valid. // CONTRACT: No writes may happen within a domain while an iterator exists over it. - // CONTRACT: start, end readonly []byte + // CONTRACT: start, end readonly []byte. ReverseIterator(start, end []byte) (Iterator, error) } @@ -41,10 +41,10 @@ type Store interface { ReadonlyStore // Set sets the value for the given key, replacing it if it already exists. - // CONTRACT: key, value readonly []byte + // CONTRACT: key, value readonly []byte. Set(key, value []byte) error // Delete deletes the key, or does nothing if the key does not exist. - // CONTRACT: key readonly []byte + // CONTRACT: key readonly []byte. Delete(key []byte) error } diff --git a/orm/types/ormerrors/errors.go b/orm/types/ormerrors/errors.go index ef4dac26e035..08b4e71d055b 100644 --- a/orm/types/ormerrors/errors.go +++ b/orm/types/ormerrors/errors.go @@ -5,43 +5,43 @@ import ( "google.golang.org/grpc/codes" ) -var codespace = "orm" +var ormcodespace = "orm" // IsNotFound returns true if the error indicates that the record was not found. func IsNotFound(err error) bool { - return errors.IsOf(err, NotFound) + return errors.IsOf(err, ErrNotFound) } var ( - InvalidTableId = errors.New(codespace, 1, "invalid or missing table or single id, need a non-zero value") - MissingPrimaryKey = errors.New(codespace, 2, "table is missing primary key") - InvalidKeyFieldsDefinition = errors.New(codespace, 3, "invalid field definition for key") - DuplicateKeyField = errors.New(codespace, 4, "duplicate field in key") - FieldNotFound = errors.New(codespace, 5, "field not found") - InvalidAutoIncrementKey = errors.New(codespace, 6, "an auto-increment primary key must specify a single uint64 field") - InvalidIndexId = errors.New(codespace, 7, "invalid or missing index id, need a value >= 0 and < 32768") - DuplicateIndexId = errors.New(codespace, 8, "duplicate index id") - PrimaryKeyConstraintViolation = errors.New(codespace, 9, "object with primary key already exists") - PrimaryKeyInvalidOnUpdate = errors.New(codespace, 11, "can't update object with missing or invalid primary key") - AutoIncrementKeyAlreadySet = errors.New(codespace, 12, "can't create with auto-increment primary key already set") - CantFindIndex = errors.New(codespace, 13, "can't find index") - UnexpectedDecodePrefix = errors.New(codespace, 14, "unexpected prefix while trying to decode an entry") - UnsupportedOperation = errors.New(codespace, 16, "unsupported operation") - BadDecodeEntry = errors.New(codespace, 17, "bad decode entry") - IndexOutOfBounds = errors.New(codespace, 18, "index out of bounds") - InvalidListOptions = errors.New(codespace, 19, "invalid list options") - InvalidKeyField = errors.New(codespace, 20, "invalid key field") - UnexpectedError = errors.New(codespace, 21, "unexpected error") - InvalidRangeIterationKeys = errors.New(codespace, 22, "invalid range iteration keys") - JSONImportError = errors.New(codespace, 23, "json import error") - UniqueKeyViolation = errors.RegisterWithGRPCCode(codespace, 24, codes.FailedPrecondition, "unique key violation") - InvalidTableDefinition = errors.New(codespace, 25, "invalid table definition") - InvalidFileDescriptorID = errors.New(codespace, 26, "invalid file descriptor ID") - TableNotFound = errors.New(codespace, 27, "table not found") - JSONValidationError = errors.New(codespace, 28, "invalid JSON") - NotFound = errors.RegisterWithGRPCCode(codespace, 29, codes.NotFound, "not found") - ReadOnly = errors.New(codespace, 30, "database is read-only") - AlreadyExists = errors.RegisterWithGRPCCode(codespace, 31, codes.AlreadyExists, "already exists") - ConstraintViolation = errors.RegisterWithGRPCCode(codespace, 32, codes.FailedPrecondition, "failed precondition") - NoTableDescriptor = errors.New(codespace, 33, "no table descriptor found") + ErrInvalidTableID = errors.New(ormcodespace, 1, "invalid or missing table or single id, need a non-zero value") + ErrMissingPrimaryKey = errors.New(ormcodespace, 2, "table is missing primary key") + ErrInvalidKeyFieldsDefinition = errors.New(ormcodespace, 3, "invalid field definition for key") + ErrDuplicateKeyField = errors.New(ormcodespace, 4, "duplicate field in key") + ErrFieldNotFound = errors.New(ormcodespace, 5, "field not found") + ErrInvalidAutoIncrementKey = errors.New(ormcodespace, 6, "an auto-increment primary key must specify a single uint64 field") + ErrInvalidIndexID = errors.New(ormcodespace, 7, "invalid or missing index id, need a value >= 0 and < 32768") + ErrDuplicateIndexID = errors.New(ormcodespace, 8, "duplicate index id") + ErrPrimaryKeyConstraintViolation = errors.New(ormcodespace, 9, "object with primary key already exists") + ErrPrimaryKeyInvalidOnUpdate = errors.New(ormcodespace, 11, "can't update object with missing or invalid primary key") + ErrAutoIncrementKeyAlreadySet = errors.New(ormcodespace, 12, "can't create with auto-increment primary key already set") + ErrCantFindIndex = errors.New(ormcodespace, 13, "can't find index") + ErrUnexpectedDecodePrefix = errors.New(ormcodespace, 14, "unexpected prefix while trying to decode an entry") + ErrUnsupportedOperation = errors.New(ormcodespace, 16, "unsupported operation") + ErrBadDecodeEntry = errors.New(ormcodespace, 17, "bad decode entry") + ErrIndexOutOfBounds = errors.New(ormcodespace, 18, "index out of bounds") + ErrInvalidListOptions = errors.New(ormcodespace, 19, "invalid list options") + ErrInvalidKeyField = errors.New(ormcodespace, 20, "invalid key field") + ErrUnexpectedError = errors.New(ormcodespace, 21, "unexpected error") + ErrInvalidRangeIterationKeys = errors.New(ormcodespace, 22, "invalid range iteration keys") + ErrJSONImportError = errors.New(ormcodespace, 23, "json import error") + ErrUniqueKeyViolation = errors.RegisterWithGRPCCode(ormcodespace, 24, codes.FailedPrecondition, "unique key violation") + ErrInvalidTableDefinition = errors.New(ormcodespace, 25, "invalid table definition") + ErrInvalidFileDescriptorID = errors.New(ormcodespace, 26, "invalid file descriptor ID") + ErrTableNotFound = errors.New(ormcodespace, 27, "table not found") + ErrJSONValidationError = errors.New(ormcodespace, 28, "invalid JSON") + ErrNotFound = errors.RegisterWithGRPCCode(ormcodespace, 29, codes.NotFound, "not found") + ErrReadOnly = errors.New(ormcodespace, 30, "database is read-only") + ErrOrmAlreadyExists = errors.RegisterWithGRPCCode(ormcodespace, 31, codes.AlreadyExists, "already exists") + ErrConstraintViolation = errors.RegisterWithGRPCCode(ormcodespace, 32, codes.FailedPrecondition, "failed precondition") + ErrNoTableDescriptor = errors.New(ormcodespace, 33, "no table descriptor found") ) diff --git a/server/api/server.go b/server/api/server.go index 0f5090da1bcc..d48ef7a1a19f 100644 --- a/server/api/server.go +++ b/server/api/server.go @@ -60,7 +60,7 @@ func CustomGRPCHeaderMatcher(key string) (string, bool) { func New(clientCtx client.Context, logger log.Logger, grpcSrv *grpc.Server) *Server { // The default JSON marshaller used by the gRPC-Gateway is unable to marshal non-nullable non-scalar fields. - // Using the gogo/gateway package with the gRPC-Gateway WithMarshaler option fixes the scalar field marshalling issue. + // Using the gogo/gateway package with the gRPC-Gateway WithMarshaler option fixes the scalar field marshaling issue. marshalerOption := &gateway.JSONPb{ EmitDefaults: true, Indent: " ", @@ -77,7 +77,7 @@ func New(clientCtx client.Context, logger log.Logger, grpcSrv *grpc.Server) *Ser runtime.WithMarshalerOption(runtime.MIMEWildcard, marshalerOption), // This is necessary to get error details properly - // marshalled in unary requests. + // marshaled in unary requests. runtime.WithProtoErrorHandler(runtime.DefaultHTTPProtoErrorHandler), // Custom header matcher for mapping request headers to @@ -159,7 +159,7 @@ func (s *Server) Start(ctx context.Context, cfg config.Config) error { // the server failed to start properly. select { case <-ctx.Done(): - // The calling process cancelled or closed the provided context, so we must + // The calling process canceled or closed the provided context, so we must // gracefully stop the API server. s.logger.Info("stopping API server...", "address", cfg.API.Address) return s.Close() diff --git a/server/grpc/gogoreflection/serverreflection.go b/server/grpc/gogoreflection/serverreflection.go index ac1e3c2d0526..52b10f4f8f0c 100644 --- a/server/grpc/gogoreflection/serverreflection.go +++ b/server/grpc/gogoreflection/serverreflection.go @@ -46,7 +46,6 @@ import ( "sort" "sync" - //nolint: staticcheck "github.com/golang/protobuf/proto" dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "google.golang.org/grpc" @@ -290,8 +289,8 @@ func fileDescWithDependencies(fd *dpb.FileDescriptorProto, sentFileDescriptors m } // fileDescEncodingByFilename finds the file descriptor for given filename, -// finds all of its previously unsent transitive dependencies, does marshalling -// on them, and returns the marshalled result. +// finds all of its previously unsent transitive dependencies, does marshaling +// on them, and returns the marshaled result. func (s *serverReflectionServer) fileDescEncodingByFilename(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { enc := getFileDescriptor(name) if enc == nil { @@ -324,7 +323,7 @@ func parseMetadata(meta interface{}) ([]byte, bool) { // fileDescEncodingContainingSymbol finds the file descriptor containing the // given symbol, finds all of its previously unsent transitive dependencies, -// does marshalling on them, and returns the marshalled result. The given symbol +// does marshaling on them, and returns the marshaled result. The given symbol // can be a type, a service or a method. func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { _, symbols := s.getSymbols() @@ -349,7 +348,7 @@ func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string, s // fileDescEncodingContainingExtension finds the file descriptor containing // given extension, finds all of its previously unsent transitive dependencies, -// does marshalling on them, and returns the marshalled result. +// does marshaling on them, and returns the marshaled result. func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32, sentFileDescriptors map[string]bool) ([][]byte, error) { st, err := typeForName(typeName) if err != nil { diff --git a/server/grpc/server.go b/server/grpc/server.go index 4c809e8655ed..d133fe451f15 100644 --- a/server/grpc/server.go +++ b/server/grpc/server.go @@ -91,7 +91,7 @@ func StartGRPCServer(ctx context.Context, logger log.Logger, cfg config.GRPCConf // the server failed to start properly. select { case <-ctx.Done(): - // The calling process cancelled or closed the provided context, so we must + // The calling process canceled or closed the provided context, so we must // gracefully stop the gRPC server. logger.Info("stopping gRPC server...", "address", cfg.Address) grpcSrv.GracefulStop() diff --git a/server/mock/app.go b/server/mock/app.go index 5c977b53d21f..832d50bc76b5 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -147,7 +147,7 @@ type MsgServerImpl struct { capKeyMainStore *storetypes.KVStoreKey } -func _Msg_Test_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { //nolint:revive +func _Msg_Test_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(KVStoreTx) if err := dec(in); err != nil { return nil, err diff --git a/server/start.go b/server/start.go index 5469c1923cf0..32ea3f08d78c 100644 --- a/server/start.go +++ b/server/start.go @@ -244,7 +244,7 @@ func startStandAlone(svrCtx *Context, appCreator types.AppCreator) error { return err } - // Wait for the calling process to be cancelled or close the provided context, + // Wait for the calling process to be canceled or close the provided context, // so we can gracefully stop the ABCI server. <-ctx.Done() svrCtx.Logger.Info("stopping the ABCI server...") diff --git a/simapp/app_v2.go b/simapp/app_v2.go index 01aaaeab7313..89d77b2205ba 100644 --- a/simapp/app_v2.go +++ b/simapp/app_v2.go @@ -3,7 +3,6 @@ package simapp import ( - _ "embed" "io" "os" "path/filepath" diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 9d29ecd26e66..cbd64162fbb0 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -221,8 +221,8 @@ func addModuleInitFlags(startCmd *cobra.Command) { func genesisCommand(encodingConfig params.EncodingConfig, cmds ...*cobra.Command) *cobra.Command { cmd := genutilcli.GenesisCoreCommand(encodingConfig.TxConfig, simapp.ModuleBasics, simapp.DefaultNodeHome) - for _, sub_cmd := range cmds { - cmd.AddCommand(sub_cmd) + for _, subCmd := range cmds { + cmd.AddCommand(subCmd) } return cmd } diff --git a/simapp/upgrades.go b/simapp/upgrades.go index fac518315d08..8403bb65c8a9 100644 --- a/simapp/upgrades.go +++ b/simapp/upgrades.go @@ -36,21 +36,21 @@ func (app SimApp) RegisterUpgradeHandlers() { var keyTable paramstypes.KeyTable switch subspace.Name() { case authtypes.ModuleName: - keyTable = authtypes.ParamKeyTable() + keyTable = authtypes.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades case banktypes.ModuleName: - keyTable = banktypes.ParamKeyTable() + keyTable = banktypes.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades case stakingtypes.ModuleName: - keyTable = stakingtypes.ParamKeyTable() + keyTable = stakingtypes.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades case minttypes.ModuleName: - keyTable = minttypes.ParamKeyTable() + keyTable = minttypes.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades case distrtypes.ModuleName: - keyTable = distrtypes.ParamKeyTable() + keyTable = distrtypes.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades case slashingtypes.ModuleName: - keyTable = slashingtypes.ParamKeyTable() + keyTable = slashingtypes.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades case govtypes.ModuleName: keyTable = govv1.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades case crisistypes.ModuleName: - keyTable = crisistypes.ParamKeyTable() + keyTable = crisistypes.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades } if !subspace.HasKeyTable() { diff --git a/tests/e2e/gov/tx.go b/tests/e2e/gov/tx.go index a8e06691133a..662c593a8aff 100644 --- a/tests/e2e/gov/tx.go +++ b/tests/e2e/gov/tx.go @@ -243,7 +243,7 @@ func (s *E2ETestSuite) TestNewCmdSubmitLegacyProposal() { { "valid transaction", []string{ - fmt.Sprintf("--%s='Text Proposal'", cli.FlagTitle), //nolint:staticcheck // we are intentionally using a deprecated flag here. + fmt.Sprintf("--%s='Text Proposal'", cli.FlagTitle), fmt.Sprintf("--%s='Where is the title!?'", cli.FlagDescription), //nolint:staticcheck // we are intentionally using a deprecated flag here. fmt.Sprintf("--%s=%s", cli.FlagProposalType, v1beta1.ProposalTypeText), //nolint:staticcheck // we are intentionally using a deprecated flag here. fmt.Sprintf("--%s=%s", cli.FlagDeposit, sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(5431)).String()), diff --git a/tests/e2e/tx/service_test.go b/tests/e2e/tx/service_test.go index 30b8142479cd..3295032363d1 100644 --- a/tests/e2e/tx/service_test.go +++ b/tests/e2e/tx/service_test.go @@ -1124,7 +1124,7 @@ type protoTxProvider interface { // txBuilderToProtoTx converts a txBuilder into a proto tx.Tx. // Deprecated: It's used for testing the deprecated Simulate gRPC endpoint // using a proto Tx field and for testing the TxEncode endpoint. -func txBuilderToProtoTx(txBuilder client.TxBuilder) (*tx.Tx, error) { // nolint +func txBuilderToProtoTx(txBuilder client.TxBuilder) (*tx.Tx, error) { protoProvider, ok := txBuilder.(protoTxProvider) if !ok { return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidType, "expected proto tx builder, got %T", txBuilder) diff --git a/tests/integration/aminojson/aminojson_test.go b/tests/integration/aminojson/aminojson_test.go index 8d80bcda5ce2..fc07daf3d08a 100644 --- a/tests/integration/aminojson/aminojson_test.go +++ b/tests/integration/aminojson/aminojson_test.go @@ -294,8 +294,6 @@ var ( // upgrade genType(&upgradetypes.Plan{}, &upgradeapi.Plan{}, genOpts.WithDisallowNil()), - genType(&upgradetypes.SoftwareUpgradeProposal{}, &upgradeapi.SoftwareUpgradeProposal{}, genOpts.WithDisallowNil()), - genType(&upgradetypes.CancelSoftwareUpgradeProposal{}, &upgradeapi.CancelSoftwareUpgradeProposal{}, genOpts), genType(&upgradetypes.MsgSoftwareUpgrade{}, &upgradeapi.MsgSoftwareUpgrade{}, genOpts.WithDisallowNil()), genType(&upgradetypes.MsgCancelUpgrade{}, &upgradeapi.MsgCancelUpgrade{}, genOpts), @@ -340,12 +338,12 @@ func TestAminoJSON_Equivalence(t *testing.T) { fmt.Printf("testing %s\n", tt.pulsar.ProtoReflect().Descriptor().FullName()) rapid.Check(t, func(t *rapid.T) { // uncomment to debug; catch a panic and inspect application state - //defer func() { + // defer func() { // if r := recover(); r != nil { // //fmt.Printf("Panic: %+v\n", r) // t.FailNow() // } - //}() + // }() msg := gen.Draw(t, "msg") postFixPulsarMessage(msg) @@ -362,11 +360,11 @@ func TestAminoJSON_Equivalence(t *testing.T) { err = encCfg.Codec.Unmarshal(protoBz, gogo) require.NoError(t, err) - legacyAminoJson, err := encCfg.Amino.MarshalJSON(gogo) + legacyAminoJSON, err := encCfg.Amino.MarshalJSON(gogo) require.NoError(t, err) - aminoJson, err := aj.Marshal(msg) + aminoJSON, err := aj.Marshal(msg) require.NoError(t, err) - require.Equal(t, string(legacyAminoJson), string(aminoJson)) + require.Equal(t, string(legacyAminoJSON), string(aminoJSON)) }) }) } @@ -618,6 +616,7 @@ func TestAminoJSON_LegacyParity(t *testing.T) { require.NoError(t, err) newGogoBytes, err := encCfg.Amino.MarshalJSON(newGogo) + require.NoError(t, err) if tc.roundTripUnequal { require.NotEqual(t, string(gogoBytes), string(newGogoBytes)) return @@ -650,6 +649,7 @@ func TestSendAuthorization(t *testing.T) { require.NoError(t, err) err = proto.Unmarshal(protoBz, sanityPulsar) + require.NoError(t, err) // !!! // empty []string is not the same as nil []string. this is a bug in gogo. @@ -661,17 +661,19 @@ func TestSendAuthorization(t *testing.T) { require.NotNil(t, pulsar.SpendLimit) require.Zero(t, len(pulsar.SpendLimit)) - legacyAminoJson, err := encCfg.Amino.MarshalJSON(gogo) - aminoJson, err := aj.Marshal(sanityPulsar) + legacyAminoJSON, err := encCfg.Amino.MarshalJSON(gogo) + require.NoError(t, err) + aminoJSON, err := aj.Marshal(sanityPulsar) + require.NoError(t, err) - require.Equal(t, string(legacyAminoJson), string(aminoJson)) + require.Equal(t, string(legacyAminoJSON), string(aminoJSON)) - aminoJson, err = aj.Marshal(pulsar) + aminoJSON, err = aj.Marshal(pulsar) require.NoError(t, err) // at this point, pulsar.SpendLimit = [], and gogo.SpendLimit = nil, but they will both marshal to `[]` // this is *only* possible because of Cosmos SDK's custom MarshalJSON method for Coins - require.Equal(t, string(legacyAminoJson), string(aminoJson)) + require.Equal(t, string(legacyAminoJSON), string(aminoJSON)) } func TestDecimalMutation(t *testing.T) { @@ -695,8 +697,7 @@ func TestDecimalMutation(t *testing.T) { } func postFixPulsarMessage(msg proto.Message) { - switch m := msg.(type) { - case *authapi.ModuleAccount: + if m, ok := msg.(*authapi.ModuleAccount); ok { if m.BaseAccount == nil { m.BaseAccount = &authapi.BaseAccount{} } diff --git a/tests/integration/bank/keeper/keeper_test.go b/tests/integration/bank/keeper/keeper_test.go index 3daaa4f9a099..e9a2a1261755 100644 --- a/tests/integration/bank/keeper/keeper_test.go +++ b/tests/integration/bank/keeper/keeper_test.go @@ -1245,26 +1245,26 @@ func TestBalanceTrackingEvents(t *testing.T) { for _, e := range f.ctx.EventManager().ABCIEvents() { switch e.Type { case types.EventTypeCoinBurn: - burnedCoins, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) + burnedCoins, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) assert.NilError(t, err) supply = supply.Sub(burnedCoins...) case types.EventTypeCoinMint: - mintedCoins, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) + mintedCoins, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) assert.NilError(t, err) supply = supply.Add(mintedCoins...) case types.EventTypeCoinSpent: - coinsSpent, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) + coinsSpent, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) assert.NilError(t, err) - spender, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) + spender, err := sdk.AccAddressFromBech32(e.Attributes[0].Value) assert.NilError(t, err) balances[spender.String()] = balances[spender.String()].Sub(coinsSpent...) case types.EventTypeCoinReceived: - coinsRecv, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) + coinsRecv, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) assert.NilError(t, err) - receiver, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) + receiver, err := sdk.AccAddressFromBech32(e.Attributes[0].Value) assert.NilError(t, err) balances[receiver.String()] = balances[receiver.String()].Add(coinsRecv...) } diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index ada343cf57fb..eb2cf73b2afc 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -285,7 +285,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, false) // 600 more blocks happened - height = height + 600 + height += 600 ctx = ctx.WithBlockHeight(height) // validator added back in diff --git a/tests/integration/staking/keeper/determinstic_test.go b/tests/integration/staking/keeper/determinstic_test.go index 23fb54c81490..042882bf421e 100644 --- a/tests/integration/staking/keeper/determinstic_test.go +++ b/tests/integration/staking/keeper/determinstic_test.go @@ -88,9 +88,9 @@ func pubKeyGenerator() *rapid.Generator[ed25519.PubKey] { } func bondTypeGenerator() *rapid.Generator[stakingtypes.BondStatus] { - bond_types := []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Unbonded, stakingtypes.Unbonding} + bondTypes := []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Unbonded, stakingtypes.Unbonding} return rapid.Custom(func(t *rapid.T) stakingtypes.BondStatus { - return bond_types[rapid.IntRange(0, 2).Draw(t, "range")] + return bondTypes[rapid.IntRange(0, 2).Draw(t, "range")] }) } diff --git a/tests/integration/staking/keeper/msg_server_test.go b/tests/integration/staking/keeper/msg_server_test.go index 3ccd554d5bd9..7ab5c27e4898 100644 --- a/tests/integration/staking/keeper/msg_server_test.go +++ b/tests/integration/staking/keeper/msg_server_test.go @@ -165,7 +165,7 @@ func TestCancelUnbondingDelegation(t *testing.T) { assert.ErrorContains(t, err, testCase.expErrMsg) } else { assert.NilError(t, err) - balanceForNotBondedPool := bankKeeper.GetBalance(ctx, sdk.AccAddress(notBondedPool.GetAddress()), bondDenom) + balanceForNotBondedPool := bankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom) assert.DeepEqual(t, balanceForNotBondedPool, moduleBalance.Sub(testCase.req.Amount)) moduleBalance = moduleBalance.Sub(testCase.req.Amount) } diff --git a/tests/integration/staking/keeper/unbonding_test.go b/tests/integration/staking/keeper/unbonding_test.go index 0d0eba80ebaf..28fec367058e 100644 --- a/tests/integration/staking/keeper/unbonding_test.go +++ b/tests/integration/staking/keeper/unbonding_test.go @@ -378,7 +378,7 @@ func TestUnbondingDelegationOnHold1(t *testing.T) { notBondedAmt5 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, bondedAmt1, bondedAmt5)) - // Not bonded amount back to what it was originaly + // Not bonded amount back to what it was originally assert.Assert(math.IntEq(t, notBondedAmt1.SubRaw(1), notBondedAmt5)) } @@ -414,6 +414,6 @@ func TestUnbondingDelegationOnHold2(t *testing.T) { notBondedAmt5 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, bondedAmt1, bondedAmt5)) - // Not bonded amount back to what it was originaly + // Not bonded amount back to what it was originally assert.Assert(math.IntEq(t, notBondedAmt1.SubRaw(1), notBondedAmt5)) } diff --git a/tests/integration/staking/keeper/validator_bench_test.go b/tests/integration/staking/keeper/validator_bench_test.go index 3667987138e2..e7eb60c51216 100644 --- a/tests/integration/staking/keeper/validator_bench_test.go +++ b/tests/integration/staking/keeper/validator_bench_test.go @@ -7,7 +7,7 @@ func BenchmarkGetValidator(b *testing.B) { // panic: encoding/hex: odd length hex string powersNumber := 900 - var totalPower int64 = 0 + var totalPower int64 powers := make([]int64, powersNumber) for i := range powers { powers[i] = int64(i) diff --git a/testutil/network/util.go b/testutil/network/util.go index be118ef9512f..6b049bfe23c5 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -203,7 +203,7 @@ func writeFile(name, dir string, contents []byte) error { return fmt.Errorf("could not create directory %q: %w", dir, err) } - if err := os.WriteFile(file, contents, 0o644); err != nil { //nolint: gosec + if err := os.WriteFile(file, contents, 0o600); err != nil { return err } diff --git a/testutil/rest.go b/testutil/rest.go index 93608482d195..3a3103dcbc8b 100644 --- a/testutil/rest.go +++ b/testutil/rest.go @@ -42,7 +42,7 @@ func GetRequestWithHeaders(url string, headers map[string]string) ([]byte, error // GetRequest defines a wrapper around an HTTP GET request with a provided URL. // An error is returned if the request or reading the body fails. func GetRequest(url string) ([]byte, error) { - res, err := http.Get(url) //nolint:gosec + res, err := http.Get(url) if err != nil { return nil, err } @@ -61,7 +61,7 @@ func GetRequest(url string) ([]byte, error) { // PostRequest defines a wrapper around an HTTP POST request with a provided URL and data. // An error is returned if the request or reading the body fails. func PostRequest(url, contentType string, data []byte) ([]byte, error) { - res, err := http.Post(url, contentType, bytes.NewBuffer(data)) //nolint:gosec + res, err := http.Post(url, contentType, bytes.NewBuffer(data)) if err != nil { return nil, fmt.Errorf("error while sending post request: %w", err) } diff --git a/testutil/sims/simulation_helpers.go b/testutil/sims/simulation_helpers.go index 152703bf11ae..7c017a8144e7 100644 --- a/testutil/sims/simulation_helpers.go +++ b/testutil/sims/simulation_helpers.go @@ -68,7 +68,7 @@ func SimulationOperations(app runtime.AppI, cdc codec.JSONCodec, config simtypes } } - simState.LegacyProposalContents = app.SimulationManager().GetProposalContents(simState) //nolint:staticcheck + simState.LegacyProposalContents = app.SimulationManager().GetProposalContents(simState) //nolint:staticcheck // SA1019: simState.LegacyProposalContents is deprecated: LegacyProposalContents is deprecated simState.ProposalMsgs = app.SimulationManager().GetProposalMsgs(simState) return app.SimulationManager().WeightedOperations(simState) } diff --git a/tools/confix/cmd/diff.go b/tools/confix/cmd/diff.go index 28cd337a2f26..4dc86dbf16b1 100644 --- a/tools/confix/cmd/diff.go +++ b/tools/confix/cmd/diff.go @@ -17,11 +17,13 @@ func DiffCommand() *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { var filename string clientCtx := client.GetClientContextFromCmd(cmd) - if len(args) > 1 { + switch { + + case len(args) > 1: filename = args[1] - } else if clientCtx.HomeDir != "" { + case clientCtx.HomeDir != "": filename = fmt.Sprintf("%s/config/app.toml", clientCtx.HomeDir) - } else { + default: return fmt.Errorf("must provide a path to the app.toml file") } diff --git a/tools/confix/cmd/migrate.go b/tools/confix/cmd/migrate.go index f31425bfd3f0..18546b200f8a 100644 --- a/tools/confix/cmd/migrate.go +++ b/tools/confix/cmd/migrate.go @@ -27,11 +27,12 @@ In case of any error in updating the file, no output is written.`, RunE: func(cmd *cobra.Command, args []string) error { var filename string clientCtx := client.GetClientContextFromCmd(cmd) - if len(args) > 1 { + switch { + case len(args) > 1: filename = args[1] - } else if clientCtx.HomeDir != "" { + case clientCtx.HomeDir != "": filename = fmt.Sprintf("%s/config/app.toml", clientCtx.HomeDir) - } else { + default: return fmt.Errorf("must provide a path to the app.toml file") } diff --git a/tools/confix/diff.go b/tools/confix/diff.go index e5d1fede4e5e..9abc4cd87aff 100644 --- a/tools/confix/diff.go +++ b/tools/confix/diff.go @@ -40,19 +40,21 @@ func DiffKeys(lhs, rhs *tomledit.Document) []Diff { i, j := 0, 0 for i < len(lsec) && j < len(rsec) { - if lsec[i].Name.Before(rsec[j].Name) { + switch { + + case lsec[i].Name.Before(rsec[j].Name): diff = append(diff, Diff{Type: Section, Deleted: true, KV: KV{Key: lsec[i].Name.String()}}) for _, kv := range allKVs(lsec[i]) { diff = append(diff, Diff{Type: Mapping, Deleted: true, KV: kv}) } i++ - } else if rsec[j].Name.Before(lsec[i].Name) { + case rsec[j].Name.Before(lsec[i].Name): diff = append(diff, Diff{Type: Section, KV: KV{Key: rsec[j].Name.String()}}) for _, kv := range allKVs(rsec[j]) { diff = append(diff, Diff{Type: Mapping, KV: kv}) } j++ - } else { + default: diff = append(diff, diffDocs(allKVs(lsec[i]), allKVs(rsec[j]), false)...) i++ j++ @@ -84,13 +86,14 @@ func DiffValues(lhs, rhs *tomledit.Document) []Diff { i, j := 0, 0 for i < len(lsec) && j < len(rsec) { - if lsec[i].Name.Before(rsec[j].Name) { + switch { + case lsec[i].Name.Before(rsec[j].Name): // skip keys present in lhs but not in rhs i++ - } else if rsec[j].Name.Before(lsec[i].Name) { + case rsec[j].Name.Before(lsec[i].Name): // skip keys present in rhs but not in lhs j++ - } else { + default: for _, d := range diffDocs(allKVs(lsec[i]), allKVs(rsec[j]), true) { if !d.Deleted { diff = append(diff, d) @@ -133,13 +136,14 @@ func diffDocs(lhs, rhs []KV, value bool) []Diff { i, j := 0, 0 for i < len(lhs) && j < len(rhs) { - if lhs[i].Key < rhs[j].Key { + switch { + case lhs[i].Key < rhs[j].Key: diff = append(diff, Diff{Type: Mapping, Deleted: true, KV: lhs[i]}) i++ - } else if lhs[i].Key > rhs[j].Key { + case lhs[i].Key > rhs[j].Key: diff = append(diff, Diff{Type: Mapping, KV: rhs[j]}) j++ - } else { + default: // key exists in both lhs and rhs // if value is true, compare the values if value && lhs[i].Value != rhs[j].Value { diff --git a/tools/cosmovisor/args.go b/tools/cosmovisor/args.go index 8c61c1f1c1fb..3d8c33a1e161 100644 --- a/tools/cosmovisor/args.go +++ b/tools/cosmovisor/args.go @@ -12,7 +12,6 @@ import ( "cosmossdk.io/log" cverrors "cosmossdk.io/tools/cosmovisor/errors" - upgradekeeper "cosmossdk.io/x/upgrade/keeper" "cosmossdk.io/x/upgrade/plan" upgradetypes "cosmossdk.io/x/upgrade/types" ) @@ -303,7 +302,7 @@ func (cfg *Config) SetCurrentUpgrade(u upgradetypes.Plan) (rerr error) { } cfg.currentUpgrade = u - f, err := os.Create(filepath.Join(upgrade, upgradekeeper.UpgradeInfoFileName)) + f, err := os.Create(filepath.Join(upgrade, upgradetypes.UpgradeInfoFilename)) if err != nil { return err } @@ -327,7 +326,7 @@ func (cfg *Config) UpgradeInfo() (upgradetypes.Plan, error) { return cfg.currentUpgrade, nil } - filename := filepath.Join(cfg.Root(), currentLink, upgradekeeper.UpgradeInfoFileName) + filename := filepath.Join(cfg.Root(), currentLink, upgradetypes.UpgradeInfoFilename) _, err := os.Lstat(filename) var u upgradetypes.Plan var bz []byte diff --git a/tools/cosmovisor/args_test.go b/tools/cosmovisor/args_test.go index 805255b2e0d9..82137b6113f1 100644 --- a/tools/cosmovisor/args_test.go +++ b/tools/cosmovisor/args_test.go @@ -609,15 +609,15 @@ func (s *argsTestSuite) TestGetConfigFromEnv() { cfg, err := GetConfigFromEnv() if tc.expectedErrCount == 0 { assert.NoError(t, err) - } else { - if assert.Error(t, err) { - errCount := 1 - if multi, isMulti := err.(*errors.MultiError); isMulti { - errCount = multi.Len() - } - assert.Equal(t, tc.expectedErrCount, errCount, "error count") + } + if assert.Error(t, err) { + errCount := 1 + if multi, isMulti := err.(*errors.MultiError); isMulti { + errCount = multi.Len() } + assert.Equal(t, tc.expectedErrCount, errCount, "error count") } + assert.Equal(t, tc.expectedCfg, cfg, "config") }) } diff --git a/tools/cosmovisor/buffer_test.go b/tools/cosmovisor/buffer_test.go deleted file mode 100644 index 04dd2bb4c517..000000000000 --- a/tools/cosmovisor/buffer_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package cosmovisor_test - -import ( - "bytes" - "sync" -) - -// buffer is a thread safe bytes buffer -type buffer struct { - b bytes.Buffer - m sync.Mutex -} - -func NewBuffer() *buffer { - return &buffer{} -} - -func (b *buffer) Write(bz []byte) (int, error) { - b.m.Lock() - defer b.m.Unlock() - return b.b.Write(bz) -} - -func (b *buffer) String() string { - b.m.Lock() - defer b.m.Unlock() - return b.b.String() -} - -func (b *buffer) Reset() { - b.m.Lock() - defer b.m.Unlock() - b.b.Reset() -} diff --git a/tools/cosmovisor/cmd/cosmovisor/help_test.go b/tools/cosmovisor/cmd/cosmovisor/help_test.go index 3e31774fa22c..a11f78ccee4a 100644 --- a/tools/cosmovisor/cmd/cosmovisor/help_test.go +++ b/tools/cosmovisor/cmd/cosmovisor/help_test.go @@ -1,11 +1,6 @@ package main import ( - "fmt" - "os" - "testing" - - "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "cosmossdk.io/tools/cosmovisor" @@ -15,79 +10,6 @@ type HelpTestSuite struct { suite.Suite } -func TestHelpTestSuite(t *testing.T) { - suite.Run(t, new(HelpTestSuite)) -} - -// cosmovisorHelpEnv are some string values of environment variables used to configure Cosmovisor. -type cosmovisorHelpEnv struct { - Home string - Name string -} - -// ToMap creates a map of the cosmovisorHelpEnv where the keys are the env var names. -func (c cosmovisorHelpEnv) ToMap() map[string]string { - return map[string]string{ - cosmovisor.EnvHome: c.Home, - cosmovisor.EnvName: c.Name, - } -} - -// Set sets the field in this cosmovisorHelpEnv corresponding to the provided envVar to the given envVal. -func (c *cosmovisorHelpEnv) Set(envVar, envVal string) { - switch envVar { - case cosmovisor.EnvHome: - c.Home = envVal - case cosmovisor.EnvName: - c.Name = envVal - default: - panic(fmt.Errorf("Unknown environment variable [%s]. Ccannot set field to [%s]. ", envVar, envVal)) - } -} - -// clearEnv clears environment variables and returns what they were. -// Designed to be used like this: -// -// initialEnv := clearEnv() -// defer setEnv(nil, initialEnv) -func (s *HelpTestSuite) clearEnv() *cosmovisorHelpEnv { - s.T().Logf("Clearing environment variables.") - rv := cosmovisorHelpEnv{} - for envVar := range rv.ToMap() { - rv.Set(envVar, os.Getenv(envVar)) - s.Require().NoError(os.Unsetenv(envVar)) - } - return &rv -} - -// setEnv sets environment variables to the values provided. -// If t is not nil, and there's a problem, the test will fail immediately. -// If t is nil, problems will just be logged using s.T(). -func (s *HelpTestSuite) setEnv(t *testing.T, env *cosmovisorHelpEnv) { - if t == nil { - s.T().Logf("Restoring environment variables.") - } - for envVar, envVal := range env.ToMap() { - var err error - var msg string - if len(envVal) != 0 { - err = os.Setenv(envVar, envVal) - msg = fmt.Sprintf("setting %s to %s", envVar, envVal) - } else { - err = os.Unsetenv(envVar) - msg = fmt.Sprintf("unsetting %s", envVar) - } - switch { - case t != nil: - require.NoError(t, err, msg) - case err != nil: - s.T().Logf("error %s: %v", msg, err) - default: - s.T().Logf("done %s", msg) - } - } -} - func (s *HelpTestSuite) TestGetHelpText() { expectedPieces := []string{ "Cosmovisor", diff --git a/tools/cosmovisor/process.go b/tools/cosmovisor/process.go index bdac5c8f8e7c..dea066e041c9 100644 --- a/tools/cosmovisor/process.go +++ b/tools/cosmovisor/process.go @@ -179,7 +179,7 @@ func (l *Launcher) doPreUpgrade() error { } if err := l.executePreUpgradeCmd(); err != nil { - counter += 1 + counter++ switch err.(*exec.ExitError).ProcessState.ExitCode() { case 1: diff --git a/tools/cosmovisor/process_test.go b/tools/cosmovisor/process_test.go index 02479f77e937..6713ad380735 100644 --- a/tools/cosmovisor/process_test.go +++ b/tools/cosmovisor/process_test.go @@ -35,7 +35,7 @@ func (s *processTestSuite) TestLaunchProcess() { logger := log.NewTestLogger(s.T()).With(log.ModuleKey, "cosmosvisor") // should run the genesis binary and produce expected output - stdout, stderr := NewBuffer(), NewBuffer() + stdout, stderr := newBuffer(), newBuffer() currentBin, err := cfg.CurrentBin() require.NoError(err) require.Equal(cfg.GenesisBin(), currentBin) @@ -79,7 +79,7 @@ func (s *processTestSuite) TestLaunchProcessWithRestartDelay() { logger := log.NewTestLogger(s.T()).With(log.ModuleKey, "cosmosvisor") // should run the genesis binary and produce expected output - stdout, stderr := NewBuffer(), NewBuffer() + stdout, stderr := newBuffer(), newBuffer() currentBin, err := cfg.CurrentBin() require.NoError(err) require.Equal(cfg.GenesisBin(), currentBin) @@ -123,7 +123,7 @@ func (s *processTestSuite) TestLaunchProcessWithDownloads() { launcher, err := cosmovisor.NewLauncher(logger, cfg) require.NoError(err) - stdout, stderr := NewBuffer(), NewBuffer() + stdout, stderr := newBuffer(), newBuffer() args := []string{"some", "args", upgradeFilename} doUpgrade, err := launcher.Run(args, stdout, stderr) @@ -240,3 +240,31 @@ func TestUpgradeSkipHeights(t *testing.T) { require.Equal(h, tc.expectRes) } } + +// buffer is a thread safe bytes buffer +type buffer struct { + b bytes.Buffer + m sync.Mutex +} + +func newBuffer() *buffer { + return &buffer{} +} + +func (b *buffer) Write(bz []byte) (int, error) { + b.m.Lock() + defer b.m.Unlock() + return b.b.Write(bz) +} + +func (b *buffer) String() string { + b.m.Lock() + defer b.m.Unlock() + return b.b.String() +} + +func (b *buffer) Reset() { + b.m.Lock() + defer b.m.Unlock() + b.b.Reset() +} diff --git a/tools/rosetta/converter.go b/tools/rosetta/converter.go index f71ad03e4335..bae851966016 100644 --- a/tools/rosetta/converter.go +++ b/tools/rosetta/converter.go @@ -24,7 +24,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" - auth "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) @@ -338,8 +337,8 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] default: return nil, false case banktypes.EventTypeCoinSpent: - spender := sdk.MustAccAddressFromBech32(string(event.Attributes[0].Value)) - coins, err := sdk.ParseCoinsNormalized(string(event.Attributes[1].Value)) + spender := sdk.MustAccAddressFromBech32(event.Attributes[0].Value) + coins, err := sdk.ParseCoinsNormalized(event.Attributes[1].Value) if err != nil { panic(err) } @@ -349,8 +348,8 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] accountIdentifier = spender.String() case banktypes.EventTypeCoinReceived: - receiver := sdk.MustAccAddressFromBech32(string(event.Attributes[0].Value)) - coins, err := sdk.ParseCoinsNormalized(string(event.Attributes[1].Value)) + receiver := sdk.MustAccAddressFromBech32(event.Attributes[0].Value) + coins, err := sdk.ParseCoinsNormalized(event.Attributes[1].Value) if err != nil { panic(err) } @@ -362,7 +361,7 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] // rosetta does not have the concept of burning coins, so we need to mock // the burn as a send to an address that cannot be resolved to anything case banktypes.EventTypeCoinBurn: - coins, err := sdk.ParseCoinsNormalized(string(event.Attributes[1].Value)) + coins, err := sdk.ParseCoinsNormalized(event.Attributes[1].Value) if err != nil { panic(err) } @@ -755,7 +754,7 @@ func (c converter) SigningComponents(tx authsigning.Tx, metadata *ConstructionMe // SignerData converts the given any account to signer data func (c converter) SignerData(anyAccount *codectypes.Any) (*SignerData, error) { - var acc auth.AccountI + var acc sdk.AccountI err := c.ir.UnpackAny(anyAccount, &acc) if err != nil { return nil, crgerrs.WrapError(crgerrs.ErrCodec, err.Error()) diff --git a/tools/rosetta/lib/errors/errors_test.go b/tools/rosetta/lib/errors/errors_test.go index 1b35d6a20bcb..9782c654db6e 100644 --- a/tools/rosetta/lib/errors/errors_test.go +++ b/tools/rosetta/lib/errors/errors_test.go @@ -20,7 +20,7 @@ func TestRegisterError(t *testing.T) { registeredErrorsCount++ assert.Equal(t, len(ListErrors()), registeredErrorsCount) // re-register an error should not change anything - error = RegisterError(69, "nice!", false, "nice!") + RegisterError(69, "nice!", false, "nice!") assert.Equal(t, len(ListErrors()), registeredErrorsCount) // test sealing diff --git a/types/collections.go b/types/collections.go index 993855ac152d..bda34cd0c82d 100644 --- a/types/collections.go +++ b/types/collections.go @@ -8,7 +8,7 @@ import ( var ( // AccAddressKey follows the same semantics of collections.BytesKey. - // It just uses humanised format for the String() and EncodeJSON(). + // It just uses humanized format for the String() and EncodeJSON(). AccAddressKey collcodec.KeyCodec[AccAddress] = genericAddressKey[AccAddress]{ stringDecoder: AccAddressFromBech32, keyType: "sdk.AccAddress", diff --git a/types/errors/errors.go b/types/errors/errors.go index 7e4c42bb76b4..5e17f2df481a 100644 --- a/types/errors/errors.go +++ b/types/errors/errors.go @@ -52,7 +52,7 @@ var ( // ErrNoSignatures to doc ErrNoSignatures = errorsmod.Register(RootCodespace, 15, "no signatures supplied") - // ErrJSONMarshal defines an ABCI typed JSON marshalling error + // ErrJSONMarshal defines an ABCI typed JSON marshaling error ErrJSONMarshal = errorsmod.Register(RootCodespace, 16, "failed to marshal JSON bytes") // ErrJSONUnmarshal defines an ABCI typed JSON unmarshalling error diff --git a/types/query/collections_pagination.go b/types/query/collections_pagination.go index 065564e3e30e..ae1819332069 100644 --- a/types/query/collections_pagination.go +++ b/types/query/collections_pagination.go @@ -26,7 +26,7 @@ type Collection[K, V any] interface { KeyCodec() collcodec.KeyCodec[K] } -// CollectionPaginate follows the same behaviour as Paginate but works on a Collection. +// CollectionPaginate follows the same behavior as Paginate but works on a Collection. func CollectionPaginate[K, V any, C Collection[K, V]]( ctx context.Context, coll C, @@ -87,7 +87,7 @@ func CollectionFilteredPaginate[K, V any, C Collection[K, V]]( } else { results, pageRes, err = collFilteredPaginateNoKey(ctx, coll, prefix, reverse, offset, limit, countTotal, predicateFunc) } - // invalid iter error is ignored to retain Paginate behaviour + // invalid iter error is ignored to retain Paginate behavior if errors.Is(err, collections.ErrInvalidIterator) { return results, pageRes, nil } diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 79d485f25eed..dd6d2dd5a149 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -1454,7 +1454,7 @@ func TestAnteHandlerReCheck(t *testing.T) { tx, err = suite.CreateTestTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), signing.SignMode_SIGN_MODE_DIRECT) require.NoError(t, err) txBytes, err := json.Marshal(tx) - require.Nil(t, err, "Error marshalling tx: %v", err) + require.Nil(t, err, "Error marshaling tx: %v", err) suite.ctx = suite.ctx.WithTxBytes(txBytes) // require that state machine param-dependent checking is still run on recheck since parameters can change between check and recheck diff --git a/x/auth/ante/setup_test.go b/x/auth/ante/setup_test.go index a8644c46badc..67c408218af1 100644 --- a/x/auth/ante/setup_test.go +++ b/x/auth/ante/setup_test.go @@ -82,7 +82,7 @@ func TestRecoverPanic(t *testing.T) { require.Equal(t, gasLimit, newCtx.GasMeter().Limit()) antehandler = sdk.ChainAnteDecorators(sud, PanicDecorator{}) - require.Panics(t, func() { antehandler(suite.ctx, tx, false) }, "Recovered from non-Out-of-Gas panic") //nolint:errcheck + require.Panics(t, func() { antehandler(suite.ctx, tx, false) }, "Recovered from non-Out-of-Gas panic") } type OutOfGasDecorator struct{} diff --git a/x/auth/module.go b/x/auth/module.go index 4c0703b2b05f..b9227bbc56fa 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -210,8 +210,7 @@ func ProvideAddressCodec(config *modulev1.Module) address.Codec { return codecaddress.NewBech32Codec(config.Bech32Prefix) } -//nolint:revive -type AuthInputs struct { +type Inputs struct { depinject.In Config *modulev1.Module @@ -225,15 +224,14 @@ type AuthInputs struct { LegacySubspace exported.Subspace `optional:"true"` } -//nolint:revive -type AuthOutputs struct { +type Outputs struct { depinject.Out AccountKeeper keeper.AccountKeeper Module appmodule.AppModule } -func ProvideModule(in AuthInputs) AuthOutputs { +func ProvideModule(in Inputs) Outputs { maccPerms := map[string][]string{} for _, permission := range in.Config.ModuleAccountPermissions { maccPerms[permission.Account] = permission.Permissions @@ -256,5 +254,5 @@ func ProvideModule(in AuthInputs) AuthOutputs { k := keeper.NewAccountKeeper(in.Cdc, in.StoreService, in.AccountI, maccPerms, in.Config.Bech32Prefix, authority.String()) m := NewAppModule(in.Cdc, k, in.RandomGenesisAccountsFn, in.LegacySubspace) - return AuthOutputs{AccountKeeper: k, Module: m} + return Outputs{AccountKeeper: k, Module: m} } diff --git a/x/auth/simulation/proposals.go b/x/auth/simulation/proposals.go index 87746569c22f..0e7cd95797f3 100644 --- a/x/auth/simulation/proposals.go +++ b/x/auth/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/auth/tx/config/config.go b/x/auth/tx/config/config.go index 346c9d0eebd8..103c0412b36d 100644 --- a/x/auth/tx/config/config.go +++ b/x/auth/tx/config/config.go @@ -24,8 +24,7 @@ func init() { ) } -//nolint:revive -type TxInputs struct { +type Inputs struct { depinject.In Config *txconfigv1.Config @@ -41,15 +40,14 @@ type TxInputs struct { CustomSignModeHandlers func() []signing.SignModeHandler `optional:"true"` } -//nolint:revive -type TxOutputs struct { +type Outputs struct { depinject.Out TxConfig client.TxConfig BaseAppOption runtime.BaseAppOption } -func ProvideModule(in TxInputs) TxOutputs { +func ProvideModule(in Inputs) Outputs { textual, err := NewTextualWithBankKeeper(in.TxBankKeeper) if err != nil { panic(err) @@ -100,10 +98,10 @@ func ProvideModule(in TxInputs) TxOutputs { app.SetTxEncoder(txConfig.TxEncoder()) } - return TxOutputs{TxConfig: txConfig, BaseAppOption: baseAppOption} + return Outputs{TxConfig: txConfig, BaseAppOption: baseAppOption} } -func newAnteHandler(txConfig client.TxConfig, in TxInputs) (sdk.AnteHandler, error) { +func newAnteHandler(txConfig client.TxConfig, in Inputs) (sdk.AnteHandler, error) { if in.BankKeeper == nil { return nil, fmt.Errorf("both AccountKeeper and BankKeeper are required") } diff --git a/x/auth/types/credentials.go b/x/auth/types/credentials.go index 83cd63dd2982..4c63fc8d8c41 100644 --- a/x/auth/types/credentials.go +++ b/x/auth/types/credentials.go @@ -27,7 +27,6 @@ func NewBaseAccountWithPubKey(pubkey cryptotypes.PubKey) (*BaseAccount, error) { return baseAccount, nil } -//nolint:gosec // this isn't an hardcoded credential const ModuleCredentialType = "ModuleCredential" var _ cryptotypes.PubKey = &ModuleCredential{} diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index 33fe08dea025..6cb1f39b887e 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -27,9 +27,9 @@ var ( // Simulation operation weights constants const ( - OpWeightMsgGrant = "op_weight_msg_grant" //nolint:gosec - OpWeightRevoke = "op_weight_msg_revoke" //nolint:gosec - OpWeightExec = "op_weight_msg_execute" //nolint:gosec + OpWeightMsgGrant = "op_weight_msg_grant" + OpWeightRevoke = "op_weight_msg_revoke" + OpWeightExec = "op_weight_msg_execute" ) // authz operations weights diff --git a/x/bank/simulation/genesis_test.go b/x/bank/simulation/genesis_test.go index 76be7256f84d..301596af9eb0 100644 --- a/x/bank/simulation/genesis_test.go +++ b/x/bank/simulation/genesis_test.go @@ -43,7 +43,7 @@ func TestRandomizedGenState(t *testing.T) { simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &bankGenesis) assert.Equal(t, true, bankGenesis.Params.GetDefaultSendEnabled(), "Params.GetDefaultSendEnabled") - assert.Len(t, bankGenesis.Params.GetSendEnabled(), 0, "Params.GetSendEnabled") //nolint:staticcheck + assert.Len(t, bankGenesis.Params.GetSendEnabled(), 0, "Params.GetSendEnabled") if assert.Len(t, bankGenesis.Balances, 3) { assert.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", bankGenesis.Balances[2].GetAddress().String(), "Balances[2] address") assert.Equal(t, "1000stake", bankGenesis.Balances[2].GetCoins().String(), "Balances[2] coins") diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 3f7a1b024d91..5d5037a2b858 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -18,10 +18,10 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgSend = "op_weight_msg_send" //nolint:gosec - OpWeightMsgMultiSend = "op_weight_msg_multisend" //nolint:gosec - DefaultWeightMsgSend = 100 // from simappparams.DefaultWeightMsgSend - DefaultWeightMsgMultiSend = 10 // from simappparams.DefaultWeightMsgMultiSend + OpWeightMsgSend = "op_weight_msg_send" + OpWeightMsgMultiSend = "op_weight_msg_multisend" + DefaultWeightMsgSend = 100 // from simappparams.DefaultWeightMsgSend + DefaultWeightMsgMultiSend = 10 // from simappparams.DefaultWeightMsgMultiSend ) // WeightedOperations returns all the operations from the module with their respective weights diff --git a/x/bank/simulation/proposals.go b/x/bank/simulation/proposals.go index 5a63b8632cea..3843b5f2566a 100644 --- a/x/bank/simulation/proposals.go +++ b/x/bank/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/bank/simulation/proposals_test.go b/x/bank/simulation/proposals_test.go index cc9ca7e55c08..a747b9bb2823 100644 --- a/x/bank/simulation/proposals_test.go +++ b/x/bank/simulation/proposals_test.go @@ -39,6 +39,6 @@ func TestProposalMsgs(t *testing.T) { fmt.Println(msgUpdateParams) assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) - assert.Assert(t, len(msgUpdateParams.Params.SendEnabled) == 0) //nolint:staticcheck + assert.Assert(t, len(msgUpdateParams.Params.SendEnabled) == 0) assert.Equal(t, true, msgUpdateParams.Params.DefaultSendEnabled) } diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 3eb9f2b03c7d..f840171f3c96 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -121,7 +121,7 @@ func (k Keeper) CalculateDelegationRewards(ctx sdk.Context, val stakingtypes.Val // // A small amount of this error is tolerated and corrected for, // however any greater amount should be considered a breach in expected - // behaviour. + // behavior. marginOfErr := sdk.SmallestDec().MulInt64(3) if stake.LTE(currentStake.Add(marginOfErr)) { stake = currentStake diff --git a/x/distribution/simulation/genesis_test.go b/x/distribution/simulation/genesis_test.go index 14d4a067807f..2af03304393e 100644 --- a/x/distribution/simulation/genesis_test.go +++ b/x/distribution/simulation/genesis_test.go @@ -42,8 +42,6 @@ func TestRandomizedGenState(t *testing.T) { dec1, _ := sdk.NewDecFromStr("0.210000000000000000") - require.Equal(t, sdk.ZeroDec(), distrGenesis.Params.BaseProposerReward) //nolint:staticcheck - require.Equal(t, sdk.ZeroDec(), distrGenesis.Params.BonusProposerReward) //nolint:staticcheck require.Equal(t, dec1, distrGenesis.Params.CommunityTax) require.Equal(t, true, distrGenesis.Params.WithdrawAddrEnabled) require.Len(t, distrGenesis.DelegatorStartingInfos, 0) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 40165a31798a..0a97faf3a189 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -19,10 +19,10 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" //nolint:gosec - OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" //nolint:gosec - OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" //nolint:gosec - OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool" //nolint:gosec + OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" + OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" + OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" + OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool" DefaultWeightMsgSetWithdrawAddress int = 50 DefaultWeightMsgWithdrawDelegationReward int = 50 diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index 6330691afc26..858fa09e5607 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 50 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/genutil/types/genesis_test.go b/x/genutil/types/genesis_test.go index 811c285cee4a..245568855717 100644 --- a/x/genutil/types/genesis_test.go +++ b/x/genutil/types/genesis_test.go @@ -62,7 +62,7 @@ func TestAppGenesis_ValidGenesis(t *testing.T) { assert.NilError(t, err) assert.DeepEqual(t, appGenesis.Consensus.Params, genesis.Consensus.Params) - // validate marshalling of app genesis + // validate marshaling of app genesis rawAppGenesis, err = json.Marshal(&appGenesis) assert.NilError(t, err) golden.Assert(t, string(rawAppGenesis), "app_genesis.json") diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 8bbd30220e18..6ee7ca4a6541 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -35,7 +35,7 @@ func (p Proposer) String() string { // QueryVotesByTxQuery will query for votes via a direct txs tags query. It // will fetch and build votes directly from the returned txs and returns a JSON -// marshalled result or any error that occurred. +// marshaled result or any error that occurred. func QueryVotesByTxQuery(clientCtx client.Context, params v1.QueryProposalVotesParams) ([]byte, error) { var ( votes []*v1.Vote diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index 458836cd8bb1..5539db456a71 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -141,8 +141,8 @@ func TestGetPaginatedVotes(t *testing.T) { tc := tc t.Run(tc.description, func(t *testing.T) { - marshalled := make([]cmttypes.Tx, len(tc.msgs)) - cli := TxSearchMock{txs: marshalled, txConfig: encCfg.TxConfig} + marshaled := make([]cmttypes.Tx, len(tc.msgs)) + cli := TxSearchMock{txs: marshaled, txConfig: encCfg.TxConfig} clientCtx := client.Context{}. WithLegacyAmino(encCfg.Amino). WithClient(cli). @@ -155,7 +155,7 @@ func TestGetPaginatedVotes(t *testing.T) { tx, err := clientCtx.TxConfig.TxEncoder()(txBuilder.GetTx()) require.NoError(t, err) - marshalled[i] = tx + marshaled[i] = tx } params := v1.NewQueryProposalVotesParams(0, tc.page, tc.limit) diff --git a/x/gov/keeper/grpc_query.go b/x/gov/keeper/grpc_query.go index 24e79cde19c2..d1ed9ddbc0f9 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -170,7 +170,7 @@ func (q Keeper) Params(c context.Context, req *v1.QueryParamsRequest) (*v1.Query response := &v1.QueryParamsResponse{} - //nolint:staticcheck + //nolint:staticcheck // needed for legacy parameters switch req.ParamsType { case v1.ParamDeposit: depositParams := v1.NewDepositParams(params.MinDeposit, params.MaxDepositPeriod) @@ -381,7 +381,7 @@ func (q legacyQueryServer) Votes(c context.Context, req *v1beta1.QueryVotesReque }, nil } -//nolint:staticcheck +//nolint:staticcheck // this is needed for legacy param support func (q legacyQueryServer) Params(c context.Context, req *v1beta1.QueryParamsRequest) (*v1beta1.QueryParamsResponse, error) { resp, err := q.keeper.Params(c, &v1.QueryParamsRequest{ ParamsType: req.ParamsType, diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index 028b071a65ff..f839eda2708e 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -73,7 +73,7 @@ func (suite *KeeperTestSuite) reset() { } func TestIncrementProposalNumber(t *testing.T) { - govKeeper, _, _, _, _, _, ctx := setupGovKeeper(t) //nolint:dogsled + govKeeper, _, _, _, _, _, ctx := setupGovKeeper(t) tp := TestProposal _, err := govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) @@ -93,7 +93,7 @@ func TestIncrementProposalNumber(t *testing.T) { } func TestProposalQueues(t *testing.T) { - govKeeper, _, _, _, _, _, ctx := setupGovKeeper(t) //nolint:dogsled + govKeeper, _, _, _, _, _, ctx := setupGovKeeper(t) // create test proposals tp := TestProposal diff --git a/x/gov/keeper/msg_server_test.go b/x/gov/keeper/msg_server_test.go index 8dfe414def81..b67943e0f764 100644 --- a/x/gov/keeper/msg_server_test.go +++ b/x/gov/keeper/msg_server_test.go @@ -962,7 +962,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "invalid quorum", input: func() *v1.MsgUpdateParams { params1 := params - params1.Quorum = "abc" //nolint:goconst + params1.Quorum = "abc" return &v1.MsgUpdateParams{ Authority: authority, @@ -976,7 +976,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "negative quorum", input: func() *v1.MsgUpdateParams { params1 := params - params1.Quorum = "-0.1" //nolint:goconst + params1.Quorum = "-0.1" return &v1.MsgUpdateParams{ Authority: authority, diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 4ea36900e787..caf21dbc346b 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -30,7 +30,7 @@ var ( // Simulation operation weights constants // -//nolint:gosec // these are not hard-coded credentials. + const ( OpWeightMsgDeposit = "op_weight_msg_deposit" OpWeightMsgVote = "op_weight_msg_vote" diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index 6293d9815e87..d0b85dfdc7ed 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -37,7 +37,7 @@ import ( var ( _ simtypes.WeightedProposalMsg = MockWeightedProposals{} - _ simtypes.WeightedProposalContent = MockWeightedProposals{} //nolint:staticcheck + _ simtypes.WeightedProposalContent = MockWeightedProposals{} //nolint:staticcheck // testing legacy code path ) type MockWeightedProposals struct { @@ -58,8 +58,8 @@ func (m MockWeightedProposals) MsgSimulatorFn() simtypes.MsgSimulatorFn { } } -func (m MockWeightedProposals) ContentSimulatorFn() simtypes.ContentSimulatorFn { //nolint:staticcheck - return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { //nolint:staticcheck +func (m MockWeightedProposals) ContentSimulatorFn() simtypes.ContentSimulatorFn { //nolint:staticcheck // testing legacy code path + return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { //nolint:staticcheck // testing legacy code path return v1beta1.NewTextProposal( fmt.Sprintf("title-%d: %s", m.n, simtypes.RandStringOfLength(r, 100)), fmt.Sprintf("description-%d: %s", m.n, simtypes.RandStringOfLength(r, 4000)), @@ -75,8 +75,8 @@ func mockWeightedProposalMsg(n int) []simtypes.WeightedProposalMsg { return wpc } -func mockWeightedLegacyProposalContent(n int) []simtypes.WeightedProposalContent { //nolint:staticcheck - wpc := make([]simtypes.WeightedProposalContent, n) //nolint:staticcheck +func mockWeightedLegacyProposalContent(n int) []simtypes.WeightedProposalContent { //nolint:staticcheck // testing legacy code path + wpc := make([]simtypes.WeightedProposalContent, n) //nolint:staticcheck // testing legacy code path for i := 0; i < n; i++ { wpc[i] = MockWeightedProposals{i} } diff --git a/x/group/internal/orm/primary_key_property_test.go b/x/group/internal/orm/primary_key_property_test.go index 7a40cf8c2dc5..0149531af301 100644 --- a/x/group/internal/orm/primary_key_property_test.go +++ b/x/group/internal/orm/primary_key_property_test.go @@ -18,7 +18,7 @@ func TestPrimaryKeyTable(t *testing.T) { } // primaryKeyMachine is a state machine model of the PrimaryKeyTable. The state -// is modelled as a map of strings to TableModels. +// is modeled as a map of strings to TableModels. type primaryKeyMachine struct { store storetypes.KVStore table *PrimaryKeyTable diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index 9b19fd692f46..34592cec8c64 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -42,7 +42,7 @@ var ( // Simulation operation weights constants // -//nolint:gosec // these are not hardcoded credentials. + const ( OpMsgCreateGroup = "op_weight_msg_create_group" OpMsgUpdateGroupAdmin = "op_weight_msg_update_group_admin" diff --git a/x/mint/simulation/proposals.go b/x/mint/simulation/proposals.go index 129658adcf22..0ecf4a5591d1 100644 --- a/x/mint/simulation/proposals.go +++ b/x/mint/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/params/keeper/keeper_test.go b/x/params/keeper/keeper_test.go index e9863c7c5e2d..4abc039932e1 100644 --- a/x/params/keeper/keeper_test.go +++ b/x/params/keeper/keeper_test.go @@ -153,7 +153,7 @@ func indirect(ptr interface{}) interface{} { } func TestGetSubspaces(t *testing.T) { - _, _, _, _, keeper := testComponents() //nolint:dogsled + _, _, _, _, keeper := testComponents() table := types.NewKeyTable( types.NewParamSetPair([]byte("string"), "", validateNoOp), diff --git a/x/params/module.go b/x/params/module.go index 867a8735aa33..19ec02c49307 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -120,8 +120,7 @@ func init() { )) } -//nolint:revive -type ParamsInputs struct { +type Inputs struct { depinject.In KvStoreKey *store.KVStoreKey @@ -130,8 +129,7 @@ type ParamsInputs struct { LegacyAmino *codec.LegacyAmino } -//nolint:revive -type ParamsOutputs struct { +type Outputs struct { depinject.Out ParamsKeeper keeper.Keeper @@ -139,13 +137,13 @@ type ParamsOutputs struct { GovHandler govv1beta1.HandlerRoute } -func ProvideModule(in ParamsInputs) ParamsOutputs { +func ProvideModule(in Inputs) Outputs { k := keeper.NewKeeper(in.Cdc, in.LegacyAmino, in.KvStoreKey, in.TransientStoreKey) m := NewAppModule(k) govHandler := govv1beta1.HandlerRoute{RouteKey: proposal.RouterKey, Handler: NewParamChangeProposalHandler(k)} - return ParamsOutputs{ParamsKeeper: k, Module: m, GovHandler: govHandler} + return Outputs{ParamsKeeper: k, Module: m, GovHandler: govHandler} } type SubspaceInputs struct { diff --git a/x/params/proposal_handler_test.go b/x/params/proposal_handler_test.go index aa06e18725a1..5b36ea9f067e 100644 --- a/x/params/proposal_handler_test.go +++ b/x/params/proposal_handler_test.go @@ -40,7 +40,7 @@ func (suite *HandlerTestSuite) SetupTest() { ctx := testutil.DefaultContext(key, tkey) paramsKeeper := keeper.NewKeeper(encodingCfg.Codec, encodingCfg.Amino, key, tkey) - paramsKeeper.Subspace("staking").WithKeyTable(stakingtypes.ParamKeyTable()) + paramsKeeper.Subspace("staking").WithKeyTable(stakingtypes.ParamKeyTable()) //nolint:staticcheck // TODO: depreacte this test case ctrl := gomock.NewController(suite.T()) stakingKeeper := paramstestutil.NewMockStakingKeeper(ctrl) stakingKeeper.EXPECT().MaxValidators(ctx).Return(uint32(1)) diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index 30b8f8434794..9f49b9102421 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -12,8 +12,6 @@ const ( ) // ProposalContents defines the module weighted proposals' contents -// -//nolint:staticcheck func ProposalContents(paramChanges []simtypes.LegacyParamChange) []simtypes.WeightedProposalContent { return []simtypes.WeightedProposalContent{ simulation.NewWeightedProposalContent( diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index ac2b4951f456..bb8c84477cb4 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -154,7 +154,7 @@ func (suite *SubspaceTestSuite) TestModified() { func (suite *SubspaceTestSuite) TestUpdate() { suite.Require().Panics(func() { - suite.ss.Update(suite.ctx, []byte("invalid_key"), nil) //nolint:errcheck + suite.ss.Update(suite.ctx, []byte("invalid_key"), nil) }) t := time.Hour * 48 diff --git a/x/simulation/mock_cometbft.go b/x/simulation/mock_cometbft.go index 166cf40a87d7..7e72a1ae8d91 100644 --- a/x/simulation/mock_cometbft.go +++ b/x/simulation/mock_cometbft.go @@ -69,7 +69,7 @@ func (vals mockValidators) randomProposer(r *rand.Rand) []byte { proposer := vals[key].val pk, err := cryptoenc.PubKeyFromProto(proposer.PubKey) - if err != nil { //nolint:wsl + if err != nil { panic(err) } diff --git a/x/simulation/params.go b/x/simulation/params.go index 4ac7fac95099..7837fc294f3e 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -149,8 +149,6 @@ func (w WeightedProposalMsg) MsgSimulatorFn() simulation.MsgSimulatorFn { // Legacy Proposal Content // WeightedProposalContent defines a common struct for proposal content defined by external modules (i.e outside gov) -// -//nolint:staticcheck type WeightedProposalContent struct { appParamsKey string // key used to retrieve the value of the weight from the simulation application params defaultWeight int // default weight @@ -169,7 +167,7 @@ func (w WeightedProposalContent) DefaultWeight() int { return w.defaultWeight } -func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { //nolint:staticcheck +func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { return w.contentSimulatorFn } diff --git a/x/simulation/params_test.go b/x/simulation/params_test.go index 496454142c45..9660d8ce2779 100644 --- a/x/simulation/params_test.go +++ b/x/simulation/params_test.go @@ -30,7 +30,7 @@ func TestNewWeightedProposalContent(t *testing.T) { key := "theKey" weight := 1 content := &testContent{} - f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { //nolint:staticcheck + f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { return content } diff --git a/x/slashing/keeper/genesis_test.go b/x/slashing/keeper/genesis_test.go index 5aea8f4204e5..3db4d79b580d 100644 --- a/x/slashing/keeper/genesis_test.go +++ b/x/slashing/keeper/genesis_test.go @@ -42,11 +42,11 @@ func (s *KeeperTestSuite) TestExportAndInitGenesis() { newInfo1, _ := keeper.GetValidatorSigningInfo(ctx, consAddr1) require.NotEqual(info1, newInfo1) - // Initialise genesis with genesis state before tombstone + // Initialize genesis with genesis state before tombstone s.stakingKeeper.EXPECT().IterateValidators(ctx, gomock.Any()).Return() keeper.InitGenesis(ctx, s.stakingKeeper, genesisState) - // Validator isTombstoned should return false as GenesisState is initialised + // Validator isTombstoned should return false as GenesisState is initialized ok = keeper.IsTombstoned(ctx, consAddr1) require.False(ok) diff --git a/x/slashing/module.go b/x/slashing/module.go index 7374e27ab075..7d8ccb86e2b1 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -212,7 +212,6 @@ func init() { ) } -//nolint:revive type SlashingInputs struct { depinject.In @@ -229,7 +228,6 @@ type SlashingInputs struct { LegacySubspace exported.Subspace } -//nolint:revive type SlashingOutputs struct { depinject.Out diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index 974defe4a258..599814c44cd6 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -17,7 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing/types" ) -//nolint:deadcode,varcheck var ( delPk1 = ed25519.GenPrivKey().PubKey() delAddr1 = sdk.AccAddress(delPk1.Address()) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 41649e2793d1..9937665aaf6c 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -19,7 +19,7 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgUnjail = "op_weight_msg_unjail" //nolint:gosec + OpWeightMsgUnjail = "op_weight_msg_unjail" DefaultWeightMsgUnjail = 100 ) diff --git a/x/slashing/simulation/proposals.go b/x/slashing/simulation/proposals.go index 6c17b9c44a0a..86b5d5a532d8 100644 --- a/x/slashing/simulation/proposals.go +++ b/x/slashing/simulation/proposals.go @@ -15,7 +15,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/slashing/types/expected_keepers.go b/x/slashing/types/expected_keepers.go index d3a856769f1b..ba7a34c58ac5 100644 --- a/x/slashing/types/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -42,7 +42,7 @@ type StakingKeeper interface { Validator(sdk.Context, sdk.ValAddress) stakingtypes.ValidatorI // get a particular validator by operator address ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI // get a particular validator by consensus address - // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction + // slash the validator and delegators of the validator, specifying offense height, offense power, and slash fraction Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) math.Int SlashWithInfractionReason(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec, stakingtypes.Infraction) math.Int Jail(sdk.Context, sdk.ConsAddress) // jail a validator diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index 416e9b3077f9..db8dc4c489d0 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -18,8 +18,6 @@ var ( ) // NewMsgUnjail creates a new MsgUnjail instance -// -//nolint:interfacer func NewMsgUnjail(validatorAddr sdk.ValAddress) *MsgUnjail { return &MsgUnjail{ ValidatorAddr: validatorAddr.String(), diff --git a/x/slashing/types/signing_info.go b/x/slashing/types/signing_info.go index 27ed54e0b819..8e9519d51dec 100644 --- a/x/slashing/types/signing_info.go +++ b/x/slashing/types/signing_info.go @@ -8,8 +8,6 @@ import ( ) // NewValidatorSigningInfo creates a new ValidatorSigningInfo instance -// -//nolint:interfacer func NewValidatorSigningInfo( consAddr sdk.ConsAddress, startHeight, indexOffset int64, jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64, diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 5093688b5bb9..acea5c37871b 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -57,7 +57,7 @@ func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegati // GetValidatorDelegations returns all delegations to a specific validator. // Useful for querier. -func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { //nolint:interfacer +func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { store := ctx.KVStore(k.storeKey) iterator := storetypes.KVStorePrefixIterator(store, types.DelegationKey) diff --git a/x/staking/module.go b/x/staking/module.go index 9674998406dd..87b1204f2bdf 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -205,7 +205,6 @@ func init() { ) } -//nolint:revive type StakingInputs struct { depinject.In @@ -220,8 +219,6 @@ type StakingInputs struct { } // Dependency Injection Outputs -// -//nolint:revive type StakingOutputs struct { depinject.Out diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 18794553b037..ecfb01f2feb0 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -18,7 +18,7 @@ import ( // Simulation operation weights constants // -//nolint:gosec // these are not hardcoded credentials + const ( DefaultWeightMsgCreateValidator int = 100 DefaultWeightMsgEditValidator int = 5 diff --git a/x/staking/simulation/proposals.go b/x/staking/simulation/proposals.go index 6b1f43128247..5ef5fc7a13bc 100644 --- a/x/staking/simulation/proposals.go +++ b/x/staking/simulation/proposals.go @@ -15,7 +15,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index f993d9dc28e8..3fd63b261648 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -14,8 +14,6 @@ import ( var _ DelegationI = Delegation{} // NewDelegation creates a new delegation object -// -//nolint:interfacer func NewDelegation(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, shares sdk.Dec) Delegation { return Delegation{ DelegatorAddress: delegatorAddr.String(), @@ -115,8 +113,6 @@ func UnmarshalUBDE(cdc codec.BinaryCodec, value []byte) (ubd UnbondingDelegation } // NewUnbondingDelegation - create a new unbonding delegation object -// -//nolint:interfacer func NewUnbondingDelegation( delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, creationHeight int64, minTime time.Time, balance math.Int, id uint64, @@ -213,7 +209,6 @@ func (e RedelegationEntry) OnHold() bool { return e.UnbondingOnHoldRefCount > 0 } -//nolint:interfacer func NewRedelegation( delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, creationHeight int64, minTime time.Time, balance math.Int, sharesDst sdk.Dec, id uint64, @@ -311,8 +306,6 @@ func (d DelegationResponses) String() (out string) { } // NewRedelegationResponse crates a new RedelegationEntryResponse instance. -// -//nolint:interfacer func NewRedelegationResponse( delegatorAddr sdk.AccAddress, validatorSrc, validatorDst sdk.ValAddress, entries []RedelegationEntryResponse, ) RedelegationResponse { diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index e6e44ba3c777..12c43cc80008 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -61,7 +61,7 @@ type ValidatorSet interface { TotalBondedTokens(sdk.Context) math.Int // total bonded tokens within the validator set StakingTokenSupply(sdk.Context) math.Int // total staking token supply - // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction + // slash the validator and delegators of the validator, specifying offense height, offense power, and slash fraction Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) math.Int SlashWithInfractionReason(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec, Infraction) math.Int Jail(sdk.Context, sdk.ConsAddress) // jail a validator diff --git a/x/staking/types/historical_info_test.go b/x/staking/types/historical_info_test.go index f463111d777e..90b4872733a8 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -37,7 +37,7 @@ func TestHistoricalInfo(t *testing.T) { require.NotPanics(t, func() { value = legacy.Cdc.MustMarshal(&hi) }) - require.NotNil(t, value, "Marshalled HistoricalInfo is nil") + require.NotNil(t, value, "Marshaled HistoricalInfo is nil") recv, err := types.UnmarshalHistoricalInfo(codec.NewAminoCodec(legacy.Cdc), value) require.Nil(t, err, "Unmarshalling HistoricalInfo failed") @@ -59,9 +59,7 @@ func TestValidateBasic(t *testing.T) { // Ensure validators are not sorted for sort.IsSorted(types.Validators(validators)) { rand.Shuffle(len(validators), func(i, j int) { - it := validators[i] //nolint:gocritic - validators[i] = validators[j] - validators[j] = it + validators[i], validators[j] = validators[j], validators[i] }) } hi = types.HistoricalInfo{ diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 1cd7767266aa..5a8a765020e3 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -33,7 +33,7 @@ var ( // NewMsgCreateValidator creates a new MsgCreateValidator instance. // Delegator address and validator address are the same. func NewMsgCreateValidator( - valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, //nolint:interfacer + valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation math.Int, ) (*MsgCreateValidator, error) { var pkAny *codectypes.Any @@ -120,8 +120,6 @@ func (msg MsgCreateValidator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) } // NewMsgEditValidator creates a new MsgEditValidator instance -// -//nolint:interfacer func NewMsgEditValidator(valAddr sdk.ValAddress, description Description, newRate *sdk.Dec, newMinSelfDelegation *math.Int) *MsgEditValidator { return &MsgEditValidator{ Description: description, @@ -170,8 +168,6 @@ func (msg MsgEditValidator) ValidateBasic() error { } // NewMsgDelegate creates a new MsgDelegate instance. -// -//nolint:interfacer func NewMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) *MsgDelegate { return &MsgDelegate{ DelegatorAddress: delAddr.String(), @@ -212,8 +208,6 @@ func (msg MsgDelegate) ValidateBasic() error { } // NewMsgBeginRedelegate creates a new MsgBeginRedelegate instance. -// -//nolint:interfacer func NewMsgBeginRedelegate( delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, amount sdk.Coin, ) *MsgBeginRedelegate { @@ -260,8 +254,6 @@ func (msg MsgBeginRedelegate) ValidateBasic() error { } // NewMsgUndelegate creates a new MsgUndelegate instance. -// -//nolint:interfacer func NewMsgUndelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) *MsgUndelegate { return &MsgUndelegate{ DelegatorAddress: delAddr.String(), @@ -302,8 +294,6 @@ func (msg MsgUndelegate) ValidateBasic() error { } // NewMsgCancelUnbondingDelegation creates a new MsgCancelUnbondingDelegation instance. -// -//nolint:interfacer func NewMsgCancelUnbondingDelegation(delAddr sdk.AccAddress, valAddr sdk.ValAddress, creationHeight int64, amount sdk.Coin) *MsgCancelUnbondingDelegation { return &MsgCancelUnbondingDelegation{ DelegatorAddress: delAddr.String(), diff --git a/x/staking/types/params_legacy.go b/x/staking/types/params_legacy.go index df474c02ffa1..f2ab55624976 100644 --- a/x/staking/types/params_legacy.go +++ b/x/staking/types/params_legacy.go @@ -13,14 +13,13 @@ var ( var _ paramtypes.ParamSet = (*Params)(nil) -// ParamTable for staking module // Deprecated: now params can be accessed on key `0x51` on the staking store. +// ParamTable for staking module func ParamKeyTable() paramtypes.KeyTable { return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) } -// Implements params.ParamSet -// Deprecated. +// Deprecated: Implements params.ParamSet func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { return paramtypes.ParamSetPairs{ paramtypes.NewParamSetPair(KeyUnbondingTime, &p.UnbondingTime, validateUnbondingTime), diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index c763998dc7d1..1b55f7120cf2 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -39,8 +39,6 @@ var ( var _ ValidatorI = Validator{} // NewValidator constructs a new Validator -// -//nolint:interfacer func NewValidator(operator sdk.ValAddress, pubKey cryptotypes.PubKey, description Description) (Validator, error) { pkAny, err := codectypes.NewAnyWithValue(pubKey) if err != nil { diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index 6a005cce7622..1150fbed6146 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -261,9 +261,7 @@ func TestValidatorsSortDeterminism(t *testing.T) { // Randomly shuffle validators, sort, and check it is equal to original sort for i := 0; i < 10; i++ { rand.Shuffle(10, func(i, j int) { - it := vals[i] //nolint:gocritic - vals[i] = vals[j] - vals[j] = it + vals[i], vals[j] = vals[j], vals[i] }) types.Validators(vals).Sort()