forked from okx/wasmvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.go
629 lines (578 loc) · 19.1 KB
/
lib.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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//go:build cgo
// This file contains the part of the API that is exposed when cgo is enabled.
package cosmwasm
import (
"encoding/json"
"fmt"
"github.com/CosmWasm/wasmvm/internal/api"
"github.com/CosmWasm/wasmvm/types"
)
// VM is the main entry point to this library.
// You should create an instance with its own subdirectory to manage state inside,
// and call it for all cosmwasm code related actions.
type VM struct {
cache api.Cache
printDebug bool
}
// NewVM creates a new VM.
//
// `dataDir` is a base directory for Wasm blobs and various caches.
// `supportedCapabilities` is a comma separated list of capabilities suppored by the chain.
// `memoryLimit` is the memory limit of each contract execution (in MiB)
// `printDebug` is a flag to enable/disable printing debug logs from the contract to STDOUT. This should be false in production environments.
// `cacheSize` sets the size in MiB of an in-memory cache for e.g. module caching. Set to 0 to disable.
// `deserCost` sets the gas cost of deserializing one byte of data.
func NewVM(dataDir string, supportedCapabilities string, memoryLimit uint32, printDebug bool, cacheSize uint32) (*VM, error) {
cache, err := api.InitCache(dataDir, supportedCapabilities, cacheSize, memoryLimit)
if err != nil {
return nil, err
}
return &VM{cache: cache, printDebug: printDebug}, nil
}
// Cleanup should be called when no longer using this to free resources on the rust-side
func (vm *VM) Cleanup() {
api.ReleaseCache(vm.cache)
}
// Deprecated: Renamed to StoreCode
func (vm *VM) Create(code WasmCode) (Checksum, error) {
return vm.StoreCode(code)
}
// StoreCode will compile the Wasm code, and store the resulting compiled module
// as well as the original code. Both can be referenced later via Checksum.
// This must be done one time for given code, after which it can be
// instatitated many times, and each instance called many times.
//
// For example, the code for all ERC-20 contracts should be the same.
// This function stores the code for that contract only once, but it can
// be instantiated with custom inputs in the future.
//
// TODO: return gas cost? Add gas limit??? there is no metering here...
func (vm *VM) StoreCode(code WasmCode) (Checksum, error) {
return api.StoreCode(vm.cache, code)
}
func (vm *VM) RemoveCode(checksum Checksum) error {
return api.RemoveCode(vm.cache, checksum)
}
// GetCode will load the original Wasm code for the given checksum.
// This will only succeed if that checksum was previously returned from
// a call to StoreCode.
//
// This can be used so that the (short) checksum is stored in the iavl tree
// and the larger binary blobs (wasm and compiled modules) are all managed
// by libwasmvm/cosmwasm-vm (Rust part).
func (vm *VM) GetCode(checksum Checksum) (WasmCode, error) {
return api.GetCode(vm.cache, checksum)
}
// Pin pins a code to an in-memory cache, such that is
// always loaded quickly when executed.
// Pin is idempotent.
func (vm *VM) Pin(checksum Checksum) error {
return api.Pin(vm.cache, checksum)
}
// Unpin removes the guarantee of a contract to be pinned (see Pin).
// After calling this, the code may or may not remain in memory depending on
// the implementor's choice.
// Unpin is idempotent.
func (vm *VM) Unpin(checksum Checksum) error {
return api.Unpin(vm.cache, checksum)
}
// Returns a report of static analysis of the wasm contract (uncompiled).
// This contract must have been stored in the cache previously (via Create).
// Only info currently returned is if it exposes all ibc entry points, but this may grow later
func (vm *VM) AnalyzeCode(checksum Checksum) (*types.AnalysisReport, error) {
return api.AnalyzeCode(vm.cache, checksum)
}
// GetMetrics some internal metrics for monitoring purposes.
func (vm *VM) GetMetrics() (*types.Metrics, error) {
return api.GetMetrics(vm.cache)
}
// Instantiate will create a new contract based on the given Checksum.
// We can set the initMsg (contract "genesis") here, and it then receives
// an account and address and can be invoked (Execute) many times.
//
// Storage should be set with a PrefixedKVStore that this code can safely access.
//
// Under the hood, we may recompile the wasm, use a cached native compile, or even use a cached instance
// for performance.
func (vm *VM) Instantiate(
checksum Checksum,
env types.Env,
info types.MessageInfo,
initMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.Response, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
infoBin, err := json.Marshal(info)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.Instantiate(vm.cache, checksum, envBin, infoBin, initMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var result types.ContractResult
err = json.Unmarshal(data, &result)
if err != nil {
return nil, gasUsed, err
}
if result.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", result.Err)
}
return result.Ok, gasUsed, nil
}
// Execute calls a given contract. Since the only difference between contracts with the same Checksum is the
// data in their local storage, and their address in the outside world, we need no ContractID here.
// (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 relevant info on this instance (address, balance, etc)
func (vm *VM) Execute(
checksum Checksum,
env types.Env,
info types.MessageInfo,
executeMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.Response, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
infoBin, err := json.Marshal(info)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.Execute(vm.cache, checksum, envBin, infoBin, executeMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var result types.ContractResult
err = json.Unmarshal(data, &result)
if err != nil {
return nil, gasUsed, err
}
if result.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", result.Err)
}
return result.Ok, gasUsed, nil
}
// Query allows a client to execute a contract-specific query. If the result is not empty, it should be
// valid json-encoded data to return to the client.
// The meaning of path and data can be determined by the code. Path is the suffix of the abci.QueryRequest.Path
func (vm *VM) Query(
checksum Checksum,
env types.Env,
queryMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) ([]byte, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.Query(vm.cache, checksum, envBin, queryMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.QueryResponse
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
// Migrate will migrate an existing contract to a new code binary.
// This takes storage of the data from the original contract and the Checksum of the new contract that should
// replace it. This allows it to run a migration step if needed, or return an error if unable to migrate
// the given data.
//
// MigrateMsg has some data on how to perform the migration.
func (vm *VM) Migrate(
checksum Checksum,
env types.Env,
migrateMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.Response, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.Migrate(vm.cache, checksum, envBin, migrateMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.ContractResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
// Sudo allows native Go modules to make priviledged (sudo) calls on the contract.
// The contract can expose entry points that cannot be triggered by any transaction, but only via
// native Go modules, and delegate the access control to the system.
//
// These work much like Migrate (same scenario) but allows custom apps to extend the priviledged entry points
// without forking cosmwasm-vm.
func (vm *VM) Sudo(
checksum Checksum,
env types.Env,
sudoMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.Response, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.Sudo(vm.cache, checksum, envBin, sudoMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.ContractResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
// Reply allows the native Go wasm modules to make a priviledged call to return the result
// of executing a SubMsg.
//
// These work much like Sudo (same scenario) but focuses on one specific case (and one message type)
func (vm *VM) Reply(
checksum Checksum,
env types.Env,
reply types.Reply,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.Response, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
replyBin, err := json.Marshal(reply)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.Reply(vm.cache, checksum, envBin, replyBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.ContractResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
// IBCChannelOpen is available on IBC-enabled contracts and is a hook to call into
// during the handshake pahse
func (vm *VM) IBCChannelOpen(
checksum Checksum,
env types.Env,
msg types.IBCChannelOpenMsg,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.IBC3ChannelOpenResponse, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.IBCChannelOpen(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.IBCChannelOpenResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
// IBCChannelConnect is available on IBC-enabled contracts and is a hook to call into
// during the handshake pahse
func (vm *VM) IBCChannelConnect(
checksum Checksum,
env types.Env,
msg types.IBCChannelConnectMsg,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.IBCBasicResponse, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.IBCChannelConnect(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.IBCBasicResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
// IBCChannelClose is available on IBC-enabled contracts and is a hook to call into
// at the end of the channel lifetime
func (vm *VM) IBCChannelClose(
checksum Checksum,
env types.Env,
msg types.IBCChannelCloseMsg,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.IBCBasicResponse, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.IBCChannelClose(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.IBCBasicResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
// IBCPacketReceive is available on IBC-enabled contracts and is called when an incoming
// packet is received on a channel belonging to this contract
func (vm *VM) IBCPacketReceive(
checksum Checksum,
env types.Env,
msg types.IBCPacketReceiveMsg,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.IBCReceiveResult, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.IBCPacketReceive(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.IBCReceiveResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
return &resp, gasUsed, nil
}
// IBCPacketAck is available on IBC-enabled contracts and is called when an
// the response for an outgoing packet (previously sent by this contract)
// is received
func (vm *VM) IBCPacketAck(
checksum Checksum,
env types.Env,
msg types.IBCPacketAckMsg,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.IBCBasicResponse, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.IBCPacketAck(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.IBCBasicResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
// IBCPacketTimeout is available on IBC-enabled contracts and is called when an
// outgoing packet (previously sent by this contract) will provably never be executed.
// Usually handled like ack returning an error
func (vm *VM) IBCPacketTimeout(
checksum Checksum,
env types.Env,
msg types.IBCPacketTimeoutMsg,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
deserCost types.UFraction,
) (*types.IBCBasicResponse, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.IBCPacketTimeout(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
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))
}
gasUsed += gasForDeserialization
var resp types.IBCBasicResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}