-
Notifications
You must be signed in to change notification settings - Fork 44
/
vm.go
1485 lines (1336 loc) · 37 KB
/
vm.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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package contract
/*
#cgo CFLAGS: -I${SRCDIR}/../libtool/include/luajit-2.1 -I${SRCDIR}/../libtool/include
#cgo !windows CFLAGS: -DLJ_TARGET_POSIX
#cgo darwin LDFLAGS: ${SRCDIR}/../libtool/lib/libluajit-5.1.a ${SRCDIR}/../libtool/lib/libgmp.dylib -lm
#cgo windows LDFLAGS: ${SRCDIR}/../libtool/lib/libluajit-5.1.a ${SRCDIR}/../libtool/bin/libgmp-10.dll -lm
#cgo !darwin,!windows LDFLAGS: ${SRCDIR}/../libtool/lib/libluajit-5.1.a -L${SRCDIR}/../libtool/lib64 -L${SRCDIR}/../libtool/lib -lgmp -lm
#include <stdlib.h>
#include <string.h>
#include "vm.h"
#include "bignum_module.h"
*/
import "C"
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"math/rand"
"os"
"reflect"
"sort"
"strings"
"sync"
"time"
"unsafe"
"github.com/aergoio/aergo-lib/log"
luacUtil "github.com/aergoio/aergo/v2/cmd/aergoluac/util"
"github.com/aergoio/aergo/v2/fee"
"github.com/aergoio/aergo/v2/internal/enc"
"github.com/aergoio/aergo/v2/state"
"github.com/aergoio/aergo/v2/types"
jsoniter "github.com/json-iterator/go"
)
const (
callMaxInstLimit = C.int(5000000)
queryMaxInstLimit = callMaxInstLimit * C.int(10)
dbUpdateMaxLimit = fee.StateDbMaxUpdateSize
maxCallDepthOld = 5
maxCallDepth = 64
checkFeeDelegationFn = "check_delegation"
constructor = "constructor"
vmTimeoutErrMsg = "contract timeout during vm execution"
)
var (
maxContext int
ctrLgr *log.Logger
contexts []*vmContext
lastQueryIndex int
querySync sync.Mutex
currentForkVersion int32
)
type ChainAccessor interface {
GetBlockByNo(blockNo types.BlockNo) (*types.Block, error)
GetBestBlock() (*types.Block, error)
}
type callState struct {
ctrState *state.ContractState
prevState *types.State
curState *types.State
tx sqlTx
}
type contractInfo struct {
callState *callState
sender []byte
contractId []byte
rp uint64
amount *big.Int
}
// vmContext contains context datas during execution of smart contract.
// It has both call infos which are immutable, and real time statuses
// which are mutable during execution
type vmContext struct {
curContract *contractInfo
bs *state.BlockState
cdb ChainAccessor
origin []byte
txHash []byte
blockInfo *types.BlockHeaderInfo
node string
confirmed bool
isQuery bool
nestedView int32 // indicates which parent called the contract in view (read-only mode)
isFeeDelegation bool
service C.int
callState map[types.AccountID]*callState
lastRecoveryEntry *recoveryEntry
dbUpdateTotalSize int64
seed *rand.Rand
events []*types.Event
eventCount int32
callDepth int32
traceFile *os.File
gasLimit uint64
remainedGas uint64
execCtx context.Context
}
type recoveryEntry struct {
seq int
amount *big.Int
senderState *types.State
senderNonce uint64
callState *callState
onlySend bool
isDeploy bool
sqlSaveName *string
stateRevision state.Snapshot
prev *recoveryEntry
}
type LState = C.struct_lua_State
type executor struct {
L *LState
code []byte
err error
numArgs C.int
ci *types.CallInfo
fname string
ctx *vmContext
jsonRet string
isView bool
isAutoload bool
preErr error
}
func MaxCallDepth(version int32) int32 {
if version >= 3 {
return maxCallDepth
}
return maxCallDepthOld
}
func init() {
ctrLgr = log.NewLogger("contract")
lastQueryIndex = ChainService
}
func InitContext(numCtx int) {
maxContext = numCtx
contexts = make([]*vmContext, maxContext)
}
func newContractInfo(cs *callState, sender, contractId []byte, rp uint64, amount *big.Int) *contractInfo {
return &contractInfo{
cs,
sender,
contractId,
rp,
amount,
}
}
func getTraceFile(blkno uint64, tx []byte) *os.File {
f, _ := os.OpenFile(fmt.Sprintf("%s%s%d.trace", os.TempDir(), string(os.PathSeparator), blkno), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if f != nil {
_, _ = f.WriteString(fmt.Sprintf("[START TX]: %s\n", enc.ToString(tx)))
}
return f
}
func NewVmContext(execCtx context.Context, blockState *state.BlockState, cdb ChainAccessor, sender, reciever *state.V, contractState *state.ContractState, senderID, txHash []byte, bi *types.BlockHeaderInfo, node string, confirmed, query bool, rp uint64, service int, amount *big.Int, gasLimit uint64, feeDelegation bool) *vmContext {
cs := &callState{ctrState: contractState, curState: reciever.State()}
ctx := &vmContext{
curContract: newContractInfo(cs, senderID, reciever.ID(), rp, amount),
bs: blockState,
cdb: cdb,
origin: senderID,
txHash: txHash,
node: node,
confirmed: confirmed,
isQuery: query,
blockInfo: bi,
service: C.int(service),
gasLimit: gasLimit,
remainedGas: gasLimit,
isFeeDelegation: feeDelegation,
execCtx: execCtx,
}
ctx.callState = make(map[types.AccountID]*callState)
ctx.callState[reciever.AccountID()] = cs
if sender != nil {
ctx.callState[sender.AccountID()] = &callState{curState: sender.State()}
}
if TraceBlockNo != 0 && TraceBlockNo == ctx.blockInfo.No {
ctx.traceFile = getTraceFile(ctx.blockInfo.No, txHash)
}
return ctx
}
func NewVmContextQuery(
blockState *state.BlockState,
cdb ChainAccessor,
receiverId []byte,
contractState *state.ContractState,
rp uint64,
) (*vmContext, error) {
cs := &callState{ctrState: contractState, curState: contractState.State}
bb, err := cdb.GetBestBlock()
if err != nil {
return nil, err
}
ctx := &vmContext{
curContract: newContractInfo(cs, nil, receiverId, rp, big.NewInt(0)),
bs: blockState,
cdb: cdb,
confirmed: true,
blockInfo: types.NewBlockHeaderInfo(bb),
isQuery: true,
execCtx: context.Background(), // FIXME query also should cancel if query is too long
}
ctx.callState = make(map[types.AccountID]*callState)
ctx.callState[types.ToAccountID(receiverId)] = cs
return ctx, nil
}
func (ctx *vmContext) IsGasSystem() bool {
return !ctx.isQuery && PubNet && ctx.blockInfo.ForkVersion >= 2
}
// get the remaining gas from the given LState
func (ctx *vmContext) refreshRemainingGas(L *LState) {
if ctx.IsGasSystem() {
ctx.remainedGas = uint64(C.lua_gasget(L))
}
}
// set the remaining gas on the given LState
func (ctx *vmContext) setRemainingGas(L *LState) {
if ctx.IsGasSystem() {
C.lua_gasset(L, C.ulonglong(ctx.remainedGas))
}
}
func (ctx *vmContext) usedFee() *big.Int {
if fee.IsZeroFee() {
return fee.NewZeroFee()
}
if ctx.IsGasSystem() {
usedGas := ctx.usedGas()
if ctrLgr.IsDebugEnabled() {
ctrLgr.Debug().Uint64("gas used", usedGas).Str("lua vm", "executed").Msg("gas information")
}
return new(big.Int).Mul(ctx.bs.GasPrice, new(big.Int).SetUint64(usedGas))
}
return fee.PaymentDataFee(ctx.dbUpdateTotalSize)
}
func (ctx *vmContext) usedGas() uint64 {
if fee.IsZeroFee() || !ctx.IsGasSystem() {
return 0
}
return ctx.gasLimit - ctx.remainedGas
}
func newLState() *LState {
ctrLgr.Debug().Msg("LState created")
return C.vm_newstate(C.int(currentForkVersion))
}
func (L *LState) close() {
if L != nil {
C.lua_close(L)
}
}
type lStatesBuffer struct {
s []*LState
limit int
}
func newLStatesBuffer(limit int) *lStatesBuffer {
return &lStatesBuffer{
s: make([]*LState, 0),
limit: limit,
}
}
func (Ls *lStatesBuffer) len() int {
return len(Ls.s)
}
func (Ls *lStatesBuffer) append(s *LState) {
Ls.s = append(Ls.s, s)
if Ls.len() == Ls.limit {
Ls.close()
}
}
func (Ls *lStatesBuffer) close() {
C.vm_closestates(&Ls.s[0], C.int(len(Ls.s)))
Ls.s = Ls.s[:0]
}
func resolveFunction(contractState *state.ContractState, bs *state.BlockState, name string, constructor bool) (*types.Function, error) {
abi, err := GetABI(contractState, bs)
if err != nil {
return nil, err
}
var defaultFunc *types.Function
for _, f := range abi.Functions {
if f.Name == name {
return f, nil
}
if f.Name == "default" {
defaultFunc = f
}
}
if constructor {
return nil, nil
}
if len(name) == 0 && defaultFunc != nil {
return defaultFunc, nil
}
return nil, errors.New("not found function: " + name)
}
func newExecutor(
contract []byte,
contractId []byte,
ctx *vmContext,
ci *types.CallInfo,
amount *big.Int,
isCreate bool,
isDelegation bool,
ctrState *state.ContractState,
) *executor {
if ctx.blockInfo.ForkVersion != currentForkVersion {
// force the StatePool to regenerate the LStates
// using the new hardfork version
currentForkVersion = ctx.blockInfo.ForkVersion
FlushLStates()
}
if ctx.callDepth > MaxCallDepth(ctx.blockInfo.ForkVersion) {
ce := &executor{
code: contract,
ctx: ctx,
}
ce.err = fmt.Errorf("exceeded the maximum call depth(%d)", MaxCallDepth(ctx.blockInfo.ForkVersion))
return ce
}
ctx.callDepth++
ce := &executor{
code: contract,
L: GetLState(),
ctx: ctx,
}
if ce.L == nil {
ce.err = ErrVmStart
ctrLgr.Error().Err(ce.err).Str("contract", types.EncodeAddress(contractId)).Msg("new AergoLua executor")
return ce
}
if ctx.blockInfo.ForkVersion >= 2 {
C.luaL_set_hardforkversion(ce.L, C.int(ctx.blockInfo.ForkVersion))
}
if ctx.IsGasSystem() {
ce.setGas()
defer func() {
ce.refreshRemainingGas()
if ctrLgr.IsDebugEnabled() {
ctrLgr.Debug().Uint64("gas used", ce.ctx.usedGas()).Str("lua vm", "loaded").Msg("gas information")
}
}()
}
ce.vmLoadCode(contractId)
if ce.err != nil {
return ce
}
if isCreate {
f, err := resolveFunction(ctrState, ctx.bs, constructor, isCreate)
if err != nil {
ce.preErr = err
ctrLgr.Debug().Err(ce.err).Str("contract", types.EncodeAddress(contractId)).Msg("not found function")
return ce
}
if f == nil {
f = &types.Function{
Name: constructor,
Payable: false,
}
}
err = checkPayable(f, amount)
if err != nil {
ce.preErr = err
ctrLgr.Debug().Err(ce.err).Str("contract", types.EncodeAddress(contractId)).Msg("check payable function")
return ce
}
ce.isView = f.View
ce.fname = constructor
ce.isAutoload = true
ce.numArgs = C.int(len(ci.Args))
} else if isDelegation {
_, err := resolveFunction(ctrState, ctx.bs, checkFeeDelegationFn, false)
if err != nil {
ce.preErr = err
ctrLgr.Debug().Err(ce.err).Str("contract", types.EncodeAddress(contractId)).Msg("not found function")
return ce
}
ce.isView = true
ce.fname = checkFeeDelegationFn
ce.isAutoload = true
ce.numArgs = C.int(len(ci.Args))
} else {
f, err := resolveFunction(ctrState, ctx.bs, ci.Name, isCreate)
if err != nil {
ce.preErr = err
ctrLgr.Debug().Err(ce.err).Str("contract", types.EncodeAddress(contractId)).Msg("not found function")
return ce
}
err = checkPayable(f, amount)
if err != nil {
ce.preErr = err
ctrLgr.Debug().Err(ce.err).Str("contract", types.EncodeAddress(contractId)).Msg("check payable function")
return ce
}
ce.isView = f.View
ce.fname = f.Name
ce.numArgs = C.int(len(ci.Args) + 1)
}
ce.ci = ci
return ce
}
func (ce *executor) processArgs() {
for _, v := range ce.ci.Args {
if err := pushValue(ce.L, v); err != nil {
ce.err = err
return
}
}
}
func (ce *executor) getEvents() []*types.Event {
if ce == nil || ce.ctx == nil {
return nil
}
return ce.ctx.events
}
func pushValue(L *LState, v interface{}) error {
switch arg := v.(type) {
case string:
argC := C.CBytes([]byte(arg))
C.lua_pushlstring(L, (*C.char)(argC), C.size_t(len(arg)))
C.free(argC)
case float64:
if arg == float64(int64(arg)) {
C.lua_pushinteger(L, C.lua_Integer(arg))
} else {
C.lua_pushnumber(L, C.double(arg))
}
case bool:
var b int
if arg {
b = 1
}
C.lua_pushboolean(L, C.int(b))
case json.Number:
str := arg.String()
intVal, err := arg.Int64()
if err == nil {
C.lua_pushinteger(L, C.lua_Integer(intVal))
} else {
ftVal, err := arg.Float64()
if err != nil {
return errors.New("unsupported number type:" + str)
}
C.lua_pushnumber(L, C.double(ftVal))
}
case nil:
C.lua_pushnil(L)
case []interface{}:
err := toLuaArray(L, arg)
if err != nil {
return err
}
case map[string]interface{}:
err := toLuaTable(L, arg)
if err != nil {
return err
}
default:
return errors.New("unsupported type:" + reflect.TypeOf(v).Name())
}
return nil
}
func toLuaArray(L *LState, arr []interface{}) error {
C.lua_createtable(L, C.int(len(arr)), C.int(0))
n := C.lua_gettop(L)
for i, v := range arr {
if err := pushValue(L, v); err != nil {
return err
}
C.lua_rawseti(L, n, C.int(i+1))
}
return nil
}
func toLuaTable(L *LState, tab map[string]interface{}) error {
C.lua_createtable(L, C.int(0), C.int(len(tab)))
n := C.lua_gettop(L)
// get the keys and sort them
keys := make([]string, 0, len(tab))
for k := range tab {
keys = append(keys, k)
}
if C.vm_is_hardfork(L, 3) {
sort.Strings(keys)
}
for _, k := range keys {
v := tab[k]
if len(tab) == 1 && strings.EqualFold(k, "_bignum") {
if arg, ok := v.(string); ok {
C.lua_settop(L, -2)
argC := C.CString(arg)
msg := C.lua_set_bignum(L, argC)
C.free(unsafe.Pointer(argC))
if msg != nil {
return errors.New(C.GoString(msg))
}
return nil
}
}
// push a key
key := C.CString(k)
C.lua_pushstring(L, key)
C.free(unsafe.Pointer(key))
if err := pushValue(L, v); err != nil {
return err
}
C.lua_rawset(L, n)
}
return nil
}
func checkPayable(callee *types.Function, amount *big.Int) error {
if amount.Cmp(big.NewInt(0)) <= 0 || callee.Payable {
return nil
}
return fmt.Errorf("'%s' is not payable", callee.Name)
}
func (ce *executor) call(instLimit C.int, target *LState) C.int {
if ce.err != nil {
return 0
}
defer ce.refreshRemainingGas()
if ce.isView == true {
ce.ctx.nestedView++
defer func() {
ce.ctx.nestedView--
}()
}
ce.vmLoadCall()
if ce.err != nil {
return 0
}
if ce.preErr != nil {
ce.err = ce.preErr
return 0
}
if ce.isAutoload {
if loaded := vmAutoload(ce.L, ce.fname); !loaded {
if ce.fname != constructor {
ce.err = errors.New(fmt.Sprintf("contract autoload failed %s : %s",
types.EncodeAddress(ce.ctx.curContract.contractId), ce.fname))
}
return 0
}
} else {
C.vm_remove_constructor(ce.L)
resolvedName := C.CString(ce.fname)
C.vm_get_abi_function(ce.L, resolvedName)
C.free(unsafe.Pointer(resolvedName))
}
ce.processArgs()
if ce.err != nil {
ctrLgr.Debug().Err(ce.err).Stringer("contract",
types.LogAddr(ce.ctx.curContract.contractId)).Msg("invalid argument")
return 0
}
ce.setCountHook(instLimit)
nRet := C.int(0)
cErrMsg := C.vm_pcall(ce.L, ce.numArgs, &nRet)
if cErrMsg != nil {
errMsg := C.GoString(cErrMsg)
if C.luaL_hassyserror(ce.L) != C.int(0) {
ce.err = newVmSystemError(errors.New(errMsg))
} else {
isUncatchable := C.luaL_hasuncatchablerror(ce.L) != C.int(0)
if isUncatchable && (errMsg == C.ERR_BF_TIMEOUT || errMsg == vmTimeoutErrMsg) {
ce.err = &VmTimeoutError{}
} else {
ce.err = errors.New(errMsg)
}
}
ctrLgr.Debug().Err(ce.err).Stringer(
"contract",
types.LogAddr(ce.ctx.curContract.contractId),
).Msg("contract is failed")
if target != nil {
if C.luaL_hasuncatchablerror(ce.L) != C.int(0) {
C.luaL_setuncatchablerror(target)
}
if C.luaL_hassyserror(ce.L) != C.int(0) {
C.luaL_setsyserror(target)
}
}
return 0
}
if target == nil {
var errRet C.int
retMsg := C.GoString(C.vm_get_json_ret(ce.L, nRet, &errRet))
if errRet == 1 {
ce.err = errors.New(retMsg)
} else {
ce.jsonRet = retMsg
}
} else {
if c2ErrMsg := C.vm_copy_result(ce.L, target, nRet); c2ErrMsg != nil {
errMsg := C.GoString(c2ErrMsg)
ce.err = errors.New(errMsg)
ctrLgr.Debug().Err(ce.err).Stringer(
"contract",
types.LogAddr(ce.ctx.curContract.contractId),
).Msg("failed to move results")
}
}
if ce.ctx.traceFile != nil {
address := types.EncodeAddress(ce.ctx.curContract.contractId)
codeFile := fmt.Sprintf("%s%s%s.code", os.TempDir(), string(os.PathSeparator), address)
if _, err := os.Stat(codeFile); os.IsNotExist(err) {
f, err := os.OpenFile(codeFile, os.O_WRONLY|os.O_CREATE, 0644)
if err == nil {
_, _ = f.Write(ce.code)
_ = f.Close()
}
}
_, _ = ce.ctx.traceFile.WriteString(fmt.Sprintf("contract %s used fee: %s\n",
address, ce.ctx.usedFee().String()))
}
return nRet
}
func (ce *executor) commitCalledContract() error {
ctx := ce.ctx
if ctx == nil || ctx.callState == nil {
return nil
}
bs := ctx.bs
rootContract := ctx.curContract.callState.ctrState
var err error
for k, v := range ctx.callState {
if v.tx != nil {
err = v.tx.release()
if err != nil {
return newVmError(err)
}
}
if v.ctrState == rootContract {
continue
}
if v.ctrState != nil {
err = bs.StageContractState(v.ctrState)
if err != nil {
return newDbSystemError(err)
}
}
/* For Sender */
if v.prevState == nil {
continue
}
err = bs.PutState(k, v.curState)
if err != nil {
return newDbSystemError(err)
}
}
if ctx.traceFile != nil {
_, _ = ce.ctx.traceFile.WriteString("[Put State Balance]\n")
for k, v := range ctx.callState {
_, _ = ce.ctx.traceFile.WriteString(fmt.Sprintf("%s : nonce=%d ammount=%s\n",
k.String(), v.curState.GetNonce(), v.curState.GetBalanceBigInt().String()))
}
}
return nil
}
func (ce *executor) rollbackToSavepoint() error {
ctx := ce.ctx
if ctx == nil || ctx.callState == nil {
return nil
}
var err error
for id, v := range ctx.callState {
if v.prevState != nil && len(v.prevState.GetCodeHash()) == 0 &&
len(v.curState.GetCodeHash()) != 0 {
ctx.bs.RemoveCache(id)
}
if v.tx == nil {
continue
}
err = v.tx.rollbackToSavepoint()
if err != nil {
if strings.HasPrefix(err.Error(), "no such savepoint") {
_ = v.tx.begin()
}
return newVmError(err)
}
}
return nil
}
func (ce *executor) closeQuerySql() error {
ctx := ce.ctx
if ctx == nil || ctx.callState == nil {
return nil
}
var err error
for _, v := range ctx.callState {
if v.tx == nil {
continue
}
err = v.tx.close()
if err != nil {
return newVmError(err)
}
}
return nil
}
func (ce *executor) setGas() {
if ce == nil || ce.L == nil || ce.err != nil {
return
}
C.lua_gasset(ce.L, C.ulonglong(ce.ctx.remainedGas))
}
func (ce *executor) close() {
if ce != nil {
if ce.ctx != nil {
ce.ctx.callDepth--
if ce.ctx.traceFile != nil {
ce.ctx.traceFile.Close()
ce.ctx.traceFile = nil
}
}
if ce.L != nil {
FreeLState(ce.L)
}
}
}
func (ce *executor) refreshRemainingGas() {
ce.ctx.refreshRemainingGas(ce.L)
}
func (ce *executor) gas() uint64 {
return uint64(C.lua_gasget(ce.L))
}
func getCallInfo(ci interface{}, args []byte, contractAddress []byte) error {
d := json.NewDecoder(bytes.NewReader(args))
d.UseNumber()
d.DisallowUnknownFields()
err := d.Decode(ci)
if err != nil {
ctrLgr.Debug().AnErr("error", err).Str(
"contract",
types.EncodeAddress(contractAddress),
).Msg("invalid calling information")
}
return err
}
func Call(
contractState *state.ContractState,
payload, contractAddress []byte,
ctx *vmContext,
) (string, []*types.Event, *big.Int, error) {
var err error
var ci types.CallInfo
// get contract
contract := getContract(contractState, ctx.bs)
if contract != nil {
if len(payload) > 0 {
// get call arguments
err = getCallInfo(&ci, payload, contractAddress)
}
} else {
addr := types.EncodeAddress(contractAddress)
ctrLgr.Warn().Str("error", "not found contract").Str("contract", addr).Msg("call")
err = fmt.Errorf("not found contract %s", addr)
}
if err != nil {
return "", nil, ctx.usedFee(), err
}
if ctrLgr.IsDebugEnabled() {
ctrLgr.Debug().Str("abi", string(payload)).Str("contract", types.EncodeAddress(contractAddress)).Msg("call")
}
// create a new executor
contexts[ctx.service] = ctx
ce := newExecutor(contract, contractAddress, ctx, &ci, ctx.curContract.amount, false, false, contractState)
defer ce.close()
startTime := time.Now()
// execute the contract call
ce.call(callMaxInstLimit, nil)
vmExecTime := time.Now().Sub(startTime).Microseconds()
vmLogger.Trace().Int64("execµs", vmExecTime).Stringer("txHash", types.LogBase58(ce.ctx.txHash)).Msg("tx execute time in vm")
// check if there is an error
err = ce.err
if err != nil {
// rollback the state of the contract
if dbErr := ce.rollbackToSavepoint(); dbErr != nil {
ctrLgr.Error().Err(dbErr).Str("contract", types.EncodeAddress(contractAddress)).Msg("rollback state")
}
// log the error
if ctx.traceFile != nil {
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[error] : %s\n", err))
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[usedFee] : %s\n", ctx.usedFee().String()))
events := ce.getEvents()
if events != nil {
_, _ = ctx.traceFile.WriteString("[Event]\n")
for _, event := range events {
eventJson, _ := event.MarshalJSON()
_, _ = ctx.traceFile.Write(eventJson)
_, _ = ctx.traceFile.WriteString("\n")
}
}
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[CALL END] : %s(%s)\n",
types.EncodeAddress(contractAddress), types.ToAccountID(contractAddress)))
}
// return the error
return "", ce.getEvents(), ctx.usedFee(), err
}
// save the state of the contract
err = ce.commitCalledContract()
if err != nil {
ctrLgr.Error().Err(err).Str("contract", types.EncodeAddress(contractAddress)).Msg("commit state")
return "", ce.getEvents(), ctx.usedFee(), err
}
// log the result
if ctx.traceFile != nil {
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[ret] : %s\n", ce.jsonRet))
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[usedFee] : %s\n", ctx.usedFee().String()))
events := ce.getEvents()
if events != nil {
_, _ = ctx.traceFile.WriteString("[Event]\n")
for _, event := range events {
eventJson, _ := event.MarshalJSON()
_, _ = ctx.traceFile.Write(eventJson)
_, _ = ctx.traceFile.WriteString("\n")
}
}
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[CALL END] : %s(%s)\n",
types.EncodeAddress(contractAddress), types.ToAccountID(contractAddress)))
}
// return the result
return ce.jsonRet, ce.getEvents(), ctx.usedFee(), nil
}
func setRandomSeed(ctx *vmContext) {
var randSrc rand.Source
if ctx.isQuery {
randSrc = rand.NewSource(ctx.blockInfo.Ts)
} else {
b, _ := new(big.Int).SetString(enc.ToString(ctx.blockInfo.PrevBlockHash[:7]), 62)
t, _ := new(big.Int).SetString(enc.ToString(ctx.txHash[:7]), 62)
b.Add(b, t)
randSrc = rand.NewSource(b.Int64())
}
ctx.seed = rand.New(randSrc)
}
func PreCall(
ce *executor,
bs *state.BlockState,
sender *state.V,
contractState *state.ContractState,
rp, gasLimit uint64,
) (string, []*types.Event, *big.Int, error) {
var err error
defer ce.close()
ctx := ce.ctx
ctx.bs = bs
cs := ctx.curContract.callState
cs.ctrState = contractState
cs.curState = contractState.State
ctx.callState[sender.AccountID()] = &callState{curState: sender.State()}
ctx.curContract.rp = rp
ctx.gasLimit = gasLimit
ctx.remainedGas = gasLimit
if ctx.IsGasSystem() {
ce.setGas()
}
contexts[ctx.service] = ctx
// execute the contract call
ce.call(callMaxInstLimit, nil)
err = ce.err
if err == nil {
// save the state of the contract
err = ce.commitCalledContract()
if err != nil {
ctrLgr.Error().Err(err).Str(
"contract",
types.EncodeAddress(ctx.curContract.contractId),
).Msg("pre-call")
}
} else {
// rollback the state of the contract
if dbErr := ce.rollbackToSavepoint(); dbErr != nil {
ctrLgr.Error().Err(dbErr).Str(
"contract",
types.EncodeAddress(ctx.curContract.contractId),
).Msg("pre-call")
}
}
if ctx.traceFile != nil {
contractId := ctx.curContract.contractId
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[ret] : %s\n", ce.jsonRet))
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[usedFee] : %s\n", ctx.usedFee().String()))
events := ce.getEvents()
if events != nil {
_, _ = ctx.traceFile.WriteString("[Event]\n")
for _, event := range events {
eventJson, _ := event.MarshalJSON()
_, _ = ctx.traceFile.Write(eventJson)
_, _ = ctx.traceFile.WriteString("\n")
}
}
_, _ = ctx.traceFile.WriteString(fmt.Sprintf("[PRECALL END] : %s(%s)\n",
types.EncodeAddress(contractId), types.ToAccountID(contractId)))
}
return ce.jsonRet, ce.getEvents(), ctx.usedFee(), err
}
// loads a contract and prepares it for execution
func PreloadExecutor(bs *state.BlockState, contractState *state.ContractState, payload, contractAddress []byte,
ctx *vmContext) (*executor, error) {
var err error
var ci types.CallInfo