Skip to content

Commit

Permalink
chore: fumpt sdk v45 series cosmos#12442
Browse files Browse the repository at this point in the history
  • Loading branch information
faddat authored and JeancarloBarrios committed Sep 28, 2024
1 parent f4e2fe5 commit c588d13
Show file tree
Hide file tree
Showing 155 changed files with 2,165 additions and 1,296 deletions.
11 changes: 1 addition & 10 deletions baseapp/baseapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,7 @@ type (
StoreLoader func(ms storetypes.CommitMultiStore) error
)

const (
execModeCheck execMode = iota // Check a transaction
execModeReCheck // Recheck a (pending) transaction after a commit
execModeSimulate // Simulate a transaction
execModePrepareProposal // Prepare a block proposal
execModeProcessProposal // Process a block proposal
execModeVoteExtension // Extend or verify a pre-commit vote
execModeVerifyVoteExtension // Verify a vote extension
execModeFinalize // Finalize a block proposal
)
var _ abci.Application = (*BaseApp)(nil)

var _ servertypes.ABCI = (*BaseApp)(nil)

Expand Down
2 changes: 1 addition & 1 deletion client/config/toml.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func setConfigTemplate(customTemplate string) error {
return err
}

return nil
return ioutil.WriteFile(configFilePath, buffer.Bytes(), 0o600)
}

// writeConfigFile renders config using the template and writes it to
Expand Down
57 changes: 4 additions & 53 deletions client/debug/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,16 +191,8 @@ func PubkeyRawCmd() *cobra.Command {
`, version.AppName, version.AppName, version.AppName),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)

pubkeyType, err := cmd.Flags().GetString(flagPubkeyType)
if err != nil {
return err
}
pubkeyType = strings.ToLower(pubkeyType)
if pubkeyType != "secp256k1" && pubkeyType != ed {
return errorsmod.Wrapf(errors.ErrInvalidType, "invalid pubkey type, expected oneof ed25519 or secp256k1")
}
addrString := args[0]
var addr []byte

pk, err := getPubKeyFromRawString(args[0], pubkeyType)
if err != nil {
Expand Down Expand Up @@ -239,49 +231,8 @@ func PubkeyRawCmd() *cobra.Command {
cmd.Println("Bech32 Validator Consensus:", consensusPub)
}

return nil
},
}
cmd.Flags().StringP(flagPubkeyType, "t", ed, "Pubkey type to decode (oneof secp256k1, ed25519)")
return cmd
}

func AddrCmd() *cobra.Command {
return &cobra.Command{
Use: "addr <address>",
Short: "Convert an address between hex and bech32",
Example: fmt.Sprintf("%s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg", version.AppName),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)

addrString := args[0]
// try hex, then bech32
var (
addr []byte
err error
)
decodeFns := []func(text string) ([]byte, error){
hex.DecodeString,
clientCtx.AddressCodec.StringToBytes,
clientCtx.ValidatorAddressCodec.StringToBytes,
clientCtx.ConsensusAddressCodec.StringToBytes,
}
errs := make([]any, 0, len(decodeFns))
for _, fn := range decodeFns {
if addr, err = fn(addrString); err == nil {
break
}
errs = append(errs, err)
}
if len(errs) == len(decodeFns) {
errTags := []string{
"hex", "bech32 acc", "bech32 val", "bech32 con",
}
format := ""
for i := range errs {
if format != "" {
format += ", "
if err3 != nil {
return fmt.Errorf("expected hex or bech32. Got errors: hex: %v, bech32 acc: %v, bech32 val: %v", err, err2, err3)
}
format += errTags[i] + ": %w"
}
Expand Down
11 changes: 3 additions & 8 deletions client/grpc/cmtservice/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,9 @@ var (
_ gogoprotoany.UnpackInterfacesMessage = &GetLatestValidatorSetResponse{}
)

type (
abciQueryFn = func(context.Context, *abci.QueryRequest) (*abci.QueryResponse, error)

queryServer struct {
rpc CometRPC
queryFn abciQueryFn
consensusCodec address.Codec
}
var (
_ ServiceServer = queryServer{}
_ codectypes.UnpackInterfacesMessage = &GetLatestValidatorSetResponse{}
)

// NewQueryServer creates a new CometBFT query server.
Expand Down
3 changes: 3 additions & 0 deletions client/grpc_query_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//go:build norace
// +build norace

package client_test

import (
Expand Down
1 change: 0 additions & 1 deletion client/input/input_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,4 @@ func TestReadLineFromBuf(t *testing.T) {
_, err := readLineFromBuf(buf)
require.ErrorIs(t, err, expectedErr)
})

}
2 changes: 1 addition & 1 deletion client/keys/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ HbP+c6JmeJy9JXe2rbbF1QtCX1gLqGcDQPBXiCtFvP7/8wTZtVOPj8vREzhZ9ElO

keyfile := filepath.Join(kbHome, "key.asc")

require.NoError(t, ioutil.WriteFile(keyfile, []byte(armoredKey), 0644))
require.NoError(t, ioutil.WriteFile(keyfile, []byte(armoredKey), 0o644))

defer func() {
_ = os.RemoveAll(kbHome)
Expand Down
2 changes: 1 addition & 1 deletion client/keys/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func Test_runListCmd(t *testing.T) {
WithValidatorAddressCodec(addresscodec.NewBech32Codec("cosmosvaloper")).
WithConsensusAddressCodec(addresscodec.NewBech32Codec("cosmosvalcons"))

path := "" //sdk.GetConfig().GetFullBIP44Path()
path := "" // sdk.GetConfig().GetFullBIP44Path()
_, err = kb.NewAccount("something", testdata.TestMnemonic, "", path, hd.Secp256k1)
require.NoError(t, err)

Expand Down
65 changes: 8 additions & 57 deletions client/keys/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,65 +29,16 @@ type setter interface {
type MigrateTestSuite struct {
suite.Suite

dir string
appName string
cdc codec.Codec
priv cryptotypes.PrivKey
pub cryptotypes.PubKey
}

func TestMigrateTestSuite(t *testing.T) {
suite.Run(t, new(MigrateTestSuite))
}

func (s *MigrateTestSuite) SetupSuite() {
s.dir = s.T().TempDir()
s.cdc = moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}).Codec
s.appName = "cosmos"
s.priv = cryptotypes.PrivKey(secp256k1.GenPrivKey())
s.pub = s.priv.PubKey()
}

func (s *MigrateTestSuite) Test_runListAndShowCmd() {
// adding LegacyInfo item into keyring
multi := multisig.NewLegacyAminoPubKey(
1, []cryptotypes.PubKey{
s.pub,
},
)
legacyMultiInfo, err := keyring.NewLegacyMultiInfo(s.appName, multi)
s.Require().NoError(err)
serializedLegacyMultiInfo := keyring.MarshalInfo(legacyMultiInfo)

item := design99keyring.Item{
Key: s.appName + ".info",
Data: serializedLegacyMultiInfo,
Description: "SDK keyring version",
}

// run test simd keys list - to see that the migrated key is there
cmd := ListKeysCmd()
cmd.Flags().AddFlagSet(Commands().PersistentFlags())

mockIn := testutil.ApplyMockIODiscardOutErr(cmd)
kb, err := keyring.New(s.appName, keyring.BackendTest, s.dir, mockIn, s.cdc)
s.Require().NoError(err)

setter, ok := kb.(setter)
s.Require().True(ok)
s.Require().NoError(setter.SetItem(item))

clientCtx := client.Context{}.
WithKeyring(kb).
WithAddressCodec(addresscodec.NewBech32Codec("cosmos")).
WithValidatorAddressCodec(addresscodec.NewBech32Codec("cosmosvaloper")).
WithConsensusAddressCodec(addresscodec.NewBech32Codec("cosmosvalcons"))

ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx)
cmd := MigrateCommand()
cmd.Flags().AddFlagSet(Commands("home").PersistentFlags())
// mockIn := testutil.ApplyMockIODiscardOutErr(cmd)
mockIn, mockOut := testutil.ApplyMockIO(cmd)

cmd.SetArgs([]string{
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, s.dir),
fmt.Sprintf("--%s=false", flagListNames),
kbHome,
// fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome),
fmt.Sprintf("--%s=true", flags.FlagDryRun),
fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest),
})

s.Require().NoError(cmd.ExecuteContext(ctx))
Expand Down
2 changes: 1 addition & 1 deletion client/query_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build norace
// +build norace

package client_test
Expand All @@ -11,7 +12,6 @@ import (
)

func (s *IntegrationTestSuite) TestQueryABCIHeight() {

testCases := []struct {
name string
reqHeight int64
Expand Down
2 changes: 1 addition & 1 deletion codec/amino_codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,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)
Expand Down
8 changes: 4 additions & 4 deletions codec/codec_common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,10 @@ func testMarshaling(t *testing.T, cdc interface {
m1 := mustMarshaler{cdc.Marshal, cdc.MustMarshal, cdc.Unmarshal, cdc.MustUnmarshal}
m2 := mustMarshaler{cdc.MarshalLengthPrefixed, cdc.MustMarshalLengthPrefixed, cdc.UnmarshalLengthPrefixed, cdc.MustUnmarshalLengthPrefixed}
m3 := mustMarshaler{
func(i proto.Message) ([]byte, error) { return cdc.MarshalJSON(i) },
func(i proto.Message) []byte { return cdc.MustMarshalJSON(i) },
func(bz []byte, ptr proto.Message) error { return cdc.UnmarshalJSON(bz, ptr) },
func(bz []byte, ptr proto.Message) { cdc.MustUnmarshalJSON(bz, ptr) },
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) },
}

t.Run(tc.name+"_BinaryBare",
Expand Down
5 changes: 4 additions & 1 deletion codec/proto_codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ type ProtoCodec struct {
interfaceRegistry types.InterfaceRegistry
}

var _ Codec = (*ProtoCodec)(nil)
var (
_ Codec = &ProtoCodec{}
_ ProtoCodecMarshaler = &ProtoCodec{}
)

// NewProtoCodec returns a reference to a new ProtoCodec
func NewProtoCodec(interfaceRegistry types.InterfaceRegistry) *ProtoCodec {
Expand Down
6 changes: 1 addition & 5 deletions crypto/armor.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,11 +161,7 @@ func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase, algo string) s

func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes, encBytes []byte) {
saltBytes = crypto.CRandBytes(16)

key := argon2.IDKey([]byte(passphrase), saltBytes, argon2Time, argon2Memory, argon2Threads, chacha20poly1305.KeySize)
privKeyBytes := legacy.Cdc.MustMarshal(privKey)

aead, err := chacha20poly1305.New(key)
key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter)
if err != nil {
panic(errorsmod.Wrap(err, "error generating cypher from key"))
}
Expand Down
2 changes: 1 addition & 1 deletion crypto/hd/algo.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const (
var Secp256k1 = secp256k1Algo{}

type (
DeriveFn func(mnemonic, bip39Passphrase, hdPath string) ([]byte, error)
DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error)
GenerateFn func(bz []byte) types.PrivKey
)

Expand Down
2 changes: 1 addition & 1 deletion crypto/keyring/keyring.go
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) {
continue
}

if err := os.WriteFile(keyhashFilePath, passwordHash, 0o600); err != nil {
if err := ioutil.WriteFile(dir+"/keyhash", passwordHash, 0o555); err != nil {
return "", err
}

Expand Down
5 changes: 2 additions & 3 deletions crypto/keyring/keyring_ledger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ import (
)

func TestInMemoryCreateLedger(t *testing.T) {
cdc := getCodec()
kb := NewInMemory(cdc)
kb := NewInMemory()

k, err := kb.SaveLedgerKey("some_account", hd.Secp256k1, "cosmos", 118, 3, 1)
ledger, 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())
Expand Down
4 changes: 0 additions & 4 deletions crypto/keys/internal/ecdsa/privkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down
10 changes: 5 additions & 5 deletions crypto/keys/internal/ecdsa/privkey_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"github.com/tendermint/tendermint/crypto"
"math/big"
"testing"

"github.com/tendermint/tendermint/crypto"

"github.com/stretchr/testify/suite"
)

Expand Down Expand Up @@ -39,11 +40,10 @@ func (suite *SKSuite) TestMarshal() {
const size = 32

buffer := make([]byte, size)
_, err := suite.sk.MarshalTo(buffer)
require.NoError(err)
suite.sk.MarshalTo(buffer)

sk := new(PrivKey)
err = sk.Unmarshal(buffer, secp256r1, size)
err := sk.Unmarshal(buffer, secp256r1, size)
require.NoError(err)
require.True(sk.Equal(&suite.sk.PrivateKey))
}
Expand Down Expand Up @@ -81,7 +81,7 @@ func (suite *SKSuite) TestSign() {
// leave r untouched!
high_s := new(big.Int).Mod(new(big.Int).Neg(low_s), elliptic.P256().Params().N)

require.False(suite.pk.VerifySignature(msg, signatureRaw(r,high_s)))
require.False(suite.pk.VerifySignature(msg, signatureRaw(r, high_s)))

// Valid signature using low_s, but too long
sigCpy = make([]byte, len(sig)+2)
Expand Down
1 change: 0 additions & 1 deletion crypto/keys/internal/ecdsa/pubkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,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
Expand Down
4 changes: 2 additions & 2 deletions crypto/keys/multisig/multisig.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import (
)

var (
_ multisigtypes.PubKey = &LegacyAminoPubKey{}
_ gogoprotoany.UnpackInterfacesMessage = &LegacyAminoPubKey{}
_ multisigtypes.PubKey = &LegacyAminoPubKey{}
_ types.UnpackInterfacesMessage = &LegacyAminoPubKey{}
)

// NewLegacyAminoPubKey returns a new LegacyAminoPubKey.
Expand Down
Loading

0 comments on commit c588d13

Please sign in to comment.