-
Notifications
You must be signed in to change notification settings - Fork 106
/
lib_libwasmvm_test.go
447 lines (379 loc) · 13.9 KB
/
lib_libwasmvm_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//go:build cgo && !nolink_libwasmvm
package cosmwasm
import (
"encoding/json"
"fmt"
"math"
"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"
)
const (
TESTING_PRINT_DEBUG = false
TESTING_GAS_LIMIT = uint64(500_000_000_000) // ~0.5ms
TESTING_MEMORY_LIMIT = 32 // MiB
TESTING_CACHE_SIZE = 100 // MiB
)
var TESTING_CAPABILITIES = []string{"staking", "stargate", "iterator"}
const (
CYBERPUNK_TEST_CONTRACT = "./testdata/cyberpunk.wasm"
HACKATOM_TEST_CONTRACT = "./testdata/hackatom.wasm"
)
func withVM(t *testing.T) *VM {
tmpdir, err := os.MkdirTemp("", "wasmvm-testing")
require.NoError(t, err)
vm, err := NewVM(tmpdir, TESTING_CAPABILITIES, TESTING_MEMORY_LIMIT, TESTING_PRINT_DEBUG, TESTING_CACHE_SIZE)
require.NoError(t, err)
t.Cleanup(func() {
vm.Cleanup()
os.RemoveAll(tmpdir)
})
return vm
}
func createTestContract(t *testing.T, vm *VM, path string) Checksum {
wasm, err := os.ReadFile(path)
require.NoError(t, err)
checksum, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT)
require.NoError(t, err)
return checksum
}
func TestStoreCode(t *testing.T) {
vm := withVM(t)
// Valid hackatom contract
{
wasm, err := os.ReadFile(HACKATOM_TEST_CONTRACT)
require.NoError(t, err)
_, _, err = vm.StoreCode(wasm, TESTING_GAS_LIMIT)
require.NoError(t, err)
}
// Valid cyberpunk contract
{
wasm, err := os.ReadFile(CYBERPUNK_TEST_CONTRACT)
require.NoError(t, err)
_, _, err = vm.StoreCode(wasm, TESTING_GAS_LIMIT)
require.NoError(t, err)
}
// Valid Wasm with no exports
{
// echo '(module)' | wat2wasm - -o empty.wasm
// hexdump -C < empty.wasm
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")
}
// No Wasm
{
wasm := []byte("foobar")
_, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT)
require.ErrorContains(t, err, "Wasm 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")
}
// Nil
{
var wasm []byte = nil
_, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT)
require.ErrorContains(t, err, "Null/Nil argument: wasm")
}
}
func TestSimulateStoreCode(t *testing.T) {
vm := withVM(t)
hackatom, err := os.ReadFile(HACKATOM_TEST_CONTRACT)
require.NoError(t, err)
specs := map[string]struct {
wasm []byte
err string
}{
"valid hackatom contract": {
wasm: hackatom,
},
"no wasm": {
wasm: []byte("foobar"),
err: "Wasm bytecode could not be deserialized",
},
}
for name, spec := range specs {
t.Run(name, func(t *testing.T) {
checksum, _, err := vm.SimulateStoreCode(spec.wasm, TESTING_GAS_LIMIT)
if spec.err != "" {
assert.ErrorContains(t, err, spec.err)
} else {
assert.NoError(t, err)
_, err = vm.GetCode(checksum)
assert.ErrorContains(t, err, "Error opening Wasm file for reading")
}
})
}
}
func TestStoreCodeAndGet(t *testing.T) {
vm := withVM(t)
wasm, err := os.ReadFile(HACKATOM_TEST_CONTRACT)
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)
}
func TestRemoveCode(t *testing.T) {
vm := withVM(t)
wasm, err := os.ReadFile(HACKATOM_TEST_CONTRACT)
require.NoError(t, err)
checksum, _, err := vm.StoreCode(wasm, TESTING_GAS_LIMIT)
require.NoError(t, err)
err = vm.RemoveCode(checksum)
require.NoError(t, err)
err = vm.RemoveCode(checksum)
require.ErrorContains(t, err, "Wasm file does not exist")
}
func TestHappyPath(t *testing.T) {
vm := withVM(t)
checksum := createTestContract(t, vm, HACKATOM_TEST_CONTRACT)
deserCost := types.UFraction{Numerator: 1, Denominator: 1}
gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
// instantiate it with this store
store := api.NewLookup(gasMeter1)
goapi := api.NewMockAPI()
balance := types.Array[types.Coin]{types.NewCoin(250, "ATOM")}
querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance)
// instantiate
env := api.MockEnv()
info := api.MockInfo("creator", nil)
msg := []byte(`{"verifier": "fred", "beneficiary": "bob"}`)
i, _, err := vm.Instantiate(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)
ires := i.Ok
require.Equal(t, 0, len(ires.Messages))
// execute
gasMeter2 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
store.SetGasMeter(gasMeter2)
env = api.MockEnv()
info = api.MockInfo("fred", nil)
h, _, err := vm.Execute(checksum, env, info, []byte(`{"release":{}}`), store, *goapi, querier, gasMeter2, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, h.Ok)
hres := h.Ok
require.Equal(t, 1, len(hres.Messages))
// make sure it read the balance properly and we got 250 atoms
dispatch := hres.Messages[0].Msg
require.NotNil(t, dispatch.Bank, "%#v", dispatch)
require.NotNil(t, dispatch.Bank.Send, "%#v", dispatch)
send := dispatch.Bank.Send
assert.Equal(t, "bob", send.ToAddress)
assert.Equal(t, balance, send.Amount)
// check the data is properly formatted
expectedData := []byte{0xF0, 0x0B, 0xAA}
assert.Equal(t, expectedData, hres.Data)
}
func TestEnv(t *testing.T) {
vm := withVM(t)
checksum := createTestContract(t, vm, CYBERPUNK_TEST_CONTRACT)
deserCost := types.UFraction{Numerator: 1, Denominator: 1}
gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
// instantiate it with this store
store := api.NewLookup(gasMeter1)
goapi := api.NewMockAPI()
balance := types.Array[types.Coin]{types.NewCoin(250, "ATOM")}
querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance)
// instantiate
env := api.MockEnv()
info := api.MockInfo("creator", nil)
i, _, err := vm.Instantiate(checksum, env, info, []byte(`{}`), store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)
ires := i.Ok
require.Equal(t, 0, len(ires.Messages))
// Execute mirror env without Transaction
env = types.Env{
Block: types.BlockInfo{
Height: 444,
Time: 1955939743_123456789,
ChainID: "nice-chain",
},
Contract: types.ContractInfo{
Address: "wasm10dyr9899g6t0pelew4nvf4j5c3jcgv0r5d3a5l",
},
Transaction: nil,
}
info = api.MockInfo("creator", nil)
msg := []byte(`{"mirror_env": {}}`)
i, _, err = vm.Execute(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)
ires = i.Ok
expected, _ := json.Marshal(env)
require.Equal(t, expected, ires.Data)
// Execute mirror env with Transaction
env = types.Env{
Block: types.BlockInfo{
Height: 444,
Time: 1955939743_123456789,
ChainID: "nice-chain",
},
Contract: types.ContractInfo{
Address: "wasm10dyr9899g6t0pelew4nvf4j5c3jcgv0r5d3a5l",
},
Transaction: &types.TransactionInfo{
Index: 18,
},
}
info = api.MockInfo("creator", nil)
msg = []byte(`{"mirror_env": {}}`)
i, _, err = vm.Execute(checksum, env, info, msg, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)
ires = i.Ok
expected, _ = json.Marshal(env)
require.Equal(t, expected, ires.Data)
}
func TestGetMetrics(t *testing.T) {
vm := withVM(t)
// GetMetrics 1
metrics, err := vm.GetMetrics()
require.NoError(t, err)
assert.Equal(t, &types.Metrics{}, metrics)
// Create contract
checksum := createTestContract(t, vm, HACKATOM_TEST_CONTRACT)
deserCost := types.UFraction{Numerator: 1, Denominator: 1}
// GetMetrics 2
metrics, err = vm.GetMetrics()
require.NoError(t, err)
assert.Equal(t, &types.Metrics{}, metrics)
// Instantiate 1
gasMeter1 := api.NewMockGasMeter(TESTING_GAS_LIMIT)
// instantiate it with this store
store := api.NewLookup(gasMeter1)
goapi := api.NewMockAPI()
balance := types.Array[types.Coin]{types.NewCoin(250, "ATOM")}
querier := api.DefaultQuerier(api.MOCK_CONTRACT_ADDR, balance)
env := api.MockEnv()
info := api.MockInfo("creator", nil)
msg1 := []byte(`{"verifier": "fred", "beneficiary": "bob"}`)
i, _, err := vm.Instantiate(checksum, env, info, msg1, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)
ires := i.Ok
require.Equal(t, 0, len(ires.Messages))
// GetMetrics 3
metrics, err = vm.GetMetrics()
assert.NoError(t, err)
require.Equal(t, uint32(0), metrics.HitsMemoryCache)
require.Equal(t, uint32(1), metrics.HitsFsCache)
require.Equal(t, uint64(1), metrics.ElementsMemoryCache)
t.Log(metrics.SizeMemoryCache)
require.InEpsilon(t, 3700000, metrics.SizeMemoryCache, 0.25)
// Instantiate 2
msg2 := []byte(`{"verifier": "fred", "beneficiary": "susi"}`)
i, _, err = vm.Instantiate(checksum, env, info, msg2, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)
ires = i.Ok
require.Equal(t, 0, len(ires.Messages))
// GetMetrics 4
metrics, err = vm.GetMetrics()
assert.NoError(t, err)
require.Equal(t, uint32(1), metrics.HitsMemoryCache)
require.Equal(t, uint32(1), metrics.HitsFsCache)
require.Equal(t, uint64(1), metrics.ElementsMemoryCache)
require.InEpsilon(t, 3700000, metrics.SizeMemoryCache, 0.25)
// Pin
err = vm.Pin(checksum)
require.NoError(t, err)
// GetMetrics 5
metrics, err = vm.GetMetrics()
assert.NoError(t, err)
require.Equal(t, uint32(1), metrics.HitsMemoryCache)
require.Equal(t, uint32(2), metrics.HitsFsCache)
require.Equal(t, uint64(1), metrics.ElementsPinnedMemoryCache)
require.Equal(t, uint64(1), metrics.ElementsMemoryCache)
require.InEpsilon(t, 3700000, metrics.SizePinnedMemoryCache, 0.25)
require.InEpsilon(t, 3700000, metrics.SizeMemoryCache, 0.25)
// Instantiate 3
msg3 := []byte(`{"verifier": "fred", "beneficiary": "bert"}`)
i, _, err = vm.Instantiate(checksum, env, info, msg3, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)
ires = i.Ok
require.Equal(t, 0, len(ires.Messages))
// GetMetrics 6
metrics, err = vm.GetMetrics()
assert.NoError(t, err)
require.Equal(t, uint32(1), metrics.HitsPinnedMemoryCache)
require.Equal(t, uint32(1), metrics.HitsMemoryCache)
require.Equal(t, uint32(2), metrics.HitsFsCache)
require.Equal(t, uint64(1), metrics.ElementsPinnedMemoryCache)
require.Equal(t, uint64(1), metrics.ElementsMemoryCache)
require.InEpsilon(t, 3700000, metrics.SizePinnedMemoryCache, 0.25)
require.InEpsilon(t, 3700000, metrics.SizeMemoryCache, 0.25)
// Unpin
err = vm.Unpin(checksum)
require.NoError(t, err)
// GetMetrics 7
metrics, err = vm.GetMetrics()
assert.NoError(t, err)
require.Equal(t, uint32(1), metrics.HitsPinnedMemoryCache)
require.Equal(t, uint32(1), metrics.HitsMemoryCache)
require.Equal(t, uint32(2), metrics.HitsFsCache)
require.Equal(t, uint64(0), metrics.ElementsPinnedMemoryCache)
require.Equal(t, uint64(1), metrics.ElementsMemoryCache)
require.Equal(t, uint64(0), metrics.SizePinnedMemoryCache)
require.InEpsilon(t, 3700000, metrics.SizeMemoryCache, 0.25)
// Instantiate 4
msg4 := []byte(`{"verifier": "fred", "beneficiary": "jeff"}`)
i, _, err = vm.Instantiate(checksum, env, info, msg4, store, *goapi, querier, gasMeter1, TESTING_GAS_LIMIT, deserCost)
require.NoError(t, err)
require.NotNil(t, i.Ok)
ires = i.Ok
require.Equal(t, 0, len(ires.Messages))
// GetMetrics 8
metrics, err = vm.GetMetrics()
assert.NoError(t, err)
require.Equal(t, uint32(1), metrics.HitsPinnedMemoryCache)
require.Equal(t, uint32(2), metrics.HitsMemoryCache)
require.Equal(t, uint32(2), metrics.HitsFsCache)
require.Equal(t, uint64(0), metrics.ElementsPinnedMemoryCache)
require.Equal(t, uint64(1), metrics.ElementsMemoryCache)
require.Equal(t, uint64(0), metrics.SizePinnedMemoryCache)
require.InEpsilon(t, 3700000, metrics.SizeMemoryCache, 0.25)
}
func TestLongPayloadDeserialization(t *testing.T) {
deserCost := types.UFraction{Numerator: 1, Denominator: 1}
gasReport := types.GasReport{}
// Create a valid payload
validPayload := make([]byte, 128*1024)
validPayloadJSON, err := json.Marshal(validPayload)
require.NoError(t, err)
resultJson := []byte(fmt.Sprintf(`{"ok":{"messages":[{"id":0,"msg":{"bank":{"send":{"to_address":"bob","amount":[{"denom":"ATOM","amount":"250"}]}}},"payload":%s,"reply_on":"never"}],"data":"8Auq","attributes":[],"events":[]}}`, validPayloadJSON))
// Test that a valid payload can be deserialized
var result types.ContractResult
err = DeserializeResponse(math.MaxUint64, deserCost, &gasReport, resultJson, &result)
require.NoError(t, err)
require.Equal(t, validPayload, result.Ok.Messages[0].Payload)
// Create an invalid payload (too large)
invalidPayload := make([]byte, 128*1024+1)
invalidPayloadJSON, err := json.Marshal(invalidPayload)
require.NoError(t, err)
resultJson = []byte(fmt.Sprintf(`{"ok":{"messages":[{"id":0,"msg":{"bank":{"send":{"to_address":"bob","amount":[{"denom":"ATOM","amount":"250"}]}}},"payload":%s,"reply_on":"never"}],"attributes":[],"events":[]}}`, invalidPayloadJSON))
// Test that an invalid payload cannot be deserialized
err = DeserializeResponse(math.MaxUint64, deserCost, &gasReport, resultJson, &result)
require.Error(t, err)
require.Contains(t, err.Error(), "payload")
// Test that an invalid payload cannot be deserialized to IBCBasicResult
var ibcResult types.IBCBasicResult
err = DeserializeResponse(math.MaxUint64, deserCost, &gasReport, resultJson, &ibcResult)
require.Error(t, err)
require.Contains(t, err.Error(), "payload")
// Test that an invalid payload cannot be deserialized to IBCReceiveResult
var ibcReceiveResult types.IBCReceiveResult
err = DeserializeResponse(math.MaxUint64, deserCost, &gasReport, resultJson, &ibcReceiveResult)
require.Error(t, err)
require.Contains(t, err.Error(), "payload")
}