From 0bcfe4ad555be2b595e62004ad8175f2be543e89 Mon Sep 17 00:00:00 2001 From: faddat Date: Wed, 26 Oct 2022 09:08:36 +0000 Subject: [PATCH 01/24] golangci --- .golangci.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..ead6a79bd --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,27 @@ +run: + tests: false + # timeout for analysis, e.g. 30s, 5m, default is 1m + timeout: 5m + +linters: + disable-all: true + enable: + - depguard + - dogsled + - exportloopref + - goconst + - gocritic + - gofumpt + - gosec + - gosimple + - govet + - ineffassign + - misspell + - nakedret + - nolintlint + - staticcheck + - revive + - stylecheck + - typecheck + - unconvert + - unused From e36b9ba69ff91398c0c2fe2bb6f4da52a7139b33 Mon Sep 17 00:00:00 2001 From: faddat Date: Wed, 26 Oct 2022 09:10:01 +0000 Subject: [PATCH 02/24] add golangci github action --- .github/workflows/golangci.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/golangci.yml diff --git a/.github/workflows/golangci.yml b/.github/workflows/golangci.yml new file mode 100644 index 000000000..b8ddf70a1 --- /dev/null +++ b/.github/workflows/golangci.yml @@ -0,0 +1,27 @@ +name: golangci-lint +on: + push: + tags: + - v* + branches: + - master + - main + pull_request: +permissions: + contents: read + # Optional: allow read access to pull request. Use with `only-new-issues` option. + # pull-requests: read +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v3 + with: + go-version: 1.19 # check with 1.19 because it matches dev envs. Does not need to affect go.mod. + - uses: actions/checkout@v3 + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version + version: latest From aac9c6c7f178c9bcf70ec9cfc298c3454c8acad9 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:32:57 +0700 Subject: [PATCH 03/24] tests pass and usable as reference --- cmd/demo/main.go | 8 +++++--- ibc_test.go | 22 ++++++++++++---------- internal/api/api_test.go | 4 ++-- internal/api/iterator_test.go | 3 ++- internal/api/lib_test.go | 31 +++++++++++++++---------------- internal/api/memory_test.go | 5 +++-- internal/api/mocks.go | 8 ++++---- internal/api/version_test.go | 2 +- lib_test.go | 19 ++++++++++--------- 9 files changed, 54 insertions(+), 48 deletions(-) diff --git a/cmd/demo/main.go b/cmd/demo/main.go index 2d48a35e4..30626025f 100644 --- a/cmd/demo/main.go +++ b/cmd/demo/main.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "io/ioutil" "os" wasmvm "github.com/CosmWasm/wasmvm" @@ -19,13 +18,16 @@ const ( func main() { file := os.Args[1] fmt.Printf("Running %s...\n", file) - bz, err := ioutil.ReadFile(file) + bz, err := os.ReadFile(file) if err != nil { panic(err) } fmt.Println("Loaded!") - os.MkdirAll("tmp", 0o755) + err = os.MkdirAll("tmp", 0o755) + if err != nil { + panic(err) + } vm, err := wasmvm.NewVM("tmp", SUPPORTED_FEATURES, MEMORY_LIMIT, PRINT_DEBUG, CACHE_SIZE) if err != nil { panic(err) diff --git a/ibc_test.go b/ibc_test.go index 5fe24c28c..4834681cc 100644 --- a/ibc_test.go +++ b/ibc_test.go @@ -2,7 +2,7 @@ package cosmwasm import ( "encoding/json" - "io/ioutil" + "os" "testing" "github.com/CosmWasm/wasmvm/internal/api" @@ -16,7 +16,7 @@ const IBC_TEST_CONTRACT = "./testdata/ibc_reflect.wasm" func TestIBC(t *testing.T) { vm := withVM(t) - wasm, err := ioutil.ReadFile(IBC_TEST_CONTRACT) + wasm, err := os.ReadFile(IBC_TEST_CONTRACT) require.NoError(t, err) checksum, err := vm.Create(wasm) @@ -89,7 +89,7 @@ func TestIBCHandshake(t *testing.T) { vm := withVM(t) checksum := createTestContract(t, vm, IBC_TEST_CONTRACT) gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) - deserCost := types.UFraction{1, 1} + deserCost := types.UFraction{Numerator: 1, Denominator: 1} // instantiate it with this store store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() @@ -156,7 +156,7 @@ func TestIBCPacketDispatch(t *testing.T) { vm := withVM(t) checksum := createTestContract(t, vm, IBC_TEST_CONTRACT) gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) - deserCost := types.UFraction{1, 1} + deserCost := types.UFraction{Numerator: 1, Denominator: 1} // instantiate it with this store store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() @@ -221,6 +221,7 @@ func TestIBCPacketDispatch(t *testing.T) { require.NoError(t, err) var accounts ListAccountsResponse err = json.Unmarshal(qres, &accounts) + require.NoError(t, err) require.Equal(t, 1, len(accounts.Accounts)) require.Equal(t, CHANNEL_ID, accounts.Accounts[0].ChannelID) require.Equal(t, REFLECT_ADDR, accounts.Accounts[0].Account) @@ -247,6 +248,7 @@ func TestIBCPacketDispatch(t *testing.T) { // assert app-level success var ack AcknowledgeDispatch err = json.Unmarshal(pres.Acknowledgement, &ack) + require.NoError(t, err) require.Empty(t, ack.Err) // error on message from another channel @@ -257,7 +259,7 @@ func TestIBCPacketDispatch(t *testing.T) { pres2 := pr2.Ok // assert app-level failure var ack2 AcknowledgeDispatch - err = json.Unmarshal(pres2.Acknowledgement, &ack2) + _ = json.Unmarshal(pres2.Acknowledgement, &ack2) require.Equal(t, "invalid packet: cosmwasm_std::addresses::Addr not found", ack2.Err) // check for the expected custom event @@ -275,7 +277,7 @@ func TestAnalyzeCode(t *testing.T) { vm := withVM(t) // Store non-IBC contract - wasm, err := ioutil.ReadFile(HACKATOM_TEST_CONTRACT) + wasm, err := os.ReadFile(HACKATOM_TEST_CONTRACT) require.NoError(t, err) checksum, err := vm.Create(wasm) require.NoError(t, err) @@ -287,7 +289,7 @@ func TestAnalyzeCode(t *testing.T) { require.Equal(t, "", report.RequiredCapabilities) // Store IBC contract - wasm2, err := ioutil.ReadFile(IBC_TEST_CONTRACT) + wasm2, err := os.ReadFile(IBC_TEST_CONTRACT) require.NoError(t, err) checksum2, err := vm.Create(wasm2) require.NoError(t, err) @@ -322,11 +324,11 @@ func TestIBCMsgGetCounterVersion(t *testing.T) { const VERSION = "random-garbage" msg1 := api.MockIBCChannelOpenInit(CHANNEL_ID, types.Ordered, VERSION) - v, ok := msg1.GetCounterVersion() + _, ok := msg1.GetCounterVersion() require.False(t, ok) msg2 := api.MockIBCChannelOpenTry(CHANNEL_ID, types.Ordered, VERSION) - v, ok = msg2.GetCounterVersion() + v, ok := msg2.GetCounterVersion() require.True(t, ok) require.Equal(t, VERSION, v) @@ -336,6 +338,6 @@ func TestIBCMsgGetCounterVersion(t *testing.T) { require.Equal(t, VERSION, v) msg4 := api.MockIBCChannelConnectConfirm(CHANNEL_ID, types.Ordered, VERSION) - v, ok = msg4.GetCounterVersion() + _, ok = msg4.GetCounterVersion() require.False(t, ok) } diff --git a/internal/api/api_test.go b/internal/api/api_test.go index 7efbc1440..e38e9d512 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -2,7 +2,7 @@ package api import ( "encoding/json" - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/require" @@ -15,7 +15,7 @@ func TestValidateAddressFailure(t *testing.T) { defer cleanup() // create contract - wasm, err := ioutil.ReadFile("../../testdata/hackatom.wasm") + wasm, err := os.ReadFile("../../testdata/hackatom.wasm") require.NoError(t, err) checksum, err := Create(cache, wasm) require.NoError(t, err) diff --git a/internal/api/iterator_test.go b/internal/api/iterator_test.go index 7da29b47b..a707ddbcd 100644 --- a/internal/api/iterator_test.go +++ b/internal/api/iterator_test.go @@ -143,6 +143,7 @@ func TestRetrieveIterator(t *testing.T) { index22, err := storeIterator(callID2, iter, limit) require.NoError(t, err) iter, err = store.Iterator(nil, nil) + require.NoError(t, err) index23, err := storeIterator(callID2, iter, limit) require.NoError(t, err) @@ -284,6 +285,6 @@ func TestQueueIteratorLimit(t *testing.T) { store = setup.Store(gasMeter) query = []byte(`{"open_iterators":{"count":35000}}`) env = MockEnvBin(t) - data, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TESTING_PRINT_DEBUG) + _, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TESTING_PRINT_DEBUG) require.ErrorContains(t, err, "Reached iterator limit (32768)") } diff --git a/internal/api/lib_test.go b/internal/api/lib_test.go index 3ac275512..4d9d3a3ab 100644 --- a/internal/api/lib_test.go +++ b/internal/api/lib_test.go @@ -3,7 +3,6 @@ package api import ( "encoding/json" "fmt" - "io/ioutil" "os" "testing" "time" @@ -27,7 +26,7 @@ func TestInitAndReleaseCache(t *testing.T) { _, err := InitCache(dataDir, TESTING_FEATURES, TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) require.Error(t, err) - tmpdir, err := ioutil.TempDir("", "wasmvm-testing") + tmpdir, err := os.MkdirTemp("", "wasmvm-testing") require.NoError(t, err) defer os.RemoveAll(tmpdir) @@ -37,15 +36,15 @@ func TestInitAndReleaseCache(t *testing.T) { } func TestInitCacheEmptyFeatures(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "wasmvm-testing") + tmpdir, err := os.MkdirTemp("", "wasmvm-testing") require.NoError(t, err) defer os.RemoveAll(tmpdir) - cache, err := InitCache(tmpdir, "", TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) + cache, _ := InitCache(tmpdir, "", TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) ReleaseCache(cache) } func withCache(t *testing.T) (Cache, func()) { - tmpdir, err := ioutil.TempDir("", "wasmvm-testing") + tmpdir, err := os.MkdirTemp("", "wasmvm-testing") require.NoError(t, err) cache, err := InitCache(tmpdir, TESTING_FEATURES, TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) require.NoError(t, err) @@ -61,7 +60,7 @@ func TestCreateAndGet(t *testing.T) { cache, cleanup := withCache(t) defer cleanup() - wasm, err := ioutil.ReadFile("../../testdata/hackatom.wasm") + wasm, err := os.ReadFile("../../testdata/hackatom.wasm") require.NoError(t, err) checksum, err := Create(cache, wasm) @@ -85,7 +84,7 @@ func TestPin(t *testing.T) { cache, cleanup := withCache(t) defer cleanup() - wasm, err := ioutil.ReadFile("../../testdata/hackatom.wasm") + wasm, err := os.ReadFile("../../testdata/hackatom.wasm") require.NoError(t, err) checksum, err := Create(cache, wasm) @@ -128,7 +127,7 @@ func TestUnpin(t *testing.T) { cache, cleanup := withCache(t) defer cleanup() - wasm, err := ioutil.ReadFile("../../testdata/hackatom.wasm") + wasm, err := os.ReadFile("../../testdata/hackatom.wasm") require.NoError(t, err) checksum, err := Create(cache, wasm) @@ -173,7 +172,7 @@ func TestGetMetrics(t *testing.T) { assert.Equal(t, &types.Metrics{}, metrics) // Create contract - wasm, err := ioutil.ReadFile("../../testdata/hackatom.wasm") + wasm, err := os.ReadFile("../../testdata/hackatom.wasm") require.NoError(t, err) checksum, err := Create(cache, wasm) require.NoError(t, err) @@ -283,7 +282,7 @@ func TestInstantiate(t *testing.T) { defer cleanup() // create contract - wasm, err := ioutil.ReadFile("../../testdata/hackatom.wasm") + wasm, err := os.ReadFile("../../testdata/hackatom.wasm") require.NoError(t, err) checksum, err := Create(cache, wasm) require.NoError(t, err) @@ -406,7 +405,7 @@ func TestExecuteCpuLoop(t *testing.T) { store.SetGasMeter(gasMeter2) info = MockInfoBin(t, "fred") start = time.Now() - res, cost, err = Execute(cache, checksum, env, info, []byte(`{"cpu_loop":{}}`), &igasMeter2, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) + _, cost, err = Execute(cache, checksum, env, info, []byte(`{"cpu_loop":{}}`), &igasMeter2, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) diff = time.Now().Sub(start) require.Error(t, err) assert.Equal(t, cost, maxGas) @@ -431,7 +430,7 @@ func TestExecuteStorageLoop(t *testing.T) { msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) require.NoError(t, err) requireOkResponse(t, res, 0) @@ -441,7 +440,7 @@ func TestExecuteStorageLoop(t *testing.T) { store.SetGasMeter(gasMeter2) info = MockInfoBin(t, "fred") start := time.Now() - res, cost, err = Execute(cache, checksum, env, info, []byte(`{"storage_loop":{}}`), &igasMeter2, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) + _, cost, err := Execute(cache, checksum, env, info, []byte(`{"storage_loop":{}}`), &igasMeter2, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) diff := time.Now().Sub(start) require.Error(t, err) t.Logf("StorageLoop Time (%d gas): %s\n", cost, diff) @@ -516,7 +515,7 @@ func TestMigrate(t *testing.T) { // migrate to a new verifier - alice // we use the same code blob as we are testing hackatom self-migration - res, _, err = Migrate(cache, checksum, env, []byte(`{"verifier":"alice"}`), &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + _, _, err = Migrate(cache, checksum, env, []byte(`{"verifier":"alice"}`), &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) require.NoError(t, err) // should update verifier to alice @@ -787,7 +786,7 @@ func createReflectContract(t *testing.T, cache Cache) []byte { } func createContract(t *testing.T, cache Cache, wasmFile string) []byte { - wasm, err := ioutil.ReadFile(wasmFile) + wasm, err := os.ReadFile(wasmFile) require.NoError(t, err) checksum, err := Create(cache, wasm) require.NoError(t, err) @@ -877,7 +876,7 @@ func TestHackatomQuerier(t *testing.T) { require.NoError(t, err) require.Equal(t, "", qres.Err) var balances types.AllBalancesResponse - err = json.Unmarshal(qres.Ok, &balances) + _ = json.Unmarshal(qres.Ok, &balances) require.Equal(t, balances.Amount, initBalance) } diff --git a/internal/api/memory_test.go b/internal/api/memory_test.go index b05b94fdf..18d32ed22 100644 --- a/internal/api/memory_test.go +++ b/internal/api/memory_test.go @@ -58,18 +58,19 @@ func TestCreateAndDestroyUnmanagedVector(t *testing.T) { // Like the test above but without `newUnmanagedVector` calls. // Since only Rust can actually create them, we only test edge cases here. +// //go:nocheckptr func TestCopyDestroyUnmanagedVector(t *testing.T) { { // ptr, cap and len broken. Do not access those values when is_none is true - invalid_ptr := unsafe.Pointer(uintptr(42)) + invalid_ptr := unsafe.Pointer(uintptr(42)) //nolint:unsafeptr uv := constructUnmanagedVector(cbool(true), cu8_ptr(invalid_ptr), cusize(0xBB), cusize(0xAA)) copy := copyAndDestroyUnmanagedVector(uv) require.Nil(t, copy) } { // Capacity is 0, so no allocation happened. Do not access the pointer. - invalid_ptr := unsafe.Pointer(uintptr(42)) + invalid_ptr := unsafe.Pointer(uintptr(42)) //nolint:unsafeptr uv := constructUnmanagedVector(cbool(false), cu8_ptr(invalid_ptr), cusize(0), cusize(0)) copy := copyAndDestroyUnmanagedVector(uv) require.Equal(t, []byte{}, copy) diff --git a/internal/api/mocks.go b/internal/api/mocks.go index 8d913968c..59b88ec2e 100644 --- a/internal/api/mocks.go +++ b/internal/api/mocks.go @@ -417,10 +417,10 @@ func (q MockQuerier) Query(request types.QueryRequest, _gasLimit uint64) ([]byte return q.Custom.Query(request.Custom) } if request.Staking != nil { - return nil, types.UnsupportedRequest{"staking"} + return nil, types.UnsupportedRequest{Kind: "staking"} } if request.Wasm != nil { - return nil, types.UnsupportedRequest{"wasm"} + return nil, types.UnsupportedRequest{Kind: "wasm"} } return nil, types.Unknown{} } @@ -466,7 +466,7 @@ func (q BankQuerier) Query(request *types.BankQuery) ([]byte, error) { } return json.Marshal(resp) } - return nil, types.UnsupportedRequest{"Empty BankQuery"} + return nil, types.UnsupportedRequest{Kind: "Empty BankQuery"} } type CustomQuerier interface { @@ -478,7 +478,7 @@ type NoCustom struct{} var _ CustomQuerier = NoCustom{} func (q NoCustom) Query(request json.RawMessage) ([]byte, error) { - return nil, types.UnsupportedRequest{"custom"} + return nil, types.UnsupportedRequest{Kind: "custom"} } // ReflectCustom fulfills the requirements for testing `reflect` contract diff --git a/internal/api/version_test.go b/internal/api/version_test.go index 9adda9e1f..4de361db6 100644 --- a/internal/api/version_test.go +++ b/internal/api/version_test.go @@ -10,5 +10,5 @@ import ( func TestLibwasmvmVersion(t *testing.T) { version, err := LibwasmvmVersion() require.NoError(t, err) - require.Regexp(t, regexp.MustCompile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)(-[a-z0-9.]+)?$"), version) + require.Regexp(t, regexp.MustCompile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)(-[a-z0-9.]+)?$"), version) //nolint:gosimple } diff --git a/lib_test.go b/lib_test.go index b6c087b77..c6acb27e5 100644 --- a/lib_test.go +++ b/lib_test.go @@ -2,7 +2,6 @@ package cosmwasm import ( "encoding/json" - "io/ioutil" "os" "testing" @@ -20,11 +19,13 @@ const ( TESTING_CACHE_SIZE = 100 // MiB ) -const CYBERPUNK_TEST_CONTRACT = "./testdata/cyberpunk.wasm" -const HACKATOM_TEST_CONTRACT = "./testdata/hackatom.wasm" +const ( + CYBERPUNK_TEST_CONTRACT = "./testdata/cyberpunk.wasm" + HACKATOM_TEST_CONTRACT = "./testdata/hackatom.wasm" +) func withVM(t *testing.T) *VM { - tmpdir, err := ioutil.TempDir("", "wasmvm-testing") + tmpdir, err := os.MkdirTemp("", "wasmvm-testing") require.NoError(t, err) vm, err := NewVM(tmpdir, TESTING_FEATURES, TESTING_MEMORY_LIMIT, TESTING_PRINT_DEBUG, TESTING_CACHE_SIZE) require.NoError(t, err) @@ -37,7 +38,7 @@ func withVM(t *testing.T) *VM { } func createTestContract(t *testing.T, vm *VM, path string) Checksum { - wasm, err := ioutil.ReadFile(path) + wasm, err := os.ReadFile(path) require.NoError(t, err) checksum, err := vm.Create(wasm) require.NoError(t, err) @@ -47,7 +48,7 @@ func createTestContract(t *testing.T, vm *VM, path string) Checksum { func TestCreateAndGet(t *testing.T) { vm := withVM(t) - wasm, err := ioutil.ReadFile(HACKATOM_TEST_CONTRACT) + wasm, err := os.ReadFile(HACKATOM_TEST_CONTRACT) require.NoError(t, err) checksum, err := vm.Create(wasm) @@ -62,7 +63,7 @@ func TestHappyPath(t *testing.T) { vm := withVM(t) checksum := createTestContract(t, vm, HACKATOM_TEST_CONTRACT) - deserCost := types.UFraction{1, 1} + deserCost := types.UFraction{Numerator: 1, Denominator: 1} gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) // instantiate it with this store store := api.NewLookup(gasMeter1) @@ -103,7 +104,7 @@ func TestEnv(t *testing.T) { vm := withVM(t) checksum := createTestContract(t, vm, CYBERPUNK_TEST_CONTRACT) - deserCost := types.UFraction{1, 1} + deserCost := types.UFraction{Numerator: 1, Denominator: 1} gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) // instantiate it with this store store := api.NewLookup(gasMeter1) @@ -170,7 +171,7 @@ func TestGetMetrics(t *testing.T) { // Create contract checksum := createTestContract(t, vm, HACKATOM_TEST_CONTRACT) - deserCost := types.UFraction{1, 1} + deserCost := types.UFraction{Numerator: 1, Denominator: 1} // GetMetrics 2 metrics, err = vm.GetMetrics() From 7e16295a1e6778b33c0eec5c73a4da0c87bdeb13 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:45:52 +0700 Subject: [PATCH 04/24] querier_vtable -> querierVtable --- internal/api/callbacks.go | 11 ++++++----- internal/api/iterator.go | 12 ++++++++---- internal/api/mocks.go | 4 ++-- lib.go | 2 +- types/ibc.go | 6 ++++-- types/queries.go | 2 +- 6 files changed, 22 insertions(+), 15 deletions(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index 5651ea44b..9f2207ef8 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -136,9 +136,10 @@ type DBState struct { } // use this to create C.Db in two steps, so the pointer lives as long as the calling stack -// state := buildDBState(kv, callID) -// db := buildDB(&state, &gasMeter) -// // then pass db into some FFI function +// +// state := buildDBState(kv, callID) +// db := buildDB(&state, &gasMeter) +// // then pass db into some FFI function func buildDBState(kv KVStore, callID uint64) DBState { return DBState{ Store: kv, @@ -422,7 +423,7 @@ func cCanonicalAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, /****** Go Querier ********/ -var querier_vtable = C.Querier_vtable{ +var querierVtable = C.Querier_vtable{ query_external: (C.query_external_fn)(C.cQueryExternal_cgo), } @@ -431,7 +432,7 @@ var querier_vtable = C.Querier_vtable{ func buildQuerier(q *Querier) C.GoQuerier { return C.GoQuerier{ state: (*C.querier_t)(unsafe.Pointer(q)), - vtable: querier_vtable, + vtable: querierVtable, } } diff --git a/internal/api/iterator.go b/internal/api/iterator.go index a394164bc..6e30d1824 100644 --- a/internal/api/iterator.go +++ b/internal/api/iterator.go @@ -11,12 +11,16 @@ import ( type frame []dbm.Iterator // iteratorFrames contains one frame for each contract call, indexed by contract call ID. -var iteratorFrames = make(map[uint64]frame) -var iteratorFramesMutex sync.Mutex +var ( + iteratorFrames = make(map[uint64]frame) + iteratorFramesMutex sync.Mutex +) // this is a global counter for creating call IDs -var latestCallID uint64 -var latestCallIDMutex sync.Mutex +var ( + latestCallID uint64 + latestCallIDMutex sync.Mutex +) // startCall is called at the beginning of a contract call to create a new frame in iteratorFrames. // It updates latestCallID for generating a new call ID. diff --git a/internal/api/mocks.go b/internal/api/mocks.go index 59b88ec2e..ed63c2382 100644 --- a/internal/api/mocks.go +++ b/internal/api/mocks.go @@ -517,7 +517,7 @@ func (q ReflectCustom) Query(request json.RawMessage) ([]byte, error) { return json.Marshal(resp) } -//************ test code for mocks *************************// +// ************ test code for mocks *************************// func TestBankQuerierAllBalances(t *testing.T) { addr := "foobar" @@ -622,7 +622,7 @@ func TestReflectCustomQuerier(t *testing.T) { require.NoError(t, err) assert.Equal(t, resp.Msg, "PONG") - // try captial + // try capital msg2, err := json.Marshal(CustomQuery{Capitalized: &CapitalizedQuery{Text: "small."}}) require.NoError(t, err) bz, err = q.Query(msg2) diff --git a/lib.go b/lib.go index 774e3b9e9..3d0c39982 100644 --- a/lib.go +++ b/lib.go @@ -162,7 +162,7 @@ func (vm *VM) Instantiate( // (That is a detail for the external, sdk-facing, side). // // The caller is responsible for passing the correct `store` (which must have been initialized exactly once), -// and setting the env with relevent info on this instance (address, balance, etc) +// and setting the env with relevant info on this instance (address, balance, etc) func (vm *VM) Execute( checksum Checksum, env types.Env, diff --git a/types/ibc.go b/types/ibc.go index 47b7745c3..6fc412f17 100644 --- a/types/ibc.go +++ b/types/ibc.go @@ -154,8 +154,10 @@ type IBCPacketTimeoutMsg struct { type IBCOrder = string // These are the only two valid values for IbcOrder -const Unordered = "ORDER_UNORDERED" -const Ordered = "ORDER_ORDERED" +const ( + Unordered = "ORDER_UNORDERED" + Ordered = "ORDER_ORDERED" +) // IBCTimeoutBlock Height is a monotonically increasing data type // that can be compared against another Height for the purposes of updating and diff --git a/types/queries.go b/types/queries.go index 7142773ba..d368d4f44 100644 --- a/types/queries.go +++ b/types/queries.go @@ -354,7 +354,7 @@ type WasmQuery struct { ContractInfo *ContractInfoQuery `json:"contract_info,omitempty"` } -// SmartQuery respone is raw bytes ([]byte) +// SmartQuery response is raw bytes ([]byte) type SmartQuery struct { // Bech32 encoded sdk.AccAddress of the contract ContractAddr string `json:"contract_addr"` From 6655144bd61593fd2735ef8819149ecf660d3214 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:46:54 +0700 Subject: [PATCH 05/24] make dest not use pointer --- internal/api/callbacks.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index 9f2207ef8..836bdec28 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -401,7 +401,7 @@ func cCanonicalAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, if dest == nil || errOut == nil { return C.GoError_BadArgument } - if !(*dest).is_none || !(*errOut).is_none { + if !dest.is_none || !(*errOut).is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } @@ -444,7 +444,7 @@ func cQueryExternal(ptr *C.querier_t, gasLimit C.uint64_t, usedGas *C.uint64_t, // we received an invalid pointer return C.GoError_BadArgument } - if !(*result).is_none || !(*errOut).is_none { + if !result.is_none || !(*errOut).is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } From a262ffd0cb9d8852adaa474db496c29b0e39d61d Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:48:03 +0700 Subject: [PATCH 06/24] ignore allcaps linter issues --- cmd/demo/main.go | 1 + 1 file changed, 1 insertion(+) diff --git a/cmd/demo/main.go b/cmd/demo/main.go index 30626025f..a918a953b 100644 --- a/cmd/demo/main.go +++ b/cmd/demo/main.go @@ -7,6 +7,7 @@ import ( wasmvm "github.com/CosmWasm/wasmvm" ) +//nolint:revive,stylecheck const ( SUPPORTED_FEATURES = "staking" PRINT_DEBUG = true From f0d2c8b79743abf104d18991163526d2245a977c Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:48:57 +0700 Subject: [PATCH 07/24] iterator_vtable -> iteratorVtable --- internal/api/callbacks.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index 836bdec28..9366c15b7 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -122,7 +122,7 @@ type KVStore interface { ReverseIterator(start, end []byte) dbm.Iterator } -var db_vtable = C.Db_vtable{ +var dbVtable = C.Db_vtable{ read_db: (C.read_db_fn)(C.cGet_cgo), write_db: (C.write_db_fn)(C.cSet_cgo), remove_db: (C.remove_db_fn)(C.cDelete_cgo), @@ -153,11 +153,11 @@ func buildDB(state *DBState, gm *GasMeter) C.Db { return C.Db{ gas_meter: (*C.gas_meter_t)(unsafe.Pointer(gm)), state: (*C.db_t)(unsafe.Pointer(state)), - vtable: db_vtable, + vtable: dbVtable, } } -var iterator_vtable = C.Iterator_vtable{ +var iteratorVtable = C.Iterator_vtable{ next_db: (C.next_db_fn)(C.cNext_cgo), } @@ -295,7 +295,7 @@ func cScan(ptr *C.db_t, gasMeter *C.gas_meter_t, usedGas *C.uint64_t, start C.U8 } out.state = cIterator - out.vtable = iterator_vtable + out.vtable = iteratorVtable return C.GoError_None } From 8defdd0d00e0e1f0234491598083ef812a50afb8 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:49:53 +0700 Subject: [PATCH 08/24] val.is_none and errOut.is_none --- internal/api/callbacks.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index 9366c15b7..d0ebcd721 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -187,7 +187,7 @@ func cGet(ptr *C.db_t, gasMeter *C.gas_meter_t, usedGas *cu64, key C.U8SliceView // we received an invalid pointer return C.GoError_BadArgument } - if !(*val).is_none || !(*errOut).is_none { + if !val.is_none || !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } From f27701a32edab2e95267620c8fbcdd8b64384e31 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:50:35 +0700 Subject: [PATCH 09/24] increment with ++ --- internal/api/callbacks.go | 2 +- internal/api/iterator.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index d0ebcd721..6a81e63fd 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -215,7 +215,7 @@ func cSet(ptr *C.db_t, gasMeter *C.gas_meter_t, usedGas *C.uint64_t, key C.U8Sli // we received an invalid pointer return C.GoError_BadArgument } - if !(*errOut).is_none { + if !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } diff --git a/internal/api/iterator.go b/internal/api/iterator.go index 6e30d1824..2490d2154 100644 --- a/internal/api/iterator.go +++ b/internal/api/iterator.go @@ -27,7 +27,7 @@ var ( func startCall() uint64 { latestCallIDMutex.Lock() defer latestCallIDMutex.Unlock() - latestCallID += 1 + latestCallID++ return latestCallID } From 85f0997a524dd9087683187e0c506d1eb7d7ab97 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:51:39 +0700 Subject: [PATCH 10/24] more undefref --- internal/api/callbacks.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index 6a81e63fd..695789ca3 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -240,7 +240,7 @@ func cDelete(ptr *C.db_t, gasMeter *C.gas_meter_t, usedGas *C.uint64_t, key C.U8 // we received an invalid pointer return C.GoError_BadArgument } - if !(*errOut).is_none { + if !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } @@ -264,7 +264,7 @@ func cScan(ptr *C.db_t, gasMeter *C.gas_meter_t, usedGas *C.uint64_t, start C.U8 // we received an invalid pointer return C.GoError_BadArgument } - if !(*errOut).is_none { + if !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } @@ -312,7 +312,7 @@ func cNext(ref C.iterator_t, gasMeter *C.gas_meter_t, usedGas *C.uint64_t, key * // we received an invalid pointer return C.GoError_BadArgument } - if !(*key).is_none || !(*val).is_none || !(*errOut).is_none { + if !key.is_none || !val.is_none || !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } From 6419bb9c6faab13975d66ce66e905b1a77f753e2 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 16:52:57 +0700 Subject: [PATCH 11/24] more linting --- internal/api/callbacks.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index 695789ca3..869845985 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -352,7 +352,7 @@ type GoAPI struct { CanonicalAddress CanonicalizeAddress } -var api_vtable = C.GoApi_vtable{ +var apiVtable = C.GoApi_vtable{ humanize_address: (C.humanize_address_fn)(C.cHumanAddress_cgo), canonicalize_address: (C.canonicalize_address_fn)(C.cCanonicalAddress_cgo), } @@ -362,18 +362,18 @@ var api_vtable = C.GoApi_vtable{ func buildAPI(api *GoAPI) C.GoApi { return C.GoApi{ state: (*C.api_t)(unsafe.Pointer(api)), - vtable: api_vtable, + vtable: apiVtable, } } //export cHumanAddress -func cHumanAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, errOut *C.UnmanagedVector, used_gas *cu64) (ret C.GoError) { +func cHumanAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, errOut *C.UnmanagedVector, usedGas *cu64) (ret C.GoError) { defer recoverPanic(&ret) if dest == nil || errOut == nil { return C.GoError_BadArgument } - if !(*dest).is_none || !(*errOut).is_none { + if !dest.is_none || !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } @@ -381,7 +381,7 @@ func cHumanAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, err s := copyU8Slice(src) h, cost, err := api.HumanAddress(s) - *used_gas = cu64(cost) + *usedGas = cu64(cost) if err != nil { // store the actual error message in the return buffer *errOut = newUnmanagedVector([]byte(err.Error())) From daecd0a9e0ee655f115f0a147f5fc4ab5836bfb0 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:06:01 +0700 Subject: [PATCH 12/24] linting.... --- ibc_test.go | 4 ++-- internal/api/api_test.go | 2 +- internal/api/callbacks.go | 4 ++-- internal/api/iterator_test.go | 2 +- internal/api/lib_test.go | 26 +++++++++++++------------- internal/api/mocks.go | 4 ++-- lib_test.go | 6 +++--- types/submessages.go | 4 ++-- 8 files changed, 26 insertions(+), 26 deletions(-) diff --git a/ibc_test.go b/ibc_test.go index 4834681cc..c0f24e5da 100644 --- a/ibc_test.go +++ b/ibc_test.go @@ -94,7 +94,7 @@ func TestIBCHandshake(t *testing.T) { store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() balance := types.Coins{} - querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance) + querier := api.DefaultQuerier(api.MockContractAddr, balance) // instantiate env := api.MockEnv() @@ -161,7 +161,7 @@ func TestIBCPacketDispatch(t *testing.T) { store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() balance := types.Coins{} - querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance) + querier := api.DefaultQuerier(api.MockContractAddr, balance) // instantiate env := api.MockEnv() diff --git a/internal/api/api_test.go b/internal/api/api_test.go index e38e9d512..811120e39 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -24,7 +24,7 @@ func TestValidateAddressFailure(t *testing.T) { // instantiate it with this store store := NewLookup(gasMeter) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, types.Coins{types.NewCoin(100, "ATOM")}) + querier := DefaultQuerier(MockContractAddr, types.Coins{types.NewCoin(100, "ATOM")}) env := MockEnvBin(t) info := MockInfoBin(t, "creator") diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index 869845985..b48d3ba4a 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -395,7 +395,7 @@ func cHumanAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, err } //export cCanonicalAddress -func cCanonicalAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, errOut *C.UnmanagedVector, used_gas *cu64) (ret C.GoError) { +func cCanonicalAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, errOut *C.UnmanagedVector, usedGas *cu64) (ret C.GoError) { defer recoverPanic(&ret) if dest == nil || errOut == nil { @@ -408,7 +408,7 @@ func cCanonicalAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, api := (*GoAPI)(unsafe.Pointer(ptr)) s := string(copyU8Slice(src)) c, cost, err := api.CanonicalAddress(s) - *used_gas = cu64(cost) + *usedGas = cu64(cost) if err != nil { // store the actual error message in the return buffer *errOut = newUnmanagedVector([]byte(err.Error())) diff --git a/internal/api/iterator_test.go b/internal/api/iterator_test.go index a707ddbcd..4280b7e88 100644 --- a/internal/api/iterator_test.go +++ b/internal/api/iterator_test.go @@ -31,7 +31,7 @@ func setupQueueContractWithData(t *testing.T, cache Cache, values ...int) queueD // instantiate it with this store store := NewLookup(gasMeter1) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, types.Coins{types.NewCoin(100, "ATOM")}) + querier := DefaultQuerier(MockContractAddr, types.Coins{types.NewCoin(100, "ATOM")}) env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg := []byte(`{}`) diff --git a/internal/api/lib_test.go b/internal/api/lib_test.go index 4d9d3a3ab..42778632a 100644 --- a/internal/api/lib_test.go +++ b/internal/api/lib_test.go @@ -187,7 +187,7 @@ func TestGetMetrics(t *testing.T) { igasMeter := GasMeter(gasMeter) store := NewLookup(gasMeter) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, types.Coins{types.NewCoin(100, "ATOM")}) + querier := DefaultQuerier(MockContractAddr, types.Coins{types.NewCoin(100, "ATOM")}) env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg1 := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) @@ -292,7 +292,7 @@ func TestInstantiate(t *testing.T) { // instantiate it with this store store := NewLookup(gasMeter) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, types.Coins{types.NewCoin(100, "ATOM")}) + querier := DefaultQuerier(MockContractAddr, types.Coins{types.NewCoin(100, "ATOM")}) env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) @@ -320,7 +320,7 @@ func TestExecute(t *testing.T) { store := NewLookup(gasMeter1) api := NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, balance) + querier := DefaultQuerier(MockContractAddr, balance) env := MockEnvBin(t) info := MockInfoBin(t, "creator") @@ -384,7 +384,7 @@ func TestExecuteCpuLoop(t *testing.T) { store := NewLookup(gasMeter1) api := NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, balance) + querier := DefaultQuerier(MockContractAddr, balance) env := MockEnvBin(t) info := MockInfoBin(t, "creator") @@ -424,7 +424,7 @@ func TestExecuteStorageLoop(t *testing.T) { store := NewLookup(gasMeter1) api := NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, balance) + querier := DefaultQuerier(MockContractAddr, balance) env := MockEnvBin(t) info := MockInfoBin(t, "creator") @@ -463,7 +463,7 @@ func TestExecuteUserErrorsInApiCalls(t *testing.T) { // instantiate it with this store store := NewLookup(gasMeter1) balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, balance) + querier := DefaultQuerier(MockContractAddr, balance) env := MockEnvBin(t) info := MockInfoBin(t, "creator") @@ -494,7 +494,7 @@ func TestMigrate(t *testing.T) { store := NewLookup(gasMeter) api := NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, balance) + querier := DefaultQuerier(MockContractAddr, balance) env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) @@ -538,7 +538,7 @@ func TestMultipleInstances(t *testing.T) { igasMeter1 := GasMeter(gasMeter1) store1 := NewLookup(gasMeter1) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, types.Coins{types.NewCoin(100, "ATOM")}) + querier := DefaultQuerier(MockContractAddr, types.Coins{types.NewCoin(100, "ATOM")}) env := MockEnvBin(t) info := MockInfoBin(t, "regen") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) @@ -593,7 +593,7 @@ func TestSudo(t *testing.T) { store := NewLookup(gasMeter1) api := NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, balance) + querier := DefaultQuerier(MockContractAddr, balance) env := MockEnvBin(t) info := MockInfoBin(t, "creator") @@ -636,7 +636,7 @@ func TestDispatchSubmessage(t *testing.T) { // instantiate it with this store store := NewLookup(gasMeter1) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, nil) + querier := DefaultQuerier(MockContractAddr, nil) env := MockEnvBin(t) info := MockInfoBin(t, "creator") @@ -689,7 +689,7 @@ func TestReplyAndQuery(t *testing.T) { // instantiate it with this store store := NewLookup(gasMeter1) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, nil) + querier := DefaultQuerier(MockContractAddr, nil) env := MockEnvBin(t) info := MockInfoBin(t, "creator") @@ -819,7 +819,7 @@ func TestQuery(t *testing.T) { igasMeter1 := GasMeter(gasMeter1) store := NewLookup(gasMeter1) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, types.Coins{types.NewCoin(100, "ATOM")}) + querier := DefaultQuerier(MockContractAddr, types.Coins{types.NewCoin(100, "ATOM")}) env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) @@ -905,7 +905,7 @@ func TestCustomReflectQuerier(t *testing.T) { store := NewLookup(gasMeter) api := NewMockAPI() initBalance := types.Coins{types.NewCoin(1234, "ATOM")} - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, initBalance) + querier := DefaultQuerier(MockContractAddr, initBalance) // we need this to handle the custom requests from the reflect contract innerQuerier := querier.(MockQuerier) innerQuerier.Custom = ReflectCustom{} diff --git a/internal/api/mocks.go b/internal/api/mocks.go index ed63c2382..378876ad0 100644 --- a/internal/api/mocks.go +++ b/internal/api/mocks.go @@ -17,7 +17,7 @@ import ( /** helper constructors **/ -const MOCK_CONTRACT_ADDR = "contract" +const MockContractAddr = "contract" func MockEnv() types.Env { return types.Env{ @@ -30,7 +30,7 @@ func MockEnv() types.Env { Index: 4, }, Contract: types.ContractInfo{ - Address: MOCK_CONTRACT_ADDR, + Address: MockContractAddr, }, } } diff --git a/lib_test.go b/lib_test.go index c6acb27e5..5beaaaa44 100644 --- a/lib_test.go +++ b/lib_test.go @@ -69,7 +69,7 @@ func TestHappyPath(t *testing.T) { store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance) + querier := api.DefaultQuerier(api.MockContractAddr, balance) // instantiate env := api.MockEnv() @@ -110,7 +110,7 @@ func TestEnv(t *testing.T) { store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance) + querier := api.DefaultQuerier(api.MockContractAddr, balance) // instantiate env := api.MockEnv() @@ -184,7 +184,7 @@ func TestGetMetrics(t *testing.T) { store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance) + querier := api.DefaultQuerier(api.MockContractAddr, balance) env := api.MockEnv() info := api.MockInfo("creator", nil) diff --git a/types/submessages.go b/types/submessages.go index 2799df79f..84a428b84 100644 --- a/types/submessages.go +++ b/types/submessages.go @@ -32,11 +32,11 @@ func (r replyOn) String() string { return fromReplyOn[r] } -func (s replyOn) MarshalJSON() ([]byte, error) { +func (s replyOn) MarshalJSON() ([]byte, error) { //nolint:revive,stylecheck return json.Marshal(s.String()) } -func (s *replyOn) UnmarshalJSON(b []byte) error { +func (s *replyOn) UnmarshalJSON(b []byte) error { //nolint:revive var j string err := json.Unmarshal(b, &j) if err != nil { From b150696b70d2bcfdccf43c4394fa8e0f18f6c35b Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:07:09 +0700 Subject: [PATCH 13/24] more linting, strictly follow language conventiosn --- internal/api/callbacks.go | 2 +- internal/api/iterator.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index b48d3ba4a..b892ad2e0 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -401,7 +401,7 @@ func cCanonicalAddress(ptr *C.api_t, src C.U8SliceView, dest *C.UnmanagedVector, if dest == nil || errOut == nil { return C.GoError_BadArgument } - if !dest.is_none || !(*errOut).is_none { + if !dest.is_none || !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } diff --git a/internal/api/iterator.go b/internal/api/iterator.go index 2490d2154..3d726df41 100644 --- a/internal/api/iterator.go +++ b/internal/api/iterator.go @@ -60,14 +60,14 @@ func storeIterator(callID uint64, it dbm.Iterator, frameLenLimit int) (uint64, e iteratorFramesMutex.Lock() defer iteratorFramesMutex.Unlock() - old_frame_len := len(iteratorFrames[callID]) - if old_frame_len >= frameLenLimit { + oldFrameLen := len(iteratorFrames[callID]) + if oldFrameLen >= frameLenLimit { return 0, fmt.Errorf("Reached iterator limit (%d)", frameLenLimit) } // store at array position `old_frame_len` iteratorFrames[callID] = append(iteratorFrames[callID], it) - new_index := old_frame_len + 1 + new_index := oldFrameLen + 1 return uint64(new_index), nil } From b61bc0234fa9112222d625088f4cb6f1f43b50cf Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:07:39 +0700 Subject: [PATCH 14/24] follow language conventions --- internal/api/iterator.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/api/iterator.go b/internal/api/iterator.go index 3d726df41..0a4d9abd9 100644 --- a/internal/api/iterator.go +++ b/internal/api/iterator.go @@ -67,9 +67,9 @@ func storeIterator(callID uint64, it dbm.Iterator, frameLenLimit int) (uint64, e // store at array position `old_frame_len` iteratorFrames[callID] = append(iteratorFrames[callID], it) - new_index := oldFrameLen + 1 + newIndex := oldFrameLen + 1 - return uint64(new_index), nil + return uint64(newIndex), nil } // retrieveIterator will recover an iterator based on index. This ensures it will not be garbage collected. From c2a9509229280ac71e6d9d2304b815322640749b Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:23:16 +0700 Subject: [PATCH 15/24] linting --- internal/api/lib.go | 2 +- internal/api/memory.go | 2 +- types/msg.go | 10 ++++++---- types/queries.go | 8 ++++---- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/internal/api/lib.go b/internal/api/lib.go index e81d9d774..158e4f422 100644 --- a/internal/api/lib.go +++ b/internal/api/lib.go @@ -60,7 +60,7 @@ func Create(cache Cache, wasm []byte) ([]byte, error) { w := makeView(wasm) defer runtime.KeepAlive(wasm) errmsg := newUnmanagedVector(nil) - checksum, err := C.save_wasm(cache.ptr, w, &errmsg) + checksum, err := C.save_wasm(cache.ptr, w, &errmsg) //nolint:gocritic if err != nil { return nil, errorWithMessage(err, errmsg) } diff --git a/internal/api/memory.go b/internal/api/memory.go index c7479c249..aeaf9a374 100644 --- a/internal/api/memory.go +++ b/internal/api/memory.go @@ -40,7 +40,7 @@ func constructUnmanagedVector(is_none cbool, ptr cu8_ptr, len cusize, cap cusize } func newUnmanagedVector(data []byte) C.UnmanagedVector { - if data == nil { + if data == nil { //nolint:gocritic return C.new_unmanaged_vector(cbool(true), cu8_ptr(nil), cusize(0)) } else if len(data) == 0 { // in Go, accessing the 0-th element of an empty array triggers a panic. That is why in the case diff --git a/types/msg.go b/types/msg.go index 745fd2612..cd3c8e3cb 100644 --- a/types/msg.go +++ b/types/msg.go @@ -5,6 +5,8 @@ import ( "fmt" ) +var null = "null" + //------- Results / Msgs ------------- // ContractResult is the raw response from the instantiate/execute/migrate calls. @@ -46,7 +48,7 @@ func (e Events) MarshalJSON() ([]byte, error) { // UnmarshalJSON ensures that we get [] for empty arrays func (e *Events) UnmarshalJSON(data []byte) error { // make sure we deserialize [] back to null - if string(data) == "[]" || string(data) == "null" { + if string(data) == "[]" || string(data) == null { return nil } var raw []Event @@ -77,7 +79,7 @@ func (a EventAttributes) MarshalJSON() ([]byte, error) { // UnmarshalJSON ensures that we get [] for empty arrays func (a *EventAttributes) UnmarshalJSON(data []byte) error { // make sure we deserialize [] back to null - if string(data) == "[]" || string(data) == "null" { + if string(data) == "[]" || string(data) == null { return nil } var raw []EventAttribute @@ -169,11 +171,11 @@ func (v voteOption) String() string { return fromVoteOption[v] } -func (v voteOption) MarshalJSON() ([]byte, error) { +func (v voteOption) MarshalJSON() ([]byte, error) { //nolint:stylecheck return json.Marshal(v.String()) } -func (s *voteOption) UnmarshalJSON(b []byte) error { +func (s *voteOption) UnmarshalJSON(b []byte) error { //nolint:revive var j string err := json.Unmarshal(b, &j) if err != nil { diff --git a/types/queries.go b/types/queries.go index d368d4f44..20ef298ce 100644 --- a/types/queries.go +++ b/types/queries.go @@ -165,7 +165,7 @@ func (e IBCChannels) MarshalJSON() ([]byte, error) { // UnmarshalJSON ensures that we get [] for empty arrays func (e *IBCChannels) UnmarshalJSON(data []byte) error { // make sure we deserialize [] back to null - if string(data) == "[]" || string(data) == "null" { + if string(data) == "[]" || string(data) == null { return nil } var raw []IBCChannel @@ -191,7 +191,7 @@ func (e IBCEndpoints) MarshalJSON() ([]byte, error) { // UnmarshalJSON ensures that we get [] for empty arrays func (e *IBCEndpoints) UnmarshalJSON(data []byte) error { // make sure we deserialize [] back to null - if string(data) == "[]" || string(data) == "null" { + if string(data) == "[]" || string(data) == null { return nil } var raw []IBCEndpoint @@ -243,7 +243,7 @@ func (v Validators) MarshalJSON() ([]byte, error) { // UnmarshalJSON ensures that we get [] for empty arrays func (v *Validators) UnmarshalJSON(data []byte) error { // make sure we deserialize [] back to null - if string(data) == "[]" || string(data) == "null" { + if string(data) == "[]" || string(data) == null { return nil } var raw []Validator @@ -302,7 +302,7 @@ func (d Delegations) MarshalJSON() ([]byte, error) { // UnmarshalJSON ensures that we get [] for empty arrays func (d *Delegations) UnmarshalJSON(data []byte) error { // make sure we deserialize [] back to null - if string(data) == "[]" || string(data) == "null" { + if string(data) == "[]" || string(data) == null { return nil } var raw []Delegation From fba3882c153790c57232e728dfb3a00e65bdbd86 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:23:48 +0700 Subject: [PATCH 16/24] linting --- types/types.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/types.go b/types/types.go index f67b566de..ad90a05c7 100644 --- a/types/types.go +++ b/types/types.go @@ -62,7 +62,7 @@ func (o OutOfGasError) Error() string { // This type is returned by VM.AnalyzeCode(). type AnalysisReport struct { HasIBCEntryPoints bool - // Deprecated, use RequiredCapabilities. For now both fields contain the same value. + // Deprecated: use RequiredCapabilities. For now both fields contain the same value. RequiredFeatures string RequiredCapabilities string } From 768ffa75cf5a7f1cbce39e1a3b50bf6d73fad495 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:24:28 +0700 Subject: [PATCH 17/24] linting --- internal/api/callbacks.go | 2 +- internal/api/memory.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index b892ad2e0..09b807606 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -444,7 +444,7 @@ func cQueryExternal(ptr *C.querier_t, gasLimit C.uint64_t, usedGas *C.uint64_t, // we received an invalid pointer return C.GoError_BadArgument } - if !result.is_none || !(*errOut).is_none { + if !result.is_none || !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } diff --git a/internal/api/memory.go b/internal/api/memory.go index aeaf9a374..4a2d4d766 100644 --- a/internal/api/memory.go +++ b/internal/api/memory.go @@ -56,7 +56,7 @@ func newUnmanagedVector(data []byte) C.UnmanagedVector { func copyAndDestroyUnmanagedVector(v C.UnmanagedVector) []byte { var out []byte - if v.is_none { + if v.is_none { //nolint:gocritic out = nil } else if v.cap == cusize(0) { // There is no allocation we can copy From 12d6402686713e5bb3dc39c4e0851de9631b3b16 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:25:08 +0700 Subject: [PATCH 18/24] linting --- internal/api/iterator.go | 2 +- internal/api/lib.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/api/iterator.go b/internal/api/iterator.go index 0a4d9abd9..775607a37 100644 --- a/internal/api/iterator.go +++ b/internal/api/iterator.go @@ -62,7 +62,7 @@ func storeIterator(callID uint64, it dbm.Iterator, frameLenLimit int) (uint64, e oldFrameLen := len(iteratorFrames[callID]) if oldFrameLen >= frameLenLimit { - return 0, fmt.Errorf("Reached iterator limit (%d)", frameLenLimit) + return 0, fmt.Errorf("Reached iterator limit (%d)", frameLenLimit) //nolint:stylecheck } // store at array position `old_frame_len` diff --git a/internal/api/lib.go b/internal/api/lib.go index 158e4f422..ee3954797 100644 --- a/internal/api/lib.go +++ b/internal/api/lib.go @@ -26,7 +26,7 @@ type ( ) // Pointers -type cu8_ptr = *C.uint8_t +type cu8_ptr = *C.uint8_t //nolint:revive type Cache struct { ptr *C.cache_t From b80cc002d2a3ee3bc75f0bb87a4759217b4d806e Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:27:43 +0700 Subject: [PATCH 19/24] linting --- internal/api/lib.go | 2 +- internal/api/memory.go | 4 ++-- internal/api/mocks.go | 2 ++ lib.go | 8 ++++---- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/internal/api/lib.go b/internal/api/lib.go index ee3954797..71dfb5ee7 100644 --- a/internal/api/lib.go +++ b/internal/api/lib.go @@ -26,7 +26,7 @@ type ( ) // Pointers -type cu8_ptr = *C.uint8_t //nolint:revive +type cu8_ptr = *C.uint8_t //nolint:revive,stylecheck type Cache struct { ptr *C.cache_t diff --git a/internal/api/memory.go b/internal/api/memory.go index 4a2d4d766..baeb86448 100644 --- a/internal/api/memory.go +++ b/internal/api/memory.go @@ -30,9 +30,9 @@ func makeView(s []byte) C.ByteSliceView { } // Creates a C.UnmanagedVector, which cannot be done in test files directly -func constructUnmanagedVector(is_none cbool, ptr cu8_ptr, len cusize, cap cusize) C.UnmanagedVector { +func constructUnmanagedVector(isNone cbool, ptr cu8_ptr, len cusize, cap cusize) C.UnmanagedVector { return C.UnmanagedVector{ - is_none: is_none, + is_none: isNone, ptr: ptr, len: len, cap: cap, diff --git a/internal/api/mocks.go b/internal/api/mocks.go index 378876ad0..55bceb005 100644 --- a/internal/api/mocks.go +++ b/internal/api/mocks.go @@ -247,6 +247,8 @@ func (g *mockGasMeter) ConsumeGas(amount Gas, descriptor string) { // // We making simple values and non-clear multiples so it is easy to see their impact in test output // Also note we do not charge for each read on an iterator (out of simplicity and not needed for tests) +// +//nolint:staticcheck const ( GetPrice uint64 = 99000 SetPrice = 187000 diff --git a/lib.go b/lib.go index 3d0c39982..461301bbe 100644 --- a/lib.go +++ b/lib.go @@ -142,7 +142,7 @@ func (vm *VM) Instantiate( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization @@ -190,7 +190,7 @@ func (vm *VM) Execute( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization @@ -230,7 +230,7 @@ func (vm *VM) Query( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization @@ -273,7 +273,7 @@ func (vm *VM) Migrate( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization From 75fe4ca344ca45d5eb7637543739522e7369a331 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:49:23 +0700 Subject: [PATCH 20/24] use language convention --- internal/api/lib.go | 36 ++++++++++++++++++------------------ internal/api/mocks.go | 29 ++++++++++++++++------------- internal/api/version.go | 6 +++--- lib.go | 10 +++++----- types/msg.go | 2 +- 5 files changed, 43 insertions(+), 40 deletions(-) diff --git a/internal/api/lib.go b/internal/api/lib.go index 71dfb5ee7..a13a051cf 100644 --- a/internal/api/lib.go +++ b/internal/api/lib.go @@ -45,7 +45,7 @@ func InitCache(dataDir string, supportedFeatures string, cacheSize uint32, insta errmsg := newUnmanagedVector(nil) - ptr, err := C.init_cache(d, f, cu32(cacheSize), cu32(instanceMemoryLimit), &errmsg) + ptr, err := C.init_cache(d, f, cu32(cacheSize), cu32(instanceMemoryLimit), &errmsg) //nolint:gocritic if err != nil { return Cache{}, errorWithMessage(err, errmsg) } @@ -71,7 +71,7 @@ func GetCode(cache Cache, checksum []byte) ([]byte, error) { cs := makeView(checksum) defer runtime.KeepAlive(checksum) errmsg := newUnmanagedVector(nil) - wasm, err := C.load_wasm(cache.ptr, cs, &errmsg) + wasm, err := C.load_wasm(cache.ptr, cs, &errmsg) //nolint:gocritic if err != nil { return nil, errorWithMessage(err, errmsg) } @@ -82,7 +82,7 @@ func Pin(cache Cache, checksum []byte) error { cs := makeView(checksum) defer runtime.KeepAlive(checksum) errmsg := newUnmanagedVector(nil) - _, err := C.pin(cache.ptr, cs, &errmsg) + _, err := C.pin(cache.ptr, cs, &errmsg) //nolint:gocritic if err != nil { return errorWithMessage(err, errmsg) } @@ -93,7 +93,7 @@ func Unpin(cache Cache, checksum []byte) error { cs := makeView(checksum) defer runtime.KeepAlive(checksum) errmsg := newUnmanagedVector(nil) - _, err := C.unpin(cache.ptr, cs, &errmsg) + _, err := C.unpin(cache.ptr, cs, &errmsg) //nolint:gocritic if err != nil { return errorWithMessage(err, errmsg) } @@ -104,7 +104,7 @@ func AnalyzeCode(cache Cache, checksum []byte) (*types.AnalysisReport, error) { cs := makeView(checksum) defer runtime.KeepAlive(checksum) errmsg := newUnmanagedVector(nil) - report, err := C.analyze_code(cache.ptr, cs, &errmsg) + report, err := C.analyze_code(cache.ptr, cs, &errmsg) //nolint:gocritic if err != nil { return nil, errorWithMessage(err, errmsg) } @@ -119,7 +119,7 @@ func AnalyzeCode(cache Cache, checksum []byte) (*types.AnalysisReport, error) { func GetMetrics(cache Cache) (*types.Metrics, error) { errmsg := newUnmanagedVector(nil) - metrics, err := C.get_metrics(cache.ptr, &errmsg) + metrics, err := C.get_metrics(cache.ptr, &errmsg) //nolint:gocritic if err != nil { return nil, errorWithMessage(err, errmsg) } @@ -168,7 +168,7 @@ func Instantiate( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.instantiate(cache.ptr, cs, e, i, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.instantiate(cache.ptr, cs, e, i, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -208,7 +208,7 @@ func Execute( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.execute(cache.ptr, cs, e, i, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.execute(cache.ptr, cs, e, i, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -245,7 +245,7 @@ func Migrate( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.migrate(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.migrate(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -282,7 +282,7 @@ func Sudo( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.sudo(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.sudo(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -319,7 +319,7 @@ func Reply( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.reply(cache.ptr, cs, e, r, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.reply(cache.ptr, cs, e, r, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -356,7 +356,7 @@ func Query( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.query(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.query(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -393,7 +393,7 @@ func IBCChannelOpen( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.ibc_channel_open(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.ibc_channel_open(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -430,7 +430,7 @@ func IBCChannelConnect( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.ibc_channel_connect(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.ibc_channel_connect(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -467,7 +467,7 @@ func IBCChannelClose( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.ibc_channel_close(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.ibc_channel_close(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -504,7 +504,7 @@ func IBCPacketReceive( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.ibc_packet_receive(cache.ptr, cs, e, pa, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.ibc_packet_receive(cache.ptr, cs, e, pa, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -541,7 +541,7 @@ func IBCPacketAck( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.ibc_packet_ack(cache.ptr, cs, e, ac, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.ibc_packet_ack(cache.ptr, cs, e, ac, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) @@ -578,7 +578,7 @@ func IBCPacketTimeout( var gasUsed cu64 errmsg := newUnmanagedVector(nil) - res, err := C.ibc_packet_timeout(cache.ptr, cs, e, pa, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) + res, err := C.ibc_packet_timeout(cache.ptr, cs, e, pa, db, a, q, cu64(gasLimit), cbool(printDebug), &gasUsed, &errmsg) //nolint:gocritic if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success { // Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0. return nil, uint64(gasUsed), errorWithMessage(err, errmsg) diff --git a/internal/api/mocks.go b/internal/api/mocks.go index 55bceb005..90bec80d1 100644 --- a/internal/api/mocks.go +++ b/internal/api/mocks.go @@ -17,7 +17,10 @@ import ( /** helper constructors **/ -const MockContractAddr = "contract" +const ( + MockContractAddr = "contract" + Foobar = "foobar" +) func MockEnv() types.Env { return types.Env{ @@ -370,8 +373,8 @@ func NewMockAPI() *GoAPI { } } -func TestMockApi(t *testing.T) { - human := "foobar" +func TestMockAPI(t *testing.T) { + human := Foobar canon, cost, err := MockCanonicalAddress(human) require.NoError(t, err) assert.Equal(t, CanonicalLength, len(canon)) @@ -385,7 +388,7 @@ func TestMockApi(t *testing.T) { /**** MockQuerier ****/ -const DEFAULT_QUERIER_GAS_LIMIT = 1_000_000 +const DefaultQuerierGasLimit = 1_000_000 type MockQuerier struct { Bank BankQuerier @@ -411,7 +414,7 @@ func (q MockQuerier) Query(request types.QueryRequest, _gasLimit uint64) ([]byte if err != nil { return nil, err } - q.usedGas += uint64(len(marshaled)) + q.usedGas += uint64(len(marshaled)) //nolint:staticcheck if request.Bank != nil { return q.Bank.Query(request.Bank) } @@ -509,7 +512,7 @@ func (q ReflectCustom) Query(request json.RawMessage) ([]byte, error) { return nil, err } var resp CustomResponse - if query.Ping != nil { + if query.Ping != nil { //nolint:gocritic resp.Msg = "PONG" } else if query.Capitalized != nil { resp.Msg = strings.ToUpper(query.Capitalized.Text) @@ -522,7 +525,7 @@ func (q ReflectCustom) Query(request json.RawMessage) ([]byte, error) { // ************ test code for mocks *************************// func TestBankQuerierAllBalances(t *testing.T) { - addr := "foobar" + addr := Foobar balance := types.Coins{types.NewCoin(12345678, "ATOM"), types.NewCoin(54321, "ETH")} q := DefaultQuerier(addr, balance) @@ -534,7 +537,7 @@ func TestBankQuerierAllBalances(t *testing.T) { }, }, } - res, err := q.Query(req, DEFAULT_QUERIER_GAS_LIMIT) + res, err := q.Query(req, DefaultQuerierGasLimit) require.NoError(t, err) var resp types.AllBalancesResponse err = json.Unmarshal(res, &resp) @@ -549,7 +552,7 @@ func TestBankQuerierAllBalances(t *testing.T) { }, }, } - res, err = q.Query(req2, DEFAULT_QUERIER_GAS_LIMIT) + res, err = q.Query(req2, DefaultQuerierGasLimit) require.NoError(t, err) var resp2 types.AllBalancesResponse err = json.Unmarshal(res, &resp2) @@ -558,7 +561,7 @@ func TestBankQuerierAllBalances(t *testing.T) { } func TestBankQuerierBalance(t *testing.T) { - addr := "foobar" + addr := Foobar balance := types.Coins{types.NewCoin(12345678, "ATOM"), types.NewCoin(54321, "ETH")} q := DefaultQuerier(addr, balance) @@ -571,7 +574,7 @@ func TestBankQuerierBalance(t *testing.T) { }, }, } - res, err := q.Query(req, DEFAULT_QUERIER_GAS_LIMIT) + res, err := q.Query(req, DefaultQuerierGasLimit) require.NoError(t, err) var resp types.BalanceResponse err = json.Unmarshal(res, &resp) @@ -587,7 +590,7 @@ func TestBankQuerierBalance(t *testing.T) { }, }, } - res, err = q.Query(req2, DEFAULT_QUERIER_GAS_LIMIT) + res, err = q.Query(req2, DefaultQuerierGasLimit) require.NoError(t, err) var resp2 types.BalanceResponse err = json.Unmarshal(res, &resp2) @@ -603,7 +606,7 @@ func TestBankQuerierBalance(t *testing.T) { }, }, } - res, err = q.Query(req3, DEFAULT_QUERIER_GAS_LIMIT) + res, err = q.Query(req3, DefaultQuerierGasLimit) require.NoError(t, err) var resp3 types.BalanceResponse err = json.Unmarshal(res, &resp3) diff --git a/internal/api/version.go b/internal/api/version.go index 43a13f0b9..63a48095a 100644 --- a/internal/api/version.go +++ b/internal/api/version.go @@ -6,12 +6,12 @@ package api import "C" func LibwasmvmVersion() (string, error) { - version_ptr, err := C.version_str() + versionPtr, err := C.version_str() if err != nil { return "", err } // For C.GoString documentation see https://pkg.go.dev/cmd/cgo and // https://gist.github.com/helinwang/2c7bd2867ea5110f70e6431a7c80cd9b - version_copy := C.GoString(version_ptr) - return version_copy, nil + versionCopy := C.GoString(versionPtr) + return versionCopy, nil } diff --git a/lib.go b/lib.go index 461301bbe..a91e69c15 100644 --- a/lib.go +++ b/lib.go @@ -316,7 +316,7 @@ func (vm *VM) Sudo( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization @@ -361,7 +361,7 @@ func (vm *VM) Reply( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization @@ -447,7 +447,7 @@ func (vm *VM) IBCChannelConnect( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization @@ -490,7 +490,7 @@ func (vm *VM) IBCChannelClose( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization @@ -533,7 +533,7 @@ func (vm *VM) IBCPacketReceive( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) //nolint:stylecheck } gasUsed += gasForDeserialization diff --git a/types/msg.go b/types/msg.go index cd3c8e3cb..9c59fc9c4 100644 --- a/types/msg.go +++ b/types/msg.go @@ -142,7 +142,7 @@ type GovMsg struct { type voteOption int type VoteMsg struct { - ProposalId uint64 `json:"proposal_id"` + ProposalId uint64 `json:"proposal_id"` //nolint:revive,stylecheck Vote voteOption `json:"vote"` } From f806dcfb9e2b2ad291f0b03a9ec283ad0a742e76 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 26 Oct 2022 17:50:27 +0700 Subject: [PATCH 21/24] finish linting --- internal/api/mocks.go | 2 +- lib.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/api/mocks.go b/internal/api/mocks.go index 90bec80d1..c05bed7a6 100644 --- a/internal/api/mocks.go +++ b/internal/api/mocks.go @@ -517,7 +517,7 @@ func (q ReflectCustom) Query(request json.RawMessage) ([]byte, error) { } else if query.Capitalized != nil { resp.Msg = strings.ToUpper(query.Capitalized.Text) } else { - return nil, errors.New("Unsupported query") + return nil, errors.New("unsupported query") } return json.Marshal(resp) } diff --git a/lib.go b/lib.go index a91e69c15..a8207ff5f 100644 --- a/lib.go +++ b/lib.go @@ -574,7 +574,7 @@ func (vm *VM) IBCPacketAck( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) } gasUsed += gasForDeserialization @@ -618,7 +618,7 @@ func (vm *VM) IBCPacketTimeout( gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasUsed { - return nil, gasUsed, fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return nil, gasUsed, fmt.Errorf("insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) } gasUsed += gasForDeserialization From fe74a1c329b2787fab8fab9716e352ddab813a43 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 28 Feb 2023 21:07:34 +0700 Subject: [PATCH 22/24] further lints --- .golangci.yml | 69 +++++++++++++- cmd/demo/main.go | 11 +-- ibc_test.go | 122 ++++++++++++------------ internal/api/api_test.go | 4 +- internal/api/callbacks.go | 6 +- internal/api/iterator_test.go | 26 +++--- internal/api/lib.go | 3 +- internal/api/lib_test.go | 171 +++++++++++++++++----------------- internal/api/memory_test.go | 8 +- lib_test.go | 59 ++++++------ types/msg.go | 6 +- types/msg_test.go | 4 +- types/submessages.go | 2 +- 13 files changed, 277 insertions(+), 214 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index ead6a79bd..456413cab 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,5 @@ run: - tests: false + tests: true # timeout for analysis, e.g. 30s, 5m, default is 1m timeout: 5m @@ -8,6 +8,7 @@ linters: enable: - depguard - dogsled + - errcheck - exportloopref - goconst - gocritic @@ -19,9 +20,73 @@ linters: - misspell - nakedret - nolintlint - - staticcheck - revive + - staticcheck - stylecheck - typecheck - unconvert + - unparam - unused + +# TODO: fix the sdkerrors.Wrap deprecation warning and re-enable staticcheck +# TODO: fix the use of deprecated gov style + +issues: + exclude-rules: + - text: "SA1019: sdkerrors.Register" + linters: + - staticcheck + - text: "sdkerrors.ABCIInfo is deprecated" + linters: + - staticcheck + - text: "sdkerrors.IsOf is deprecated" + linters: + - staticcheck + - text: "Use WeightedProposalMsg instead" + linters: + - staticcheck + - text: "Use MsgSimulatorFn instead" + linters: + - staticcheck + - text: "Error return value of `flagSet.Set` is not checked" + linters: + - errcheck + - text: "SA1019: sdkerrors.Wrapf is deprecated: functionality of this package has been moved to it's own module" + linters: + - staticcheck + - text: "sdkerrors.Error is deprecated: the type has been moved to cosmossdk.io/errors module" + linters: + - staticcheck + - text: "sdkerrors.Wrap is deprecated" + linters: + - staticcheck + - text: "Use of weak random number generator" + linters: + - gosec + - text: "ST1003:" + linters: + - stylecheck + # FIXME: Disabled until golangci-lint updates stylecheck with this fix: + # https://github.com/dominikh/go-tools/issues/389 + - text: "ST1016:" + linters: + - stylecheck + - path: "migrations" + text: "SA1019:" + linters: + - staticcheck + + max-issues-per-linter: 10000 + max-same-issues: 10000 + +linters-settings: + dogsled: + max-blank-identifiers: 3 + maligned: + # print struct with more effective memory layout or not, false by default + suggest-new: true + nolintlint: + allow-unused: false + allow-leading-space: true + require-explanation: false + require-specific: false diff --git a/cmd/demo/main.go b/cmd/demo/main.go index 77b7011b4..b66d2f51f 100644 --- a/cmd/demo/main.go +++ b/cmd/demo/main.go @@ -7,12 +7,11 @@ import ( wasmvm "github.com/CosmWasm/wasmvm" ) -//nolint:revive,stylecheck const ( - SUPPORTED_FEATURES = "staking" - PRINT_DEBUG = true - MEMORY_LIMIT = 32 // MiB - CACHE_SIZE = 100 // MiB + SupportedFeatures = "staking" + PrintDebug = true + MemoryLimit = 32 // MiB + CacheSize = 100 // MiB ) // This is just a demo to ensure we can compile a static go binary @@ -29,7 +28,7 @@ func main() { if err != nil { panic(err) } - vm, err := wasmvm.NewVM("tmp", SUPPORTED_FEATURES, MEMORY_LIMIT, PRINT_DEBUG, CACHE_SIZE) + vm, err := wasmvm.NewVM("tmp", SupportedFeatures, MemoryLimit, PrintDebug, CacheSize) if err != nil { panic(err) } diff --git a/ibc_test.go b/ibc_test.go index 6ccee8259..b95fdf6ef 100644 --- a/ibc_test.go +++ b/ibc_test.go @@ -14,12 +14,12 @@ import ( "github.com/CosmWasm/wasmvm/types" ) -const IBC_TEST_CONTRACT = "./testdata/ibc_reflect.wasm" +const IBCTestContract = "./testdata/ibc_reflect.wasm" func TestIBC(t *testing.T) { vm := withVM(t) - wasm, err := os.ReadFile(IBC_TEST_CONTRACT) + wasm, err := os.ReadFile(IBCTestContract) require.NoError(t, err) checksum, err := vm.StoreCode(wasm) @@ -81,17 +81,17 @@ func toBytes(t *testing.T, v interface{}) []byte { return bz } -const IBC_VERSION = "ibc-reflect-v1" +const IBCVersion = "ibc-reflect-v1" func TestIBCHandshake(t *testing.T) { // code id of the reflect contract - const REFLECT_ID uint64 = 101 + const ReflectID uint64 = 101 // channel id for handshake - const CHANNEL_ID = "channel-432" + const ChannelID = "channel-432" vm := withVM(t) - checksum := createTestContract(t, vm, IBC_TEST_CONTRACT) - gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + checksum := createTestContract(t, vm, IBCTestContract) + gasMeter1 := api.NewMockGasMeter(TestingGasLimit) deserCost := types.UFraction{Numerator: 1, Denominator: 1} // instantiate it with this store store := api.NewLookup(gasMeter1) @@ -102,63 +102,63 @@ func TestIBCHandshake(t *testing.T) { // instantiate env := api.MockEnv() info := api.MockInfo("creator", nil) - init_msg := IBCInstantiateMsg{ - ReflectCodeID: REFLECT_ID, + initMsg := IBCInstantiateMsg{ + ReflectCodeID: ReflectID, } - ires, _, err := vm.Instantiate(checksum, env, info, toBytes(t, init_msg), store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err := vm.Instantiate(checksum, env, info, toBytes(t, initMsg), store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 0, len(ires.Messages)) // channel open - gasMeter2 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := api.NewMockGasMeter(TestingGasLimit) store.SetGasMeter(gasMeter2) env = api.MockEnv() - openMsg := api.MockIBCChannelOpenInit(CHANNEL_ID, types.Ordered, IBC_VERSION) - ores, _, err := vm.IBCChannelOpen(checksum, env, openMsg, store, *goapi, querier, gasMeter2, TESTING_GAS_LIMIT, deserCost) + openMsg := api.MockIBCChannelOpenInit(ChannelID, types.Ordered, IBCVersion) + ores, _, err := vm.IBCChannelOpen(checksum, env, openMsg, store, *goapi, querier, gasMeter2, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, &types.IBC3ChannelOpenResponse{Version: "ibc-reflect-v1"}, ores) // channel connect - gasMeter3 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter3 := api.NewMockGasMeter(TestingGasLimit) store.SetGasMeter(gasMeter3) env = api.MockEnv() // completes and dispatches message to create reflect contract - connectMsg := api.MockIBCChannelConnectAck(CHANNEL_ID, types.Ordered, IBC_VERSION) - res, _, err := vm.IBCChannelConnect(checksum, env, connectMsg, store, *goapi, querier, gasMeter2, TESTING_GAS_LIMIT, deserCost) + connectMsg := api.MockIBCChannelConnectAck(ChannelID, types.Ordered, IBCVersion) + res, _, err := vm.IBCChannelConnect(checksum, env, connectMsg, store, *goapi, querier, gasMeter2, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 1, len(res.Messages)) // check for the expected custom event - expected_events := []types.Event{{ + expectedEvents := []types.Event{{ Type: "ibc", Attributes: []types.EventAttribute{{ Key: "channel", Value: "connect", }}, }} - require.Equal(t, expected_events, res.Events) + require.Equal(t, expectedEvents, res.Events) // make sure it read the balance properly and we got 250 atoms dispatch := res.Messages[0].Msg require.NotNil(t, dispatch.Wasm, "%#v", dispatch) require.NotNil(t, dispatch.Wasm.Instantiate, "%#v", dispatch) init := dispatch.Wasm.Instantiate - assert.Equal(t, REFLECT_ID, init.CodeID) + assert.Equal(t, ReflectID, init.CodeID) assert.Empty(t, init.Funds) } func TestIBCPacketDispatch(t *testing.T) { // code id of the reflect contract - const REFLECT_ID uint64 = 77 + const ReflectID uint64 = 77 // address of first reflect contract instance that we created - const REFLECT_ADDR = "reflect-acct-1" + const ReflectAddress = "reflect-acct-1" // channel id for handshake - const CHANNEL_ID = "channel-234" + const ChannelID = "channel-234" // setup vm := withVM(t) - checksum := createTestContract(t, vm, IBC_TEST_CONTRACT) - gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + checksum := createTestContract(t, vm, IBCTestContract) + gasMeter1 := api.NewMockGasMeter(TestingGasLimit) deserCost := types.UFraction{Numerator: 1, Denominator: 1} // instantiate it with this store store := api.NewLookup(gasMeter1) @@ -170,31 +170,31 @@ func TestIBCPacketDispatch(t *testing.T) { env := api.MockEnv() info := api.MockInfo("creator", nil) initMsg := IBCInstantiateMsg{ - ReflectCodeID: REFLECT_ID, + ReflectCodeID: ReflectID, } - _, _, err := vm.Instantiate(checksum, env, info, toBytes(t, initMsg), store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + _, _, err := vm.Instantiate(checksum, env, info, toBytes(t, initMsg), store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) // channel open - gasMeter2 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := api.NewMockGasMeter(TestingGasLimit) store.SetGasMeter(gasMeter2) - openMsg := api.MockIBCChannelOpenInit(CHANNEL_ID, types.Ordered, IBC_VERSION) - ores, _, err := vm.IBCChannelOpen(checksum, env, openMsg, store, *goapi, querier, gasMeter2, TESTING_GAS_LIMIT, deserCost) + openMsg := api.MockIBCChannelOpenInit(ChannelID, types.Ordered, IBCVersion) + ores, _, err := vm.IBCChannelOpen(checksum, env, openMsg, store, *goapi, querier, gasMeter2, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, &types.IBC3ChannelOpenResponse{Version: "ibc-reflect-v1"}, ores) // channel connect - gasMeter3 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter3 := api.NewMockGasMeter(TestingGasLimit) store.SetGasMeter(gasMeter3) // completes and dispatches message to create reflect contract - connectMsg := api.MockIBCChannelConnectAck(CHANNEL_ID, types.Ordered, IBC_VERSION) - res, _, err := vm.IBCChannelConnect(checksum, env, connectMsg, store, *goapi, querier, gasMeter3, TESTING_GAS_LIMIT, deserCost) + connectMsg := api.MockIBCChannelConnectAck(ChannelID, types.Ordered, IBCVersion) + res, _, err := vm.IBCChannelConnect(checksum, env, connectMsg, store, *goapi, querier, gasMeter3, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 1, len(res.Messages)) id := res.Messages[0].ID // mock reflect init callback (to store address) - gasMeter4 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter4 := api.NewMockGasMeter(TestingGasLimit) store.SetGasMeter(gasMeter4) reply := types.Reply{ ID: id, @@ -205,7 +205,7 @@ func TestIBCPacketDispatch(t *testing.T) { Attributes: types.EventAttributes{ { Key: "_contract_address", - Value: REFLECT_ADDR, + Value: ReflectAddress, }, }, }}, @@ -213,24 +213,24 @@ func TestIBCPacketDispatch(t *testing.T) { }, }, } - _, _, err = vm.Reply(checksum, env, reply, store, *goapi, querier, gasMeter4, TESTING_GAS_LIMIT, deserCost) + _, _, err = vm.Reply(checksum, env, reply, store, *goapi, querier, gasMeter4, TestingGasLimit, deserCost) require.NoError(t, err) // ensure the channel is registered queryMsg := IBCQueryMsg{ ListAccounts: &struct{}{}, } - qres, _, err := vm.Query(checksum, env, toBytes(t, queryMsg), store, *goapi, querier, gasMeter4, TESTING_GAS_LIMIT, deserCost) + qres, _, err := vm.Query(checksum, env, toBytes(t, queryMsg), store, *goapi, querier, gasMeter4, TestingGasLimit, deserCost) require.NoError(t, err) var accounts ListAccountsResponse err = json.Unmarshal(qres, &accounts) require.NoError(t, err) require.Equal(t, 1, len(accounts.Accounts)) - require.Equal(t, CHANNEL_ID, accounts.Accounts[0].ChannelID) - require.Equal(t, REFLECT_ADDR, accounts.Accounts[0].Account) + require.Equal(t, ChannelID, accounts.Accounts[0].ChannelID) + require.Equal(t, ReflectAddress, accounts.Accounts[0].Account) // process message received on this channel - gasMeter5 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter5 := api.NewMockGasMeter(TestingGasLimit) store.SetGasMeter(gasMeter5) ibcMsg := IBCPacketMsg{ Dispatch: &DispatchMsg{ @@ -242,8 +242,8 @@ func TestIBCPacketDispatch(t *testing.T) { }}, }, } - msg := api.MockIBCPacketReceive(CHANNEL_ID, toBytes(t, ibcMsg)) - pr, _, err := vm.IBCPacketReceive(checksum, env, msg, store, *goapi, querier, gasMeter5, TESTING_GAS_LIMIT, deserCost) + msg := api.MockIBCPacketReceive(ChannelID, toBytes(t, ibcMsg)) + pr, _, err := vm.IBCPacketReceive(checksum, env, msg, store, *goapi, querier, gasMeter5, TestingGasLimit, deserCost) require.NoError(t, err) assert.NotNil(t, pr.Ok) pres := pr.Ok @@ -256,7 +256,7 @@ func TestIBCPacketDispatch(t *testing.T) { // error on message from another channel msg2 := api.MockIBCPacketReceive("no-such-channel", toBytes(t, ibcMsg)) - pr2, _, err := vm.IBCPacketReceive(checksum, env, msg2, store, *goapi, querier, gasMeter5, TESTING_GAS_LIMIT, deserCost) + pr2, _, err := vm.IBCPacketReceive(checksum, env, msg2, store, *goapi, querier, gasMeter5, TestingGasLimit, deserCost) require.NoError(t, err) assert.NotNil(t, pr.Ok) pres2 := pr2.Ok @@ -266,21 +266,21 @@ func TestIBCPacketDispatch(t *testing.T) { require.Equal(t, "invalid packet: cosmwasm_std::addresses::Addr not found", ack2.Err) // check for the expected custom event - expected_events := []types.Event{{ + expectedEvents := []types.Event{{ Type: "ibc", Attributes: []types.EventAttribute{{ Key: "packet", Value: "receive", }}, }} - require.Equal(t, expected_events, pres2.Events) + require.Equal(t, expectedEvents, pres2.Events) } func TestAnalyzeCode(t *testing.T) { vm := withVM(t) // Store non-IBC contract - wasm, err := os.ReadFile(HACKATOM_TEST_CONTRACT) + wasm, err := os.ReadFile(HackatomTestContract) require.NoError(t, err) checksum, err := vm.StoreCode(wasm) require.NoError(t, err) @@ -288,11 +288,11 @@ func TestAnalyzeCode(t *testing.T) { report, err := vm.AnalyzeCode(checksum) require.NoError(t, err) require.False(t, report.HasIBCEntryPoints) - require.Equal(t, "", report.RequiredFeatures) + require.Equal(t, "", report.RequiredFeatures) //nolint:staticcheck // ignore deprecation require.Equal(t, "", report.RequiredCapabilities) // Store IBC contract - wasm2, err := os.ReadFile(IBC_TEST_CONTRACT) + wasm2, err := os.ReadFile(IBCTestContract) require.NoError(t, err) checksum2, err := vm.StoreCode(wasm2) require.NoError(t, err) @@ -300,47 +300,47 @@ func TestAnalyzeCode(t *testing.T) { report2, err := vm.AnalyzeCode(checksum2) require.NoError(t, err) require.True(t, report2.HasIBCEntryPoints) - require.Equal(t, "iterator,stargate", report2.RequiredFeatures) + require.Equal(t, "iterator,stargate", report2.RequiredFeatures) //nolint:staticcheck // ignore deprecation require.Equal(t, "iterator,stargate", report2.RequiredCapabilities) } func TestIBCMsgGetChannel(t *testing.T) { - const CHANNEL_ID = "channel-432" + const ChannelID = "channel-432" - msg1 := api.MockIBCChannelOpenInit(CHANNEL_ID, types.Ordered, "random-garbage") - msg2 := api.MockIBCChannelOpenTry(CHANNEL_ID, types.Ordered, "random-garbage") - msg3 := api.MockIBCChannelConnectAck(CHANNEL_ID, types.Ordered, "random-garbage") - msg4 := api.MockIBCChannelConnectConfirm(CHANNEL_ID, types.Ordered, "random-garbage") - msg5 := api.MockIBCChannelCloseInit(CHANNEL_ID, types.Ordered, "random-garbage") - msg6 := api.MockIBCChannelCloseConfirm(CHANNEL_ID, types.Ordered, "random-garbage") + msg1 := api.MockIBCChannelOpenInit(ChannelID, types.Ordered, "random-garbage") + msg2 := api.MockIBCChannelOpenTry(ChannelID, types.Ordered, "random-garbage") + msg3 := api.MockIBCChannelConnectAck(ChannelID, types.Ordered, "random-garbage") + msg4 := api.MockIBCChannelConnectConfirm(ChannelID, types.Ordered, "random-garbage") + msg5 := api.MockIBCChannelCloseInit(ChannelID, types.Ordered, "random-garbage") + msg6 := api.MockIBCChannelCloseConfirm(ChannelID, types.Ordered, "random-garbage") require.Equal(t, msg1.GetChannel(), msg2.GetChannel()) require.Equal(t, msg1.GetChannel(), msg3.GetChannel()) require.Equal(t, msg1.GetChannel(), msg4.GetChannel()) require.Equal(t, msg1.GetChannel(), msg5.GetChannel()) require.Equal(t, msg1.GetChannel(), msg6.GetChannel()) - require.Equal(t, msg1.GetChannel().Endpoint.ChannelID, CHANNEL_ID) + require.Equal(t, msg1.GetChannel().Endpoint.ChannelID, ChannelID) } func TestIBCMsgGetCounterVersion(t *testing.T) { - const CHANNEL_ID = "channel-432" + const ChannelID = "channel-432" const VERSION = "random-garbage" - msg1 := api.MockIBCChannelOpenInit(CHANNEL_ID, types.Ordered, VERSION) + msg1 := api.MockIBCChannelOpenInit(ChannelID, types.Ordered, VERSION) _, ok := msg1.GetCounterVersion() require.False(t, ok) - msg2 := api.MockIBCChannelOpenTry(CHANNEL_ID, types.Ordered, VERSION) + msg2 := api.MockIBCChannelOpenTry(ChannelID, types.Ordered, VERSION) v, ok := msg2.GetCounterVersion() require.True(t, ok) require.Equal(t, VERSION, v) - msg3 := api.MockIBCChannelConnectAck(CHANNEL_ID, types.Ordered, VERSION) + msg3 := api.MockIBCChannelConnectAck(ChannelID, types.Ordered, VERSION) v, ok = msg3.GetCounterVersion() require.True(t, ok) require.Equal(t, VERSION, v) - msg4 := api.MockIBCChannelConnectConfirm(CHANNEL_ID, types.Ordered, VERSION) + msg4 := api.MockIBCChannelConnectConfirm(ChannelID, types.Ordered, VERSION) _, ok = msg4.GetCounterVersion() require.False(t, ok) } diff --git a/internal/api/api_test.go b/internal/api/api_test.go index 278ee4fd4..9364bd627 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -20,7 +20,7 @@ func TestValidateAddressFailure(t *testing.T) { checksum, err := StoreCode(cache, wasm) require.NoError(t, err) - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) // instantiate it with this store store := NewLookup(gasMeter) api := NewMockAPI() @@ -34,7 +34,7 @@ func TestValidateAddressFailure(t *testing.T) { // make sure the call doesn't error, but we get a JSON-encoded error result from ContractResult igasMeter := types.GasMeter(gasMeter) - res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var result types.ContractResult err = json.Unmarshal(res, &result) diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index df8b0f25b..1db53d9ad 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -94,8 +94,7 @@ func recoverPanic(ret *C.GoError) { /****** DB ********/ - -var db_vtable = C.Db_vtable{ +var dbVtable = C.Db_vtable{ read_db: (C.read_db_fn)(C.cGet_cgo), write_db: (C.write_db_fn)(C.cSet_cgo), remove_db: (C.remove_db_fn)(C.cDelete_cgo), @@ -314,8 +313,7 @@ func cNext(ref C.iterator_t, gasMeter *C.gas_meter_t, usedGas *cu64, key *C.Unma return C.GoError_None } - -var api_vtable = C.GoApi_vtable{ +var apiVtable = C.GoApi_vtable{ humanize_address: (C.humanize_address_fn)(C.cHumanAddress_cgo), canonicalize_address: (C.canonicalize_address_fn)(C.cCanonicalAddress_cgo), } diff --git a/internal/api/iterator_test.go b/internal/api/iterator_test.go index e5cce31eb..4df5150d0 100644 --- a/internal/api/iterator_test.go +++ b/internal/api/iterator_test.go @@ -28,7 +28,7 @@ func (q queueData) Store(meter MockGasMeter) types.KVStore { func setupQueueContractWithData(t *testing.T, cache Cache, values ...int) queueData { checksum := createQueueContract(t, cache) - gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := NewMockGasMeter(TestingGasLimit) // instantiate it with this store store := NewLookup(gasMeter1) api := NewMockAPI() @@ -38,15 +38,15 @@ func setupQueueContractWithData(t *testing.T, cache Cache, values ...int) queueD msg := []byte(`{}`) igasMeter1 := types.GasMeter(gasMeter1) - res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) for _, value := range values { // push 17 - var gasMeter2 types.GasMeter = NewMockGasMeter(TESTING_GAS_LIMIT) + var gasMeter2 types.GasMeter = NewMockGasMeter(TestingGasLimit) push := []byte(fmt.Sprintf(`{"enqueue":{"value":%d}}`, value)) - res, _, err = Execute(cache, checksum, env, info, push, &gasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err = Execute(cache, checksum, env, info, push, &gasMeter2, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) } @@ -176,12 +176,12 @@ func TestQueueIteratorSimple(t *testing.T) { checksum, querier, api := setup.checksum, setup.querier, setup.api // query the sum - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) igasMeter := types.GasMeter(gasMeter) store := setup.Store(gasMeter) query := []byte(`{"sum":{}}`) env := MockEnvBin(t) - data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var qres types.QueryResponse err = json.Unmarshal(data, &qres) @@ -191,7 +191,7 @@ func TestQueueIteratorSimple(t *testing.T) { // query reduce (multiple iterators at once) query = []byte(`{"reducer":{}}`) - data, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var reduced types.QueryResponse err = json.Unmarshal(data, &reduced) @@ -213,13 +213,13 @@ func TestQueueIteratorRaces(t *testing.T) { reduceQuery := func(t *testing.T, setup queueData, expected string) { checksum, querier, api := setup.checksum, setup.querier, setup.api - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) igasMeter := types.GasMeter(gasMeter) store := setup.Store(gasMeter) // query reduce (multiple iterators at once) query := []byte(`{"reducer":{}}`) - data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var reduced types.QueryResponse err = json.Unmarshal(data, &reduced) @@ -266,13 +266,13 @@ func TestQueueIteratorLimit(t *testing.T) { var gasLimit uint64 // Open 5000 iterators - gasLimit = TESTING_GAS_LIMIT + gasLimit = TestingGasLimit gasMeter := NewMockGasMeter(gasLimit) igasMeter := types.GasMeter(gasMeter) store := setup.Store(gasMeter) query := []byte(`{"open_iterators":{"count":5000}}`) env := MockEnvBin(t) - data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TESTING_PRINT_DEBUG) + data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TestingPrintDebug) require.NoError(t, err) err = json.Unmarshal(data, &qres) require.NoError(t, err) @@ -280,12 +280,12 @@ func TestQueueIteratorLimit(t *testing.T) { require.Equal(t, `{}`, string(qres.Ok)) // Open 35000 iterators - gasLimit = TESTING_GAS_LIMIT * 4 + gasLimit = TestingGasLimit * 4 gasMeter = NewMockGasMeter(gasLimit) igasMeter = types.GasMeter(gasMeter) store = setup.Store(gasMeter) query = []byte(`{"open_iterators":{"count":35000}}`) env = MockEnvBin(t) - _, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TESTING_PRINT_DEBUG) + _, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TestingPrintDebug) require.ErrorContains(t, err, "Reached iterator limit (32768)") } diff --git a/internal/api/lib.go b/internal/api/lib.go index a310bd1d8..516e2806c 100644 --- a/internal/api/lib.go +++ b/internal/api/lib.go @@ -26,8 +26,7 @@ type ( ) // Pointers -type cu8_ptr = *C.uint8_t //nolint:revive,stylecheck - +type cu8_ptr = *C.uint8_t //nolint:revive type Cache struct { ptr *C.cache_t diff --git a/internal/api/lib_test.go b/internal/api/lib_test.go index df39f22d1..8f229dfde 100644 --- a/internal/api/lib_test.go +++ b/internal/api/lib_test.go @@ -3,6 +3,7 @@ package api import ( "encoding/json" "fmt" + "io/ioutil" "os" "path/filepath" "testing" @@ -15,24 +16,24 @@ import ( ) const ( - TESTING_FEATURES = "staking,stargate,iterator,cosmwasm_1_1,cosmwasm_1_2" - TESTING_PRINT_DEBUG = false - TESTING_GAS_LIMIT = uint64(500_000_000_000) // ~0.5ms - TESTING_MEMORY_LIMIT = 32 // MiB - TESTING_CACHE_SIZE = 100 // MiB + TestingFeatures = "staking,stargate,iterator,cosmwasm_1_1,cosmwasm_1_2" + TestingPrintDebug = false + TestingGasLimit = uint64(500_000_000_000) // ~0.5ms + TestingMemoryLimit = 32 // MiB + TestingCacheSize = 100 // MiB ) func TestInitAndReleaseCache(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "wasmvm-testing") + tmpdir, err := os.MkdirTemp("", "wasmvm-testing") require.NoError(t, err) defer os.RemoveAll(tmpdir) - cache, err := InitCache(tmpdir, TESTING_FEATURES, TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) + cache, err := InitCache(tmpdir, TestingFeatures, TestingCacheSize, TestingMemoryLimit) require.NoError(t, err) ReleaseCache(cache) } -// wasmd expectes us to create the base directory +// wasmd expects us to create the base directory // https://github.com/CosmWasm/wasmd/blob/v0.30.0/x/wasm/keeper/keeper.go#L128 func TestInitCacheWorksForNonExistentDir(t *testing.T) { tmpdir, err := ioutil.TempDir("", "wasmvm-testing") @@ -40,7 +41,7 @@ func TestInitCacheWorksForNonExistentDir(t *testing.T) { defer os.RemoveAll(tmpdir) createMe := filepath.Join(tmpdir, "does-not-yet-exist") - cache, err := InitCache(createMe, TESTING_FEATURES, TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) + cache, err := InitCache(createMe, TestingFeatures, TestingCacheSize, TestingMemoryLimit) require.NoError(t, err) ReleaseCache(cache) } @@ -50,7 +51,7 @@ func TestInitCacheErrorsForBrokenDir(t *testing.T) { // https://gist.github.com/doctaphred/d01d05291546186941e1b7ddc02034d3 // On Unix we should not have permission to create this. cannotBeCreated := "/foo:bar" - _, err := InitCache(cannotBeCreated, TESTING_FEATURES, TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) + _, err := InitCache(cannotBeCreated, TestingFeatures, TestingCacheSize, TestingMemoryLimit) require.ErrorContains(t, err, "Error creating state directory") } @@ -58,14 +59,14 @@ func TestInitCacheEmptyFeatures(t *testing.T) { tmpdir, err := os.MkdirTemp("", "wasmvm-testing") require.NoError(t, err) defer os.RemoveAll(tmpdir) - cache, _ := InitCache(tmpdir, "", TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) + cache, _ := InitCache(tmpdir, "", TestingCacheSize, TestingMemoryLimit) ReleaseCache(cache) } func withCache(t *testing.T) (Cache, func()) { tmpdir, err := os.MkdirTemp("", "wasmvm-testing") require.NoError(t, err) - cache, err := InitCache(tmpdir, TESTING_FEATURES, TESTING_CACHE_SIZE, TESTING_MEMORY_LIMIT) + cache, err := InitCache(tmpdir, TestingFeatures, TestingCacheSize, TestingMemoryLimit) require.NoError(t, err) cleanup := func() { @@ -221,7 +222,7 @@ func TestGetMetrics(t *testing.T) { assert.Equal(t, &types.Metrics{}, metrics) // Instantiate 1 - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) igasMeter := types.GasMeter(gasMeter) store := NewLookup(gasMeter) api := NewMockAPI() @@ -229,7 +230,7 @@ func TestGetMetrics(t *testing.T) { env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg1 := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - _, _, err = Instantiate(cache, checksum, env, info, msg1, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + _, _, err = Instantiate(cache, checksum, env, info, msg1, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) // GetMetrics 3 @@ -242,7 +243,7 @@ func TestGetMetrics(t *testing.T) { // Instantiate 2 msg2 := []byte(`{"verifier": "fred", "beneficiary": "susi"}`) - _, _, err = Instantiate(cache, checksum, env, info, msg2, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + _, _, err = Instantiate(cache, checksum, env, info, msg2, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) // GetMetrics 4 @@ -269,7 +270,7 @@ func TestGetMetrics(t *testing.T) { // Instantiate 3 msg3 := []byte(`{"verifier": "fred", "beneficiary": "bert"}`) - _, _, err = Instantiate(cache, checksum, env, info, msg3, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + _, _, err = Instantiate(cache, checksum, env, info, msg3, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) // GetMetrics 6 @@ -300,7 +301,7 @@ func TestGetMetrics(t *testing.T) { // Instantiate 4 msg4 := []byte(`{"verifier": "fred", "beneficiary": "jeff"}`) - _, _, err = Instantiate(cache, checksum, env, info, msg4, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + _, _, err = Instantiate(cache, checksum, env, info, msg4, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) // GetMetrics 8 @@ -325,7 +326,7 @@ func TestInstantiate(t *testing.T) { checksum, err := StoreCode(cache, wasm) require.NoError(t, err) - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) igasMeter := types.GasMeter(gasMeter) // instantiate it with this store store := NewLookup(gasMeter) @@ -335,7 +336,7 @@ func TestInstantiate(t *testing.T) { info := MockInfoBin(t, "creator") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) assert.Equal(t, uint64(0x13a78a36c), cost) @@ -352,7 +353,7 @@ func TestExecute(t *testing.T) { defer cleanup() checksum := createHackatomContract(t, cache) - gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := NewMockGasMeter(TestingGasLimit) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store store := NewLookup(gasMeter1) @@ -365,22 +366,22 @@ func TestExecute(t *testing.T) { msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) start := time.Now() - res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) - diff := time.Now().Sub(start) + res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TestingGasLimit, TestingPrintDebug) + diff := time.Since(start) require.NoError(t, err) requireOkResponse(t, res, 0) assert.Equal(t, uint64(0x13a78a36c), cost) t.Logf("Time (%d gas): %s\n", cost, diff) // execute with the same store - gasMeter2 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := NewMockGasMeter(TestingGasLimit) igasMeter2 := types.GasMeter(gasMeter2) store.SetGasMeter(gasMeter2) env = MockEnvBin(t) info = MockInfoBin(t, "fred") start = time.Now() - res, cost, err = Execute(cache, checksum, env, info, []byte(`{"release":{}}`), &igasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) - diff = time.Now().Sub(start) + res, cost, err = Execute(cache, checksum, env, info, []byte(`{"release":{}}`), &igasMeter2, store, api, &querier, TestingGasLimit, TestingPrintDebug) + diff = time.Since(start) require.NoError(t, err) assert.Equal(t, uint64(0x222892d70), cost) t.Logf("Time (%d gas): %s\n", cost, diff) @@ -416,7 +417,7 @@ func TestExecutePanic(t *testing.T) { defer cleanup() checksum := createCyberpunkContract(t, cache) - maxGas := TESTING_GAS_LIMIT + maxGas := TestingGasLimit gasMeter1 := NewMockGasMeter(maxGas) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store @@ -427,7 +428,7 @@ func TestExecutePanic(t *testing.T) { env := MockEnvBin(t) info := MockInfoBin(t, "creator") - res, _, err := Instantiate(cache, checksum, env, info, []byte(`{}`), &igasMeter1, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, []byte(`{}`), &igasMeter1, store, api, &querier, maxGas, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) @@ -436,7 +437,7 @@ func TestExecutePanic(t *testing.T) { igasMeter2 := types.GasMeter(gasMeter2) store.SetGasMeter(gasMeter2) info = MockInfoBin(t, "fred") - res, _, err = Execute(cache, checksum, env, info, []byte(`{"panic":{}}`), &igasMeter2, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) + _, _, err = Execute(cache, checksum, env, info, []byte(`{"panic":{}}`), &igasMeter2, store, api, &querier, maxGas, TestingPrintDebug) require.ErrorContains(t, err, "RuntimeError: Aborted: panicked at 'This page intentionally faulted'") } @@ -445,18 +446,18 @@ func TestExecuteUnreachable(t *testing.T) { defer cleanup() checksum := createCyberpunkContract(t, cache) - maxGas := TESTING_GAS_LIMIT + maxGas := TestingGasLimit gasMeter1 := NewMockGasMeter(maxGas) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store store := NewLookup(gasMeter1) api := NewMockAPI() balance := types.Coins{types.NewCoin(250, "ATOM")} - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, balance) + querier := DefaultQuerier(MockContractAddr, balance) env := MockEnvBin(t) info := MockInfoBin(t, "creator") - res, _, err := Instantiate(cache, checksum, env, info, []byte(`{}`), &igasMeter1, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, []byte(`{}`), &igasMeter1, store, api, &querier, maxGas, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) @@ -465,7 +466,7 @@ func TestExecuteUnreachable(t *testing.T) { igasMeter2 := types.GasMeter(gasMeter2) store.SetGasMeter(gasMeter2) info = MockInfoBin(t, "fred") - res, _, err = Execute(cache, checksum, env, info, []byte(`{"unreachable":{}}`), &igasMeter2, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) + _, _, err = Execute(cache, checksum, env, info, []byte(`{"unreachable":{}}`), &igasMeter2, store, api, &querier, maxGas, TestingPrintDebug) require.ErrorContains(t, err, "RuntimeError: unreachable") } @@ -474,20 +475,20 @@ func TestExecuteCpuLoop(t *testing.T) { defer cleanup() checksum := createCyberpunkContract(t, cache) - gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := NewMockGasMeter(TestingGasLimit) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store store := NewLookup(gasMeter1) api := NewMockAPI() - querier := DefaultQuerier(MOCK_CONTRACT_ADDR, nil) + querier := DefaultQuerier(MockContractAddr, nil) env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg := []byte(`{}`) start := time.Now() - res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) - diff := time.Now().Sub(start) + res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TestingGasLimit, TestingPrintDebug) + diff := time.Since(start) require.NoError(t, err) requireOkResponse(t, res, 0) assert.Equal(t, uint64(0xd45091d0), cost) @@ -500,8 +501,8 @@ func TestExecuteCpuLoop(t *testing.T) { store.SetGasMeter(gasMeter2) info = MockInfoBin(t, "fred") start = time.Now() - _, cost, err = Execute(cache, checksum, env, info, []byte(`{"cpu_loop":{}}`), &igasMeter2, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) - diff = time.Now().Sub(start) + _, cost, err = Execute(cache, checksum, env, info, []byte(`{"cpu_loop":{}}`), &igasMeter2, store, api, &querier, maxGas, TestingPrintDebug) + diff = time.Since(start) require.Error(t, err) assert.Equal(t, cost, maxGas) t.Logf("CPULoop Time (%d gas): %s\n", cost, diff) @@ -512,7 +513,7 @@ func TestExecuteStorageLoop(t *testing.T) { defer cleanup() checksum := createHackatomContract(t, cache) - maxGas := TESTING_GAS_LIMIT + maxGas := TestingGasLimit gasMeter1 := NewMockGasMeter(maxGas) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store @@ -525,7 +526,7 @@ func TestExecuteStorageLoop(t *testing.T) { msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, maxGas, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) @@ -535,8 +536,8 @@ func TestExecuteStorageLoop(t *testing.T) { store.SetGasMeter(gasMeter2) info = MockInfoBin(t, "fred") start := time.Now() - _, cost, err := Execute(cache, checksum, env, info, []byte(`{"storage_loop":{}}`), &igasMeter2, store, api, &querier, maxGas, TESTING_PRINT_DEBUG) - diff := time.Now().Sub(start) + _, cost, err := Execute(cache, checksum, env, info, []byte(`{"storage_loop":{}}`), &igasMeter2, store, api, &querier, maxGas, TestingPrintDebug) + diff := time.Since(start) require.Error(t, err) t.Logf("StorageLoop Time (%d gas): %s\n", cost, diff) t.Logf("Gas used: %d\n", gasMeter2.GasConsumed()) @@ -552,7 +553,7 @@ func TestExecuteUserErrorsInApiCalls(t *testing.T) { defer cleanup() checksum := createHackatomContract(t, cache) - maxGas := TESTING_GAS_LIMIT + maxGas := TestingGasLimit gasMeter1 := NewMockGasMeter(maxGas) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store @@ -562,9 +563,9 @@ func TestExecuteUserErrorsInApiCalls(t *testing.T) { env := MockEnvBin(t) info := MockInfoBin(t, "creator") - defaultApi := NewMockAPI() + defaultAPI := NewMockAPI() msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, defaultApi, &querier, maxGas, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, defaultAPI, &querier, maxGas, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) @@ -572,8 +573,8 @@ func TestExecuteUserErrorsInApiCalls(t *testing.T) { igasMeter2 := types.GasMeter(gasMeter2) store.SetGasMeter(gasMeter2) info = MockInfoBin(t, "fred") - failingApi := NewMockFailureAPI() - res, _, err = Execute(cache, checksum, env, info, []byte(`{"user_errors_in_api_calls":{}}`), &igasMeter2, store, failingApi, &querier, maxGas, TESTING_PRINT_DEBUG) + failingAPI := NewMockFailureAPI() + res, _, err = Execute(cache, checksum, env, info, []byte(`{"user_errors_in_api_calls":{}}`), &igasMeter2, store, failingAPI, &querier, maxGas, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) } @@ -583,7 +584,7 @@ func TestMigrate(t *testing.T) { defer cleanup() checksum := createHackatomContract(t, cache) - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) igasMeter := types.GasMeter(gasMeter) // instantiate it with this store store := NewLookup(gasMeter) @@ -594,13 +595,13 @@ func TestMigrate(t *testing.T) { info := MockInfoBin(t, "creator") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) // verifier is fred query := []byte(`{"verifier":{}}`) - data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var qres types.QueryResponse err = json.Unmarshal(data, &qres) @@ -610,11 +611,11 @@ func TestMigrate(t *testing.T) { // migrate to a new verifier - alice // we use the same code blob as we are testing hackatom self-migration - _, _, err = Migrate(cache, checksum, env, []byte(`{"verifier":"alice"}`), &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + _, _, err = Migrate(cache, checksum, env, []byte(`{"verifier":"alice"}`), &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) // should update verifier to alice - data, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var qres2 types.QueryResponse err = json.Unmarshal(data, &qres2) @@ -629,7 +630,7 @@ func TestMultipleInstances(t *testing.T) { checksum := createHackatomContract(t, cache) // instance1 controlled by fred - gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := NewMockGasMeter(TestingGasLimit) igasMeter1 := types.GasMeter(gasMeter1) store1 := NewLookup(gasMeter1) api := NewMockAPI() @@ -637,19 +638,19 @@ func TestMultipleInstances(t *testing.T) { env := MockEnvBin(t) info := MockInfoBin(t, "regen") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store1, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, cost, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store1, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) // we now count wasm gas charges and db writes assert.Equal(t, uint64(0x138559c5c), cost) // instance2 controlled by mary - gasMeter2 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := NewMockGasMeter(TestingGasLimit) igasMeter2 := types.GasMeter(gasMeter2) store2 := NewLookup(gasMeter2) info = MockInfoBin(t, "chrous") msg = []byte(`{"verifier": "mary", "beneficiary": "sue"}`) - res, cost, err = Instantiate(cache, checksum, env, info, msg, &igasMeter2, store2, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, cost, err = Instantiate(cache, checksum, env, info, msg, &igasMeter2, store2, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) assert.Equal(t, uint64(0x1399177bc), cost) @@ -682,7 +683,7 @@ func TestSudo(t *testing.T) { defer cleanup() checksum := createHackatomContract(t, cache) - gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := NewMockGasMeter(TestingGasLimit) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store store := NewLookup(gasMeter1) @@ -693,17 +694,17 @@ func TestSudo(t *testing.T) { info := MockInfoBin(t, "creator") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) // call sudo with same store - gasMeter2 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := NewMockGasMeter(TestingGasLimit) igasMeter2 := types.GasMeter(gasMeter2) store.SetGasMeter(gasMeter2) env = MockEnvBin(t) msg = []byte(`{"steal_funds":{"recipient":"community-pool","amount":[{"amount":"700","denom":"gold"}]}}`) - res, _, err = Sudo(cache, checksum, env, msg, &igasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err = Sudo(cache, checksum, env, msg, &igasMeter2, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) // make sure it blindly followed orders @@ -726,7 +727,7 @@ func TestDispatchSubmessage(t *testing.T) { defer cleanup() checksum := createReflectContract(t, cache) - gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := NewMockGasMeter(TestingGasLimit) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store store := NewLookup(gasMeter1) @@ -736,7 +737,7 @@ func TestDispatchSubmessage(t *testing.T) { info := MockInfoBin(t, "creator") msg := []byte(`{}`) - res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) @@ -754,11 +755,11 @@ func TestDispatchSubmessage(t *testing.T) { require.NoError(t, err) payloadMsg := []byte(fmt.Sprintf(`{"reflect_sub_msg":{"msgs":[%s]}}`, string(payloadBin))) - gasMeter2 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := NewMockGasMeter(TestingGasLimit) igasMeter2 := types.GasMeter(gasMeter2) store.SetGasMeter(gasMeter2) env = MockEnvBin(t) - res, _, err = Execute(cache, checksum, env, info, payloadMsg, &igasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err = Execute(cache, checksum, env, info, payloadMsg, &igasMeter2, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) // make sure it blindly followed orders @@ -779,7 +780,7 @@ func TestReplyAndQuery(t *testing.T) { defer cleanup() checksum := createReflectContract(t, cache) - gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := NewMockGasMeter(TestingGasLimit) igasMeter1 := types.GasMeter(gasMeter1) // instantiate it with this store store := NewLookup(gasMeter1) @@ -789,7 +790,7 @@ func TestReplyAndQuery(t *testing.T) { info := MockInfoBin(t, "creator") msg := []byte(`{}`) - res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) @@ -804,8 +805,8 @@ func TestReplyAndQuery(t *testing.T) { }} reply := types.Reply{ ID: id, - Result: types.SubcallResult{ - Ok: &types.SubcallResponse{ + Result: types.SubcallResult{ //nolint:staticcheck // ignore deprecated warning + Ok: &types.SubcallResponse{ //nolint:staticcheck // ignore deprecated warning Events: events, Data: data, }, @@ -814,22 +815,22 @@ func TestReplyAndQuery(t *testing.T) { replyBin, err := json.Marshal(reply) require.NoError(t, err) - gasMeter2 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := NewMockGasMeter(TestingGasLimit) igasMeter2 := types.GasMeter(gasMeter2) store.SetGasMeter(gasMeter2) env = MockEnvBin(t) - res, _, err = Reply(cache, checksum, env, replyBin, &igasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err = Reply(cache, checksum, env, replyBin, &igasMeter2, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireOkResponse(t, res, 0) // now query the state to see if it stored the data properly badQuery := []byte(`{"sub_msg_result":{"id":7777}}`) - res, _, err = Query(cache, checksum, env, badQuery, &igasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err = Query(cache, checksum, env, badQuery, &igasMeter2, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) requireQueryError(t, res) query := []byte(`{"sub_msg_result":{"id":1234}}`) - res, _, err = Query(cache, checksum, env, query, &igasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, _, err = Query(cache, checksum, env, query, &igasMeter2, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) qres := requireQueryOk(t, res) @@ -843,7 +844,7 @@ func TestReplyAndQuery(t *testing.T) { require.Equal(t, events, val.Events) } -func requireOkResponse(t *testing.T, res []byte, expectedMsgs int) { +func requireOkResponse(t *testing.T, res []byte, expectedMsgs int) { //nolint:unparam var result types.ContractResult err := json.Unmarshal(res, &result) require.NoError(t, err) @@ -894,11 +895,11 @@ func createContract(t *testing.T, cache Cache, wasmFile string) []byte { // exec runs the handle tx with the given signer func exec(t *testing.T, cache Cache, checksum []byte, signer types.HumanAddress, store types.KVStore, api *types.GoAPI, querier Querier, gasExpected uint64) types.ContractResult { - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) igasMeter := types.GasMeter(gasMeter) env := MockEnvBin(t) info := MockInfoBin(t, signer) - res, cost, err := Execute(cache, checksum, env, info, []byte(`{"release":{}}`), &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + res, cost, err := Execute(cache, checksum, env, info, []byte(`{"release":{}}`), &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) assert.Equal(t, gasExpected, cost) @@ -914,7 +915,7 @@ func TestQuery(t *testing.T) { checksum := createHackatomContract(t, cache) // set up contract - gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := NewMockGasMeter(TestingGasLimit) igasMeter1 := types.GasMeter(gasMeter1) store := NewLookup(gasMeter1) api := NewMockAPI() @@ -922,15 +923,15 @@ func TestQuery(t *testing.T) { env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - _, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + _, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) // invalid query - gasMeter2 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := NewMockGasMeter(TestingGasLimit) igasMeter2 := types.GasMeter(gasMeter2) store.SetGasMeter(gasMeter2) query := []byte(`{"Raw":{"val":"config"}}`) - data, _, err := Query(cache, checksum, env, query, &igasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err := Query(cache, checksum, env, query, &igasMeter2, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var badResp types.QueryResponse err = json.Unmarshal(data, &badResp) @@ -938,11 +939,11 @@ func TestQuery(t *testing.T) { require.Contains(t, badResp.Err, "Error parsing into type hackatom::msg::QueryMsg: unknown variant `Raw`, expected one of") // make a valid query - gasMeter3 := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter3 := NewMockGasMeter(TestingGasLimit) igasMeter3 := types.GasMeter(gasMeter3) store.SetGasMeter(gasMeter3) query = []byte(`{"verifier":{}}`) - data, _, err = Query(cache, checksum, env, query, &igasMeter3, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err = Query(cache, checksum, env, query, &igasMeter3, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var qres types.QueryResponse err = json.Unmarshal(data, &qres) @@ -957,7 +958,7 @@ func TestHackatomQuerier(t *testing.T) { checksum := createHackatomContract(t, cache) // set up contract - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) igasMeter := types.GasMeter(gasMeter) store := NewLookup(gasMeter) api := NewMockAPI() @@ -968,7 +969,7 @@ func TestHackatomQuerier(t *testing.T) { query := []byte(`{"other_balance":{"address":"foobar"}}`) // TODO The query happens before the contract is initialized. How is this legal? env := MockEnvBin(t) - data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var qres types.QueryResponse err = json.Unmarshal(data, &qres) @@ -999,7 +1000,7 @@ func TestCustomReflectQuerier(t *testing.T) { checksum := createReflectContract(t, cache) // set up contract - gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter := NewMockGasMeter(TestingGasLimit) igasMeter := types.GasMeter(gasMeter) store := NewLookup(gasMeter) api := NewMockAPI() @@ -1019,7 +1020,7 @@ func TestCustomReflectQuerier(t *testing.T) { query, err := json.Marshal(queryMsg) require.NoError(t, err) env := MockEnvBin(t) - data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) + data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TestingGasLimit, TestingPrintDebug) require.NoError(t, err) var qres types.QueryResponse err = json.Unmarshal(data, &qres) diff --git a/internal/api/memory_test.go b/internal/api/memory_test.go index 18d32ed22..ad4a125fd 100644 --- a/internal/api/memory_test.go +++ b/internal/api/memory_test.go @@ -63,15 +63,15 @@ func TestCreateAndDestroyUnmanagedVector(t *testing.T) { func TestCopyDestroyUnmanagedVector(t *testing.T) { { // ptr, cap and len broken. Do not access those values when is_none is true - invalid_ptr := unsafe.Pointer(uintptr(42)) //nolint:unsafeptr - uv := constructUnmanagedVector(cbool(true), cu8_ptr(invalid_ptr), cusize(0xBB), cusize(0xAA)) + invalidPtr := unsafe.Pointer(uintptr(42)) //nolint:unsafeptr + uv := constructUnmanagedVector(cbool(true), cu8_ptr(invalidPtr), cusize(0xBB), cusize(0xAA)) copy := copyAndDestroyUnmanagedVector(uv) require.Nil(t, copy) } { // Capacity is 0, so no allocation happened. Do not access the pointer. - invalid_ptr := unsafe.Pointer(uintptr(42)) //nolint:unsafeptr - uv := constructUnmanagedVector(cbool(false), cu8_ptr(invalid_ptr), cusize(0), cusize(0)) + invalidPtr := unsafe.Pointer(uintptr(42)) //nolint:unsafeptr + uv := constructUnmanagedVector(cbool(false), cu8_ptr(invalidPtr), cusize(0), cusize(0)) copy := copyAndDestroyUnmanagedVector(uv) require.Equal(t, []byte{}, copy) } diff --git a/lib_test.go b/lib_test.go index 292122d59..d46c58d4b 100644 --- a/lib_test.go +++ b/lib_test.go @@ -4,6 +4,7 @@ package cosmwasm import ( "encoding/json" + "io/ioutil" "os" "testing" @@ -15,22 +16,22 @@ import ( ) const ( - TESTING_FEATURES = "staking,stargate,iterator" - TESTING_PRINT_DEBUG = false - TESTING_GAS_LIMIT = uint64(500_000_000_000) // ~0.5ms - TESTING_MEMORY_LIMIT = 32 // MiB - TESTING_CACHE_SIZE = 100 // MiB + TestingFeatures = "staking,stargate,iterator" + TestingPrintDebug = false + TestingGasLimit = uint64(500_000_000_000) // ~0.5ms + TestingMemoryLimit = 32 // MiB + TestingCacheSize = 100 // MiB ) const ( - CYBERPUNK_TEST_CONTRACT = "./testdata/cyberpunk.wasm" - HACKATOM_TEST_CONTRACT = "./testdata/hackatom.wasm" + CyberpunkTestContract = "./testdata/cyberpunk.wasm" + HackatomTestContract = "./testdata/hackatom.wasm" ) func withVM(t *testing.T) *VM { tmpdir, err := os.MkdirTemp("", "wasmvm-testing") require.NoError(t, err) - vm, err := NewVM(tmpdir, TESTING_FEATURES, TESTING_MEMORY_LIMIT, TESTING_PRINT_DEBUG, TESTING_CACHE_SIZE) + vm, err := NewVM(tmpdir, TestingFeatures, TestingMemoryLimit, TestingPrintDebug, TestingCacheSize) require.NoError(t, err) t.Cleanup(func() { @@ -53,7 +54,7 @@ func TestStoreCode(t *testing.T) { // Valid hackatom contract { - wasm, err := ioutil.ReadFile(HACKATOM_TEST_CONTRACT) + wasm, err := ioutil.ReadFile(HackatomTestContract) require.NoError(t, err) _, err = vm.StoreCode(wasm) require.NoError(t, err) @@ -61,7 +62,7 @@ func TestStoreCode(t *testing.T) { // Valid cyberpunk contract { - wasm, err := ioutil.ReadFile(CYBERPUNK_TEST_CONTRACT) + wasm, err := ioutil.ReadFile(CyberpunkTestContract) require.NoError(t, err) _, err = vm.StoreCode(wasm) require.NoError(t, err) @@ -93,7 +94,7 @@ func TestStoreCode(t *testing.T) { // Nil { - var wasm []byte = nil + var wasm []byte _, err := vm.StoreCode(wasm) require.ErrorContains(t, err, "Null/Nil argument: wasm") } @@ -102,7 +103,7 @@ func TestStoreCode(t *testing.T) { func TestStoreCodeAndGet(t *testing.T) { vm := withVM(t) - wasm, err := os.ReadFile(HACKATOM_TEST_CONTRACT) + wasm, err := os.ReadFile(HackatomTestContract) require.NoError(t, err) checksum, err := vm.StoreCode(wasm) @@ -116,7 +117,7 @@ func TestStoreCodeAndGet(t *testing.T) { func TestRemoveCode(t *testing.T) { vm := withVM(t) - wasm, err := ioutil.ReadFile(HACKATOM_TEST_CONTRACT) + wasm, err := os.ReadFile(HackatomTestContract) require.NoError(t, err) checksum, err := vm.StoreCode(wasm) @@ -131,10 +132,10 @@ func TestRemoveCode(t *testing.T) { func TestHappyPath(t *testing.T) { vm := withVM(t) - checksum := createTestContract(t, vm, HACKATOM_TEST_CONTRACT) + checksum := createTestContract(t, vm, HackatomTestContract) deserCost := types.UFraction{Numerator: 1, Denominator: 1} - gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := api.NewMockGasMeter(TestingGasLimit) // instantiate it with this store store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() @@ -145,16 +146,16 @@ func TestHappyPath(t *testing.T) { env := api.MockEnv() info := api.MockInfo("creator", nil) msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - ires, _, err := vm.Instantiate(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err := vm.Instantiate(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 0, len(ires.Messages)) // execute - gasMeter2 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter2 := api.NewMockGasMeter(TestingGasLimit) store.SetGasMeter(gasMeter2) env = api.MockEnv() info = api.MockInfo("fred", nil) - hres, _, err := vm.Execute(checksum, env, info, []byte(`{"release":{}}`), store, *goapi, querier, gasMeter2, TESTING_GAS_LIMIT, deserCost) + hres, _, err := vm.Execute(checksum, env, info, []byte(`{"release":{}}`), store, *goapi, querier, gasMeter2, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 1, len(hres.Messages)) @@ -172,10 +173,10 @@ func TestHappyPath(t *testing.T) { func TestEnv(t *testing.T) { vm := withVM(t) - checksum := createTestContract(t, vm, CYBERPUNK_TEST_CONTRACT) + checksum := createTestContract(t, vm, CyberpunkTestContract) deserCost := types.UFraction{Numerator: 1, Denominator: 1} - gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := api.NewMockGasMeter(TestingGasLimit) // instantiate it with this store store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() @@ -185,7 +186,7 @@ func TestEnv(t *testing.T) { // instantiate env := api.MockEnv() info := api.MockInfo("creator", nil) - ires, _, err := vm.Instantiate(checksum, env, info, []byte(`{}`), store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err := vm.Instantiate(checksum, env, info, []byte(`{}`), store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 0, len(ires.Messages)) @@ -203,7 +204,7 @@ func TestEnv(t *testing.T) { } info = api.MockInfo("creator", nil) msg := []byte(`{"mirror_env": {}}`) - ires, _, err = vm.Execute(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err = vm.Execute(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) expected, _ := json.Marshal(env) require.Equal(t, expected, ires.Data) @@ -224,7 +225,7 @@ func TestEnv(t *testing.T) { } info = api.MockInfo("creator", nil) msg = []byte(`{"mirror_env": {}}`) - ires, _, err = vm.Execute(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err = vm.Execute(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) expected, _ = json.Marshal(env) require.Equal(t, expected, ires.Data) @@ -239,7 +240,7 @@ func TestGetMetrics(t *testing.T) { assert.Equal(t, &types.Metrics{}, metrics) // Create contract - checksum := createTestContract(t, vm, HACKATOM_TEST_CONTRACT) + checksum := createTestContract(t, vm, HackatomTestContract) deserCost := types.UFraction{Numerator: 1, Denominator: 1} @@ -249,7 +250,7 @@ func TestGetMetrics(t *testing.T) { assert.Equal(t, &types.Metrics{}, metrics) // Instantiate 1 - gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT) + gasMeter1 := api.NewMockGasMeter(TestingGasLimit) // instantiate it with this store store := api.NewLookup(gasMeter1) goapi := api.NewMockAPI() @@ -259,7 +260,7 @@ func TestGetMetrics(t *testing.T) { env := api.MockEnv() info := api.MockInfo("creator", nil) msg1 := []byte(`{"verifier": "fred", "beneficiary": "bob"}`) - ires, _, err := vm.Instantiate(checksum, env, info, msg1, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err := vm.Instantiate(checksum, env, info, msg1, store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 0, len(ires.Messages)) @@ -273,7 +274,7 @@ func TestGetMetrics(t *testing.T) { // Instantiate 2 msg2 := []byte(`{"verifier": "fred", "beneficiary": "susi"}`) - ires, _, err = vm.Instantiate(checksum, env, info, msg2, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err = vm.Instantiate(checksum, env, info, msg2, store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 0, len(ires.Messages)) @@ -301,7 +302,7 @@ func TestGetMetrics(t *testing.T) { // Instantiate 3 msg3 := []byte(`{"verifier": "fred", "beneficiary": "bert"}`) - ires, _, err = vm.Instantiate(checksum, env, info, msg3, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err = vm.Instantiate(checksum, env, info, msg3, store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 0, len(ires.Messages)) @@ -333,7 +334,7 @@ func TestGetMetrics(t *testing.T) { // Instantiate 4 msg4 := []byte(`{"verifier": "fred", "beneficiary": "jeff"}`) - ires, _, err = vm.Instantiate(checksum, env, info, msg4, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost) + ires, _, err = vm.Instantiate(checksum, env, info, msg4, store, *goapi, querier, gasMeter1, TestingGasLimit, deserCost) require.NoError(t, err) require.Equal(t, 0, len(ires.Messages)) diff --git a/types/msg.go b/types/msg.go index b655872e3..d4bf0765d 100644 --- a/types/msg.go +++ b/types/msg.go @@ -144,7 +144,7 @@ type GovMsg struct { type voteOption int type VoteMsg struct { - ProposalId uint64 `json:"proposal_id"` + ProposalID uint64 `json:"proposal_id"` // Vote is the vote option. // // This should be called "option" for consistency with Cosmos SDK. Sorry for that. @@ -153,7 +153,7 @@ type VoteMsg struct { } type VoteWeightedMsg struct { - ProposalId uint64 `json:"proposal_id"` + ProposalID uint64 `json:"proposal_id"` Options []WeightedVoteOption `json:"options"` } @@ -189,7 +189,7 @@ func (v voteOption) String() string { return fromVoteOption[v] } -func (v voteOption) MarshalJSON() ([]byte, error) { //nolint:stylecheck +func (v voteOption) MarshalJSON() ([]byte, error) { return json.Marshal(v.String()) } diff --git a/types/msg_test.go b/types/msg_test.go index 1dc89abe1..30624687a 100644 --- a/types/msg_test.go +++ b/types/msg_test.go @@ -86,7 +86,7 @@ func TestGovMsgVoteSerialization(t *testing.T) { require.Nil(t, msg.VoteWeighted) require.NotNil(t, msg.Vote) - require.Equal(t, uint64(4), msg.Vote.ProposalId) + require.Equal(t, uint64(4), msg.Vote.ProposalID) require.Equal(t, NoWithVeto, msg.Vote.Vote) } @@ -100,7 +100,7 @@ func TestGovMsgVoteWeightedSerialization(t *testing.T) { require.Nil(t, msg.Vote) require.NotNil(t, msg.VoteWeighted) - require.Equal(t, uint64(25), msg.VoteWeighted.ProposalId) + require.Equal(t, uint64(25), msg.VoteWeighted.ProposalID) require.Equal(t, []WeightedVoteOption{ {Yes, "0.25"}, {No, "0.25"}, diff --git a/types/submessages.go b/types/submessages.go index f808c35d1..806b37972 100644 --- a/types/submessages.go +++ b/types/submessages.go @@ -33,7 +33,7 @@ func (r replyOn) String() string { return fromReplyOn[r] } -func (s replyOn) MarshalJSON() ([]byte, error) { //nolint:revive,stylecheck +func (s replyOn) MarshalJSON() ([]byte, error) { //nolint:revive return json.Marshal(s.String()) } From cc4e2752512c8a7f4409bdd83d9a4b020719da00 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sat, 21 Dec 2024 02:40:31 +0700 Subject: [PATCH 23/24] lint --- .golangci.yml | 9 +++++++-- go.mod | 2 +- ibc_test.go | 5 ++--- internal/api/api_test.go | 3 +-- internal/api/iterator.go | 2 +- internal/api/iterator_test.go | 5 ++--- internal/api/lib.go | 13 ++++++------- internal/api/lib_test.go | 25 ++++++++++++------------- internal/api/mocks.go | 13 +++++++------ lib.go | 6 +++--- lib_libwasmvm.go | 2 +- lib_libwasmvm_test.go | 5 ++--- lib_test.go | 3 +-- types/msg.go | 2 -- 14 files changed, 46 insertions(+), 49 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 449da08bb..f5735c4fe 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,17 +10,19 @@ linters: - dogsled - errcheck - exportloopref + - gci - goconst - - gocritic + # - gocritic - gofumpt - gosec - gosimple - govet - ineffassign + - maintidx - misspell - nakedret - nolintlint - - revive + # - revive - staticcheck - stylecheck - typecheck @@ -80,6 +82,9 @@ issues: max-same-issues: 10000 linters-settings: + revive: + disable: + - var-naming dogsled: max-blank-identifiers: 3 maligned: diff --git a/go.mod b/go.mod index b8a003356..16083455d 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/CosmWasm/wasmvm/v2 -go 1.21 +go 1.23 require ( github.com/google/btree v1.0.0 diff --git a/ibc_test.go b/ibc_test.go index 18cb09bd7..c6b542c21 100644 --- a/ibc_test.go +++ b/ibc_test.go @@ -7,11 +7,10 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/CosmWasm/wasmvm/v2/internal/api" "github.com/CosmWasm/wasmvm/v2/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const IBCTestContract = "./testdata/ibc_reflect.wasm" diff --git a/internal/api/api_test.go b/internal/api/api_test.go index b9bb3e8dd..ff1d95f64 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -5,9 +5,8 @@ import ( "os" "testing" - "github.com/stretchr/testify/require" - "github.com/CosmWasm/wasmvm/v2/types" + "github.com/stretchr/testify/require" ) func TestValidateAddressFailure(t *testing.T) { diff --git a/internal/api/iterator.go b/internal/api/iterator.go index 2f997e707..4ba47e792 100644 --- a/internal/api/iterator.go +++ b/internal/api/iterator.go @@ -65,7 +65,7 @@ func storeIterator(callID uint64, it types.Iterator, frameLenLimit int) (uint64, new_index := len(iteratorFrames[callID]) if new_index >= frameLenLimit { - return 0, fmt.Errorf("Reached iterator limit (%d)", frameLenLimit) + return 0, fmt.Errorf("reached iterator limit (%d)", frameLenLimit) } // store at array position `new_index` diff --git a/internal/api/iterator_test.go b/internal/api/iterator_test.go index ef9070975..31ad6b705 100644 --- a/internal/api/iterator_test.go +++ b/internal/api/iterator_test.go @@ -6,11 +6,10 @@ import ( "sync" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/CosmWasm/wasmvm/v2/internal/api/testdb" "github.com/CosmWasm/wasmvm/v2/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type queueData struct { diff --git a/internal/api/lib.go b/internal/api/lib.go index 2e1bc3cf2..a454af2f8 100644 --- a/internal/api/lib.go +++ b/internal/api/lib.go @@ -13,9 +13,8 @@ import ( "strings" "syscall" - "golang.org/x/sys/unix" - "github.com/CosmWasm/wasmvm/v2/types" + "golang.org/x/sys/unix" ) // Value types @@ -45,26 +44,26 @@ func InitCache(config types.VMConfig) (Cache, error) { // libwasmvm would create this directory too but we need it earlier for the lockfile err := os.MkdirAll(config.Cache.BaseDir, 0o755) if err != nil { - return Cache{}, fmt.Errorf("Could not create base directory") + return Cache{}, fmt.Errorf("could not create base directory") } lockfile, err := os.OpenFile(filepath.Join(config.Cache.BaseDir, "exclusive.lock"), os.O_WRONLY|os.O_CREATE, 0o666) if err != nil { - return Cache{}, fmt.Errorf("Could not open exclusive.lock") + return Cache{}, fmt.Errorf("could not open exclusive.lock") } _, err = lockfile.WriteString("This is a lockfile that prevent two VM instances to operate on the same directory in parallel.\nSee codebase at github.com/CosmWasm/wasmvm for more information.\nSafety first – brought to you by Confio ❤️\n") if err != nil { - return Cache{}, fmt.Errorf("Error writing to exclusive.lock") + return Cache{}, fmt.Errorf("error writing to exclusive.lock") } err = unix.Flock(int(lockfile.Fd()), unix.LOCK_EX|unix.LOCK_NB) if err != nil { - return Cache{}, fmt.Errorf("Could not lock exclusive.lock. Is a different VM running in the same directory already?") + return Cache{}, fmt.Errorf("could not lock exclusive.lock. is a different VM running in the same directory already?") } configBytes, err := json.Marshal(config) if err != nil { - return Cache{}, fmt.Errorf("Could not serialize config") + return Cache{}, fmt.Errorf("could not serialize config") } configView := makeView(configBytes) defer runtime.KeepAlive(configBytes) diff --git a/internal/api/lib_test.go b/internal/api/lib_test.go index ab1531e3d..eae45e310 100644 --- a/internal/api/lib_test.go +++ b/internal/api/lib_test.go @@ -13,10 +13,9 @@ import ( "testing" "time" + "github.com/CosmWasm/wasmvm/v2/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/CosmWasm/wasmvm/v2/types" ) const ( @@ -501,9 +500,9 @@ func TestGetPinnedMetrics(t *testing.T) { findMetrics := func(list []types.PerModuleEntry, checksum types.Checksum) *types.PerModuleMetrics { found := (*types.PerModuleMetrics)(nil) - for _, structure := range list { - if bytes.Equal(structure.Checksum, checksum) { - found = &structure.Metrics + for i := range list { + if bytes.Equal(list[i].Checksum, checksum) { + found = &list[i].Metrics break } } @@ -1156,7 +1155,7 @@ func TestReplyAndQuery(t *testing.T) { require.Equal(t, events, val.Events) } -func requireOkResponse(t testing.TB, res []byte, expectedMsgs int) { +func requireOkResponse(t testing.TB, res []byte, expectedMsgs int) { //nolint:unparam // expectedMsgs always receives 0 but that could change var result types.ContractResult err := json.Unmarshal(res, &result) require.NoError(t, err) @@ -1361,17 +1360,17 @@ func TestFloats(t *testing.T) { // helper to print the value in the same format as Rust's Debug trait debugStr := func(value Value) string { - if value.U32 != nil { + switch { + case value.U32 != nil: return fmt.Sprintf("U32(%d)", *value.U32) - } else if value.U64 != nil { + case value.U64 != nil: return fmt.Sprintf("U64(%d)", *value.U64) - } else if value.F32 != nil { + case value.F32 != nil: return fmt.Sprintf("F32(%d)", *value.F32) - } else if value.F64 != nil { + case value.F64 != nil: return fmt.Sprintf("F64(%d)", *value.F64) - } else { - t.FailNow() - return "" + default: + return "None" } } diff --git a/internal/api/mocks.go b/internal/api/mocks.go index d2f5e20ea..01ce06be2 100644 --- a/internal/api/mocks.go +++ b/internal/api/mocks.go @@ -8,11 +8,10 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/CosmWasm/wasmvm/v2/internal/api/testdb" "github.com/CosmWasm/wasmvm/v2/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) /** helper constructors **/ @@ -392,8 +391,8 @@ func NewMockAPI() *types.GoAPI { } } -func TestMockApi(t *testing.T) { - human := Foobar +func TestMockAPI(t *testing.T) { + human := "Foobar" canon, cost, err := MockCanonicalizeAddress(human) require.NoError(t, err) assert.Equal(t, CanonicalLength, len(canon)) @@ -428,7 +427,9 @@ func DefaultQuerier(contractAddr string, coins types.Array[types.Coin]) types.Qu } } -func (q *MockQuerier) Query(request types.QueryRequest, _gasLimit uint64) ([]byte, error) { +// Query is a mock implementation of the Querier interface. It takes a request and a gas limit. +// It returns the marshaled request and an error if the request is not supported. +func (q *MockQuerier) Query(request types.QueryRequest, _ uint64) ([]byte, error) { marshaled, err := json.Marshal(request) if err != nil { return nil, err diff --git a/lib.go b/lib.go index 458af0740..cb18a4c61 100644 --- a/lib.go +++ b/lib.go @@ -44,15 +44,15 @@ func LibwasmvmVersion() (string, error) { // to avoid accidental misusage. func CreateChecksum(wasm []byte) (Checksum, error) { if len(wasm) == 0 { - return Checksum{}, fmt.Errorf("Wasm bytes nil or empty") + return Checksum{}, fmt.Errorf("wasm bytes nil or empty") } if len(wasm) < 4 { - return Checksum{}, fmt.Errorf("Wasm bytes shorter than 4 bytes") + return Checksum{}, fmt.Errorf("wasm bytes shorter than 4 bytes") } // magic number for Wasm is "\0asm" // See https://webassembly.github.io/spec/core/binary/modules.html#binary-module if !bytes.Equal(wasm[:4], []byte("\x00\x61\x73\x6D")) { - return Checksum{}, fmt.Errorf("Wasm bytes do not start with Wasm magic number") + return Checksum{}, fmt.Errorf("wasm bytes do not start with wasm magic number") } hash := sha256.Sum256(wasm) return Checksum(hash[:]), nil diff --git a/lib_libwasmvm.go b/lib_libwasmvm.go index 3f66b71ea..66a687500 100644 --- a/lib_libwasmvm.go +++ b/lib_libwasmvm.go @@ -703,7 +703,7 @@ var ( func DeserializeResponse(gasLimit uint64, deserCost types.UFraction, gasReport *types.GasReport, data []byte, response any) error { gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor() if gasLimit < gasForDeserialization+gasReport.UsedInternally { - return fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) + return fmt.Errorf("insufficient gas left to deserialize contract execution result (%d bytes)", len(data)) } gasReport.UsedInternally += gasForDeserialization gasReport.Remaining -= gasForDeserialization diff --git a/lib_libwasmvm_test.go b/lib_libwasmvm_test.go index 7b6f3fb32..f54ca2913 100644 --- a/lib_libwasmvm_test.go +++ b/lib_libwasmvm_test.go @@ -9,11 +9,10 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/CosmWasm/wasmvm/v2/internal/api" "github.com/CosmWasm/wasmvm/v2/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( diff --git a/lib_test.go b/lib_test.go index 35094e7df..54b2d3293 100644 --- a/lib_test.go +++ b/lib_test.go @@ -3,9 +3,8 @@ package cosmwasm import ( "testing" - "github.com/stretchr/testify/require" - "github.com/CosmWasm/wasmvm/v2/types" + "github.com/stretchr/testify/require" ) func TestCreateChecksum(t *testing.T) { diff --git a/types/msg.go b/types/msg.go index 696894e8f..369a3616b 100644 --- a/types/msg.go +++ b/types/msg.go @@ -5,8 +5,6 @@ import ( "fmt" ) -var null = "null" - //------- Results / Msgs ------------- // ContractResult is the raw response from the instantiate/execute/migrate calls. From dbb50a38b2d59c369ad437897f69cd0940efdd83 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sat, 21 Dec 2024 03:28:53 +0700 Subject: [PATCH 24/24] continue linting --- .github/workflows/golangci.yml | 2 +- .golangci.yml | 60 +++++++--------------------------- internal/api/callbacks.go | 2 +- internal/api/iterator_test.go | 7 ++-- internal/api/lib_test.go | 8 +++-- internal/api/memory_test.go | 25 ++++++++++---- lib_libwasmvm_test.go | 6 ++-- lib_test.go | 2 +- types/msg.go | 6 ++-- types/msg_test.go | 2 +- types/submessages.go | 4 +-- 11 files changed, 52 insertions(+), 72 deletions(-) diff --git a/.github/workflows/golangci.yml b/.github/workflows/golangci.yml index b8ddf70a1..a51dd836b 100644 --- a/.github/workflows/golangci.yml +++ b/.github/workflows/golangci.yml @@ -18,7 +18,7 @@ jobs: steps: - uses: actions/setup-go@v3 with: - go-version: 1.19 # check with 1.19 because it matches dev envs. Does not need to affect go.mod. + go-version: 1.23 # check with 1.19 because it matches dev envs. Does not need to affect go.mod. - uses: actions/checkout@v3 - name: golangci-lint uses: golangci/golangci-lint-action@v3 diff --git a/.golangci.yml b/.golangci.yml index f5735c4fe..e6381dbc2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -9,10 +9,9 @@ linters: - copyloopvar - dogsled - errcheck - - exportloopref - gci - goconst - # - gocritic + - gocritic - gofumpt - gosec - gosimple @@ -24,7 +23,7 @@ linters: - nolintlint # - revive - staticcheck - - stylecheck + # - stylecheck - typecheck - unconvert - unparam @@ -34,57 +33,20 @@ linters: # TODO: fix the use of deprecated gov style issues: - exclude-rules: - - text: "SA1019: sdkerrors.Register" - linters: - - staticcheck - - text: "sdkerrors.ABCIInfo is deprecated" - linters: - - staticcheck - - text: "sdkerrors.IsOf is deprecated" - linters: - - staticcheck - - text: "Use WeightedProposalMsg instead" - linters: - - staticcheck - - text: "Use MsgSimulatorFn instead" - linters: - - staticcheck - - text: "Error return value of `flagSet.Set` is not checked" - linters: - - errcheck - - text: "SA1019: sdkerrors.Wrapf is deprecated: functionality of this package has been moved to it's own module" - linters: - - staticcheck - - text: "sdkerrors.Error is deprecated: the type has been moved to cosmossdk.io/errors module" - linters: - - staticcheck - - text: "sdkerrors.Wrap is deprecated" - linters: - - staticcheck - - text: "Use of weak random number generator" - linters: - - gosec - - text: "ST1003:" - linters: - - stylecheck - # FIXME: Disabled until golangci-lint updates stylecheck with this fix: - # https://github.com/dominikh/go-tools/issues/389 - - text: "ST1016:" - linters: - - stylecheck - - path: "migrations" - text: "SA1019:" - linters: - - staticcheck - max-issues-per-linter: 10000 max-same-issues: 10000 linters-settings: revive: - disable: - - var-naming + rules: + - name: var-naming + severity: warning + disabled: false + exclude: [""] + arguments: + - ["ID"] # AllowList + - ["VM"] # DenyList + - - upperCaseConst: true # Extra parameter (upperCaseConst|skipPackageNameChecks) dogsled: max-blank-identifiers: 3 maligned: diff --git a/internal/api/callbacks.go b/internal/api/callbacks.go index 908055be8..1fe276547 100644 --- a/internal/api/callbacks.go +++ b/internal/api/callbacks.go @@ -440,7 +440,7 @@ func cValidateAddress(ptr *C.api_t, src C.U8SliceView, errOut *C.UnmanagedVector if errOut == nil { return C.GoError_BadArgument } - if !(*errOut).is_none { + if !errOut.is_none { panic("Got a non-none UnmanagedVector we're about to override. This is a bug because someone has to drop the old one.") } diff --git a/internal/api/iterator_test.go b/internal/api/iterator_test.go index 31ad6b705..53e254317 100644 --- a/internal/api/iterator_test.go +++ b/internal/api/iterator_test.go @@ -115,7 +115,7 @@ func TestStoreIteratorHitsLimit(t *testing.T) { iter, _ = store.Iterator(nil, nil) _, err = storeIterator(callID, iter, limit) - require.ErrorContains(t, err, "Reached iterator limit (2)") + require.ErrorContains(t, err, "reached iterator limit (2)") endCall(callID) } @@ -216,6 +216,9 @@ func TestQueueIteratorRaces(t *testing.T) { env := MockEnvBin(t) reduceQuery := func(t *testing.T, setup queueData, expected string) { + callID := startCall() + defer endCall(callID) + checksum, querier, api := setup.checksum, setup.querier, setup.api gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) igasMeter := types.GasMeter(gasMeter) @@ -291,5 +294,5 @@ func TestQueueIteratorLimit(t *testing.T) { query = []byte(`{"open_iterators":{"count":35000}}`) env = MockEnvBin(t) _, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TESTING_PRINT_DEBUG) - require.ErrorContains(t, err, "Reached iterator limit (32768)") + require.ErrorContains(t, err, "reached iterator limit (32768)") } diff --git a/internal/api/lib_test.go b/internal/api/lib_test.go index eae45e310..62fabbc74 100644 --- a/internal/api/lib_test.go +++ b/internal/api/lib_test.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "math" "os" "path/filepath" "strings" @@ -80,7 +81,7 @@ func TestInitCacheErrorsForBrokenDir(t *testing.T) { }, } _, err := InitCache(config) - require.ErrorContains(t, err, "Could not create base directory") + require.ErrorContains(t, err, "could not create base directory") } func TestInitLockingPreventsConcurrentAccess(t *testing.T) { @@ -108,7 +109,7 @@ func TestInitLockingPreventsConcurrentAccess(t *testing.T) { }, } _, err2 := InitCache(config2) - require.ErrorContains(t, err2, "Could not lock exclusive.lock") + require.ErrorContains(t, err2, "could not lock exclusive.lock") ReleaseCache(cache1) @@ -777,6 +778,9 @@ func TestExecuteStorageLoop(t *testing.T) { // the "sdk gas" * GasMultiplier + the wasm cost should equal the maxGas (or be very close) totalCost := gasReport.UsedInternally + gasMeter2.GasConsumed() + if totalCost > math.MaxInt64 { + t.Fatal("gas cost overflow") + } require.Equal(t, int64(maxGas), int64(totalCost)) } diff --git a/internal/api/memory_test.go b/internal/api/memory_test.go index e6ca02ebe..892a6f37e 100644 --- a/internal/api/memory_test.go +++ b/internal/api/memory_test.go @@ -1,6 +1,7 @@ package api import ( + "math" "testing" "unsafe" @@ -11,7 +12,9 @@ func TestMakeView(t *testing.T) { data := []byte{0xaa, 0xbb, 0x64} dataView := makeView(data) require.Equal(t, cbool(false), dataView.is_nil) - require.Equal(t, cusize(3), dataView.len) + length := int(dataView.len) + require.Less(t, length, math.MaxInt) + require.Equal(t, 3, length) empty := []byte{} emptyView := makeView(empty) @@ -28,8 +31,12 @@ func TestCreateAndDestroyUnmanagedVector(t *testing.T) { original := []byte{0xaa, 0xbb, 0x64} unmanaged := newUnmanagedVector(original) require.Equal(t, cbool(false), unmanaged.is_none) - require.Equal(t, 3, int(unmanaged.len)) - require.GreaterOrEqual(t, 3, int(unmanaged.cap)) // Rust implementation decides this + length := int(unmanaged.len) + require.Less(t, length, math.MaxInt) + require.Equal(t, 3, length) + cap := int(unmanaged.cap) + require.Less(t, cap, math.MaxInt) + require.GreaterOrEqual(t, cap, 3) // Rust implementation decides this copy := copyAndDestroyUnmanagedVector(unmanaged) require.Equal(t, original, copy) } @@ -39,8 +46,12 @@ func TestCreateAndDestroyUnmanagedVector(t *testing.T) { original := []byte{} unmanaged := newUnmanagedVector(original) require.Equal(t, cbool(false), unmanaged.is_none) - require.Equal(t, 0, int(unmanaged.len)) - require.GreaterOrEqual(t, 0, int(unmanaged.cap)) // Rust implementation decides this + length := int(unmanaged.len) + require.Less(t, length, math.MaxInt) + require.Equal(t, 0, length) + cap := int(unmanaged.cap) + require.Less(t, cap, math.MaxInt) + require.GreaterOrEqual(t, cap, 0) // Rust implementation decides this copy := copyAndDestroyUnmanagedVector(unmanaged) require.Equal(t, original, copy) } @@ -63,14 +74,14 @@ func TestCreateAndDestroyUnmanagedVector(t *testing.T) { func TestCopyDestroyUnmanagedVector(t *testing.T) { { // ptr, cap and len broken. Do not access those values when is_none is true - invalidPtr := unsafe.Pointer(uintptr(42)) //nolint:unsafeptr + invalidPtr := unsafe.Pointer(uintptr(42)) uv := constructUnmanagedVector(cbool(true), cu8_ptr(invalidPtr), cusize(0xBB), cusize(0xAA)) copy := copyAndDestroyUnmanagedVector(uv) require.Nil(t, copy) } { // Capacity is 0, so no allocation happened. Do not access the pointer. - invalidPtr := unsafe.Pointer(uintptr(42)) //nolint:unsafeptr + invalidPtr := unsafe.Pointer(uintptr(42)) uv := constructUnmanagedVector(cbool(false), cu8_ptr(invalidPtr), cusize(0), cusize(0)) copy := copyAndDestroyUnmanagedVector(uv) require.Equal(t, []byte{}, copy) diff --git a/lib_libwasmvm_test.go b/lib_libwasmvm_test.go index f54ca2913..83be94e10 100644 --- a/lib_libwasmvm_test.go +++ b/lib_libwasmvm_test.go @@ -76,21 +76,21 @@ func TestStoreCode(t *testing.T) { wasm := []byte{0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00} _, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT) - require.ErrorContains(t, err, "Error during static Wasm validation: Wasm contract must contain exactly one memory") + require.ErrorContains(t, err, "Error calling the VM: Error during static Wasm validation: Wasm contract must contain exactly one memory") } // No Wasm { wasm := []byte("foobar") _, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT) - require.ErrorContains(t, err, "Wasm bytecode could not be deserialized") + require.ErrorContains(t, err, "bytecode could not be deserialized") } // Empty { wasm := []byte("") _, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT) - require.ErrorContains(t, err, "Wasm bytecode could not be deserialized") + require.ErrorContains(t, err, "bytecode could not be deserialized") } // Nil diff --git a/lib_test.go b/lib_test.go index 54b2d3293..c2d40c8e8 100644 --- a/lib_test.go +++ b/lib_test.go @@ -28,5 +28,5 @@ func TestCreateChecksum(t *testing.T) { // Text file fails _, err = CreateChecksum([]byte("Hello world")) - require.ErrorContains(t, err, "do not start with Wasm magic number") + require.ErrorContains(t, err, "do not start with wasm magic number") } diff --git a/types/msg.go b/types/msg.go index 369a3616b..4998c4590 100644 --- a/types/msg.go +++ b/types/msg.go @@ -139,7 +139,7 @@ type GovMsg struct { type voteOption int type VoteMsg struct { - ProposalId uint64 `json:"proposal_id"` + ProposalID uint64 `json:"proposal_id"` // Option is the vote option. // // This used to be called "vote", but was changed for consistency with Cosmos SDK. @@ -150,7 +150,7 @@ type VoteMsg struct { func (m *VoteMsg) UnmarshalJSON(data []byte) error { // We need a custom unmarshaler to parse both the "stargate" and "any" variants type InternalVoteMsg struct { - ProposalId uint64 `json:"proposal_id"` + ProposalID uint64 `json:"proposal_id"` Option *voteOption `json:"option"` Vote *voteOption `json:"vote"` // old version } @@ -168,7 +168,7 @@ func (m *VoteMsg) UnmarshalJSON(data []byte) error { } *m = VoteMsg{ - ProposalId: tmp.ProposalId, + ProposalID: tmp.ProposalID, Option: *tmp.Option, } return nil diff --git a/types/msg_test.go b/types/msg_test.go index caf2d4538..d26d63c3d 100644 --- a/types/msg_test.go +++ b/types/msg_test.go @@ -123,7 +123,7 @@ func TestGovMsgVoteSerialization(t *testing.T) { require.Nil(t, msg.VoteWeighted) require.NotNil(t, msg.Vote) - require.Equal(t, uint64(4), msg.Vote.ProposalId) + require.Equal(t, uint64(4), msg.Vote.ProposalID) require.Equal(t, NoWithVeto, msg.Vote.Option) newDocument := []byte(`{"vote":{"proposal_id":4,"option":"no_with_veto"}}`) diff --git a/types/submessages.go b/types/submessages.go index f258b7448..d7d58c075 100644 --- a/types/submessages.go +++ b/types/submessages.go @@ -29,8 +29,8 @@ var toReplyOn = map[string]replyOn{ "never": ReplyNever, } -func (r replyOn) String() string { - return fromReplyOn[r] +func (s replyOn) String() string { + return fromReplyOn[s] } func (s replyOn) MarshalJSON() ([]byte, error) { //nolint:revive