/
wasm_engine.go
308 lines (261 loc) · 7.35 KB
/
wasm_engine.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
package vm
import (
"context"
"fmt"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/lru"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/configs"
"hash/fnv"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/log"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/rlp"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/wagon/exec"
"github.com/pkg/errors"
)
const (
callEntryName = "invoke"
initFn = "init"
)
const memoryLimit = 16 * 1024 * 1024
const (
verifyModule = true
unVerifyModule = false
)
type wagonEngineCreator struct {
}
func (w *wagonEngineCreator) Create(evm *EVM, config Config, gasTable configs.GasTable, contract *Contract) (wasmEngine, error) {
return &wagonEngine{
evm: evm,
config: config,
gasTable: gasTable,
contract: contract,
}, nil
}
type wasmEngine interface {
Run(input []byte, readOnly bool) (ret []byte, err error)
}
type wagonEngine struct {
evm *EVM
config Config
gasTable configs.GasTable
vm *exec.CompileVM
contract *Contract
}
func (engine *wagonEngine) EVM() *EVM {
return engine.evm
}
func (engine *wagonEngine) Config() Config {
return engine.config
}
func (engine *wagonEngine) StateDB() StateDB {
return engine.evm.StateDB
}
func (engine *wagonEngine) Contract() *Contract {
return engine.contract
}
func (engine *wagonEngine) Run(input []byte, readOnly bool) ([]byte, error) {
if engine.Contract().DeployContract { // deploy contract
contractCode, calldata, err := disassemblyDeployCode(engine.Contract().Code)
if nil != err {
return nil, err
}
if err := validateFunc(calldata, engine.Contract().DeployContract); nil != err {
return nil, err
}
engine.Contract().Code = contractCode
input = calldata
} else { // call contract
if len(input) == 0 { // When calling, do nothing without input
return nil, nil
}
if err := validateFunc(input, engine.Contract().DeployContract); nil != err {
return nil, err
}
}
module, entryIndex, moduleErr := engine.MakeModule(engine.Contract().DeployContract)
if nil != moduleErr {
return nil, moduleErr
}
if err := engine.prepare(module, input); nil != err {
return nil, err
}
if readOnly && !engine.isReadOnly() {
engine.setReadOnly(true)
defer func() { engine.setReadOnly(false) }()
}
go func(ctx context.Context) {
<-ctx.Done()
// shutdown vm, change the vm.abort mark
engine.vm.Close()
}(engine.evm.Ctx)
//exec vm
ret, err := engine.exec(entryIndex)
if engine.Contract().DeployContract {
return engine.Contract().Code, err
}
return ret, err
}
func (engine *wagonEngine) prepare(module *exec.CompiledModule, input []byte) error {
vm, err := exec.NewVMWithCompiled(module, memoryLimit)
if nil != err {
return err
}
vm.RecoverPanic = false // NOTE: There is no need for wagon vm to handle err and panic and it will be handled by wagon engine.
ctx := &VMContext{
evm: engine.EVM(),
contract: engine.Contract(),
config: engine.Config(),
gasTable: engine.gasTable,
db: engine.StateDB(),
Input: input, //set input bytes
Log: NewWasmLogger(engine.config, log.WasmRoot()),
}
vm.SetHostCtx(ctx)
vm.SetUseGas(func(b byte) {
gas := WasmGasCostTable[b]
if !ctx.contract.UseGas(gas) {
panic(ErrOutOfGas)
}
})
engine.vm = vm
return nil
}
func (engine *wagonEngine) exec(index int64) (ret []byte, err error) {
defer func() {
if r := recover(); r != nil {
switch e := r.(type) {
case error:
ret, err = nil, e
default:
log.Error("Failed to exec wagon vm", "the undefined err", fmt.Sprintf("%v", e))
ret, err = nil, ErrWASMUndefinedPanic
}
}
}()
_, err = engine.vm.ExecCode(index)
if err != nil {
return nil, errors.Wrap(err, "execute function code")
}
ctx := engine.vm.HostCtx().(*VMContext)
switch {
case ctx.Revert:
return nil, ErrExecutionReverted
case engine.vm.Abort():
return nil, ErrAbort
}
return ctx.Output, nil
}
func (engine *wagonEngine) MakeModule(deploy bool) (*exec.CompiledModule, int64, error) {
if !deploy {
return engine.makeModuleWithCall()
} else {
return engine.makeModuleWithDeploy()
}
}
func validateFunc(input []byte, deploy bool) error {
if deploy {
return validateDeployFunc(input)
} else {
return validateCallFunc(input)
}
}
func fnNameHashUint() uint64 {
hash := fnv.New64()
_, err := hash.Write([]byte(initFn))
if nil != err {
panic(err)
}
return hash.Sum64()
}
func validateDeployFunc(input []byte) error {
funcName, _, err := decodeFuncAndParams(input)
if nil != err {
return err
}
if funcName != fnNameHashUint() {
return errors.New("deploy contract must be call init func")
}
return nil
}
func validateCallFunc(input []byte) error {
funcName, _, err := decodeFuncAndParams(input)
if nil != err {
return err
}
if funcName == fnNameHashUint() {
return errors.New("init func can only be called when deploy contract")
}
return nil
}
func (engine *wagonEngine) makeModuleWithDeploy() (*exec.CompiledModule, int64, error) {
cache := &lru.WasmModule{}
module, err := ReadWasmModule(engine.Contract().Code, verifyModule)
if nil != err {
return nil, 0, err
}
// Short circuit if the `invoke` function is not existing in the module
entry, ok := module.RawModule.Export.Entries[callEntryName]
if !ok {
return nil, 0, errors.New("The skeleton of the contract is illegal")
}
index := int64(entry.Index)
fidx := module.RawModule.Function.Types[int(index)]
ftype := module.RawModule.Types.Entries[int(fidx)]
if len(ftype.ParamTypes) > 0 || len(ftype.ReturnTypes) > 0 {
return nil, 0, errors.New("function sig error")
}
cache.Module = module
lru.WasmCache().Add(*(engine.Contract().CodeAddr), cache)
return module, index, nil
}
func (engine *wagonEngine) makeModuleWithCall() (*exec.CompiledModule, int64, error) {
// load module
cache, ok := lru.WasmCache().Get(*(engine.Contract().CodeAddr))
if !ok || (ok && nil == cache.Module) {
cache = &lru.WasmModule{}
module, err := ReadWasmModule(engine.Contract().Code, unVerifyModule)
if nil != err {
return nil, 0, err
}
cache.Module = module
lru.WasmCache().Add(*(engine.Contract().CodeAddr), cache)
}
mod := cache.Module
entry, ok := mod.RawModule.Export.Entries[callEntryName]
if !ok {
return nil, 0, errors.New("The contract hadn't invoke fn")
}
index := int64(entry.Index)
return mod, index, nil
}
func (engine *wagonEngine) isReadOnly() bool {
ctx := engine.vm.HostCtx().(*VMContext)
return ctx.readOnly
}
func (engine *wagonEngine) setReadOnly(ro bool) {
ctx := engine.vm.HostCtx().(*VMContext)
ctx.readOnly = ro
engine.vm.SetHostCtx(ctx)
}
// disassemblyDeployCode parses out the contract code and call data during wasm deployment.
// The composition of `code` is `magicNum|rlp([contractCode, rlp(init,args1, args2, ...)])`
func disassemblyDeployCode(code []byte) (contractCode []byte, calldata []byte, err error) {
if len(code) == 0 {
return nil, nil, errors.New("No contract code to be parsed")
}
// discard the magic number
prefixMagic, code := BytesToInterpType(code[:InterpTypeLen]), code[InterpTypeLen:]
var data [][]byte
if err = rlp.DecodeBytes(code, &data); nil != err {
return
}
if len(data) != 2 {
return nil, nil, errors.New("No contract code to be parsed")
}
contractCode = data[0]
calldata = data[1]
codeMagic := BytesToInterpType(contractCode[:InterpTypeLen])
// check magic on contract code
if prefixMagic != codeMagic {
return nil, nil, errors.New("No contract code to be parsed")
}
return
}