chore: gofumpt (#11839)

* fumpt using main not master...

* be more descriptive

* fumpt

* fix nits

Co-authored-by: Julien Robert <julien@rbrt.fr>
This commit is contained in:
Jacob Gadikian 2022-05-19 15:55:27 +07:00 committed by GitHub
parent bc2d553f77
commit 55054282d2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
412 changed files with 1020 additions and 1059 deletions

View File

@ -31,6 +31,7 @@ v1.0.0-beta1 → v1.0.0-beta2 → ... → v1.0.0-rc1 → v1.0.0-rc2 → ... →
* create new release candidate tags after bugs are fixed.
* After the team feels the release branch is stable and everything works, create a full release:
* update `CHANGELOG.md`.
* run `gofumpt -w -l .` to format the code.
* create a new annotated git tag (eg `git -a v1.1.0`) in the release branch.
* Create a GitHub release.

View File

@ -143,7 +143,6 @@ func (app *BaseApp) FilterPeerByID(info string) abci.ResponseQuery {
// BeginBlock implements the ABCI application interface.
func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) {
if app.cms.TracingEnabled() {
app.cms.SetTracingContext(sdk.TraceContext(
map[string]interface{}{"blockHeight": req.Header.Height},
@ -209,7 +208,6 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg
// EndBlock implements the ABCI interface.
func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBlock) {
if app.deliverState.ms.TracingEnabled() {
app.deliverState.ms = app.deliverState.ms.SetTracingContext(nil).(sdk.CacheMultiStore)
}
@ -240,7 +238,6 @@ func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBloc
// will contain releveant error information. Regardless of tx execution outcome,
// the ResponseCheckTx will contain relevant gas execution context.
func (app *BaseApp) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
var mode runTxMode
switch {
@ -274,7 +271,6 @@ func (app *BaseApp) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx {
// Regardless of tx execution outcome, the ResponseDeliverTx will contain relevant
// gas execution context.
func (app *BaseApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx {
var abciRes abci.ResponseDeliverTx
defer func() {
for _, streamingListener := range app.abciListeners {
@ -297,7 +293,6 @@ func (app *BaseApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx
}
return abciRes
}
// Commit implements the ABCI interface. It will commit all state that exists in
@ -308,7 +303,6 @@ func (app *BaseApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx
// against that height and gracefully halt if it matches the latest committed
// height.
func (app *BaseApp) Commit() (res abci.ResponseCommit) {
header := app.deliverState.ctx.BlockHeader()
retainHeight := app.GetBlockRetentionHeight(header.Height)

View File

@ -25,9 +25,7 @@ const (
runTxModeDeliver // Deliver a transaction
)
var (
_ abci.Application = (*BaseApp)(nil)
)
var _ abci.Application = (*BaseApp)(nil)
type (
// Enum mode for app.runTx

View File

@ -66,5 +66,4 @@ func TestBroadcastError(t *testing.T) {
require.Equal(t, txHash, resp.TxHash)
}
}
}

View File

@ -42,7 +42,7 @@ func writeConfigToFile(configFilePath string, config *ClientConfig) error {
return err
}
return os.WriteFile(configFilePath, buffer.Bytes(), 0600)
return os.WriteFile(configFilePath, buffer.Bytes(), 0o600)
}
// ensureConfigPath creates a directory configPath if it does not exist

View File

@ -20,9 +20,7 @@ import (
legacybech32 "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32"
)
var (
flagPubkeyType = "type"
)
var flagPubkeyType = "type"
// Cmd creates a main CLI command
func Cmd() *cobra.Command {
@ -178,7 +176,6 @@ $ %s debug pubkey-raw cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg
cmd.Println("Bech32 Acc:", accPub)
cmd.Println("Bech32 Validator Operator:", valPub)
if pubkeyType == "ed25519" {
cmd.Println("Bech32 Validator Consensus:", consensusPub)
}
@ -200,7 +197,6 @@ $ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg
`, version.AppName),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
addrString := args[0]
var addr []byte
@ -216,7 +212,6 @@ $ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg
if err3 != nil {
return fmt.Errorf("expected hex or bech32. Got errors: hex: %v, bech32 acc: %v, bech32 val: %v", err, err2, err3)
}
}
}

View File

@ -2,6 +2,7 @@ package tmservice
import (
"context"
"github.com/cosmos/cosmos-sdk/client"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/tendermint/tendermint/rpc/coretypes"

View File

@ -113,7 +113,7 @@ func (s IntegrationTestSuite) TestQueryLatestValidatorSet() {
s.Require().Equal(true, ok)
s.Require().Equal(content, val.PubKey)
//with pagination
// with pagination
_, err = s.queryClient.GetLatestValidatorSet(context.Background(), &tmservice.GetLatestValidatorSetRequest{Pagination: &qtypes.PageRequest{
Offset: 0,
Limit: 10,

View File

@ -4,11 +4,12 @@ import (
gocontext "context"
"errors"
"fmt"
"reflect"
"strconv"
"github.com/cosmos/cosmos-sdk/codec"
proto "github.com/gogo/protobuf/proto"
"google.golang.org/grpc/encoding"
"reflect"
"strconv"
gogogrpc "github.com/gogo/protobuf/grpc"
abci "github.com/tendermint/tendermint/abci/types"

View File

@ -1,3 +1,4 @@
//go:build norace
// +build norace
package client_test

View File

@ -53,5 +53,4 @@ func TestReadLineFromBuf(t *testing.T) {
_, err := readLineFromBuf(buf)
require.ErrorIs(t, err, expectedErr)
})
}

View File

@ -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), 0644))
require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o644))
defer func() {
_ = os.RemoveAll(kbHome)

View File

@ -42,7 +42,7 @@ func Test_runListCmd(t *testing.T) {
clientCtx := client.Context{}.WithKeyring(kb)
ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx)
path := "" //sdk.GetConfig().GetFullBIP44Path()
path := "" // sdk.GetConfig().GetFullBIP44Path()
_, err = kb.NewAccount("something", testdata.TestMnemonic, "", path, hd.Secp256k1)
require.NoError(t, err)

View File

@ -43,7 +43,6 @@ func (s *MigrateTestSuite) SetupSuite() {
}
func (s *MigrateTestSuite) Test_runListAndShowCmd() {
// adding LegacyInfo item into keyring
multi := multisig.NewLegacyAminoPubKey(
1, []cryptotypes.PubKey{
@ -60,7 +59,7 @@ func (s *MigrateTestSuite) Test_runListAndShowCmd() {
Description: "SDK keyring version",
}
//run test simd keys list - to see that the migrated key is there
// run test simd keys list - to see that the migrated key is there
cmd := ListKeysCmd()
cmd.Flags().AddFlagSet(Commands("home").PersistentFlags())

View File

@ -1,3 +1,4 @@
//go:build norace
// +build norace
package client_test
@ -11,7 +12,6 @@ import (
)
func (s *IntegrationTestSuite) TestQueryABCIHeight() {
testCases := []struct {
name string
reqHeight int64

View File

@ -20,7 +20,6 @@ func ConvertTxToStdTx(codec *codec.LegacyAmino, tx signing.Tx) (legacytx.StdTx,
err := CopyTx(tx, builder, true)
if err != nil {
return legacytx.StdTx{}, err
}

View File

@ -10,7 +10,6 @@ import (
// Builder manages options for building CLI commands.
type Builder struct {
// flag.Builder embeds the flag builder and its options.
flag.Builder

View File

@ -20,7 +20,6 @@ type FieldValueBinder interface {
// Options specifies options for specific flags.
type Options struct {
// Prefix is a prefix to prepend to all flags.
Prefix string
}

View File

@ -8,7 +8,6 @@ import (
// Type specifies a custom flag type.
type Type interface {
// NewValue returns a new pflag.Value which must also implement either
// SimpleValue or ListValue.
NewValue(context.Context, *Builder) pflag.Value

View File

@ -6,14 +6,12 @@ import (
// SimpleValue wraps a simple (non-list and non-map) protobuf value.
type SimpleValue interface {
// Get returns the value.
Get() protoreflect.Value
}
// ListValue wraps a protobuf list/repeating value.
type ListValue interface {
// AppendTo appends the values to the provided list.
AppendTo(protoreflect.List)
}

View File

@ -121,7 +121,7 @@ func TestAminoCodecUnpackAnyFails(t *testing.T) {
func TestAminoCodecFullDecodeAndEncode(t *testing.T) {
// This tx comes from https://github.com/cosmos/cosmos-sdk/issues/8117.
txSigned := `{"type":"cosmos-sdk/StdTx","value":{"msg":[{"type":"cosmos-sdk/MsgCreateValidator","value":{"description":{"moniker":"fulltest","identity":"satoshi","website":"example.com","details":"example inc"},"commission":{"rate":"0.500000000000000000","max_rate":"1.000000000000000000","max_change_rate":"0.200000000000000000"},"min_self_delegation":"1000000","delegator_address":"cosmos14pt0q5cwf38zt08uu0n6yrstf3rndzr5057jys","validator_address":"cosmosvaloper14pt0q5cwf38zt08uu0n6yrstf3rndzr52q28gr","pubkey":{"type":"tendermint/PubKeyEd25519","value":"CYrOiM3HtS7uv1B1OAkknZnFYSRpQYSYII8AtMMtev0="},"value":{"denom":"umuon","amount":"700000000"}}}],"fee":{"amount":[{"denom":"umuon","amount":"6000"}],"gas":"160000"},"signatures":[{"pub_key":{"type":"tendermint/PubKeySecp256k1","value":"AwAOXeWgNf1FjMaayrSnrOOKz+Fivr6DiI/i0x0sZCHw"},"signature":"RcnfS/u2yl7uIShTrSUlDWvsXo2p2dYu6WJC8VDVHMBLEQZWc8bsINSCjOnlsIVkUNNe1q/WCA9n3Gy1+0zhYA=="}],"memo":"","timeout_height":"0"}}`
var legacyCdc = simapp.MakeTestEncodingConfig().Amino
legacyCdc := simapp.MakeTestEncodingConfig().Amino
var tx legacytx.StdTx
err := legacyCdc.UnmarshalJSON([]byte(txSigned), &tx)
require.NoError(t, err)

View File

@ -79,7 +79,7 @@ func TestMarshalProtoPubKey(t *testing.T) {
var pkI cryptotypes.PubKey
err = ccfg.InterfaceRegistry.UnpackAny(&pkAny2, &pkI)
require.NoError(err)
var pk2 = pkAny2.GetCachedValue().(cryptotypes.PubKey)
pk2 := pkAny2.GetCachedValue().(cryptotypes.PubKey)
require.True(pk2.Equals(pk))
// **** test binary serialization ****
@ -92,7 +92,7 @@ func TestMarshalProtoPubKey(t *testing.T) {
require.NoError(err)
err = ccfg.InterfaceRegistry.UnpackAny(&pkAny3, &pkI)
require.NoError(err)
var pk3 = pkAny3.GetCachedValue().(cryptotypes.PubKey)
pk3 := pkAny3.GetCachedValue().(cryptotypes.PubKey)
require.True(pk3.Equals(pk))
}

View File

@ -104,7 +104,8 @@ func testMarshaling(t *testing.T, cdc codec.Codec) {
&testdata.Cat{},
false,
true,
}}
},
}
if _, ok := cdc.(*codec.AminoCodec); ok {
testCases = append(testCases, testCase{
"any marshaling",
@ -123,7 +124,8 @@ func testMarshaling(t *testing.T, cdc codec.Codec) {
func(i codec.ProtoMarshaler) ([]byte, error) { return cdc.MarshalJSON(i) },
func(i codec.ProtoMarshaler) []byte { return cdc.MustMarshalJSON(i) },
func(bz []byte, ptr codec.ProtoMarshaler) error { return cdc.UnmarshalJSON(bz, ptr) },
func(bz []byte, ptr codec.ProtoMarshaler) { cdc.MustUnmarshalJSON(bz, ptr) }}
func(bz []byte, ptr codec.ProtoMarshaler) { cdc.MustUnmarshalJSON(bz, ptr) },
}
t.Run(tc.name+"_BinaryBare",
func(t *testing.T) { testMarshalingTestCase(require.New(t), tc, m1) })

View File

@ -29,8 +29,10 @@ type ProtoCodec struct {
interfaceRegistry types.InterfaceRegistry
}
var _ Codec = &ProtoCodec{}
var _ ProtoCodecMarshaler = &ProtoCodec{}
var (
_ Codec = &ProtoCodec{}
_ ProtoCodecMarshaler = &ProtoCodec{}
)
// NewProtoCodec returns a reference to a new ProtoCodec
func NewProtoCodec(interfaceRegistry types.InterfaceRegistry) *ProtoCodec {

View File

@ -99,8 +99,8 @@ func mustAny(msg proto.Message) *types.Any {
}
func BenchmarkProtoCodecMarshalLengthPrefixed(b *testing.B) {
var pCdc = codec.NewProtoCodec(types.NewInterfaceRegistry())
var msg = &testdata.HasAnimal{
pCdc := codec.NewProtoCodec(types.NewInterfaceRegistry())
msg := &testdata.HasAnimal{
X: 1000,
Animal: mustAny(&testdata.HasAnimal{
X: 2000,

View File

@ -23,8 +23,10 @@ type Animal interface {
Greet() string
}
var _ Animal = (*Dog)(nil)
var _ proto.Message = (*Dog)(nil)
var (
_ Animal = (*Dog)(nil)
_ proto.Message = (*Dog)(nil)
)
func TestAnyPackUnpack(t *testing.T) {
registry := NewInterfaceRegistry()

View File

@ -45,6 +45,7 @@ func init() {
func BenchmarkRejectUnknownFields_serial(b *testing.B) {
benchmarkRejectUnknownFields(b, false)
}
func BenchmarkRejectUnknownFields_parallel(b *testing.B) {
benchmarkRejectUnknownFields(b, true)
}
@ -82,9 +83,11 @@ func benchmarkRejectUnknownFields(b *testing.B, parallel bool) {
func BenchmarkProtoUnmarshal_serial(b *testing.B) {
benchmarkProtoUnmarshal(b, false)
}
func BenchmarkProtoUnmarshal_parallel(b *testing.B) {
benchmarkProtoUnmarshal(b, true)
}
func benchmarkProtoUnmarshal(b *testing.B, parallel bool) {
b.ReportAllocs()

View File

@ -162,8 +162,10 @@ func RejectUnknownFields(bz []byte, msg proto.Message, allowUnknownNonCriticals
return hasUnknownNonCriticals, nil
}
var protoMessageForTypeNameMu sync.RWMutex
var protoMessageForTypeNameCache = make(map[string]proto.Message)
var (
protoMessageForTypeNameMu sync.RWMutex
protoMessageForTypeNameCache = make(map[string]proto.Message)
)
// protoMessageForTypeName takes in a fully qualified name e.g. testdata.TestVersionFD1
// and returns a corresponding empty protobuf message that serves the prototype for typechecking.
@ -382,8 +384,10 @@ type descriptorMatch struct {
desc *descriptor.DescriptorProto
}
var descprotoCacheMu sync.RWMutex
var descprotoCache = make(map[reflect.Type]*descriptorMatch)
var (
descprotoCacheMu sync.RWMutex
descprotoCache = make(map[reflect.Type]*descriptorMatch)
)
// getDescriptorInfo retrieves the mapping of field numbers to their respective field descriptors.
func getDescriptorInfo(desc descriptorIface, msg proto.Message) (map[int32]*descriptor.FieldDescriptorProto, *descriptor.DescriptorProto, error) {

View File

@ -82,5 +82,4 @@ func LogErrors(logger *zerolog.Logger, msg string, err error) {
default:
logger.Error().Err(err).Msg(msg)
}
}

View File

@ -95,7 +95,7 @@ func (l Launcher) WaitForUpgradeOrExit(cmd *exec.Cmd) (bool, error) {
l.logger.Error().Err(err)
}
var cmdDone = make(chan error)
cmdDone := make(chan error)
go func() {
cmdDone <- cmd.Wait()
}()
@ -212,7 +212,6 @@ func IsSkipUpgradeHeight(args []string, upgradeInfo upgradetypes.Plan) bool {
if h == int(upgradeInfo.Height) {
return true
}
}
return false
}

View File

@ -32,7 +32,7 @@ func (s *processTestSuite) TestLaunchProcess() {
logger := cosmovisor.NewLogger()
// should run the genesis binary and produce expected output
var stdout, stderr = NewBuffer(), NewBuffer()
stdout, stderr := NewBuffer(), NewBuffer()
currentBin, err := cfg.CurrentBin()
require.NoError(err)
require.Equal(cfg.GenesisBin(), currentBin)
@ -91,7 +91,7 @@ func (s *processTestSuite) TestLaunchProcessWithDownloads() {
launcher, err := cosmovisor.NewLauncher(logger, cfg)
require.NoError(err)
var stdout, stderr = NewBuffer(), NewBuffer()
stdout, stderr := NewBuffer(), NewBuffer()
args := []string{"some", "args", upgradeFilename}
doUpgrade, err := launcher.Run(args, stdout, stderr)

View File

@ -91,11 +91,11 @@ func MarkExecutable(path string) error {
return fmt.Errorf("stating binary: %w", err)
}
// end early if world exec already set
if info.Mode()&0001 == 1 {
if info.Mode()&0o001 == 1 {
return nil
}
// now try to set all exec bits
newMode := info.Mode().Perm() | 0111
newMode := info.Mode().Perm() | 0o111
return os.Chmod(path, newMode)
}
@ -162,7 +162,7 @@ func EnsureBinary(path string) error {
}
// this checks if the world-executable bit is set (we cannot check owner easily)
exec := info.Mode().Perm() & 0001
exec := info.Mode().Perm() & 0o001
if exec == 0 {
return fmt.Errorf("%s is not world executable", info.Name())
}

View File

@ -148,7 +148,6 @@ func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase string, algo st
func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) {
saltBytes = crypto.CRandBytes(16)
key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter)
if err != nil {
panic(sdkerrors.Wrap(err, "error generating bcrypt key from passphrase"))
}

View File

@ -22,21 +22,20 @@ const (
Sr25519Type = PubKeyType("sr25519")
)
var (
// Secp256k1 uses the Bitcoin secp256k1 ECDSA parameters.
Secp256k1 = secp256k1Algo{}
)
// Secp256k1 uses the Bitcoin secp256k1 ECDSA parameters.
var Secp256k1 = secp256k1Algo{}
type DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error)
type GenerateFn func(bz []byte) types.PrivKey
type (
DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error)
GenerateFn func(bz []byte) types.PrivKey
)
type WalletGenerator interface {
Derive(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error)
Generate(bz []byte) types.PrivKey
}
type secp256k1Algo struct {
}
type secp256k1Algo struct{}
func (s secp256k1Algo) Name() PubKeyType {
return Secp256k1Type
@ -63,7 +62,7 @@ func (s secp256k1Algo) Derive() DeriveFn {
// Generate generates a secp256k1 private key from the given bytes.
func (s secp256k1Algo) Generate() GenerateFn {
return func(bz []byte) types.PrivKey {
var bzArr = make([]byte, secp256k1.PrivKeySize)
bzArr := make([]byte, secp256k1.PrivKeySize)
copy(bzArr, bz)
return &secp256k1.PrivKey{Key: bzArr}

View File

@ -89,7 +89,6 @@ func TestParamsFromPath(t *testing.T) {
require.Nil(t, params, errStr)
require.Error(t, err, errStr)
}
}
func TestCreateHDPath(t *testing.T) {

View File

@ -19,7 +19,6 @@ func TestInMemoryCreateLedger(t *testing.T) {
kb := NewInMemory(cdc)
k, err := kb.SaveLedgerKey("some_account", hd.Secp256k1, "cosmos", 118, 3, 1)
if err != nil {
require.Error(t, err)
require.Equal(t, "ledger nano S: support for ledger devices is not available in this executable", err.Error())

View File

@ -255,7 +255,6 @@ func unMarshalLegacyInfo(bz []byte) (info LegacyInfo, err error) {
// privKeyFromLegacyInfo exports a private key from LegacyInfo
func privKeyFromLegacyInfo(info LegacyInfo) (cryptotypes.PrivKey, error) {
switch linfo := info.(type) {
case legacyLocalInfo:
if linfo.PrivKeyArmor == "" {

View File

@ -229,6 +229,7 @@ func (s *MigrationTestSuite) TestMigrateErrEmptyItemData() {
_, err := s.ks.migrate(n1)
s.Require().EqualError(err, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, n1).Error())
}
func TestMigrationTestSuite(t *testing.T) {
suite.Run(t, new(MigrationTestSuite))
}

View File

@ -59,8 +59,7 @@ func TestAltSigningAlgoList_String(t *testing.T) {
require.Equal(t, fmt.Sprintf("%s,notSupported", hd.Secp256k1Type), list.String())
}
type notSupportedAlgo struct {
}
type notSupportedAlgo struct{}
func (n notSupportedAlgo) Name() hd.PubKeyType {
return "notSupported"

View File

@ -34,8 +34,10 @@ const (
keyType = "ed25519"
)
var _ cryptotypes.PrivKey = &PrivKey{}
var _ codec.AminoMarshaler = &PrivKey{}
var (
_ cryptotypes.PrivKey = &PrivKey{}
_ codec.AminoMarshaler = &PrivKey{}
)
// Bytes returns the privkey byte format.
func (privKey *PrivKey) Bytes() []byte {
@ -150,8 +152,10 @@ func GenPrivKeyFromSecret(secret []byte) *PrivKey {
//-------------------------------------
var _ cryptotypes.PubKey = &PubKey{}
var _ codec.AminoMarshaler = &PubKey{}
var (
_ cryptotypes.PubKey = &PubKey{}
_ codec.AminoMarshaler = &PubKey{}
)
// Address is the SHA256-20 of the raw pubkey bytes.
// It doesn't implement ADR-28 addresses and it must not be used

View File

@ -30,7 +30,6 @@ func BenchmarkSigning(b *testing.B, priv types.PrivKey) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := priv.Sign(message)
if err != nil {
b.FailNow()
}

View File

@ -29,7 +29,6 @@ func IsSNormalized(sigS *big.Int) bool {
// NormalizeS will invert the s value if not already in the lower half
// of curve order value
func NormalizeS(sigS *big.Int) *big.Int {
if IsSNormalized(sigS) {
return sigS
}
@ -41,7 +40,6 @@ func NormalizeS(sigS *big.Int) *big.Int {
// R, S are padded to 32 bytes respectively.
// code roughly copied from secp256k1_nocgo.go
func signatureRaw(r *big.Int, s *big.Int) []byte {
rBytes := r.Bytes()
sBytes := s.Bytes()
sigBytes := make([]byte, 64)
@ -90,10 +88,8 @@ func (sk *PrivKey) Bytes() []byte {
// It then raw encodes the signature as two fixed width 32-byte values
// concatenated, reusing the code copied from secp256k1_nocgo.go
func (sk *PrivKey) Sign(msg []byte) ([]byte, error) {
digest := sha256.Sum256(msg)
r, s, err := ecdsa.Sign(rand.Reader, &sk.PrivateKey, digest[:])
if err != nil {
return nil, err
}

View File

@ -38,11 +38,11 @@ func (suite *SKSuite) TestMarshal() {
require := suite.Require()
const size = 32
var buffer = make([]byte, size)
buffer := make([]byte, size)
_, err := suite.sk.MarshalTo(buffer)
require.NoError(err)
var sk = new(PrivKey)
sk := new(PrivKey)
err = sk.Unmarshal(buffer, secp256r1, size)
require.NoError(err)
require.True(sk.Equal(&suite.sk.PrivateKey))

View File

@ -60,7 +60,6 @@ func (pk *PubKey) Bytes() []byte {
// lower half of the curve order
// 7/21/21 - expects raw encoded signature (fixed-width 64-bytes, R || S)
func (pk *PubKey) VerifySignature(msg []byte, sig []byte) bool {
// check length for raw signature
// which is two 32-byte padded big.Ints
// concatenated

View File

@ -59,12 +59,12 @@ func (suite *PKSuite) TestMarshal() {
require := suite.Require()
const size = 33 // secp256r1 size
var buffer = make([]byte, size)
buffer := make([]byte, size)
n, err := suite.pk.MarshalTo(buffer)
require.NoError(err)
require.Equal(size, n)
var pk = new(PubKey)
pk := new(PubKey)
err = pk.Unmarshal(buffer, secp256r1, size)
require.NoError(err)
require.True(pk.PublicKey.Equal(&suite.pk.PublicKey))

View File

@ -11,8 +11,10 @@ import (
"github.com/cosmos/cosmos-sdk/types/tx/signing"
)
var _ multisigtypes.PubKey = &LegacyAminoPubKey{}
var _ types.UnpackInterfacesMessage = &LegacyAminoPubKey{}
var (
_ multisigtypes.PubKey = &LegacyAminoPubKey{}
_ types.UnpackInterfacesMessage = &LegacyAminoPubKey{}
)
// NewLegacyAminoPubKey returns a new LegacyAminoPubKey.
// Multisig can be constructed with multiple same keys - it will increase the power of

View File

@ -110,7 +110,8 @@ func TestVerifyMultisignature(t *testing.T) {
pk = genPk
},
true,
}, {
},
{
"wrong size for sig bit array",
func(require *require.Assertions) {
pubKeys := generatePubKeys(3)
@ -165,7 +166,8 @@ func TestVerifyMultisignature(t *testing.T) {
)
},
true,
}, {
},
{
"duplicate signatures",
func(require *require.Assertions) {
pubKeys, sigs := generatePubKeysAndSignatures(5, msg)
@ -178,7 +180,8 @@ func TestVerifyMultisignature(t *testing.T) {
sig.Signatures = append(sig.Signatures, sigs[0])
},
false,
}, {
},
{
"duplicated key",
func(require *require.Assertions) {
// here we test an edge case where we create a multi sig with two same
@ -191,7 +194,8 @@ func TestVerifyMultisignature(t *testing.T) {
multisig.AddSignature(sig, sigs[0], 1)
},
true,
}, {
},
{
"same key used twice",
func(require *require.Assertions) {
pubkeys, sigs := generatePubKeysAndSignatures(3, msg)
@ -201,7 +205,8 @@ func TestVerifyMultisignature(t *testing.T) {
multisig.AddSignature(sig, sigs[0], 1)
},
false,
}, {
},
{
"unable to verify signature",
func(require *require.Assertions) {
pubKeys := generatePubKeys(2)

View File

@ -93,19 +93,19 @@ func (BitCurve *BitCurve) Params() *elliptic.CurveParams {
// IsOnCurve returns true if the given (x,y) lies on the BitCurve.
func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
// y² = x³ + b
y2 := new(big.Int).Mul(y, y) //
y2.Mod(y2, BitCurve.P) //y²%P
y2 := new(big.Int).Mul(y, y) //
y2.Mod(y2, BitCurve.P) // y²%P
x3 := new(big.Int).Mul(x, x) //
x3.Mul(x3, x) //
x3 := new(big.Int).Mul(x, x) //
x3.Mul(x3, x) //
x3.Add(x3, BitCurve.B) //x³+B
x3.Add(x3, BitCurve.B) // x³+B
x3.Mod(x3, BitCurve.P) //(x³+B)%P
return x3.Cmp(y2) == 0
}
//TODO: double check if the function is okay
// TODO: double check if the function is okay
// affineFromJacobian reverses the Jacobian transform. See the comment at the
// top of the file.
func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
@ -217,30 +217,30 @@ func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
a := new(big.Int).Mul(x, x) //X1²
b := new(big.Int).Mul(y, y) //Y1²
c := new(big.Int).Mul(b, b) //
a := new(big.Int).Mul(x, x) // X1²
b := new(big.Int).Mul(y, y) // Y1²
c := new(big.Int).Mul(b, b) //
d := new(big.Int).Add(x, b) //X1+B
d := new(big.Int).Add(x, b) // X1+B
d.Mul(d, d) //(X1+B)²
d.Sub(d, a) //(X1+B)²-A
d.Sub(d, c) //(X1+B)²-A-C
d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C)
d.Mul(d, big.NewInt(2)) // 2*((X1+B)²-A-C)
e := new(big.Int).Mul(big.NewInt(3), a) //3*A
f := new(big.Int).Mul(e, e) //
e := new(big.Int).Mul(big.NewInt(3), a) // 3*A
f := new(big.Int).Mul(e, e) //
x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
x3.Sub(f, x3) //F-2*D
x3 := new(big.Int).Mul(big.NewInt(2), d) // 2*D
x3.Sub(f, x3) // F-2*D
x3.Mod(x3, BitCurve.P)
y3 := new(big.Int).Sub(d, x3) //D-X3
y3.Mul(e, y3) //E*(D-X3)
y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
y3 := new(big.Int).Sub(d, x3) // D-X3
y3.Mul(e, y3) // E*(D-X3)
y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) // E*(D-X3)-8*C
y3.Mod(y3, BitCurve.P)
z3 := new(big.Int).Mul(y, z) //Y1*Z1
z3.Mul(big.NewInt(2), z3) //3*Y1*Z1
z3 := new(big.Int).Mul(y, z) // Y1*Z1
z3.Mul(big.NewInt(2), z3) // 3*Y1*Z1
z3.Mod(z3, BitCurve.P)
return x3, y3, z3

View File

@ -1,3 +1,4 @@
//go:build dummy
// +build dummy
// Package c contains only a C file.

View File

@ -1,3 +1,4 @@
//go:build dummy
// +build dummy
// Package c contains only a C file.

View File

@ -1,3 +1,4 @@
//go:build dummy
// +build dummy
// Package c contains only a C file.

View File

@ -1,3 +1,4 @@
//go:build dummy
// +build dummy
// Package c contains only a C file.

View File

@ -1,3 +1,4 @@
//go:build dummy
// +build dummy
// Package c contains only a C file.

View File

@ -1,3 +1,4 @@
//go:build dummy
// +build dummy
// Package c contains only a C file.

View File

@ -1,3 +1,4 @@
//go:build dummy
// +build dummy
// Package c contains only a C file.

View File

@ -48,7 +48,7 @@ func randSig() []byte {
// tests for malleability
// highest bit of signature ECDSA s value must be 0, in the 33th byte
func compactSigCheck(t *testing.T, sig []byte) {
var b = int(sig[32])
b := int(sig[32])
if b < 0 {
t.Errorf("highest bit is negative: %d", b)
}

View File

@ -17,8 +17,10 @@ import (
"github.com/cosmos/cosmos-sdk/types/errors"
)
var _ cryptotypes.PrivKey = &PrivKey{}
var _ codec.AminoMarshaler = &PrivKey{}
var (
_ cryptotypes.PrivKey = &PrivKey{}
_ codec.AminoMarshaler = &PrivKey{}
)
const (
PrivKeySize = 32
@ -138,8 +140,10 @@ func GenPrivKeyFromSecret(secret []byte) *PrivKey {
//-------------------------------------
var _ cryptotypes.PubKey = &PubKey{}
var _ codec.AminoMarshaler = &PubKey{}
var (
_ cryptotypes.PubKey = &PubKey{}
_ codec.AminoMarshaler = &PubKey{}
)
// PubKeySize is comprised of 32 bytes for one field element
// (the x-coordinate), plus one byte for the parity of the y-coordinate.

View File

@ -10,7 +10,6 @@ import (
)
func Test_genPrivKey(t *testing.T) {
empty := make([]byte, 32)
oneB := big.NewInt(1).Bytes()
onePadded := make([]byte, 32)

View File

@ -41,7 +41,7 @@ func TestPubKeySecp256k1Address(t *testing.T) {
addrBbz, _, _ := base58.CheckDecode(d.addr)
addrB := crypto.Address(addrBbz)
var priv = secp256k1.PrivKey{Key: privB}
priv := secp256k1.PrivKey{Key: privB}
pubKey := priv.PubKey()
pubT, _ := pubKey.(*secp256k1.PubKey)

View File

@ -44,7 +44,6 @@ func ExamplePrintRegisteredTypes() {
}
func TestNilEncodings(t *testing.T) {
// Check nil Signature.
var a, b []byte
checkAminoJSON(t, &a, &b, true)
@ -59,5 +58,4 @@ func TestNilEncodings(t *testing.T) {
var e, f cryptotypes.PrivKey
checkAminoJSON(t, &e, &f, true)
require.EqualValues(t, e, f)
}

View File

@ -28,8 +28,7 @@ func init() {
}
}
type LedgerSECP256K1Mock struct {
}
type LedgerSECP256K1Mock struct{}
func (mock LedgerSECP256K1Mock) Close() error {
return nil

View File

@ -1,3 +1,4 @@
//go:build cgo && ledger && !test_ledger_mock
// +build cgo,ledger,!test_ledger_mock
package ledger

View File

@ -14,11 +14,9 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/types"
)
var (
// discoverLedger defines a function to be invoked at runtime for discovering
// a connected Ledger device.
discoverLedger discoverLedgerFn
)
// discoverLedger defines a function to be invoked at runtime for discovering
// a connected Ledger device.
var discoverLedger discoverLedgerFn
type (
// discoverLedgerFn defines a Ledger discovery function that returns a
@ -102,8 +100,7 @@ func (pkl PrivKeyLedgerSecp256k1) Sign(message []byte) ([]byte, error) {
}
// ShowAddress triggers a ledger device to show the corresponding address.
func ShowAddress(path hd.BIP44Params, expectedPubKey types.PubKey,
accountAddressPrefix string) error {
func ShowAddress(path hd.BIP44Params, expectedPubKey types.PubKey, accountAddressPrefix string) error {
device, err := getDevice()
if err != nil {
return err

View File

@ -67,7 +67,6 @@ func TestBitArrayEqual(t *testing.T) {
}
func TestJSONMarshalUnmarshal(t *testing.T) {
bA1 := NewCompactBitArray(0)
bA2 := NewCompactBitArray(1)
@ -218,7 +217,6 @@ func TestCompactBitArrayNumOfTrueBitsBefore(t *testing.T) {
require.NoError(t, err)
for i := 0; i < len(tc.bAIndex); i++ {
require.Equal(t, tc.trueValueIndex[i], bA.NumTrueBitsBefore(tc.bAIndex[i]), "tc %d, i %d", tcIndex, i)
}
})

View File

@ -10,8 +10,10 @@ import (
// TODO, make this into a struct that implements crypto.Symmetric.
const nonceLen = 24
const secretLen = 32
const (
nonceLen = 24
secretLen = 32
)
// secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase))
// The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext.

View File

@ -11,7 +11,6 @@ import (
)
func TestSimple(t *testing.T) {
plaintext := []byte("sometext")
secret := []byte("somesecretoflengththirtytwo===32")
ciphertext := EncryptSymmetric(plaintext, secret)
@ -22,7 +21,6 @@ func TestSimple(t *testing.T) {
}
func TestSimpleWithKDF(t *testing.T) {
plaintext := []byte("sometext")
secretPass := []byte("somesecret")
secret, err := bcrypt.GenerateFromPassword(secretPass, 12)

View File

@ -19,9 +19,7 @@ import (
"github.com/dgraph-io/ristretto/z"
)
var (
versionsFilename = "versions.csv"
)
var versionsFilename = "versions.csv"
var (
_ db.DBConnection = (*BadgerDB)(nil)
@ -74,7 +72,7 @@ type versionManager struct {
func NewDB(dir string) (*BadgerDB, error) {
// Since Badger doesn't support database names, we join both to obtain
// the final directory to use for the database.
if err := os.MkdirAll(dir, 0755); err != nil {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
opts := badger.DefaultOptions(dir)
@ -102,7 +100,7 @@ func NewDBWithOptions(opts badger.Options) (*BadgerDB, error) {
// Load metadata CSV file containing valid versions
func readVersionsFile(path string) (*versionManager, error) {
file, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0644)
file, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0o644)
if err != nil {
return nil, err
}
@ -143,14 +141,14 @@ func readVersionsFile(path string) (*versionManager, error) {
// Write version metadata to CSV file
func writeVersionsFile(vm *versionManager, path string) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644)
if err != nil {
return err
}
defer file.Close()
w := csv.NewWriter(file)
rows := [][]string{
[]string{"0", strconv.FormatUint(vm.lastTs, 10)},
{"0", strconv.FormatUint(vm.lastTs, 10)},
}
for it := vm.Iterator(); it.Next(); {
version := it.Value()

View File

@ -2,6 +2,7 @@ package util
import (
"fmt"
dbm "github.com/cosmos/cosmos-sdk/db"
)

View File

@ -178,7 +178,7 @@ func (dbm *MemDB) Revert() error {
if !has {
return fmt.Errorf("bad version history: version %v not saved", last)
}
for ver, _ := range dbm.saved {
for ver := range dbm.saved {
if ver > last {
delete(dbm.saved, ver)
}

View File

@ -24,9 +24,11 @@ type prefixW struct {
prefix []byte
}
var _ db.DBReader = (*prefixR)(nil)
var _ db.DBReadWriter = (*prefixRW)(nil)
var _ db.DBWriter = (*prefixW)(nil)
var (
_ db.DBReader = (*prefixR)(nil)
_ db.DBReadWriter = (*prefixRW)(nil)
_ db.DBWriter = (*prefixW)(nil)
)
// NewPrefixReader returns a DBReader that only has access to the subset of DB keys
// that contain the given prefix.

View File

@ -71,7 +71,7 @@ type dbOptions struct {
// NewDB creates a new RocksDB key-value database with inside the given directory.
// If dir does not exist, it will be created.
func NewDB(dir string) (*dbManager, error) {
if err := os.MkdirAll(dir, 0755); err != nil {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
@ -100,7 +100,7 @@ func NewDB(dir string) (*dbManager, error) {
cpCache: checkpointCache{cache: map[uint64]*cpCacheEntry{}},
}
err := os.MkdirAll(mgr.checkpointsDir(), 0755)
err := os.MkdirAll(mgr.checkpointsDir(), 0o755)
if err != nil {
return nil, err
}

View File

@ -65,7 +65,7 @@ func (vm *VersionManager) Save(target uint64) (uint64, error) {
}
func findLimit(m map[uint64]struct{}, cmp func(uint64, uint64) bool, init uint64) uint64 {
for x, _ := range m {
for x := range m {
if cmp(x, init) {
init = x
}
@ -99,7 +99,7 @@ func (vi *vmIterator) Value() uint64 { return vi.buf }
func (vm *VersionManager) Iterator() VersionIterator {
ch := make(chan uint64)
go func() {
for ver, _ := range vm.versions {
for ver := range vm.versions {
ch <- ver
}
close(ch)
@ -125,7 +125,7 @@ func (vm *VersionManager) Equal(that VersionSet) bool {
func (vm *VersionManager) Copy() *VersionManager {
vmap := make(map[uint64]struct{})
for ver, _ := range vm.versions {
for ver := range vm.versions {
vmap[ver] = struct{}{}
}
return &VersionManager{versions: vmap, initial: vm.initial, last: vm.last}

View File

@ -3,11 +3,12 @@ package errors
import (
stdlib "errors"
"fmt"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/suite"
"google.golang.org/grpc/codes"
grpcstatus "google.golang.org/grpc/status"
"testing"
)
type errorsTestSuite struct {
@ -114,8 +115,8 @@ func (s *errorsTestSuite) TestIsOf() {
require := s.Require()
var errNil *Error
var err = ErrInvalidAddress
var errW = Wrap(ErrLogic, "more info")
err := ErrInvalidAddress
errW := Wrap(ErrLogic, "more info")
require.False(IsOf(errNil), "nil error should always have no causer")
require.False(IsOf(errNil, err), "nil error should always have no causer")
@ -127,12 +128,11 @@ func (s *errorsTestSuite) TestIsOf() {
require.True(IsOf(errW, ErrLogic))
require.True(IsOf(errW, err, ErrLogic))
require.True(IsOf(errW, nil, errW), "error should much itself")
var err2 = errors.New("other error")
err2 := errors.New("other error")
require.True(IsOf(err2, nil, err2), "error should much itself")
}
type customError struct {
}
type customError struct{}
func (customError) Error() string {
return "custom error"
@ -169,35 +169,35 @@ func (s *errorsTestSuite) TestWrappedIs() {
}
func (s *errorsTestSuite) TestWrappedIsMultiple() {
var errTest = errors.New("test error")
var errTest2 = errors.New("test error 2")
errTest := errors.New("test error")
errTest2 := errors.New("test error 2")
err := Wrap(errTest2, Wrap(errTest, "some random description").Error())
s.Require().True(stdlib.Is(err, errTest2))
}
func (s *errorsTestSuite) TestWrappedIsFail() {
var errTest = errors.New("test error")
var errTest2 = errors.New("test error 2")
errTest := errors.New("test error")
errTest2 := errors.New("test error 2")
err := Wrap(errTest2, Wrap(errTest, "some random description").Error())
s.Require().False(stdlib.Is(err, errTest))
}
func (s *errorsTestSuite) TestWrappedUnwrap() {
var errTest = errors.New("test error")
errTest := errors.New("test error")
err := Wrap(errTest, "some random description")
s.Require().Equal(errTest, stdlib.Unwrap(err))
}
func (s *errorsTestSuite) TestWrappedUnwrapMultiple() {
var errTest = errors.New("test error")
var errTest2 = errors.New("test error 2")
errTest := errors.New("test error")
errTest2 := errors.New("test error 2")
err := Wrap(errTest2, Wrap(errTest, "some random description").Error())
s.Require().Equal(errTest2, stdlib.Unwrap(err))
}
func (s *errorsTestSuite) TestWrappedUnwrapFail() {
var errTest = errors.New("test error")
var errTest2 = errors.New("test error 2")
errTest := errors.New("test error")
errTest2 := errors.New("test error 2")
err := Wrap(errTest2, Wrap(errTest, "some random description").Error())
s.Require().NotEqual(errTest, stdlib.Unwrap(err))
}

View File

@ -170,7 +170,6 @@ func (s *intTestSuite) TestArithInt() {
s.Require().Equal(tc.nres, tc.ires.Int64(), "Int arithmetic operation does not match with int64 operation. tc #%d", tcnum)
}
}
}
func (s *intTestSuite) TestCompInt() {
@ -394,7 +393,7 @@ func (s *intTestSuite) TestIntEq() {
}
func TestRoundTripMarshalToInt(t *testing.T) {
var values = []int64{
values := []int64{
0,
1,
1 << 10,

View File

@ -51,5 +51,4 @@ func (s *uintInternalTestSuite) TestUintSize() {
s.Require().Equal(2, x.Size())
x = NewUint(100)
s.Require().Equal(3, x.Size())
}

View File

@ -292,7 +292,7 @@ func maxuint(i1, i2 uint64) uint64 {
}
func TestRoundTripMarshalToUint(t *testing.T) {
var values = []uint64{
values := []uint64{
0,
1,
1 << 10,

View File

@ -13,7 +13,6 @@ import (
// Codec defines an interface for decoding and encoding values in ORM index keys.
type Codec interface {
// Decode decodes a value in a key.
Decode(r Reader) (protoreflect.Value, error)

View File

@ -14,8 +14,10 @@ type Int32Codec struct{}
var int32Codec = Int32Codec{}
const int32Max = 2147483647
const int32Offset = int32Max + 1
const (
int32Max = 2147483647
int32Offset = int32Max + 1
)
func (i Int32Codec) Decode(r Reader) (protoreflect.Value, error) {
var x uint32

View File

@ -6,7 +6,6 @@ import "google.golang.org/protobuf/reflect/protoreflect"
// kv-store backing an ORM instance. EntryCodec's enable full logical decoding
// of ORM data.
type EntryCodec interface {
// DecodeEntry decodes a kv-pair into an Entry.
DecodeEntry(k, v []byte) (Entry, error)

View File

@ -26,7 +26,6 @@ type Entry interface {
// PrimaryKeyEntry represents a logically decoded primary-key entry.
type PrimaryKeyEntry struct {
// TableName is the table this entry represents.
TableName protoreflect.FullName
@ -71,7 +70,6 @@ func (p *PrimaryKeyEntry) doNotImplement() {}
// IndexKeyEntry represents a logically decoded index entry.
type IndexKeyEntry struct {
// TableName is the table this entry represents.
TableName protoreflect.FullName
@ -111,14 +109,12 @@ func (i *IndexKeyEntry) String() string {
if i.IsUnique {
return fmt.Sprintf("UNIQ %s", i.string())
} else {
return fmt.Sprintf("IDX %s", i.string())
}
}
// SeqEntry represents a sequence for tables with auto-incrementing primary keys.
type SeqEntry struct {
// TableName is the table this entry represents.
TableName protoreflect.FullName

View File

@ -62,7 +62,6 @@ 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
if err == io.EOF {

View File

@ -51,7 +51,6 @@ func (p PrimaryKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey []
primaryKey = indexFields
}
return indexFields, primaryKey, nil
}
func (p PrimaryKeyCodec) DecodeEntry(k, v []byte) (Entry, error) {

View File

@ -153,7 +153,6 @@ func (f fileGen) genStoreConstructor(stores []*protogen.Message) {
}
f.P("}, nil")
f.P("}")
}
func (f fileGen) fieldsToCamelCase(fields string) string {

View File

@ -9,7 +9,6 @@ import (
)
func (t tableGen) genIndexKeys() {
// interface that all keys must adhere to
t.P("type ", t.indexKeyInterfaceName(), " interface {")
t.P("id() uint32")
@ -112,7 +111,6 @@ func (t tableGen) genIndex(fields string, id uint32, isPrimaryKey bool) {
for i := 1; i < len(fieldsSlc)+1; i++ {
t.genWithMethods(idxKeyName, fieldsSlc[:i])
}
}
func (t tableGen) genIndexInterfaceMethods(id uint32, indexStructName string) {

View File

@ -14,7 +14,6 @@ import (
// Debugger is an interface that handles debug info from the debug store wrapper.
type Debugger interface {
// Log logs a single log message.
Log(string)

View File

@ -51,7 +51,6 @@ type moduleDB struct {
// ModuleDBOptions are options for constructing a ModuleDB.
type ModuleDBOptions struct {
// TypeResolver is an optional type resolver to be used when unmarshaling
// protobuf messages. If it is nil, protoregistry.GlobalTypes will be used.
TypeResolver ormtable.TypeResolver

View File

@ -355,13 +355,14 @@ func TestGetBackendResolver(t *testing.T) {
})
assert.ErrorContains(t, err, "unsupported")
_, err = ormdb.NewModuleDB(&ormv1alpha1.ModuleSchemaDescriptor{SchemaFile: []*ormv1alpha1.ModuleSchemaDescriptor_FileEntry{
{
Id: 1,
ProtoFileName: testpb.File_testpb_bank_proto.Path(),
StorageType: ormv1alpha1.StorageType_STORAGE_TYPE_MEMORY,
_, err = ormdb.NewModuleDB(&ormv1alpha1.ModuleSchemaDescriptor{
SchemaFile: []*ormv1alpha1.ModuleSchemaDescriptor_FileEntry{
{
Id: 1,
ProtoFileName: testpb.File_testpb_bank_proto.Path(),
StorageType: ormv1alpha1.StorageType_STORAGE_TYPE_MEMORY,
},
},
},
}, ormdb.ModuleDBOptions{
GetBackendResolver: getResolver,
})

View File

@ -50,7 +50,6 @@ type Backend interface {
// If the index store is not defined, the commitment store will be
// used for all operations.
type ReadBackendOptions struct {
// CommitmentStoreReader is a reader for the commitment store.
CommitmentStoreReader kv.ReadonlyStore
@ -135,7 +134,6 @@ func (c backend) IndexStore() kv.Store {
// If the index store is not defined, the commitment store will be
// used for all operations.
type BackendOptions struct {
// CommitmentStore is the commitment store.
CommitmentStore kv.Store

View File

@ -75,7 +75,6 @@ func flushBuf(store kv.Store, writes []*batchWriterEntry) error {
return err
}
}
}
return nil
}

View File

@ -219,7 +219,7 @@ func getBalance(store kv.Store, address, denom string) (*testpb.Balance, error)
return nil, fmt.Errorf("not found")
}
var balance = testpb.Balance{}
balance := testpb.Balance{}
err = proto.Unmarshal(bz, &balance)
if err != nil {
return nil, err

View File

@ -9,7 +9,6 @@ import (
// ValidateHooks defines an interface for a table hooks which can intercept
// insert, update and delete operations and possibly return an error.
type ValidateHooks interface {
// ValidateInsert is called before the message is inserted.
// If error is not nil the insertion will fail.
ValidateInsert(context.Context, proto.Message) error
@ -30,7 +29,6 @@ type ValidateHooks interface {
// may be called but the enclosing transaction may still fail. The context
// is provided in each method to help coordinate this.
type WriteHooks interface {
// OnInsert is called after an message is inserted into the store.
OnInsert(context.Context, proto.Message)

View File

@ -16,7 +16,6 @@ import (
// are stateless, with all state existing only in the store passed
// to index methods.
type Index interface {
// List does iteration over the index with the provided prefix key and options.
// 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,

View File

@ -61,8 +61,10 @@ func (i indexKeyIndex) ListRange(ctx context.Context, from, to []interface{}, op
return rangeIterator(backend.IndexStoreReader(), backend, i, i.KeyCodec, from, to, options)
}
var _ indexer = &indexKeyIndex{}
var _ Index = &indexKeyIndex{}
var (
_ indexer = &indexKeyIndex{}
_ Index = &indexKeyIndex{}
)
func (i indexKeyIndex) doNotImplement() {}

View File

@ -18,7 +18,6 @@ import (
// Instead you should do reads and writes separately, or use a helper
// function like DeleteBy which does this efficiently.
type Iterator interface {
// Next advances the iterator and returns true if a valid entry is found.
// Next must be called before starting iteration.
Next() bool

View File

@ -76,7 +76,6 @@ func (it *paginationIterator) Next() bool {
// so the index == total entries.
it.pageRes.Total = uint64(it.i)
}
}
return false
}

View File

@ -3,11 +3,12 @@ package ormtable_test
import (
"context"
"fmt"
"testing"
"github.com/cosmos/cosmos-sdk/orm/model/ormtable"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"testing"
"github.com/regen-network/gocuke"
"gotest.tools/v3/assert"

View File

@ -414,8 +414,10 @@ func (t tableImpl) Get(ctx context.Context, message proto.Message) (found bool,
return t.primaryKeyIndex.get(backend, message, keyValues)
}
var _ Table = &tableImpl{}
var _ Schema = &tableImpl{}
var (
_ Table = &tableImpl{}
_ Schema = &tableImpl{}
)
type saveMode int

View File

@ -98,7 +98,6 @@ func TestPaginationLimitCountTotal(t *testing.T) {
pr := it.PageResponse()
assert.Check(t, pr != nil)
assert.Equal(t, uint64(3), pr.Total)
}
func TestImportedMessageIterator(t *testing.T) {
@ -187,7 +186,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen
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
@ -498,7 +497,6 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen
it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{})
assert.NilError(t, err)
assertIteratorItems(it, 2, 6, 10)
}
func TestRandomTableData(t *testing.T) {
@ -604,7 +602,6 @@ func testIndex(t *testing.T, model *IndexModel) {
assert.DeepEqual(t, model.data[i], data2[i], protocmp.Transform())
}
}
}
func reverseData(data []proto.Message) []proto.Message {

View File

@ -190,8 +190,10 @@ func (u uniqueKeyIndex) Fields() string {
return u.fields.String()
}
var _ indexer = &uniqueKeyIndex{}
var _ UniqueIndex = &uniqueKeyIndex{}
var (
_ indexer = &uniqueKeyIndex{}
_ UniqueIndex = &uniqueKeyIndex{}
)
// isNonTrivialUniqueKey checks if unique key fields are non-trivial, meaning that they
// don't contain the full primary key. If they contain the full primary key, then

View File

@ -4,7 +4,6 @@ import (
"container/list"
"errors"
"fmt"
"testing"
"github.com/golang/mock/gomock"
@ -312,7 +311,6 @@ func TestHandleHeight_FlushLoadFromDisk(t *testing.T) {
}
func TestHandleHeight_DbErr_Panic(t *testing.T) {
ctrl := gomock.NewController(t)
// Setup
@ -367,7 +365,6 @@ func TestHandleHeightSnapshot_FlushLoadFromDisk(t *testing.T) {
}
func TestHandleHeightSnapshot_DbErr_Panic(t *testing.T) {
ctrl := gomock.NewController(t)
// Setup
@ -509,7 +506,7 @@ func TestLoadPruningHeights(t *testing.T) {
}
func TestLoadPruningHeights_PruneNothing(t *testing.T) {
var manager = pruning.NewManager(db.NewMemDB(), log.NewNopLogger())
manager := pruning.NewManager(db.NewMemDB(), log.NewNopLogger())
require.NotNil(t, manager)
manager.SetOptions(types.NewPruningOptions(types.PruningNothing))
@ -518,7 +515,6 @@ func TestLoadPruningHeights_PruneNothing(t *testing.T) {
}
func TestGetFlushAndResetPruningHeights_DbErr_Panic(t *testing.T) {
ctrl := gomock.NewController(t)
// Setup

Some files were not shown because too many files have changed in this diff Show More