-
Notifications
You must be signed in to change notification settings - Fork 77
/
vm.go
2036 lines (1782 loc) · 52.3 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
package vm
import (
"crypto/elliptic"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/big"
"os"
"text/tabwriter"
"unicode/utf8"
"github.com/nspcc-dev/neo-go/pkg/core/interop/interopnames"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
"github.com/nspcc-dev/neo-go/pkg/encoding/bigint"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/nef"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm/invocations"
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
"github.com/nspcc-dev/neo-go/pkg/vm/vmstate"
)
type errorAtInstruct struct {
ip int
op opcode.Opcode
err any
}
func (e *errorAtInstruct) Error() string {
return fmt.Sprintf("at instruction %d (%s): %s", e.ip, e.op, e.err)
}
func newError(ip int, op opcode.Opcode, err any) *errorAtInstruct {
return &errorAtInstruct{ip: ip, op: op, err: err}
}
// StateMessage is a vm state message which could be used as an additional info, for example by cli.
type StateMessage string
const (
// MaxInvocationStackSize is the maximum size of an invocation stack.
MaxInvocationStackSize = 1024
// MaxTryNestingDepth is the maximum level of TRY nesting allowed,
// that is you can't have more exception handling contexts than this.
MaxTryNestingDepth = 16
// MaxStackSize is the maximum number of items allowed to be
// on all stacks at once.
MaxStackSize = 2 * 1024
maxSHLArg = stackitem.MaxBigIntegerSizeBits
)
// SyscallHandler is a type for syscall handler.
type SyscallHandler = func(*VM, uint32) error
// VM represents the virtual machine.
type VM struct {
state vmstate.State
// callback to get interop price
getPrice func(opcode.Opcode, []byte) int64
istack []*Context // invocation stack.
estack *Stack // execution stack.
uncaughtException stackitem.Item // exception being handled
refs refCounter
gasConsumed int64
GasLimit int64
// SyscallHandler handles SYSCALL opcode.
SyscallHandler func(v *VM, id uint32) error
// LoadToken handles CALLT opcode.
LoadToken func(id int32) error
trigger trigger.Type
// invTree is a top-level invocation tree (if enabled).
invTree *invocations.Tree
}
var (
bigMinusOne = big.NewInt(-1)
bigZero = big.NewInt(0)
bigOne = big.NewInt(1)
bigTwo = big.NewInt(2)
)
// New returns a new VM object ready to load AVM bytecode scripts.
func New() *VM {
return NewWithTrigger(trigger.Application)
}
// NewWithTrigger returns a new VM for executions triggered by t.
func NewWithTrigger(t trigger.Type) *VM {
vm := &VM{
state: vmstate.None,
trigger: t,
}
vm.istack = make([]*Context, 0, 8) // Most of invocations use one-two contracts, but they're likely to have internal calls.
vm.estack = newStack("evaluation", &vm.refs)
return vm
}
// SetPriceGetter registers the given PriceGetterFunc in v.
// f accepts vm's Context, current instruction and instruction parameter.
func (v *VM) SetPriceGetter(f func(opcode.Opcode, []byte) int64) {
v.getPrice = f
}
// Reset allows to reuse existing VM for subsequent executions making them somewhat
// more efficient. It reuses invocation and evaluation stacks as well as VM structure
// itself.
func (v *VM) Reset(t trigger.Type) {
v.state = vmstate.None
v.getPrice = nil
v.istack = v.istack[:0]
v.estack.elems = v.estack.elems[:0]
v.uncaughtException = nil
v.refs = 0
v.gasConsumed = 0
v.GasLimit = 0
v.SyscallHandler = nil
v.LoadToken = nil
v.trigger = t
v.invTree = nil
}
// GasConsumed returns the amount of GAS consumed during execution.
func (v *VM) GasConsumed() int64 {
return v.gasConsumed
}
// AddGas consumes the specified amount of gas. It returns true if gas limit wasn't exceeded.
func (v *VM) AddGas(gas int64) bool {
v.gasConsumed += gas
return v.GasLimit < 0 || v.gasConsumed <= v.GasLimit
}
// Estack returns the evaluation stack, so interop hooks can utilize this.
func (v *VM) Estack() *Stack {
return v.estack
}
// Istack returns the invocation stack, so interop hooks can utilize this.
func (v *VM) Istack() []*Context {
return v.istack
}
// PrintOps prints the opcodes of the current loaded program to stdout.
func (v *VM) PrintOps(out io.Writer) {
if out == nil {
out = os.Stdout
}
w := tabwriter.NewWriter(out, 0, 0, 4, ' ', 0)
fmt.Fprintln(w, "INDEX\tOPCODE\tPARAMETER")
realctx := v.Context()
ctx := &Context{sc: realctx.sc}
for {
cursor := ""
instr, parameter, err := ctx.Next()
if ctx.ip == realctx.ip {
cursor = "\t<<"
}
if err != nil {
fmt.Fprintf(w, "%d\t%s\tERROR: %s%s\n", ctx.ip, instr, err, cursor)
break
}
var desc = ""
if parameter != nil {
switch instr {
case opcode.JMP, opcode.JMPIF, opcode.JMPIFNOT, opcode.CALL,
opcode.JMPEQ, opcode.JMPNE,
opcode.JMPGT, opcode.JMPGE, opcode.JMPLE, opcode.JMPLT,
opcode.JMPL, opcode.JMPIFL, opcode.JMPIFNOTL, opcode.CALLL,
opcode.JMPEQL, opcode.JMPNEL,
opcode.JMPGTL, opcode.JMPGEL, opcode.JMPLEL, opcode.JMPLTL,
opcode.PUSHA, opcode.ENDTRY, opcode.ENDTRYL:
desc = getOffsetDesc(ctx, parameter)
case opcode.TRY, opcode.TRYL:
catchP, finallyP := getTryParams(instr, parameter)
desc = fmt.Sprintf("catch %s, finally %s",
getOffsetDesc(ctx, catchP), getOffsetDesc(ctx, finallyP))
case opcode.INITSSLOT:
desc = fmt.Sprint(parameter[0])
case opcode.CONVERT, opcode.ISTYPE:
typ := stackitem.Type(parameter[0])
desc = fmt.Sprintf("%s (%x)", typ, parameter[0])
case opcode.INITSLOT:
desc = fmt.Sprintf("%d local, %d arg", parameter[0], parameter[1])
case opcode.SYSCALL:
name, err := interopnames.FromID(GetInteropID(parameter))
if err != nil {
name = "not found"
}
desc = fmt.Sprintf("%s (%x)", name, parameter)
case opcode.PUSHINT8, opcode.PUSHINT16, opcode.PUSHINT32,
opcode.PUSHINT64, opcode.PUSHINT128, opcode.PUSHINT256:
val := bigint.FromBytes(parameter)
desc = fmt.Sprintf("%d (%x)", val, parameter)
case opcode.LDLOC, opcode.STLOC, opcode.LDARG, opcode.STARG, opcode.LDSFLD, opcode.STSFLD:
desc = fmt.Sprintf("%d (%x)", parameter[0], parameter)
default:
if utf8.Valid(parameter) {
desc = fmt.Sprintf("%x (%q)", parameter, parameter)
} else {
// Try converting the parameter to an address and swap the endianness
// if the parameter is a 20-byte value.
u, err := util.Uint160DecodeBytesBE(parameter)
if err == nil {
desc = fmt.Sprintf("%x (%q, %q)", parameter, address.Uint160ToString(u), "0x"+hex.EncodeToString(slice.CopyReverse(parameter)))
} else {
desc = fmt.Sprintf("%x", parameter)
}
}
}
}
fmt.Fprintf(w, "%d\t%s\t%s%s\n", ctx.ip, instr, desc, cursor)
if ctx.nextip >= len(ctx.sc.prog) {
break
}
}
w.Flush()
}
func getOffsetDesc(ctx *Context, parameter []byte) string {
offset, rOffset, err := calcJumpOffset(ctx, parameter)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
return fmt.Sprintf("%d (%d/%x)", offset, rOffset, parameter)
}
// AddBreakPoint adds a breakpoint to the current context.
func (v *VM) AddBreakPoint(n int) {
ctx := v.Context()
ctx.sc.breakPoints = append(ctx.sc.breakPoints, n)
}
// AddBreakPointRel adds a breakpoint relative to the current
// instruction pointer.
func (v *VM) AddBreakPointRel(n int) {
ctx := v.Context()
v.AddBreakPoint(ctx.nextip + n)
}
// LoadFileWithFlags loads a program in NEF format from the given path, ready to execute it.
func (v *VM) LoadFileWithFlags(path string, f callflag.CallFlag) error {
b, err := os.ReadFile(path)
if err != nil {
return err
}
nef, err := nef.FileFromBytes(b)
if err != nil {
return err
}
v.LoadWithFlags(nef.Script, f)
return nil
}
// CollectInvocationTree enables collecting invocation tree data.
func (v *VM) EnableInvocationTree() {
v.invTree = &invocations.Tree{}
}
// GetInvocationTree returns the current invocation tree structure.
func (v *VM) GetInvocationTree() *invocations.Tree {
return v.invTree
}
// Load initializes the VM with the program given.
func (v *VM) Load(prog []byte) {
v.LoadWithFlags(prog, callflag.NoneFlag)
}
// LoadWithFlags initializes the VM with the program and flags given.
func (v *VM) LoadWithFlags(prog []byte, f callflag.CallFlag) {
// Clear all stacks and state, it could be a reload.
v.istack = v.istack[:0]
v.estack.Clear()
v.state = vmstate.None
v.gasConsumed = 0
v.invTree = nil
v.LoadScriptWithFlags(prog, f)
}
// LoadScript loads a script from the internal script table. It
// will immediately push a new context created from this script to
// the invocation stack and starts executing it.
func (v *VM) LoadScript(b []byte) {
v.LoadScriptWithFlags(b, callflag.NoneFlag)
}
// LoadScriptWithFlags loads script and sets call flag to f.
func (v *VM) LoadScriptWithFlags(b []byte, f callflag.CallFlag) {
v.loadScriptWithCallingHash(b, nil, v.GetCurrentScriptHash(), util.Uint160{}, f, -1, 0, nil)
}
// LoadDynamicScript loads the given script with the given flags. This script is
// considered to be dynamic, it can either return no value at all or return
// exactly one value.
func (v *VM) LoadDynamicScript(b []byte, f callflag.CallFlag) {
v.loadScriptWithCallingHash(b, nil, v.GetCurrentScriptHash(), util.Uint160{}, f, -1, 0, DynamicOnUnload)
}
// LoadScriptWithHash is similar to the LoadScriptWithFlags method, but it also loads
// the given script hash directly into the Context to avoid its recalculations and to make
// it possible to override it for deployed contracts with special hashes (the function
// assumes that it is used for deployed contracts setting context's parameters
// accordingly). It's up to the user of this function to make sure the script and hash match
// each other.
func (v *VM) LoadScriptWithHash(b []byte, hash util.Uint160, f callflag.CallFlag) {
v.loadScriptWithCallingHash(b, nil, v.GetCurrentScriptHash(), hash, f, 1, 0, nil)
}
// LoadNEFMethod allows to create a context to execute a method from the NEF
// file with the specified caller and executing hash, call flags, return value,
// method and _initialize offsets.
func (v *VM) LoadNEFMethod(exe *nef.File, caller util.Uint160, hash util.Uint160, f callflag.CallFlag,
hasReturn bool, methodOff int, initOff int, onContextUnload ContextUnloadCallback) {
var rvcount int
if hasReturn {
rvcount = 1
}
v.loadScriptWithCallingHash(exe.Script, exe, caller, hash, f, rvcount, methodOff, onContextUnload)
if initOff >= 0 {
v.Call(initOff)
}
}
// loadScriptWithCallingHash is similar to LoadScriptWithHash but sets calling hash explicitly.
// It should be used for calling from native contracts.
func (v *VM) loadScriptWithCallingHash(b []byte, exe *nef.File, caller util.Uint160,
hash util.Uint160, f callflag.CallFlag, rvcount int, offset int, onContextUnload ContextUnloadCallback) {
v.checkInvocationStackSize()
ctx := NewContextWithParams(b, rvcount, offset)
parent := v.Context()
if parent != nil {
ctx.sc.callingContext = parent.sc
parent.sc.estack = v.estack
}
if rvcount != -1 || v.estack.Len() != 0 {
v.estack = subStack(v.estack)
}
ctx.sc.estack = v.estack
initStack(&ctx.tryStack, "exception", nil)
ctx.sc.callFlag = f
ctx.sc.scriptHash = hash
ctx.sc.callingScriptHash = caller
ctx.sc.NEF = exe
if v.invTree != nil {
curTree := v.invTree
if parent != nil {
curTree = parent.sc.invTree
}
newTree := &invocations.Tree{Current: ctx.ScriptHash()}
curTree.Calls = append(curTree.Calls, newTree)
ctx.sc.invTree = newTree
}
ctx.sc.onUnload = onContextUnload
v.istack = append(v.istack, ctx)
}
// Context returns the current executed context. Nil if there is no context,
// which implies no program is loaded.
func (v *VM) Context() *Context {
if len(v.istack) == 0 {
return nil
}
return v.istack[len(v.istack)-1]
}
// PopResult is used to pop the first item of the evaluation stack. This allows
// us to test the compiler and the vm in a bi-directional way.
func (v *VM) PopResult() any {
if v.estack.Len() == 0 {
return nil
}
return v.estack.Pop().Value()
}
// DumpIStack returns json formatted representation of the invocation stack.
func (v *VM) DumpIStack() string {
b, _ := json.MarshalIndent(v.istack, "", " ")
return string(b)
}
// DumpEStack returns json formatted representation of the execution stack.
func (v *VM) DumpEStack() string {
return dumpStack(v.estack)
}
// dumpStack returns json formatted representation of the given stack.
func dumpStack(s *Stack) string {
b, _ := json.MarshalIndent(s, "", " ")
return string(b)
}
// State returns the state for the VM.
func (v *VM) State() vmstate.State {
return v.state
}
// Ready returns true if the VM is ready to execute the loaded program.
// It will return false if no program is loaded.
func (v *VM) Ready() bool {
return len(v.istack) > 0
}
// Run starts execution of the loaded program.
func (v *VM) Run() error {
var ctx *Context
if !v.Ready() {
v.state = vmstate.Fault
return errors.New("no program loaded")
}
if v.state.HasFlag(vmstate.Fault) {
// VM already ran something and failed, in general its state is
// undefined in this case so we can't run anything.
return errors.New("VM has failed")
}
// vmstate.Halt (the default) or vmstate.Break are safe to continue.
v.state = vmstate.None
ctx = v.Context()
for {
switch {
case v.state.HasFlag(vmstate.Fault):
// Should be caught and reported already by the v.Step(),
// but we're checking here anyway just in case.
return errors.New("VM has failed")
case v.state.HasFlag(vmstate.Halt), v.state.HasFlag(vmstate.Break):
// Normal exit from this loop.
return nil
case v.state == vmstate.None:
if err := v.step(ctx); err != nil {
return err
}
default:
v.state = vmstate.Fault
return errors.New("unknown state")
}
// check for breakpoint before executing the next instruction
ctx = v.Context()
if ctx != nil && ctx.atBreakPoint() {
v.state = vmstate.Break
}
}
}
// Step 1 instruction in the program.
func (v *VM) Step() error {
ctx := v.Context()
return v.step(ctx)
}
// step executes one instruction in the given context.
func (v *VM) step(ctx *Context) error {
op, param, err := ctx.Next()
if err != nil {
v.state = vmstate.Fault
return newError(ctx.ip, op, err)
}
return v.execute(ctx, op, param)
}
// StepInto behaves the same as “step over” in case the line does not contain a function. Otherwise,
// the debugger will enter the called function and continue line-by-line debugging there.
func (v *VM) StepInto() error {
ctx := v.Context()
if ctx == nil {
v.state = vmstate.Halt
}
if v.HasStopped() {
return nil
}
if ctx != nil && ctx.sc.prog != nil {
op, param, err := ctx.Next()
if err != nil {
v.state = vmstate.Fault
return newError(ctx.ip, op, err)
}
vErr := v.execute(ctx, op, param)
if vErr != nil {
return vErr
}
}
cctx := v.Context()
if cctx != nil && cctx.atBreakPoint() {
v.state = vmstate.Break
}
return nil
}
// StepOut takes the debugger to the line where the current function was called.
func (v *VM) StepOut() error {
var err error
if v.state == vmstate.Break {
v.state = vmstate.None
}
expSize := len(v.istack)
for v.state == vmstate.None && len(v.istack) >= expSize {
err = v.StepInto()
}
if v.state == vmstate.None {
v.state = vmstate.Break
}
return err
}
// StepOver takes the debugger to the line that will step over the given line.
// If the line contains a function, the function will be executed and the result is returned without debugging each line.
func (v *VM) StepOver() error {
var err error
if v.HasStopped() {
return err
}
if v.state == vmstate.Break {
v.state = vmstate.None
}
expSize := len(v.istack)
for {
err = v.StepInto()
if !(v.state == vmstate.None && len(v.istack) > expSize) {
break
}
}
if v.state == vmstate.None {
v.state = vmstate.Break
}
return err
}
// HasFailed returns whether the VM is in the failed state now. Usually, it's used to
// check status after Run.
func (v *VM) HasFailed() bool {
return v.state.HasFlag(vmstate.Fault)
}
// HasStopped returns whether the VM is in the Halt or Failed state.
func (v *VM) HasStopped() bool {
return v.state.HasFlag(vmstate.Halt) || v.state.HasFlag(vmstate.Fault)
}
// HasHalted returns whether the VM is in the Halt state.
func (v *VM) HasHalted() bool {
return v.state.HasFlag(vmstate.Halt)
}
// AtBreakpoint returns whether the VM is at breakpoint.
func (v *VM) AtBreakpoint() bool {
return v.state.HasFlag(vmstate.Break)
}
// GetInteropID converts instruction parameter to an interop ID.
func GetInteropID(parameter []byte) uint32 {
return binary.LittleEndian.Uint32(parameter)
}
// execute performs an instruction cycle in the VM. Acting on the instruction (opcode).
func (v *VM) execute(ctx *Context, op opcode.Opcode, parameter []byte) (err error) {
// Instead of polluting the whole VM logic with error handling, we will recover
// each panic at a central point, putting the VM in a fault state and setting error.
defer func() {
if errRecover := recover(); errRecover != nil {
v.state = vmstate.Fault
err = newError(ctx.ip, op, errRecover)
} else if v.refs > MaxStackSize {
v.state = vmstate.Fault
err = newError(ctx.ip, op, "stack is too big")
}
}()
if v.getPrice != nil && ctx.ip < len(ctx.sc.prog) {
v.gasConsumed += v.getPrice(op, parameter)
if v.GasLimit >= 0 && v.gasConsumed > v.GasLimit {
panic("gas limit is exceeded")
}
}
if op <= opcode.PUSHINT256 {
v.estack.PushItem(stackitem.NewBigInteger(bigint.FromBytes(parameter)))
return
}
switch op {
case opcode.PUSHM1, opcode.PUSH0, opcode.PUSH1, opcode.PUSH2, opcode.PUSH3,
opcode.PUSH4, opcode.PUSH5, opcode.PUSH6, opcode.PUSH7,
opcode.PUSH8, opcode.PUSH9, opcode.PUSH10, opcode.PUSH11,
opcode.PUSH12, opcode.PUSH13, opcode.PUSH14, opcode.PUSH15,
opcode.PUSH16:
val := int(op) - int(opcode.PUSH0)
v.estack.PushItem(stackitem.NewBigInteger(big.NewInt(int64(val))))
case opcode.PUSHDATA1, opcode.PUSHDATA2, opcode.PUSHDATA4:
v.estack.PushItem(stackitem.NewByteArray(parameter))
case opcode.PUSHT, opcode.PUSHF:
v.estack.PushItem(stackitem.NewBool(op == opcode.PUSHT))
case opcode.PUSHA:
n := getJumpOffset(ctx, parameter)
ptr := stackitem.NewPointerWithHash(n, ctx.sc.prog, ctx.ScriptHash())
v.estack.PushItem(ptr)
case opcode.PUSHNULL:
v.estack.PushItem(stackitem.Null{})
case opcode.ISNULL:
_, ok := v.estack.Pop().value.(stackitem.Null)
v.estack.PushItem(stackitem.Bool(ok))
case opcode.ISTYPE:
res := v.estack.Pop().Item()
v.estack.PushItem(stackitem.Bool(res.Type() == stackitem.Type(parameter[0])))
case opcode.CONVERT:
typ := stackitem.Type(parameter[0])
item := v.estack.Pop().Item()
result, err := item.Convert(typ)
if err != nil {
panic(err)
}
v.estack.PushItem(result)
case opcode.INITSSLOT:
if parameter[0] == 0 {
panic("zero argument")
}
ctx.sc.static.init(int(parameter[0]), &v.refs)
case opcode.INITSLOT:
if ctx.local != nil || ctx.arguments != nil {
panic("already initialized")
}
if parameter[0] == 0 && parameter[1] == 0 {
panic("zero argument")
}
if parameter[0] > 0 {
ctx.local.init(int(parameter[0]), &v.refs)
}
if parameter[1] > 0 {
sz := int(parameter[1])
ctx.arguments.init(sz, &v.refs)
for i := 0; i < sz; i++ {
ctx.arguments.Set(i, v.estack.Pop().Item(), &v.refs)
}
}
case opcode.LDSFLD0, opcode.LDSFLD1, opcode.LDSFLD2, opcode.LDSFLD3, opcode.LDSFLD4, opcode.LDSFLD5, opcode.LDSFLD6:
item := ctx.sc.static.Get(int(op - opcode.LDSFLD0))
v.estack.PushItem(item)
case opcode.LDSFLD:
item := ctx.sc.static.Get(int(parameter[0]))
v.estack.PushItem(item)
case opcode.STSFLD0, opcode.STSFLD1, opcode.STSFLD2, opcode.STSFLD3, opcode.STSFLD4, opcode.STSFLD5, opcode.STSFLD6:
item := v.estack.Pop().Item()
ctx.sc.static.Set(int(op-opcode.STSFLD0), item, &v.refs)
case opcode.STSFLD:
item := v.estack.Pop().Item()
ctx.sc.static.Set(int(parameter[0]), item, &v.refs)
case opcode.LDLOC0, opcode.LDLOC1, opcode.LDLOC2, opcode.LDLOC3, opcode.LDLOC4, opcode.LDLOC5, opcode.LDLOC6:
item := ctx.local.Get(int(op - opcode.LDLOC0))
v.estack.PushItem(item)
case opcode.LDLOC:
item := ctx.local.Get(int(parameter[0]))
v.estack.PushItem(item)
case opcode.STLOC0, opcode.STLOC1, opcode.STLOC2, opcode.STLOC3, opcode.STLOC4, opcode.STLOC5, opcode.STLOC6:
item := v.estack.Pop().Item()
ctx.local.Set(int(op-opcode.STLOC0), item, &v.refs)
case opcode.STLOC:
item := v.estack.Pop().Item()
ctx.local.Set(int(parameter[0]), item, &v.refs)
case opcode.LDARG0, opcode.LDARG1, opcode.LDARG2, opcode.LDARG3, opcode.LDARG4, opcode.LDARG5, opcode.LDARG6:
item := ctx.arguments.Get(int(op - opcode.LDARG0))
v.estack.PushItem(item)
case opcode.LDARG:
item := ctx.arguments.Get(int(parameter[0]))
v.estack.PushItem(item)
case opcode.STARG0, opcode.STARG1, opcode.STARG2, opcode.STARG3, opcode.STARG4, opcode.STARG5, opcode.STARG6:
item := v.estack.Pop().Item()
ctx.arguments.Set(int(op-opcode.STARG0), item, &v.refs)
case opcode.STARG:
item := v.estack.Pop().Item()
ctx.arguments.Set(int(parameter[0]), item, &v.refs)
case opcode.NEWBUFFER:
n := toInt(v.estack.Pop().BigInt())
if n < 0 || n > stackitem.MaxSize {
panic("invalid size")
}
v.estack.PushItem(stackitem.NewBuffer(make([]byte, n)))
case opcode.MEMCPY:
n := toInt(v.estack.Pop().BigInt())
if n < 0 {
panic("invalid size")
}
si := toInt(v.estack.Pop().BigInt())
if si < 0 {
panic("invalid source index")
}
src := v.estack.Pop().Bytes()
if sum := si + n; sum < 0 || sum > len(src) {
panic("size is too big")
}
di := toInt(v.estack.Pop().BigInt())
if di < 0 {
panic("invalid destination index")
}
dst := v.estack.Pop().value.(*stackitem.Buffer).Value().([]byte)
if sum := di + n; sum < 0 || sum > len(dst) {
panic("size is too big")
}
copy(dst[di:], src[si:si+n])
case opcode.CAT:
b := v.estack.Pop().Bytes()
a := v.estack.Pop().Bytes()
l := len(a) + len(b)
if l > stackitem.MaxSize {
panic(fmt.Sprintf("too big item: %d", l))
}
ab := make([]byte, l)
copy(ab, a)
copy(ab[len(a):], b)
v.estack.PushItem(stackitem.NewBuffer(ab))
case opcode.SUBSTR:
l := toInt(v.estack.Pop().BigInt())
if l < 0 {
panic("negative length")
}
o := toInt(v.estack.Pop().BigInt())
if o < 0 {
panic("negative index")
}
s := v.estack.Pop().Bytes()
last := l + o
if last > len(s) {
panic("invalid offset")
}
res := make([]byte, l)
copy(res, s[o:last])
v.estack.PushItem(stackitem.NewBuffer(res))
case opcode.LEFT:
l := toInt(v.estack.Pop().BigInt())
if l < 0 {
panic("negative length")
}
s := v.estack.Pop().Bytes()
if t := len(s); l > t {
panic("size is too big")
}
res := make([]byte, l)
copy(res, s[:l])
v.estack.PushItem(stackitem.NewBuffer(res))
case opcode.RIGHT:
l := toInt(v.estack.Pop().BigInt())
if l < 0 {
panic("negative length")
}
s := v.estack.Pop().Bytes()
res := make([]byte, l)
copy(res, s[len(s)-l:])
v.estack.PushItem(stackitem.NewBuffer(res))
case opcode.DEPTH:
v.estack.PushItem(stackitem.NewBigInteger(big.NewInt(int64(v.estack.Len()))))
case opcode.DROP:
if v.estack.Len() < 1 {
panic("stack is too small")
}
v.estack.Pop()
case opcode.NIP:
if v.estack.Len() < 2 {
panic("no second element found")
}
_ = v.estack.RemoveAt(1)
case opcode.XDROP:
n := toInt(v.estack.Pop().BigInt())
if n < 0 {
panic("invalid length")
}
if v.estack.Len() < n+1 {
panic("bad index")
}
_ = v.estack.RemoveAt(n)
case opcode.CLEAR:
v.estack.Clear()
case opcode.DUP:
v.estack.Push(v.estack.Dup(0))
case opcode.OVER:
if v.estack.Len() < 2 {
panic("no second element found")
}
a := v.estack.Dup(1)
v.estack.Push(a)
case opcode.PICK:
n := toInt(v.estack.Pop().BigInt())
if n < 0 {
panic("negative stack item returned")
}
if v.estack.Len() < n+1 {
panic("no nth element found")
}
a := v.estack.Dup(n)
v.estack.Push(a)
case opcode.TUCK:
if v.estack.Len() < 2 {
panic("too short stack to TUCK")
}
a := v.estack.Dup(0)
v.estack.InsertAt(a, 2)
case opcode.SWAP:
err := v.estack.Swap(1, 0)
if err != nil {
panic(err.Error())
}
case opcode.ROT:
err := v.estack.Roll(2)
if err != nil {
panic(err.Error())
}
case opcode.ROLL:
n := toInt(v.estack.Pop().BigInt())
err := v.estack.Roll(n)
if err != nil {
panic(err.Error())
}
case opcode.REVERSE3, opcode.REVERSE4, opcode.REVERSEN:
n := 3
switch op {
case opcode.REVERSE4:
n = 4
case opcode.REVERSEN:
n = toInt(v.estack.Pop().BigInt())
}
if err := v.estack.ReverseTop(n); err != nil {
panic(err.Error())
}
// Bit operations.
case opcode.INVERT:
i := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Not(i)))
case opcode.AND:
b := v.estack.Pop().BigInt()
a := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).And(b, a)))
case opcode.OR:
b := v.estack.Pop().BigInt()
a := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Or(b, a)))
case opcode.XOR:
b := v.estack.Pop().BigInt()
a := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Xor(b, a)))
case opcode.EQUAL, opcode.NOTEQUAL:
if v.estack.Len() < 2 {
panic("need a pair of elements on the stack")
}
b := v.estack.Pop()
a := v.estack.Pop()
res := stackitem.Bool(a.value.Equals(b.value) == (op == opcode.EQUAL))
v.estack.PushItem(res)
// Numeric operations.
case opcode.SIGN:
x := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(big.NewInt(int64(x.Sign()))))
case opcode.ABS:
x := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Abs(x)))
case opcode.NEGATE:
x := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Neg(x)))
case opcode.INC:
x := v.estack.Pop().BigInt()
a := new(big.Int).Add(x, bigOne)
v.estack.PushItem(stackitem.NewBigInteger(a))
case opcode.DEC:
x := v.estack.Pop().BigInt()
a := new(big.Int).Sub(x, bigOne)
v.estack.PushItem(stackitem.NewBigInteger(a))
case opcode.ADD:
a := v.estack.Pop().BigInt()
b := v.estack.Pop().BigInt()
c := new(big.Int).Add(a, b)
v.estack.PushItem(stackitem.NewBigInteger(c))
case opcode.SUB:
b := v.estack.Pop().BigInt()
a := v.estack.Pop().BigInt()
c := new(big.Int).Sub(a, b)
v.estack.PushItem(stackitem.NewBigInteger(c))
case opcode.MUL:
a := v.estack.Pop().BigInt()
b := v.estack.Pop().BigInt()
c := new(big.Int).Mul(a, b)
v.estack.PushItem(stackitem.NewBigInteger(c))
case opcode.DIV:
b := v.estack.Pop().BigInt()
a := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Quo(a, b)))
case opcode.MOD:
b := v.estack.Pop().BigInt()
a := v.estack.Pop().BigInt()
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Rem(a, b)))
case opcode.POW:
exp := v.estack.Pop().BigInt()
a := v.estack.Pop().BigInt()
if ei := exp.Uint64(); !exp.IsUint64() || ei > maxSHLArg {
panic("invalid exponent")
}
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Exp(a, exp, nil)))
case opcode.SQRT:
a := v.estack.Pop().BigInt()
if a.Sign() == -1 {
panic("negative value")
}
v.estack.PushItem(stackitem.NewBigInteger(new(big.Int).Sqrt(a)))
case opcode.MODMUL:
modulus := v.estack.Pop().BigInt()
if modulus.Sign() == 0 {
panic("zero modulus")
}
x2 := v.estack.Pop().BigInt()