From 059268e29b6240fbdec1ccb7f353bb0c35efa849 Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Tue, 29 Nov 2022 10:22:36 +0000 Subject: [PATCH] fix(wasmer): `ext_storage_exists_version_1` for empty values (#2973) - If the value is `[]byte{}`, the key exists (leaf node, branch with value) - If the value is `[]byte(nil)`, the key does not exist (node not found or branch without value) - Change unit test to be cases-based and add case --- lib/runtime/wasmer/imports.go | 4 +-- lib/runtime/wasmer/imports_test.go | 55 ++++++++++++++++++++++-------- 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/lib/runtime/wasmer/imports.go b/lib/runtime/wasmer/imports.go index c09dc92f84..b4eddac10a 100644 --- a/lib/runtime/wasmer/imports.go +++ b/lib/runtime/wasmer/imports.go @@ -1910,8 +1910,8 @@ func ext_storage_exists_version_1(context unsafe.Pointer, keySpan C.int64_t) C.i key := asMemorySlice(instanceContext, keySpan) logger.Debugf("key: 0x%x", key) - val := storage.Get(key) - if len(val) > 0 { + value := storage.Get(key) + if value != nil { return 1 } diff --git a/lib/runtime/wasmer/imports_test.go b/lib/runtime/wasmer/imports_test.go index e993fe6715..12f84c4819 100644 --- a/lib/runtime/wasmer/imports_test.go +++ b/lib/runtime/wasmer/imports_test.go @@ -509,26 +509,51 @@ func Test_ext_storage_get_version_1(t *testing.T) { func Test_ext_storage_exists_version_1(t *testing.T) { t.Parallel() - inst := NewTestInstance(t, runtime.HOST_API_TEST_RUNTIME) - testkey := []byte("noot") - testvalue := []byte{1, 2} - inst.ctx.Storage.Set(testkey, testvalue) + testCases := map[string]struct { + key []byte + value []byte // leave to nil to not insert pair + result byte + }{ + "value does not exist": { + key: []byte{1}, + result: 0, + }, + "empty value exists": { + key: []byte{1}, + value: []byte{}, + result: 1, + }, + "value exist": { + key: []byte{1}, + value: []byte{2}, + result: 1, + }, + } - enc, err := scale.Marshal(testkey) - require.NoError(t, err) + for name, testCase := range testCases { + testCase := testCase + t.Run(name, func(t *testing.T) { + t.Parallel() + instance := NewTestInstance(t, runtime.HOST_API_TEST_RUNTIME) - ret, err := inst.Exec("rtm_ext_storage_exists_version_1", enc) - require.NoError(t, err) - require.Equal(t, byte(1), ret[0]) + if testCase.value != nil { + instance.ctx.Storage.Set(testCase.key, testCase.value) + } - nonexistent := []byte("none") - enc, err = scale.Marshal(nonexistent) - require.NoError(t, err) + encodedKey, err := scale.Marshal(testCase.key) + require.NoError(t, err) - ret, err = inst.Exec("rtm_ext_storage_exists_version_1", enc) - require.NoError(t, err) - require.Equal(t, byte(0), ret[0]) + encodedResult, err := instance.Exec("rtm_ext_storage_exists_version_1", encodedKey) + require.NoError(t, err) + + var result byte + err = scale.Unmarshal(encodedResult, &result) + require.NoError(t, err) + + assert.Equal(t, testCase.result, result) + }) + } } func Test_ext_storage_next_key_version_1(t *testing.T) {