Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Table Driven tests V2 #596

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ build-go:
.PHONY: test
test:
# Use package list mode to include all subdirectores. The -count=1 turns off caching.
RUST_BACKTRACE=1 go test -v -count=1 ./...
CGO_ENABLED=1 RUST_BACKTRACE=1 go test -v -count=1 ./...

.PHONY: test-safety
test-safety:
Expand Down
305 changes: 305 additions & 0 deletions ibc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package cosmwasm
import (
"encoding/json"
"os"
"runtime"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -358,3 +359,307 @@ func TestIBCMsgGetCounterVersion(t *testing.T) {
_, ok = msg4.GetCounterVersion()
require.False(t, ok)
}

// (Original tests such as TestIBC, TestIBCHandshake, etc. remain unchanged.)
// … [Original tests omitted for brevity] …

// -----------------------------------------------------------------------------
// Memory Leak Test Helpers
// -----------------------------------------------------------------------------

// measureMemoryLeak runs the passed function 'f' for 'iterations' times,
// forcing garbage collection before and after and then logging the average
// increase in Allocated memory per iteration. If the average exceeds a given
// threshold (in bytes), the test will fail.
func measureMemoryLeak(t *testing.T, iterations int, testName string, f func()) {
t.Helper()
// Run one round to “warm up” (optional)
f()

runtime.GC()
var mBefore, mAfter runtime.MemStats
runtime.ReadMemStats(&mBefore)

for i := 0; i < iterations; i++ {
f()
}

runtime.GC()
runtime.ReadMemStats(&mAfter)

// Calculate the average difference in allocated bytes per iteration.
diff := mAfter.Alloc - mBefore.Alloc
avg := diff / uint64(iterations)
t.Logf("%s: %d iterations, total alloc diff: %d bytes, average diff: %d bytes/iter", testName, iterations, diff, avg)

// Optionally assert that the average increase is below a threshold.
// (Adjust maxAvgAllocBytes as needed; here we set an example threshold of 2KB.)
const maxAvgAllocBytes = 2048
if avg > maxAvgAllocBytes {
t.Errorf("%s: memory leak suspected, average allocation per iteration %d bytes exceeds threshold (%d bytes)",
testName, avg, maxAvgAllocBytes)
}
}

// -----------------------------------------------------------------------------
// Helpers to run complete IBC transactions in one “iteration”
// -----------------------------------------------------------------------------

// runStoreAndGetCode performs a store code and retrieval transaction.
func runStoreAndGetCode(t *testing.T, wasmPath string) {
t.Helper()
vm := withVM(t)
wasm, err := os.ReadFile(wasmPath)
require.NoError(t, err)

checksum, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT)
require.NoError(t, err)

code, err := vm.GetCode(checksum)
require.NoError(t, err)
require.Equal(t, WasmCode(wasm), code)
}

// runIBCHandshake performs the full handshake (instantiate, channel open, connect, reply)
// sequence. Note that we use hard-coded values here (e.g. IBC_VERSION) as in the original test.
func runIBCHandshake(t *testing.T, wasmPath string, reflectID uint64, channelID string) {
t.Helper()
vm := withVM(t)

_, err := os.ReadFile(wasmPath)
require.NoError(t, err)

// Store the contract code.
checksum := createTestContract(t, vm, IBC_TEST_CONTRACT)

gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
deserCost := types.UFraction{Numerator: 1, Denominator: 1}
store := api.NewLookup(gasMeter1)
goapi := api.NewMockAPI()
balance := types.Array[types.Coin]{}
querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance)

// Instantiate the contract.
env := api.MockEnv()
info := api.MockInfo("creator", nil)
initMsg := IBCInstantiateMsg{ReflectCodeID: reflectID}
i, _, err := vm.Instantiate(checksum, env, info, toBytes(t, initMsg), store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)

// Channel open.
gasMeter2 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeter2)
env = api.MockEnv()
openMsg := api.MockIBCChannelOpenInit(channelID, types.Ordered, IBC_VERSION)
o, _, err := vm.IBCChannelOpen(checksum, env, openMsg, store, *goapi, querier, gasMeter2, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, o.Ok)
require.Equal(t, &types.IBC3ChannelOpenResponse{Version: IBC_VERSION}, o.Ok)

// Channel connect.
gasMeter3 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeter3)
env = api.MockEnv()
connectMsg := api.MockIBCChannelConnectAck(channelID, types.Ordered, IBC_VERSION)
conn, _, err := vm.IBCChannelConnect(checksum, env, connectMsg, store, *goapi, querier, gasMeter3, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, conn.Ok)
require.Len(t, conn.Ok.Messages, 1)

// Simulate reply for the reflect init callback.
gasMeter4 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeter4)
reply := types.Reply{
ID: conn.Ok.Messages[0].ID,
Result: types.SubMsgResult{
Ok: &types.SubMsgResponse{
Events: types.Array[types.Event]{
{
Type: "instantiate",
Attributes: types.Array[types.EventAttribute]{
{Key: "_contract_address", Value: "dummy-address"},
},
},
},
Data: nil,
},
},
}
_, _, err = vm.Reply(checksum, env, reply, store, *goapi, querier, gasMeter4, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
}

// runIBCPacketDispatch performs the full packet dispatch transaction
// (including instantiation, handshake, reply, query, and IBC packet receive).
func runIBCPacketDispatch(t *testing.T, wasmPath string, reflectID uint64, channelID string, reflectAddr string) {
t.Helper()
vm := withVM(t)

_, err := os.ReadFile(wasmPath)
require.NoError(t, err)

// Store the contract code.
checksum := createTestContract(t, vm, IBC_TEST_CONTRACT)

gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
deserCost := types.UFraction{Numerator: 1, Denominator: 1}
store := api.NewLookup(gasMeter1)
goapi := api.NewMockAPI()
balance := types.Array[types.Coin]{}
querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance)

// Instantiate the contract.
env := api.MockEnv()
info := api.MockInfo("creator", nil)
initMsg := IBCInstantiateMsg{ReflectCodeID: reflectID}
_, _, err = vm.Instantiate(checksum, env, info, toBytes(t, initMsg), store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)

// Channel open.
gasMeter2 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeter2)
openMsg := api.MockIBCChannelOpenInit(channelID, types.Ordered, IBC_VERSION)
o, _, err := vm.IBCChannelOpen(checksum, env, openMsg, store, *goapi, querier, gasMeter2, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, o.Ok)

// Channel connect.
gasMeter3 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeter3)
connectMsg := api.MockIBCChannelConnectAck(channelID, types.Ordered, IBC_VERSION)
conn, _, err := vm.IBCChannelConnect(checksum, env, connectMsg, store, *goapi, querier, gasMeter3, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, conn.Ok)
require.Len(t, conn.Ok.Messages, 1)
id := conn.Ok.Messages[0].ID

// Simulate reply for the reflect init callback.
gasMeter4 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeter4)
reply := types.Reply{
ID: id,
Result: types.SubMsgResult{
Ok: &types.SubMsgResponse{
Events: types.Array[types.Event]{
{
Type: "instantiate",
Attributes: types.Array[types.EventAttribute]{
{Key: "_contract_address", Value: reflectAddr},
},
},
},
Data: nil,
},
},
}
_, _, err = vm.Reply(checksum, env, reply, store, *goapi, querier, gasMeter4, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)

// Query the list of accounts.
gasMeterQuery := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeterQuery)
queryMsg := IBCQueryMsg{ListAccounts: &struct{}{}}
q, _, err := vm.Query(checksum, env, toBytes(t, queryMsg), store, *goapi, querier, gasMeterQuery, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
var accounts ListAccountsResponse
err = json.Unmarshal(q.Ok, &accounts)
require.NoError(t, err)
require.Len(t, accounts.Accounts, 1)
require.Equal(t, channelID, accounts.Accounts[0].ChannelID)
require.Equal(t, reflectAddr, accounts.Accounts[0].Account)

// Process a valid IBC packet receive.
gasMeter5 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeter5)
ibcMsg := IBCPacketMsg{
Dispatch: &DispatchMsg{
Msgs: []types.CosmosMsg{{
Bank: &types.BankMsg{Send: &types.SendMsg{
ToAddress: "my-friend",
Amount: types.Array[types.Coin]{types.NewCoin(12345678, "uatom")},
}},
}},
},
}
msg := api.MockIBCPacketReceive(channelID, toBytes(t, ibcMsg))
pr, _, err := vm.IBCPacketReceive(checksum, env, msg, store, *goapi, querier, gasMeter5, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
var ack AcknowledgeDispatch
err = json.Unmarshal(pr.Ok.Acknowledgement, &ack)
require.NoError(t, err)
require.Empty(t, ack.Err)

// Process an IBC packet receive with an invalid 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)
require.NoError(t, err)
var ack2 AcknowledgeDispatch
err = json.Unmarshal(pr2.Ok.Acknowledgement, &ack2)
require.NoError(t, err)
require.Equal(t, "invalid packet: cosmwasm_std::addresses::Addr not found", ack2.Err)
}

// -----------------------------------------------------------------------------
// Memory Leak Test Functions
// -----------------------------------------------------------------------------

// TestMemoryLeakStoreAndGetCode repeatedly runs StoreCode and GetCode
// to ensure no unexpected memory accumulation occurs.
func TestMemoryLeakStoreAndGetCode(t *testing.T) {
const iterations = 1000
measureMemoryLeak(t, iterations, "StoreAndGetCode", func() {
runStoreAndGetCode(t, IBC_TEST_CONTRACT)
})
}

// TestMemoryLeakIBCHandshake repeatedly runs the full handshake process.
func TestMemoryLeakIBCHandshake(t *testing.T) {
const iterations = 1000
const reflectID = 101
const channelID = "channel-432"
measureMemoryLeak(t, iterations, "IBCHandshake", func() {
runIBCHandshake(t, IBC_TEST_CONTRACT, reflectID, channelID)
})
}

// TestMemoryLeakIBCPacketDispatch repeatedly runs the packet dispatch process.
func TestMemoryLeakIBCPacketDispatch(t *testing.T) {
const iterations = 1000
const reflectID = 77
const channelID = "channel-234"
const reflectAddr = "reflect-acct-1"
measureMemoryLeak(t, iterations, "IBCPacketDispatch", func() {
runIBCPacketDispatch(t, IBC_TEST_CONTRACT, reflectID, channelID, reflectAddr)
})
}

// TestMemoryLeakAnalyzeCode repeatedly calls AnalyzeCode on stored contracts.
func TestMemoryLeakAnalyzeCode(t *testing.T) {
const iterations = 1000

vm := withVM(t)
// _ := types.UFraction{Numerator: 1, Denominator: 1}

// For a non-IBC contract.
wasm, err := os.ReadFile(HACKATOM_TEST_CONTRACT)
require.NoError(t, err)
checksum, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT)
require.NoError(t, err)
measureMemoryLeak(t, iterations, "AnalyzeCodeNonIBC", func() {
report, err := vm.AnalyzeCode(checksum)
require.NoError(t, err)
require.False(t, report.HasIBCEntryPoints)
})

// For an IBC contract.
wasm2, err := os.ReadFile(IBC_TEST_CONTRACT)
require.NoError(t, err)
checksum2, _, err := vm.StoreCode(wasm2, TESTING_GAS_LIMIT)
require.NoError(t, err)
measureMemoryLeak(t, iterations, "AnalyzeCodeIBC", func() {
report2, err := vm.AnalyzeCode(checksum2)
require.NoError(t, err)
require.True(t, report2.HasIBCEntryPoints)
})
}
Loading