diff --git a/.changelog/unreleased/dependencies/2132-bump-go-to-1.23.md b/.changelog/unreleased/dependencies/2132-bump-go-to-1.23.md new file mode 100644 index 0000000000..d8390f222f --- /dev/null +++ b/.changelog/unreleased/dependencies/2132-bump-go-to-1.23.md @@ -0,0 +1,2 @@ +* Bump `go` to 1.23 (from 1.21) [#2132](https://github.com/provenance-io/provenance/pull/2132). +* Bump `golangci-lint` to v1.60.2 (from v1.54.2) [#2132](https://github.com/provenance-io/provenance/pull/2132). diff --git a/.changelog/unreleased/summary.md b/.changelog/unreleased/summary.md new file mode 100644 index 0000000000..18b3c5cd08 --- /dev/null +++ b/.changelog/unreleased/summary.md @@ -0,0 +1,2 @@ +Building or installing `provenanced` from source now requires you to use [Go 1.23](https://golang.org/dl/). +Linting now requires `golangci-lint` v1.60.2. You can update yours using `make golangci-lint-update` or install it using `make golangci-lint`. diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 6cb32bd870..35b6386023 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -82,7 +82,7 @@ jobs: - uses: actions/setup-go@v5 with: - go-version: '1.21' + go-version-file: 'go.mod' - run: go mod vendor diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 3cc12a8e0e..f49e0e0eee 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -30,12 +30,12 @@ jobs: - uses: actions/setup-go@v5 if: env.GIT_DIFF with: - go-version: '1.21' + go-version-file: 'go.mod' - uses: golangci/golangci-lint-action@v6 if: env.GIT_DIFF with: # If you change this version, be sure to also change it in contrib/devtools/Makefile. - version: v1.54 + version: v1.60 args: --timeout 10m --out-${NO_FUTURE}format colored-line-number github-token: ${{ secrets.github_token }} - name: No Now Usage diff --git a/.github/workflows/proto.yml b/.github/workflows/proto.yml index f936aac961..bacbe31777 100644 --- a/.github/workflows/proto.yml +++ b/.github/workflows/proto.yml @@ -30,7 +30,7 @@ jobs: - name: Setup go uses: actions/setup-go@v5 with: - go-version: '1.21' + go-version-file: 'go.mod' - name: Setup Job id: setup run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b7c3e56dcf..2bb824b20d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -55,7 +55,6 @@ jobs: version: ${{ steps.vars.outputs.version }} is_release: ${{ steps.vars.outputs.is_release }} prerelease: ${{ steps.vars.outputs.prerelease }} - go_version: '1.21' build_osx: runs-on: macos-latest @@ -68,7 +67,7 @@ jobs: - name: Setup go uses: actions/setup-go@v5 with: - go-version: ${{ needs.build_init.outputs.go_version }} + go-version-file: 'go.mod' - name: Build osx binary run: | export VERSION=${{ needs.build_init.outputs.version }} @@ -93,7 +92,7 @@ jobs: - name: Setup go uses: actions/setup-go@v5 with: - go-version: ${{ needs.build_init.outputs.go_version }} + go-version-file: 'go.mod' - name: Install deps run: | sudo apt-get update @@ -163,7 +162,7 @@ jobs: - name: Setup go uses: actions/setup-go@v5 with: - go-version: ${{ needs.build_init.outputs.go_version }} + go-version-file: 'go.mod' - name: Download linux zip artifact uses: actions/download-artifact@v4 with: diff --git a/.github/workflows/sims.yml b/.github/workflows/sims.yml index 878dbcb200..db40d975a2 100644 --- a/.github/workflows/sims.yml +++ b/.github/workflows/sims.yml @@ -41,22 +41,9 @@ jobs: file_prefix="sim-test-${GITHUB_SHA:0:7}-${GITHUB_RUN_ATTEMPT}" echo "Setting output: file-prefix=$file_prefix" echo "file-prefix=$file_prefix" >> "$GITHUB_OUTPUT" - go_cache_key_hash="${{ hashFiles('go.sum') }}" - echo "Setting output: go-cache-key-hash=$go_cache_key_hash" - echo "go-cache-key-hash=$go_cache_key_hash" >> "$GITHUB_OUTPUT" outputs: - go-version: '1.21' should-run: ${{ env.GIT_DIFF }} file-prefix: ${{ steps.def-vars.outputs.file-prefix }} - go-cache-key-suffix: sims-go3-${{ steps.def-vars.outputs.go-cache-key-hash }} - # In Order: - # * Go binary directory - # * Go module directory - # * Go build cache (Linux) - go-cache-path: | - ~/go/bin - ~/go/pkg/mod - ~/.cache/go-build build-linux: needs: setup @@ -66,17 +53,8 @@ jobs: - uses: actions/checkout@v4 - name: Output setup run: | - echo " go-version: [${{ needs.setup.outputs.go-version }}]" - echo " should-run: [${{ needs.setup.outputs.should-run }}]" - echo " file-prefix: [${{ needs.setup.outputs.file-prefix }}]" - echo "go-cache-key-suffix: [${{ needs.setup.outputs.go-cache-key-suffix }}]" - echo " go-cache-path: [${{ needs.setup.outputs.go-cache-path }}]" - - uses: actions/cache@v4 - name: Load go cache - id: go-cache-setup - with: - key: ${{ runner.os }}-${{ needs.setup.outputs.go-cache-key-suffix }} - path: ${{ needs.setup.outputs.go-cache-path }} + echo " should-run: [${{ needs.setup.outputs.should-run }}]" + echo "file-prefix: [${{ needs.setup.outputs.file-prefix }}]" - name: Setup build environment env: DEBIAN_FRONTEND: noninteractive @@ -85,12 +63,7 @@ jobs: sudo apt-get install -y libgflags-dev libsnappy-dev zlib1g-dev libbz2-dev liblz4-dev libzstd-dev wget curl build-essential cmake gcc sqlite3 - uses: actions/setup-go@v5 with: - go-version: ${{ needs.setup.outputs.go-version }} - - name: Display go version - run: go version - - name: Install runsim - if: steps.go-cache-setup.outputs.cache-hit != 'true' - run: export GO111MODULE="on" && go get github.com/cosmos/tools/cmd/runsim@v1.0.0 + go-version-file: 'go.mod' - name: Update provwasm contract run: make download-smart-contracts - name: Build provenanced @@ -111,11 +84,6 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: actions/cache@v4 - name: Load go cache - with: - key: ${{ runner.os }}-${{ needs.setup.outputs.go-cache-key-suffix }} - path: ${{ needs.setup.outputs.go-cache-path }} - name: Define test-logs id: test-logs run: | @@ -124,9 +92,7 @@ jobs: echo "test-logs=$test_logs" >> "$GITHUB_OUTPUT" - uses: actions/setup-go@v5 with: - go-version: ${{ needs.setup.outputs.go-version }} - - name: Display go version - run: go version + go-version-file: 'go.mod' - name: Update provwasm contract run: make download-smart-contracts - name: Test @@ -170,11 +136,6 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: actions/cache@v4 - name: Load go cache - with: - key: ${{ runner.os }}-${{ needs.setup.outputs.go-cache-key-suffix }} - path: ${{ needs.setup.outputs.go-cache-path }} - name: Define test-logs id: test-logs run: | @@ -183,9 +144,7 @@ jobs: echo "test-logs=$test_logs" >> "$GITHUB_OUTPUT" - uses: actions/setup-go@v5 with: - go-version: ${{ needs.setup.outputs.go-version }} - - name: Display go version - run: go version + go-version-file: 'go.mod' - name: Update provwasm contract run: make download-smart-contracts - name: Test @@ -214,11 +173,6 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: actions/cache@v4 - name: Load go cache - with: - key: ${{ runner.os }}-${{ needs.setup.outputs.go-cache-key-suffix }} - path: ${{ needs.setup.outputs.go-cache-path }} - name: Define test-logs id: test-logs run: | @@ -227,9 +181,7 @@ jobs: echo "test-logs=$test_logs" >> "$GITHUB_OUTPUT" - uses: actions/setup-go@v5 with: - go-version: ${{ needs.setup.outputs.go-version }} - - name: Display go version - run: go version + go-version-file: 'go.mod' - name: Update provwasm contract run: make download-smart-contracts - name: Test diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6e2337bb4d..fca6af696c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -80,7 +80,6 @@ jobs: path: ./pkgs.txt.part.04 outputs: should-run: ${{ env.GIT_DIFF }} - go-version: '1.21' file-prefix: ${{ steps.def-vars.outputs.file-prefix }} @@ -104,7 +103,7 @@ jobs: - uses: actions/setup-go@v5 if: needs.setup-tests.outputs.should-run with: - go-version: ${{ needs.setup-tests.outputs.go-version }} + go-version-file: 'go.mod' - uses: actions/download-artifact@v4 if: needs.setup-tests.outputs.should-run with: @@ -191,7 +190,7 @@ jobs: - uses: actions/setup-go@v5 if: needs.setup-tests.outputs.should-run with: - go-version: ${{ needs.setup-tests.outputs.go-version }} + go-version-file: 'go.mod' - uses: actions/download-artifact@v4 if: needs.setup-tests.outputs.should-run with: diff --git a/.golangci.yml b/.golangci.yml index c5ea87e3c3..fb2b580fcb 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -9,13 +9,13 @@ linters: - asciicheck - bidichk - bodyclose + - copyloopvar - depguard - dogsled - durationcheck - errcheck - errorlint - errname - - exportloopref # - forcetypeassert - gci - goconst @@ -150,7 +150,9 @@ linters-settings: allow: - $gostd - github.com/stretchr/testify - + errcheck: + exclude-functions: + - (fmt.State).Write gci: custom-order: true sections: diff --git a/Makefile b/Makefile index 5ac17ddc07..869ef8bb84 100644 --- a/Makefile +++ b/Makefile @@ -34,11 +34,11 @@ HTTPS_GIT := https://github.com/provenance-io/provenance.git DOCKER := $(shell which docker) DOCKER_BUF := $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace bufbuild/buf -# Only support go version 1.21 +# Only support go version 1.23 +SUPPORTED_GO_MAJOR_VERSION = 1 +SUPPORTED_GO_MINOR_VERSION = 23 GO_MAJOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f1) GO_MINOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2) -SUPPORTED_GO_MAJOR_VERSION = 1 -SUPPORTED_GO_MINOR_VERSION = 21 GO_VERSION_VALIDATION_ERR_MSG = Golang version $(GO_MAJOR_VERSION).$(GO_MINOR_VERSION) is not supported, you must use $(SUPPORTED_GO_MAJOR_VERSION).$(SUPPORTED_GO_MINOR_VERSION) # The below include contains the tools target. @@ -128,7 +128,7 @@ all: build format lint test ############################## # Install puts the binaries in the local environment path. -install: go.sum +install: validate-go-version go.sum CGO_LDFLAGS="$(CGO_LDFLAGS)" CGO_CFLAGS="$(CGO_CFLAGS)" $(GO) install $(BUILD_FLAGS) ./cmd/provenanced build: validate-go-version go.sum @@ -222,7 +222,7 @@ $(RELEASE_PLAN): $(RELEASE_CHECKSUM) build-release-libwasm: $(RELEASE_WASM) $(RELEASE_WASM): $(RELEASE_BIN) - go mod vendor && \ + $(GO) mod vendor && \ cp vendor/github.com/CosmWasm/wasmvm/v2/internal/api/$(LIBWASMVM) $(RELEASE_BIN) .PHONY: build-release-bin @@ -482,7 +482,7 @@ proto-gen: sh ./scripts/protocgen.sh; \ fi mv .go.mod.bak go.mod - go mod tidy + $(GO)go mod tidy proto-swagger-gen: @echo "Generating Protobuf Swagger" @@ -492,7 +492,7 @@ proto-swagger-gen: docker run --name $(containerProtoGenSwagger) -v $(CURDIR):/workspace --workdir /workspace $(containerProtoImage) \ sh ./scripts/protoc-swagger-gen.sh; \ fi - go mod tidy + $(GO) mod tidy proto-format: @echo "Formatting Protobuf files" diff --git a/README.md b/README.md index 555e3b1a2e..b9d1c8e0dd 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ As the [Provenance Blockchain][provenance] and its core modules are based on the Developers can use a local checkout and the make targets `make run` and `make localnet-start` to run a local development network. -Note: Requires [Go 1.21+](https://golang.org/dl/) +Note: Requires [Go 1.23](https://golang.org/dl/) (specifically). See Also: [Building](docs/Building.md) diff --git a/app/prefix.go b/app/prefix.go index 8afac2aad8..536bf57c73 100644 --- a/app/prefix.go +++ b/app/prefix.go @@ -7,8 +7,8 @@ import ( const ( AccountAddressPrefixMainNet = "pb" AccountAddressPrefixTestNet = "tp" - CoinTypeMainNet = 505 - CoinTypeTestNet = 1 + CoinTypeMainNet = uint32(505) + CoinTypeTestNet = uint32(1) Purpose = 44 ) @@ -39,7 +39,7 @@ func SetConfig(testnet bool, seal bool) { ConsNodePubKeyPrefix = AccountAddressPrefix + "valconspub" config := sdk.GetConfig() - config.SetCoinType(uint32(CoinType)) + config.SetCoinType(CoinType) config.SetPurpose(Purpose) config.SetBech32PrefixForAccount(AccountAddressPrefix, AccountPubKeyPrefix) config.SetBech32PrefixForValidator(ValidatorAddressPrefix, ValidatorPubKeyPrefix) diff --git a/app/prefix_test/prefix_test.go b/app/prefix_test/prefix_test.go index 07349b5102..b608f0b095 100644 --- a/app/prefix_test/prefix_test.go +++ b/app/prefix_test/prefix_test.go @@ -37,7 +37,7 @@ func TestSetConfig(t *testing.T) { seal bool expPath string expHRP string - expCoinType int + expCoinType uint32 expPanic string }{ { @@ -151,8 +151,8 @@ func TestSetConfig(t *testing.T) { assert.Equal(t, expConsPubPre, consPubPre, "sdkConfig.GetBech32ConsensusPubPrefix()") assert.Equal(t, tc.expPath, fullBIP44Path, "sdkConfig.GetFullBIP44Path()") - assert.Equal(t, tc.expCoinType, app.CoinType, "CoinType") - assert.Equal(t, tc.expCoinType, int(coinType), "sdkConfig.GetCoinType()") + assert.Equal(t, tc.expCoinType, app.CoinType, "CoinType - Exp = %d, Act = %d", tc.expCoinType, app.CoinType) + assert.Equal(t, tc.expCoinType, coinType, "sdkConfig.GetCoinType() - Exp = %d, Act = %d", tc.expCoinType, coinType) assert.Equal(t, 44, app.Purpose, "Purpose") assert.Equal(t, 44, int(purpose), "sdkConfig.GetPurpose()") } diff --git a/cmd/provenanced/cmd/tree.go b/cmd/provenanced/cmd/tree.go index 6784059a26..4489a3c06a 100644 --- a/cmd/provenanced/cmd/tree.go +++ b/cmd/provenanced/cmd/tree.go @@ -26,7 +26,7 @@ func GetTreeCmd() *cobra.Command { cmd.SilenceUsage = true return fmt.Errorf("command not found: %q", args) } - cmd.Printf(strings.Join(cmds, "\n") + "\n") + cmd.Printf("%s\n", strings.Join(cmds, "\n")) return nil }, DisableFlagsInUseLine: true, diff --git a/contrib/devtools/Makefile b/contrib/devtools/Makefile index 7c8dca4b9a..8e9fce5201 100644 --- a/contrib/devtools/Makefile +++ b/contrib/devtools/Makefile @@ -80,7 +80,7 @@ tools-clean: rm -f proto-tools-stamp tools-stamp # If you change this version, be sure to also change it in .github/workflows/lint.yml. -GOLANGCI_LINT_VERSION = v1.54.2 +GOLANGCI_LINT_VERSION = v1.60.2 golangci-lint: $(GOLANGCI_LINT) $(GOLANGCI_LINT): @$(MAKE) golangci-lint-update diff --git a/docker/blockchain/Dockerfile b/docker/blockchain/Dockerfile index 62727f8a06..9d840aad4f 100644 --- a/docker/blockchain/Dockerfile +++ b/docker/blockchain/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.21-bullseye as build +FROM golang:1.23-bullseye as build ARG VERSION WORKDIR /go/src/github.com/provenance-io/provenance diff --git a/docs/Building.md b/docs/Building.md index 2d896e4ef2..851336078d 100644 --- a/docs/Building.md +++ b/docs/Building.md @@ -18,7 +18,7 @@ Built executables are placed in the `build/` directory. ### Go -Building `provenanced` requires [Go 1.21+](https://golang.org/dl/) (or higher). +Building `provenanced` requires [Go 1.23](https://golang.org/dl/) (specifically). ## Building or Installing `provenanced` diff --git a/go.mod b/go.mod index 39d0d9e13a..bbb660137d 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/provenance-io/provenance -go 1.21 +go 1.23 require ( cosmossdk.io/api v0.7.5 diff --git a/internal/antewrapper/min_gas_prices_decorator.go b/internal/antewrapper/min_gas_prices_decorator.go index b5fef35ab5..516b7db441 100644 --- a/internal/antewrapper/min_gas_prices_decorator.go +++ b/internal/antewrapper/min_gas_prices_decorator.go @@ -61,7 +61,7 @@ func checkTxFeeWithValidatorMinGasPrices(ctx sdk.Context, tx sdk.Tx) error { // Determine the required fees by multiplying each required minimum gas // price by the gas limit, where fee = ceil(minGasPrice * gasLimit). - glDec := sdkmath.LegacyNewDec(int64(gas)) + glDec := sdkmath.LegacyNewDecFromBigInt(sdkmath.NewIntFromUint64(gas).BigInt()) for i, gp := range minGasPrices { fee := gp.Amount.Mul(glDec) requiredFees[i] = sdk.NewCoin(gp.Denom, fee.Ceil().RoundInt()) diff --git a/internal/collections/maps.go b/internal/collections/maps.go deleted file mode 100644 index 979e80bdcc..0000000000 --- a/internal/collections/maps.go +++ /dev/null @@ -1,15 +0,0 @@ -package collections - -// This file houses functions that are in "golang.org/x/exp/maps" but not "maps", but that we want to use. -// If any show up in "maps", delete them from here and switch uses to the official ones. - -// Keys returns the unordered keys of the given map. -// This is the same as the experimental maps.Keys function. -// As of writing, that isn't in the standard library version yet. Once it is, remove this and switch to that. -func Keys[M ~map[K]V, K comparable, V any](m M) []K { - rv := make([]K, 0, len(m)) - for k := range m { - rv = append(rv, k) - } - return rv -} diff --git a/internal/rand/int.go b/internal/rand/int.go index 79cc69ad51..653beb708e 100644 --- a/internal/rand/int.go +++ b/internal/rand/int.go @@ -3,6 +3,6 @@ package rand import "math/rand" // IntBetween generates a random number between min and max inclusive. -func IntBetween(r *rand.Rand, min, max int) int { - return r.Intn(max-min+1) + min +func IntBetween(r *rand.Rand, minVal, maxVal int) int { + return r.Intn(maxVal-minVal+1) + minVal } diff --git a/internal/rand/int_test.go b/internal/rand/int_test.go index 690ff1b868..434025e169 100644 --- a/internal/rand/int_test.go +++ b/internal/rand/int_test.go @@ -2,11 +2,11 @@ package rand import ( "fmt" + "maps" "math/rand" "slices" "testing" - internalcollections "github.com/provenance-io/provenance/internal/collections" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -81,7 +81,7 @@ func TestIntBetween(t *testing.T) { assert.True(t, seen[tc.min], "minimum value %d in seen map", tc.min) assert.True(t, seen[tc.max], "maximum value %d in seen map", tc.max) - seenVals := internalcollections.Keys(seen) + seenVals := slices.Collect(maps.Keys(seen)) slices.Sort(seenVals) // Make sure the smallest and largest are as expected. assert.Equal(t, tc.min, seenVals[0], "smallest number generated") diff --git a/networks/dev/blockchain-dev/Dockerfile b/networks/dev/blockchain-dev/Dockerfile index a213abacdb..45738f3ed4 100644 --- a/networks/dev/blockchain-dev/Dockerfile +++ b/networks/dev/blockchain-dev/Dockerfile @@ -2,7 +2,7 @@ # Use `make docker-build-dev` to build or `make devnet-start` to # start the test network and `make devnet-stop` to stop it. -FROM golang:1.21-bullseye as build-x86_64 +FROM golang:1.23-bullseye as build-x86_64 WORKDIR /go/src/github.com/provenance-io/provenance ENV GOPRIVATE=github.com/provenance-io RUN apt-get update && apt-get upgrade -y @@ -48,7 +48,7 @@ CMD ["start"] ## Build provenance for ARM -FROM golang:1.21-bullseye as build-arm64 +FROM golang:1.23-bullseye as build-arm64 WORKDIR /go/src/github.com/provenance-io/provenance ENV GOPRIVATE=github.com/provenance-io RUN apt-get update && apt-get upgrade -y diff --git a/networks/ibc/blockchain-ibc/Dockerfile b/networks/ibc/blockchain-ibc/Dockerfile index 2c46dea624..5bc95c6992 100644 --- a/networks/ibc/blockchain-ibc/Dockerfile +++ b/networks/ibc/blockchain-ibc/Dockerfile @@ -3,7 +3,7 @@ # start the test network and `make localnet-stop` to stop it. ## Build provenance for x86_64 -FROM golang:1.21-bullseye as build-x86_64 +FROM golang:1.23-bullseye as build-x86_64 WORKDIR /go/src/github.com/provenance-io/provenance ENV GOPRIVATE=github.com/provenance-io RUN apt-get update && apt-get upgrade -y @@ -52,7 +52,7 @@ CMD ["start"] ## Build provenance for ARM -FROM golang:1.21-bullseye as build-arm64 +FROM golang:1.23-bullseye as build-arm64 WORKDIR /go/src/github.com/provenance-io/provenance ENV GOPRIVATE=github.com/provenance-io RUN apt-get update && apt-get upgrade -y diff --git a/networks/ibc/blockchain-relayer/Dockerfile b/networks/ibc/blockchain-relayer/Dockerfile index 9835001b13..1029e2d4f0 100644 --- a/networks/ibc/blockchain-relayer/Dockerfile +++ b/networks/ibc/blockchain-relayer/Dockerfile @@ -1,5 +1,5 @@ ## Build provenance for ARM -FROM golang:1.21-bullseye as build +FROM golang:1.23-bullseye as build WORKDIR / ARG VERSION RUN apt-get update && apt-get upgrade -y && apt-get install -y git diff --git a/networks/local/blockchain-local/Dockerfile b/networks/local/blockchain-local/Dockerfile index 01deb0b6b9..8b01168e78 100644 --- a/networks/local/blockchain-local/Dockerfile +++ b/networks/local/blockchain-local/Dockerfile @@ -3,7 +3,7 @@ # start the test network and `make localnet-stop` to stop it. ## Build provenance for x86_64 -FROM golang:1.21-bullseye as build-x86_64 +FROM golang:1.23-bullseye as build-x86_64 WORKDIR /go/src/github.com/provenance-io/provenance ENV GOPRIVATE=github.com/provenance-io RUN apt-get update && apt-get upgrade -y @@ -52,7 +52,7 @@ CMD ["start"] ## Build provenance for ARM -FROM golang:1.21-bullseye as build-arm64 +FROM golang:1.23-bullseye as build-arm64 WORKDIR /go/src/github.com/provenance-io/provenance ENV GOPRIVATE=github.com/provenance-io RUN apt-get update && apt-get upgrade -y diff --git a/testutil/sims.go b/testutil/sims.go index 06a99538ba..37e2b93303 100644 --- a/testutil/sims.go +++ b/testutil/sims.go @@ -38,6 +38,7 @@ func LogOperationMsg(t *testing.T, operationMsg simtypes.OperationMsg, msg strin ) } +// GenerateTestingAccounts generates n new accounts, creates them (in state) and gives each 1 million power worth of bond tokens. func GenerateTestingAccounts(t *testing.T, ctx sdk.Context, app *app.App, r *rand.Rand, n int) []simtypes.Account { return GenerateTestingAccountsWithPower(t, ctx, app, r, n, 1_000_000) } @@ -131,7 +132,6 @@ func (a SimTestHelper) WithTestingAccountsWithPower(n int, power int64) *SimTest return &a } -// GenerateTestingAccounts generates n new accounts, creates them (in state) and gives each 1 million power worth of bond tokens. // ExpectedWeightedOp is the various aspects of a simulation.WeightedOperation to check. type ExpectedWeightedOp struct { // Weight is the expected WeightedOperation.Weight. @@ -298,7 +298,7 @@ func (a SimTestHelper) AssertSimOp(expected ExpectedOp, opMaker func() simtypes. if !assert.NotPanics(a.T, testFunc, "executing the simtypes.Operation(...)") { return nil, fOps, false } - LogOperationMsg(a.T, opMsg, opDesc) + LogOperationMsg(a.T, opMsg, "%s", opDesc) // Check the error and number of future ops. ok := true diff --git a/x/attribute/client/cli/tx.go b/x/attribute/client/cli/tx.go index 88b56f611c..b32af092e2 100644 --- a/x/attribute/client/cli/tx.go +++ b/x/attribute/client/cli/tx.go @@ -339,7 +339,8 @@ func NewUpdateParamsCmd() *cobra.Command { if err != nil { return fmt.Errorf("invalid max value length: %w", err) } - msg := types.NewMsgUpdateParamsRequest(authority, uint32(maxValueLength)) + maxValueLength32 := uint32(maxValueLength) //nolint:gosec // G115: ParseUint bitsize is 32, so we know this is okay. + msg := types.NewMsgUpdateParamsRequest(authority, maxValueLength32) return provcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, flagSet, msg) }, } diff --git a/x/attribute/keeper/query_server.go b/x/attribute/keeper/query_server.go index 1ae3a267eb..13f180cce9 100644 --- a/x/attribute/keeper/query_server.go +++ b/x/attribute/keeper/query_server.go @@ -2,7 +2,6 @@ package keeper import ( "context" - "fmt" "strings" "google.golang.org/grpc/codes" @@ -33,7 +32,7 @@ func (k Keeper) Attribute(c context.Context, req *types.QueryAttributeRequest) ( return nil, status.Error(codes.InvalidArgument, "empty attribute name") } if err := types.ValidateAttributeAddress(req.Account); err != nil { - return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid account address: %v", err)) + return nil, status.Errorf(codes.InvalidArgument, "invalid account address: %v", err) } ctx := sdk.UnwrapSDKContext(c) attributes := make([]types.Attribute, 0) @@ -67,7 +66,7 @@ func (k Keeper) Attributes(c context.Context, req *types.QueryAttributesRequest) return nil, status.Error(codes.InvalidArgument, "invalid request") } if err := types.ValidateAttributeAddress(req.Account); err != nil { - return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid account address: %v", err)) + return nil, status.Errorf(codes.InvalidArgument, "invalid account address: %v", err) } ctx := sdk.UnwrapSDKContext(c) attributes := make([]types.Attribute, 0) @@ -107,7 +106,7 @@ func (k Keeper) Scan(c context.Context, req *types.QueryScanRequest) (*types.Que return nil, status.Error(codes.InvalidArgument, "empty attribute name suffix") } if err := types.ValidateAttributeAddress(req.Account); err != nil { - return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid account address: %v", err)) + return nil, status.Errorf(codes.InvalidArgument, "invalid account address: %v", err) } ctx := sdk.UnwrapSDKContext(c) attributes := make([]types.Attribute, 0) diff --git a/x/attribute/simulation/operations.go b/x/attribute/simulation/operations.go index 5e37a913be..bb06534b54 100644 --- a/x/attribute/simulation/operations.go +++ b/x/attribute/simulation/operations.go @@ -81,7 +81,7 @@ func SimulateMsgAddAttribute(simState module.SimulationState, _ keeper.Keeper, a return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgAddAttributeRequest{}), "no name records available to create under"), nil, nil } - t := types.AttributeType(r.Intn(9)) + t := types.AttributeType(r.Intn(9)) //nolint:gosec // G115: r.Intn(9) will always fit in an int32 (implicit cast here). msg := types.NewMsgAddAttributeRequest( randomRecord.GetAddress(), simAccount.Address, @@ -107,7 +107,7 @@ func SimulateMsgUpdateAttribute(simState module.SimulationState, k keeper.Keeper return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgUpdateAttributeRequest{}), "no attributes available to delete"), nil, nil } - t := types.AttributeType(r.Intn(9)) + t := types.AttributeType(r.Intn(9)) //nolint:gosec // G115: r.Intn(9) will always fit in an int32 (implicit cast here). msg := types.NewMsgUpdateAttributeRequest( randomAttribute.GetAddress(), simAccount.Address, @@ -169,7 +169,7 @@ func SimulateMsgSetAccountData(simState module.SimulationState, k keeper.Keeper, // 9 in 10 chance that it will be between 1 and MaxValueLen characters. value := "" if r.Intn(10) != 0 { - maxLen := uint(k.GetMaxValueLength(ctx)) + maxLen := k.GetMaxValueLength(ctx) if maxLen > 500 { maxLen = 500 } diff --git a/x/exchange/client/cli/flags.go b/x/exchange/client/cli/flags.go index 204266234e..e5cf3abba0 100644 --- a/x/exchange/client/cli/flags.go +++ b/x/exchange/client/cli/flags.go @@ -335,7 +335,7 @@ func ReadFlagMarketOrArg(flagSet *pflag.FlagSet, args []string) (uint32, error) if err != nil { return 0, fmt.Errorf("could not convert arg: %w", err) } - marketID = uint32(marketID64) + marketID = uint32(marketID64) //nolint:gosec // G115: ParseUint bitsize is 32, so we know this is okay. } if marketID == 0 { @@ -588,7 +588,10 @@ func ParseSplit(val string) (*exchange.DenomSplit, error) { return nil, fmt.Errorf("could not parse %q amount: %w", val, err) } - return &exchange.DenomSplit{Denom: denom, Split: uint32(amount)}, nil + return &exchange.DenomSplit{ + Denom: denom, + Split: uint32(amount), //nolint:gosec // G115: ParseUint bitsize is 32, so we know this is okay. + }, nil } // ParseSplits parses a DenomSplit from each of the provided vals. diff --git a/x/exchange/client/cli/tx_test.go b/x/exchange/client/cli/tx_test.go index d9dfb23180..a57621270c 100644 --- a/x/exchange/client/cli/tx_test.go +++ b/x/exchange/client/cli/tx_test.go @@ -3,6 +3,8 @@ package cli_test import ( "bytes" "fmt" + "maps" + "slices" "sort" sdkmath "cosmossdk.io/math" @@ -12,7 +14,6 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - internalcollections "github.com/provenance-io/provenance/internal/collections" "github.com/provenance-io/provenance/x/exchange" "github.com/provenance-io/provenance/x/exchange/client/cli" ) @@ -1010,7 +1011,7 @@ func (s *CmdTestSuite) TestCmdTxMarketManagePermissions() { } } - addrOrder := internalcollections.Keys(expPerms) + addrOrder := slices.Collect(maps.Keys(expPerms)) sort.Slice(addrOrder, func(i, j int) bool { return bytes.Compare(s.accountAddrs[addrOrder[i]], s.accountAddrs[addrOrder[j]]) < 0 }) @@ -1042,7 +1043,7 @@ func (s *CmdTestSuite) TestCmdTxMarketManagePermissions() { 3: {exchange.Permission_cancel, exchange.Permission_attributes}, } - addrOrder := internalcollections.Keys(expPerms) + addrOrder := slices.Collect(maps.Keys(expPerms)) sort.Slice(addrOrder, func(i, j int) bool { return bytes.Compare(s.accountAddrs[addrOrder[i]], s.accountAddrs[addrOrder[j]]) < 0 }) diff --git a/x/exchange/keeper/msg_server.go b/x/exchange/keeper/msg_server.go index 996f6d855f..897b7a9e08 100644 --- a/x/exchange/keeper/msg_server.go +++ b/x/exchange/keeper/msg_server.go @@ -330,7 +330,7 @@ func (k MsgServer) RejectPayments(goCtx context.Context, msg *exchange.MsgReject ctx := sdk.UnwrapSDKContext(goCtx) err = k.Keeper.RejectPayments(ctx, target, sources) if err != nil { - return nil, sdkerrors.ErrInvalidRequest.Wrapf(err.Error()) + return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } return &exchange.MsgRejectPaymentsResponse{}, nil diff --git a/x/exchange/keeper/params.go b/x/exchange/keeper/params.go index 007010370b..baac926c26 100644 --- a/x/exchange/keeper/params.go +++ b/x/exchange/keeper/params.go @@ -120,9 +120,9 @@ func (k Keeper) SetParams(ctx sdk.Context, params *exchange.Params) { deleteAllParamsSplits(store) var feeCreate, feeAccept []sdk.Coin if params != nil { - setParamsSplit(store, "", uint16(params.DefaultSplit)) + setParamsSplit(store, "", uint16(params.DefaultSplit)) //nolint:gosec // G115: Validated elsewhere to be 10,000 max. for _, split := range params.DenomSplits { - setParamsSplit(store, split.Denom, uint16(split.Split)) + setParamsSplit(store, split.Denom, uint16(split.Split)) //nolint:gosec // G115: Validated elsewhere to be 10,000 max. } feeCreate = params.FeeCreatePaymentFlat feeAccept = params.FeeAcceptPaymentFlat @@ -194,11 +194,11 @@ func (k Keeper) GetExchangeSplit(ctx sdk.Context, denom string) uint16 { if len(denom) > 0 && len(defaults.DenomSplits) > 0 { for _, ds := range defaults.DenomSplits { if ds.Denom == denom { - return uint16(ds.Split) + return uint16(ds.Split) //nolint:gosec // G115: Validated elsewhere to be 10,000 max. } } } // Lastly, use the default from the defaults. - return uint16(defaults.DefaultSplit) + return uint16(defaults.DefaultSplit) //nolint:gosec // G115: Validated elsewhere to be 10,000 max. } diff --git a/x/exchange/market_test.go b/x/exchange/market_test.go index 9250ee1126..cd263b2c5e 100644 --- a/x/exchange/market_test.go +++ b/x/exchange/market_test.go @@ -3,6 +3,8 @@ package exchange import ( "errors" "fmt" + "maps" + "slices" "sort" "strings" "testing" @@ -13,7 +15,6 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - internalcollections "github.com/provenance-io/provenance/internal/collections" "github.com/provenance-io/provenance/testutil/assertions" ) @@ -3153,7 +3154,7 @@ func TestPermission_Validate(t *testing.T) { } t.Run("all values have a test case", func(t *testing.T) { - allVals := internalcollections.Keys(Permission_name) + allVals := slices.Collect(maps.Keys(Permission_name)) sort.Slice(allVals, func(i, j int) bool { return allVals[i] < allVals[j] }) @@ -3330,7 +3331,7 @@ func TestParsePermission(t *testing.T) { } t.Run("all values have a test case", func(t *testing.T) { - allVals := internalcollections.Keys(Permission_name) + allVals := slices.Collect(maps.Keys(Permission_name)) sort.Slice(allVals, func(i, j int) bool { return allVals[i] < allVals[j] }) diff --git a/x/hold/keeper/keeper_test.go b/x/hold/keeper/keeper_test.go index c722ca4266..caf743244a 100644 --- a/x/hold/keeper/keeper_test.go +++ b/x/hold/keeper/keeper_test.go @@ -2,6 +2,8 @@ package keeper_test import ( "fmt" + "maps" + "slices" "sort" "strings" "testing" @@ -19,7 +21,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/testutil" "github.com/provenance-io/provenance/app" - internalcollections "github.com/provenance-io/provenance/internal/collections" "github.com/provenance-io/provenance/testutil/assertions" "github.com/provenance-io/provenance/x/hold" "github.com/provenance-io/provenance/x/hold/keeper" @@ -1529,7 +1530,7 @@ func (s *TestSuite) TestVestingAndHoldOverTime() { } // Put all the step values in order. - steps := internalcollections.Keys(stepsMap) + steps := slices.Collect(maps.Keys(stepsMap)) sort.Slice(steps, func(i, j int) bool { return steps[i] < steps[j] }) diff --git a/x/marker/client/cli/tx.go b/x/marker/client/cli/tx.go index 7bb9ba9c96..694c79a4cc 100644 --- a/x/marker/client/cli/tx.go +++ b/x/marker/client/cli/tx.go @@ -1391,7 +1391,7 @@ func GetCmdSetDenomMetadataProposal() *cobra.Command { }, { Denom: display, - Exponent: uint32(exponent), + Exponent: uint32(exponent), //nolint:gosec // G115: ParseUint bitsize is 32, so we know this is okay. }, }, Base: denom, diff --git a/x/marker/keeper/msg_server.go b/x/marker/keeper/msg_server.go index 82841e7240..6ad2d61843 100644 --- a/x/marker/keeper/msg_server.go +++ b/x/marker/keeper/msg_server.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/go-metrics" "cosmossdk.io/errors" + sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" @@ -113,7 +114,8 @@ func (k msgServer) AddMarker(goCtx context.Context, msg *types.MsgAddMarkerReque return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } - nav := types.NewNetAssetValue(sdk.NewInt64Coin(types.UsdDenom, int64(msg.UsdMills)), msg.Volume) + usdMills := sdkmath.NewIntFromUint64(msg.UsdMills) + nav := types.NewNetAssetValue(sdk.NewCoin(types.UsdDenom, usdMills), msg.Volume) err = k.AddSetNetAssetValues(ctx, ma, []types.NetAssetValue{nav}, types.ModuleName) if err != nil { return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) @@ -515,7 +517,8 @@ func (k msgServer) AddFinalizeActivateMarker(goCtx context.Context, msg *types.M normalizedReqAttrs, ) - err = k.AddSetNetAssetValues(ctx, ma, []types.NetAssetValue{types.NewNetAssetValue(sdk.NewInt64Coin(types.UsdDenom, int64(msg.UsdMills)), msg.Volume)}, types.ModuleName) + usdMills := sdkmath.NewIntFromUint64(msg.UsdMills) + err = k.AddSetNetAssetValues(ctx, ma, []types.NetAssetValue{types.NewNetAssetValue(sdk.NewCoin(types.UsdDenom, usdMills), msg.Volume)}, types.ModuleName) if err != nil { return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } diff --git a/x/marker/keeper/params.go b/x/marker/keeper/params.go index 52395d04e6..7417b18936 100644 --- a/x/marker/keeper/params.go +++ b/x/marker/keeper/params.go @@ -35,7 +35,7 @@ func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { } // GetMaxSupply returns the current parameter value for the max allowed supply. -func (k Keeper) GetMaxSupply(ctx sdk.Context) (max sdkmath.Int) { +func (k Keeper) GetMaxSupply(ctx sdk.Context) sdkmath.Int { return k.GetParams(ctx).MaxSupply } diff --git a/x/marker/keeper/query_server.go b/x/marker/keeper/query_server.go index c8c3cf9b11..45f343ae27 100644 --- a/x/marker/keeper/query_server.go +++ b/x/marker/keeper/query_server.go @@ -38,7 +38,7 @@ func (k Keeper) AllMarkers(c context.Context, req *types.QueryAllMarkersRequest) if err == nil { anyMsg, anyErr := codectypes.NewAnyWithValue(result) if anyErr != nil { - return status.Errorf(codes.Internal, anyErr.Error()) + return status.Error(codes.Internal, anyErr.Error()) } markers = append(markers, anyMsg) } @@ -62,7 +62,7 @@ func (k Keeper) Marker(c context.Context, req *types.QueryMarkerRequest) (*types } anyMsg, err := codectypes.NewAnyWithValue(marker) if err != nil { - return nil, status.Errorf(codes.Internal, err.Error()) + return nil, status.Error(codes.Internal, err.Error()) } return &types.QueryMarkerResponse{Marker: anyMsg}, nil } diff --git a/x/marker/simulation/genesis.go b/x/marker/simulation/genesis.go index 25dac03894..5ba362834a 100644 --- a/x/marker/simulation/genesis.go +++ b/x/marker/simulation/genesis.go @@ -36,9 +36,9 @@ func GenEnableGovernance(r *rand.Rand) bool { // GenUnrestrictedDenomRegex returns a randomized length focused string for the unrestricted denom validation expression func GenUnrestrictedDenomRegex(r *rand.Rand) string { - min := r.Int31n(16) + 3 - max := r.Int31n(64-min) + min - return fmt.Sprintf(`[a-zA-Z][a-zA-Z0-9\\-\\.]{%d,%d}`, min, max) + minLen := r.Int31n(16) + 3 + maxLen := r.Int31n(64-minLen) + minLen + return fmt.Sprintf(`[a-zA-Z][a-zA-Z0-9\\-\\.]{%d,%d}`, minLen, maxLen) } // RandomizedGenState generates a random GenesisState for marker diff --git a/x/marker/simulation/operations.go b/x/marker/simulation/operations.go index 01e10bf96a..e8f7055e5e 100644 --- a/x/marker/simulation/operations.go +++ b/x/marker/simulation/operations.go @@ -109,10 +109,10 @@ func SimulateMsgAddMarker(k keeper.Keeper, args *WeightedOpsArgs) simtypes.Opera sdkmath.NewIntFromBigInt(sdkmath.ZeroInt().BigInt().Rand(r, k.GetMaxSupply(ctx).BigInt())), simAccount.Address, mgrAccount.Address, - types.MarkerType(r.Intn(2)+1), // coin or restricted_coin - r.Intn(2) > 0, // fixed supply - r.Intn(2) > 0, // allow gov - r.Intn(2) > 0, // allow forced transfer + randMarkerType(r), // coin or restricted_coin + r.Intn(2) > 0, // fixed supply + r.Intn(2) > 0, // allow gov + r.Intn(2) > 0, // allow forced transfer []string{}, 0, 0, @@ -199,7 +199,7 @@ func SimulateMsgAddFinalizeActivateMarker(k keeper.Keeper, args *WeightedOpsArgs simAccount, _ := simtypes.RandomAcc(r, accs) mgrAccount, _ := simtypes.RandomAcc(r, accs) denom := randomUnrestrictedDenom(r, k.GetUnrestrictedDenomRegex(ctx)) - markerType := types.MarkerType(r.Intn(2) + 1) // coin or restricted_coin + markerType := randMarkerType(r) // random access grants grants := randomAccessGrants(r, accs, 100, markerType) msg := types.NewMsgAddFinalizeActivateMarkerRequest( @@ -233,8 +233,8 @@ func SimulateMsgAddMarkerProposal(k keeper.Keeper, args *WeightedOpsArgs) simtyp simAccount, _ := simtypes.RandomAcc(r, accs) denom := randomUnrestrictedDenom(r, k.GetUnrestrictedDenomRegex(ctx)) - markerStatus := types.MarkerStatus(r.Intn(3) + 1) - markerType := types.MarkerType(r.Intn(2) + 1) + markerStatus := types.MarkerStatus(r.Intn(3) + 1) //nolint:gosec // G115: 1-3 always fits in a uint32 (implicit cast). + markerType := randMarkerType(r) msg := &types.MsgAddMarkerRequest{ Amount: sdk.Coin{ Denom: denom, @@ -325,7 +325,7 @@ func SimulateMsgSetAccountData(k keeper.Keeper, args *WeightedOpsArgs) simtypes. // 1 in 10 chance that the value stays "". // 9 in 10 chance that it will be between 1 and MaxValueLen characters. if r.Intn(10) != 0 { - maxLen := uint(args.AttrK.GetMaxValueLength(ctx)) + maxLen := args.AttrK.GetMaxValueLength(ctx) if maxLen > 500 { maxLen = 500 } @@ -433,10 +433,10 @@ func randomUnrestrictedDenom(r *rand.Rand, unrestrictedDenomExp string) string { if len(matches) != 3 { panic("expected two number as range expression in unrestricted denom expression") } - min, _ := strconv.ParseInt(matches[1], 10, 32) - max, _ := strconv.ParseInt(matches[2], 10, 32) + minLen, _ := strconv.ParseInt(matches[1], 10, 32) + maxLen, _ := strconv.ParseInt(matches[2], 10, 32) - return simtypes.RandStringOfLength(r, int(randomInt63(r, max-min)+min)) + return simtypes.RandStringOfLength(r, int(randomInt63(r, maxLen-minLen)+minLen)) } // randomAccessGrants generates random access grants for randomly selected accounts. @@ -530,11 +530,15 @@ func randomAccWithAccess(r *rand.Rand, marker types.MarkerAccountI, accs []simty return simtypes.Account{}, false } -func randomInt63(r *rand.Rand, max int64) (result int64) { - if max == 0 { +func randomInt63(r *rand.Rand, maxVal int64) (result int64) { + if maxVal == 0 { return 0 } - return r.Int63n(max) + return r.Int63n(maxVal) +} + +func randMarkerType(r *rand.Rand) types.MarkerType { + return types.MarkerType(r.Intn(2) + 1) //nolint:gosec // G115: Either 1 or 2, so always fits in int32 (implicit cast). } // WeightedOpsArgs holds all the args provided to WeightedOperations so that they can be passed on later more easily. diff --git a/x/marker/types/msgs.go b/x/marker/types/msgs.go index c9f3e02b1d..37d7ad8f8e 100644 --- a/x/marker/types/msgs.go +++ b/x/marker/types/msgs.go @@ -424,7 +424,7 @@ func (msg MsgAddFinalizeActivateMarkerRequest) ValidateBasic() error { } // since this is a one shot process should have 1 access list member, to have any value for a marker - if msg.AccessList == nil || len(msg.AccessList) == 0 { + if len(msg.AccessList) == 0 { return fmt.Errorf("since this will activate the marker, must have access list defined") } diff --git a/x/marker/types/si.go b/x/marker/types/si.go index 9b7de84815..854463562c 100644 --- a/x/marker/types/si.go +++ b/x/marker/types/si.go @@ -127,7 +127,7 @@ func SIPrefixFromExponent(exp int) (SIPrefix, error) { if exp < math.MinInt32 || exp > math.MaxInt32 { return invalidSIPrefix, fmt.Errorf("exponent [%d] out of bounds for int32", exp) } - p := SIPrefix(exp) + p := SIPrefix(exp) //nolint:gosec // G115: Made sure this was okay with the above check (implicit cast of int to int32). if p.IsValid() { return p, nil } diff --git a/x/metadata/keeper/msg_server.go b/x/metadata/keeper/msg_server.go index c880b6daa6..ca019ba1b5 100644 --- a/x/metadata/keeper/msg_server.go +++ b/x/metadata/keeper/msg_server.go @@ -6,6 +6,8 @@ import ( "strings" "time" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -44,7 +46,8 @@ func (k msgServer) WriteScope( return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } - nav := types.NewNetAssetValue(sdk.NewInt64Coin(types.UsdDenom, int64(msg.UsdMills))) + usdMills := sdkmath.NewIntFromUint64(msg.UsdMills) + nav := types.NewNetAssetValue(sdk.NewCoin(types.UsdDenom, usdMills)) err := k.AddSetNetAssetValues(ctx, msg.Scope.ScopeId, []types.NetAssetValue{nav}, types.ModuleName) if err != nil { return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) diff --git a/x/metadata/keeper/oslocatorparams.go b/x/metadata/keeper/oslocatorparams.go index 04c2725b74..f40c993253 100644 --- a/x/metadata/keeper/oslocatorparams.go +++ b/x/metadata/keeper/oslocatorparams.go @@ -34,6 +34,6 @@ func (k Keeper) SetOSLocatorParams(ctx sdk.Context, params types.OSLocatorParams } // GetMaxURILength returns the configured parameter for max URI length on a locator record -func (k Keeper) GetMaxURILength(ctx sdk.Context) (max uint32) { +func (k Keeper) GetMaxURILength(ctx sdk.Context) uint32 { return k.GetOSLocatorParams(ctx).MaxUriLength } diff --git a/x/metadata/keeper/query_server.go b/x/metadata/keeper/query_server.go index 6697b8d83c..ff32c205a6 100644 --- a/x/metadata/keeper/query_server.go +++ b/x/metadata/keeper/query_server.go @@ -293,7 +293,7 @@ func (k Keeper) Sessions(c context.Context, req *types.SessionsRequest) (*types. return false }) if itErr != nil { - return &retval, sdkerrors.ErrInvalidRequest.Wrapf(fmt.Sprintf("error getting sessions for scope with address %s: %v", scopeAddr, itErr)) + return &retval, sdkerrors.ErrInvalidRequest.Wrapf("error getting sessions for scope with address %s: %v", scopeAddr, itErr) } default: return &retval, sdkerrors.ErrInvalidRequest.Wrap("empty request parameters") diff --git a/x/metadata/types/scope.go b/x/metadata/types/scope.go index 205b57fdfc..df9d12403a 100644 --- a/x/metadata/types/scope.go +++ b/x/metadata/types/scope.go @@ -124,7 +124,6 @@ func (s *Scope) AddOwners(owners []Party) error { } for _, newOwner := range owners { for _, scopeOwner := range s.Owners { - //nolint:gosec // G601: Implicit memory aliasing okay here since we're not storing the reference anywhere. if newOwner.IsSameAs(&scopeOwner) { return fmt.Errorf("party already exists with address %s and role %s", newOwner.Address, newOwner.Role) } @@ -528,7 +527,6 @@ func EqualParties(p1, p2 []Party) bool { p1Loop: for _, p1p := range p1 { for _, p2p := range p2 { - //nolint:gosec // G601: Implicit memory aliasing okay here since we're not storing the reference anywhere. if p1p.Equals(&p2p) { continue p1Loop } diff --git a/x/msgfees/keeper/keeper.go b/x/msgfees/keeper/keeper.go index b9eb9bb702..2256a05781 100644 --- a/x/msgfees/keeper/keeper.go +++ b/x/msgfees/keeper/keeper.go @@ -8,6 +8,7 @@ import ( "golang.org/x/exp/constraints" "cosmossdk.io/log" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" @@ -181,9 +182,9 @@ func (k Keeper) ConvertDenomToHash(ctx sdk.Context, coin sdk.Coin) (sdk.Coin, er conversionDenom := k.GetConversionFeeDenom(ctx) switch coin.Denom { case types.UsdDenom: - nhashPerMil := int64(k.GetNhashPerUsdMil(ctx)) - amount := coin.Amount.MulRaw(nhashPerMil) - msgFeeCoin := sdk.NewInt64Coin(conversionDenom, amount.Int64()) + nhashPerMil := sdkmath.NewIntFromUint64(k.GetNhashPerUsdMil(ctx)) + amount := coin.Amount.Mul(nhashPerMil) + msgFeeCoin := sdk.NewCoin(conversionDenom, amount) return msgFeeCoin, nil case conversionDenom: return coin, nil @@ -309,10 +310,10 @@ func DetermineBips(recipient string, recipientBasisPoints string) (uint32, error if err != nil { return bips, types.ErrInvalidBipsValue.Wrap(err.Error()) } - bips = uint32(bips64) - if bips > 10_000 { + if bips64 > 10_000 { return 0, types.ErrInvalidBipsValue.Wrap(fmt.Errorf("recipient basis points can only be between 0 and 10,000 : %v", recipientBasisPoints).Error()) } + bips = uint32(bips64) //nolint:gosec // G115: We know bips64 <= 10,000 so it'll fit into an int32 just fine. } else if len(recipientBasisPoints) == 0 && len(recipient) > 0 { bips = types.DefaultMsgFeeBips } diff --git a/x/msgfees/types/msgs.go b/x/msgfees/types/msgs.go index 4794b05b09..9b5fd29156 100644 --- a/x/msgfees/types/msgs.go +++ b/x/msgfees/types/msgs.go @@ -73,8 +73,7 @@ func (msg MsgAssessCustomMsgFeeRequest) GetBips() (uint32, error) { return 0, fmt.Errorf("recipient basis points can only be between 0 and 10,000 : %v", msg.RecipientBasisPoints) } } - - return uint32(bips), err + return uint32(bips), err //nolint:gosec // G115: ParseUint bitsize is 32, so we know this is okay. } func NewMsgAddMsgFeeProposalRequest(msgTypeURL string, additionalFee sdk.Coin, recipient string, recipientBasisPoints string, authority string) *MsgAddMsgFeeProposalRequest { diff --git a/x/name/client/cli/tx.go b/x/name/client/cli/tx.go index e07c08a34e..785d3e1d82 100644 --- a/x/name/client/cli/tx.go +++ b/x/name/client/cli/tx.go @@ -271,9 +271,9 @@ func GetUpdateNameParamsCmd() *cobra.Command { } msg := types.NewMsgUpdateParamsRequest( - uint32(maxSegmentLength), - uint32(minSegmentLength), - uint32(maxNameLevels), + uint32(maxSegmentLength), //nolint:gosec // G115: ParseUint bitsize is 32, so we know this is okay. + uint32(minSegmentLength), //nolint:gosec // G115: ParseUint bitsize is 32, so we know this is okay. + uint32(maxNameLevels), //nolint:gosec // G115: ParseUint bitsize is 32, so we know this is okay. allowUnrestrictedNames, authority, ) diff --git a/x/name/keeper/keeper.go b/x/name/keeper/keeper.go index 5a442a1151..f3bb4f5a68 100644 --- a/x/name/keeper/keeper.go +++ b/x/name/keeper/keeper.go @@ -263,12 +263,12 @@ func (k Keeper) Normalize(ctx sdk.Context, name string) (string, error) { segCount := uint32(0) for _, segment := range strings.Split(normalized, ".") { segCount++ - segLen := uint32(len(segment)) + segLen := len(segment) isUUID := types.IsValidUUID(segment) - if segLen < k.GetMinSegmentLength(ctx) { + if segLen < int(k.GetMinSegmentLength(ctx)) { return "", types.ErrNameSegmentTooShort } - if segLen > k.GetMaxSegmentLength(ctx) && !isUUID { + if segLen > int(k.GetMaxSegmentLength(ctx)) && !isUUID { return "", types.ErrNameSegmentTooLong } } diff --git a/x/name/simulation/genesis.go b/x/name/simulation/genesis.go index 744d1df94e..a46b907b91 100644 --- a/x/name/simulation/genesis.go +++ b/x/name/simulation/genesis.go @@ -26,17 +26,18 @@ const ( // GenMaxSegmentLength randomized Max Segment Length func GenMaxSegmentLength(r *rand.Rand) uint32 { - return uint32(r.Intn(22) + 11) // ensures that max is always more than range of min values (1-11) + // ensures that max is always more than range of min values (1-11) + return uint32(r.Intn(22) + 11) //nolint:gosec // G115: Max is 32, which fits in a uint32 just fine. } // GenMaxNameLevels randomized Maximum number of segment levels func GenMaxNameLevels(r *rand.Rand) uint32 { - return uint32(r.Intn(9) + 3) + return uint32(r.Intn(9) + 3) //nolint:gosec // G115: Max is 11, which fits in a uint32 just fine. } // GenMinSegmentLength randomized minimum segment name length func GenMinSegmentLength(r *rand.Rand) uint32 { - return uint32(r.Intn(10) + 1) + return uint32(r.Intn(10) + 1) //nolint:gosec // G115: Max is 10, which fits in a uint32 just fine. } // GenAllowUnrestrictedNames returns a randomized AllowUnrestrictedNames parameter. diff --git a/x/oracle/simulation/genesis.go b/x/oracle/simulation/genesis.go index 2e63088a90..eae5eaa752 100644 --- a/x/oracle/simulation/genesis.go +++ b/x/oracle/simulation/genesis.go @@ -22,8 +22,8 @@ func PortFn(r *rand.Rand) string { if r.Intn(2) > 0 { return "oracle" } - length := uint64(internalrand.IntBetween(r, 6, 10)) - return strings.ToLower(simtypes.RandStringOfLength(r, int(length))) + length := internalrand.IntBetween(r, 6, 10) + return strings.ToLower(simtypes.RandStringOfLength(r, length)) } // OracleFn randomized oracle address diff --git a/x/trigger/keeper/event_detector.go b/x/trigger/keeper/event_detector.go index c2ca46be9a..f5e58f3ff7 100644 --- a/x/trigger/keeper/event_detector.go +++ b/x/trigger/keeper/event_detector.go @@ -53,11 +53,13 @@ func (k Keeper) detectTransactionEvents(ctx sdk.Context) (triggers []types.Trigg func (k Keeper) detectBlockHeightEvents(ctx sdk.Context) (triggers []types.Trigger) { match := func(_ types.Trigger, triggerEvent types.TriggerEventI) bool { blockHeightEvent := triggerEvent.(*types.BlockHeightEvent) - return ctx.BlockHeight() >= int64(blockHeightEvent.GetBlockHeight()) + curHeight := uint64(ctx.BlockHeight()) + return curHeight >= blockHeightEvent.GetBlockHeight() } terminator := func(_ types.Trigger, triggerEvent types.TriggerEventI) bool { blockHeightEvent := triggerEvent.(*types.BlockHeightEvent) - return ctx.BlockHeight() < int64(blockHeightEvent.GetBlockHeight()) + curHeight := uint64(ctx.BlockHeight()) + return curHeight < blockHeightEvent.GetBlockHeight() } triggers = k.getMatchingTriggersUntil(ctx, types.BlockHeightPrefix, match, terminator) diff --git a/x/trigger/simulation/genesis.go b/x/trigger/simulation/genesis.go index 6c83b5a55b..d21ac1ab3b 100644 --- a/x/trigger/simulation/genesis.go +++ b/x/trigger/simulation/genesis.go @@ -3,6 +3,7 @@ package simulation import ( "encoding/json" "fmt" + "math" "math/rand" "time" @@ -135,26 +136,26 @@ func RandomGasLimits(r *rand.Rand, triggers []types.Trigger, queuedTriggers []ty return rv } -// randomTriggerAndQueueIDs generates random unique ids (1 to max inclusive) and divvies them up with the provided counts. -func randomTriggerAndQueueIDs(r *rand.Rand, triggerCount, queueCount, max int) ([]uint64, []uint64) { - ids := randomTriggerIDs(r, triggerCount+queueCount, max) +// randomTriggerAndQueueIDs generates random unique ids (1 to maxCount inclusive) and divvies them up with the provided counts. +func randomTriggerAndQueueIDs(r *rand.Rand, triggerCount, queueCount, maxCount int) ([]uint64, []uint64) { + ids := randomTriggerIDs(r, triggerCount+queueCount, maxCount) return ids[:triggerCount], ids[triggerCount:] } -// randomTriggerIDs generates count different random trigger ids between 1 and max inclusive -// If count > max, only max will be returned. -func randomTriggerIDs(r *rand.Rand, count int, max int) []uint64 { - if count > max { - panic(fmt.Errorf("cannot generate %d unique trigger ids with a max of %d", count, max)) +// randomTriggerIDs generates count different random trigger ids between 1 and maxCount inclusive +// If count > maxCount, only maxCount will be returned. +func randomTriggerIDs(r *rand.Rand, count int, maxCount int) []uint64 { + if count > maxCount { + panic(fmt.Errorf("cannot generate %d unique trigger ids with a max of %d", count, maxCount)) } if count == 0 { return []uint64{} } rv := make([]uint64, count) - // If count is 33+% of max, generate a permutation up to max (exclusive). - // Then increment each of the first of them (since we want 1 to max inclusive) and return those. - if max/3 <= count { - nums := r.Perm(max) + // If count is 33+% of maxCount, generate a permutation up to maxCount (exclusive). + // Then increment each of the first of them (since we want 1 to maxCount inclusive) and return those. + if maxCount/3 <= count { + nums := r.Perm(maxCount) for i := range rv { rv[i] = uint64(nums[i]) + 1 } @@ -165,7 +166,7 @@ func randomTriggerIDs(r *rand.Rand, count int, max int) []uint64 { seen[0] = true for i := range rv { for seen[rv[i]] { - rv[i] = uint64(r.Intn(max) + 1) + rv[i] = uint64(r.Intn(maxCount) + 1) } seen[rv[i]] = true } @@ -202,7 +203,12 @@ func RandomizedGenState(simState *module.SimulationState) { triggerID = uint64(numIniTrig) + uint64(numIniTrigQueued) } - triggerIDs, queueTriggerIDs := randomTriggerAndQueueIDs(simState.Rand, numIniTrig, numIniTrigQueued, int(triggerID)) + if triggerID > uint64(math.MaxInt) { + // This should only ever happen if using a pre-defined value for the trigger id. + panic(fmt.Errorf("cannot run sims with a %s param [%d] larger than max int (%d)", TriggerID, triggerID, math.MaxInt)) + } + triggerIDInt := int(triggerID) //nolint:gosec // G115: Overflow handled above. + triggerIDs, queueTriggerIDs := randomTriggerAndQueueIDs(simState.Rand, numIniTrig, numIniTrigQueued, triggerIDInt) var triggers []types.Trigger simState.AppParams.GetOrGenerate( Triggers, &triggers, simState.Rand,