-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathtvmExecutor.go
393 lines (358 loc) · 10.3 KB
/
tvmExecutor.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
package tvm
// #cgo darwin LDFLAGS: -L ../lib/darwin/ -Wl,-rpath,../lib/darwin/ -l emulator
// #cgo linux LDFLAGS: -L ../lib/linux/ -Wl,-rpath,../lib/linux/ -l emulator
// #include "../lib/emulator-extern.h"
// #include <stdlib.h>
// #include <stdbool.h>
import "C"
import (
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"math/rand"
"runtime"
"time"
"unsafe"
"github.com/tonkeeper/tongo/boc"
"github.com/tonkeeper/tongo/tlb"
"github.com/tonkeeper/tongo/ton"
"github.com/tonkeeper/tongo/txemulator"
"github.com/tonkeeper/tongo/utils"
)
type libResolver interface {
GetLibraries(ctx context.Context, libraryList []ton.Bits256) (map[ton.Bits256]*boc.Cell, error)
}
type Emulator struct {
emulator unsafe.Pointer
config string
balance uint64
lazyC7 bool
c7Set bool
libResolver libResolver
ignoreLibraryCells bool
}
type Config struct {
data unsafe.Pointer
}
type Options struct {
verbosityLevel txemulator.VerbosityLevel
balance int64
// libraries is a list of available libraries encoded as a base64 string.
libraries string
lazyC7 bool
libResolver libResolver
ignoreLibraryCells bool
config *Config
}
type Option func(o *Options)
// WithVerbosityLevel sets verbosity level of a TVM emulator instance.
// TODO: find a way to expose logs to the caller.
func WithVerbosityLevel(level txemulator.VerbosityLevel) Option {
return func(o *Options) {
o.verbosityLevel = level
}
}
func WithBalance(balance int64) Option {
return func(o *Options) {
o.balance = balance
}
}
func WithConfig(config *Config) Option {
return func(o *Options) {
o.config = config
}
}
// WithLibrariesBase64 provides a list of available libraries as a base64 string.
// Take a look at LibrariesToBase64() to convert a map with libraries to such a string.
func WithLibrariesBase64(libraries string) Option {
return func(o *Options) {
o.libraries = libraries
}
}
// WithLazyC7Optimization allows to make two attempts to execute a get method.
// At the first attempt an emulator invokes a get method without C7.
// This works for most get methods and significantly decreases the execution time.
// If the first attempt fails,
// an emulator invokes the same get method again but with configured C7.
func WithLazyC7Optimization() Option {
return func(o *Options) {
o.lazyC7 = true
}
}
func WithLibraryResolver(resolver libResolver) Option {
return func(o *Options) {
o.libResolver = resolver
}
}
func WithIgnoreLibraryCells(ignore bool) Option {
return func(o *Options) {
o.ignoreLibraryCells = ignore
}
}
func defaultOptions() Options {
return Options{
lazyC7: false,
balance: 1_000_000_000,
verbosityLevel: txemulator.LogTruncated,
ignoreLibraryCells: true,
}
}
// NewEmulator
// Verbosity level of VM log. 0 - log truncated to last 256 characters. 1 - unlimited length log.
// 2 - for each command prints its cell hash and offset. 3 - for each command log prints all stack values.
func NewEmulator(code, data, config *boc.Cell, opts ...Option) (*Emulator, error) {
codeBoc, err := code.ToBocBase64()
if err != nil {
return nil, err
}
dataBoc, err := data.ToBocBase64()
if err != nil {
return nil, err
}
configBoc := ""
if config != nil {
configBoc, err = config.ToBocBase64()
if err != nil {
return nil, err
}
}
return NewEmulatorFromBOCsBase64(codeBoc, dataBoc, configBoc, opts...)
}
// NewEmulatorFromBOCsBase64
// Verbosity level of VM log. 0 - log truncated to last 256 characters. 1 - unlimited length log.
// 2 - for each command prints its cell hash and offset. 3 - for each command log prints all stack values.
func NewEmulatorFromBOCsBase64(code, data, config string, opts ...Option) (*Emulator, error) {
options := defaultOptions()
for _, o := range opts {
o(&options)
}
cCodeStr := C.CString(code)
defer C.free(unsafe.Pointer(cCodeStr))
cDataStr := C.CString(data)
defer C.free(unsafe.Pointer(cDataStr))
level := C.int(options.verbosityLevel)
emulator := C.tvm_emulator_create(cCodeStr, cDataStr, level)
if emulator == nil {
return nil, fmt.Errorf("failed to create emulator")
}
e := Emulator{
emulator: emulator,
config: config,
lazyC7: options.lazyC7,
balance: uint64(options.balance),
libResolver: options.libResolver,
ignoreLibraryCells: options.ignoreLibraryCells,
}
if len(options.libraries) > 0 {
if err := e.setLibs(options.libraries); err != nil {
return nil, err
}
}
if options.config != nil {
if err := e.setConfig(options.config); err != nil {
return nil, err
}
}
runtime.SetFinalizer(&e, destroy)
return &e, nil
}
func destroy(e *Emulator) {
C.tvm_emulator_destroy(e.emulator)
}
func init() {
if err := SetVerbosityLevel(0); err != nil {
// TODO: replace Printf with logger interface
fmt.Printf("SetVerbosityLevel() failed: %v\n", err)
}
}
// SetVerbosityLevel sets verbosity level of TVM emulator.
// This is a global setting that affects all emulators.
// verbosity level (0 - never, 1 - error, 2 - warning, 3 - info, 4 - debug)
func SetVerbosityLevel(level int) error {
ok := C.emulator_set_verbosity_level(C.int(level))
if !ok {
return fmt.Errorf("set VerbosityLevel error")
}
return nil
}
func CreateConfig(configRaw string) (*Config, error) {
configStr := C.CString(configRaw)
defer C.free(unsafe.Pointer(configStr))
config := C.emulator_config_create(configStr)
if config == nil {
return nil, fmt.Errorf("failed to create config")
}
c := Config{data: config}
runtime.SetFinalizer(&c, destroyConfig)
return &c, nil
}
func destroyConfig(c *Config) {
C.emulator_config_destroy(c.data)
}
func (e *Emulator) SetBalance(balance int64) {
e.balance = uint64(balance)
}
func (e *Emulator) SetLibs(libs *boc.Cell) error {
libsBoc, err := libs.ToBocBase64()
if err != nil {
return err
}
return e.setLibs(libsBoc)
}
func (e *Emulator) setLibs(libsBoc string) error {
cLibsStr := C.CString(libsBoc)
defer C.free(unsafe.Pointer(cLibsStr))
ok := C.tvm_emulator_set_libraries(e.emulator, cLibsStr)
if !ok {
return fmt.Errorf("set libs error")
}
return nil
}
func (e *Emulator) SetGasLimit(gasLimit int64) error {
ok := C.tvm_emulator_set_gas_limit(e.emulator, C.int64_t(gasLimit))
if !ok {
return fmt.Errorf("set gas limit error")
}
return nil
}
func (e *Emulator) setConfig(config *Config) error {
ok := C.tvm_emulator_set_config_object(e.emulator, config.data)
if !ok {
return fmt.Errorf("set config error")
}
return nil
}
func (e *Emulator) setC7(address string, unixTime uint32) error {
var seed [32]byte
_, err := rand.Read(seed[:])
if err != nil {
return err
}
cConfigStr := C.CString(e.config)
defer C.free(unsafe.Pointer(cConfigStr))
if e.config == "" {
cConfigStr = nil
}
cAddressStr := C.CString(address)
defer C.free(unsafe.Pointer(cAddressStr))
cSeedStr := C.CString(hex.EncodeToString(seed[:]))
defer C.free(unsafe.Pointer(cSeedStr))
ok := C.tvm_emulator_set_c7(e.emulator, cAddressStr, C.uint32_t(unixTime), C.uint64_t(e.balance), cSeedStr, cConfigStr)
if !ok {
return fmt.Errorf("set C7 error")
}
e.c7Set = true
return nil
}
/**
* @brief Run get method
* @param tvm_emulator Pointer to TVM emulator
* @param method_id Integer method id
* @param stack_boc Base64 encoded BoC serialized stack (VmStack)
* @return Json object with error:
* {
* "success": false,
* "error": "Error description"
* }
* Or success:
* {
* "success": true
* "vm_log": "...",
* "vm_exit_code": 0,
* "stack": "Base64 encoded BoC serialized stack (VmStack)",
* "missing_library": null,
* "gas_used": 1212
* }
*/
type result struct {
Success bool `json:"success"`
Error string `json:"error"`
VmLog string `json:"vm_log"`
VmExitCode int `json:"vm_exit_code"`
Stack string `json:"stack"`
MissingLibrary string `json:"missing_library"`
GasUsed string `json:"gas_used"`
}
func (e *Emulator) RunSmcMethod(ctx context.Context, accountId ton.AccountID, method string, params tlb.VmStack) (uint32, tlb.VmStack, error) {
methodID := utils.MethodIdFromName(method)
return e.RunSmcMethodByID(ctx, accountId, methodID, params)
}
func (e *Emulator) RunSmcMethodByID(ctx context.Context, accountId ton.AccountID, methodID int, params tlb.VmStack) (uint32, tlb.VmStack, error) {
if !e.lazyC7 && !e.c7Set {
err := e.setC7(accountId.ToRaw(), uint32(time.Now().Unix()))
if err != nil {
return 0, tlb.VmStack{}, err
}
}
res, err := e.runGetMethod(methodID, params)
if err != nil {
return 0, tlb.VmStack{}, err
}
if res.Success && res.VmExitCode != 0 && res.VmExitCode != 1 && e.lazyC7 && !e.c7Set {
err = e.setC7(accountId.ToRaw(), uint32(time.Now().Unix()))
if err != nil {
return 0, tlb.VmStack{}, err
}
res, err = e.runGetMethod(methodID, params)
if err != nil {
return 0, tlb.VmStack{}, err
}
}
if !res.Success {
return 0, tlb.VmStack{}, fmt.Errorf("TVM emulation error: %v", res.Error)
}
b, err := base64.StdEncoding.DecodeString(res.Stack)
if err != nil {
return 0, tlb.VmStack{}, err
}
c, err := boc.DeserializeBoc(b)
if err != nil {
return 0, tlb.VmStack{}, err
}
var stack tlb.VmStack
decoder := tlb.NewDecoder()
if e.libResolver != nil {
decoder = decoder.WithLibraryResolver(func(hash tlb.Bits256) (*boc.Cell, error) {
if e.libResolver == nil {
return nil, fmt.Errorf("failed to fetch library: no resolver provided")
}
libs, err := e.libResolver.GetLibraries(ctx, []ton.Bits256{ton.Bits256(hash)})
if err != nil {
return nil, err
}
if len(libs) == 0 {
return nil, fmt.Errorf("library not found")
}
return libs[ton.Bits256(hash)], nil
})
}
err = decoder.Unmarshal(c[0], &stack)
if err != nil {
return 0, tlb.VmStack{}, err
}
return uint32(res.VmExitCode), stack, nil
}
func (e *Emulator) runGetMethod(methodID int, params tlb.VmStack) (result, error) {
stack := boc.NewCell()
err := tlb.Marshal(stack, params)
if err != nil {
return result{}, err
}
stackBoc, err := stack.ToBocBase64()
if err != nil {
return result{}, err
}
cStackStr := C.CString(stackBoc)
defer C.free(unsafe.Pointer(cStackStr))
var res result
r := C.tvm_emulator_run_get_method(e.emulator, C.int(methodID), cStackStr)
rJSON := C.GoString(r)
defer C.free(unsafe.Pointer(r))
err = json.Unmarshal([]byte(rJSON), &res)
if err != nil {
return result{}, err
}
return res, nil
}