-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathitem.go
1265 lines (1103 loc) · 28.5 KB
/
item.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 stackitem
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"reflect"
"unicode/utf8"
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/encoding/bigint"
"github.com/nspcc-dev/neo-go/pkg/util"
)
const (
// MaxBigIntegerSizeBits is the maximum size of a BigInt item in bits.
MaxBigIntegerSizeBits = 32 * 8
// MaxSize is the maximum item size allowed in the VM.
MaxSize = math.MaxUint16 * 2
// MaxComparableNumOfItems is the maximum number of items that can be compared for structs.
MaxComparableNumOfItems = MaxDeserialized
// MaxClonableNumOfItems is the maximum number of items that can be cloned in structs.
MaxClonableNumOfItems = MaxDeserialized
// MaxByteArrayComparableSize is the maximum allowed length of a ByteArray for Equals method.
// It is set to be the maximum uint16 value + 1.
MaxByteArrayComparableSize = math.MaxUint16 + 1
// MaxKeySize is the maximum size of a map key.
MaxKeySize = 64
)
// Item represents the "real" value that is pushed on the stack.
type Item interface {
fmt.Stringer
Value() any
// Dup duplicates current Item.
Dup() Item
// TryBool converts Item to a boolean value.
TryBool() (bool, error)
// TryBytes converts Item to a byte slice. If the underlying type is a
// byte slice, it's returned as is without copying.
TryBytes() ([]byte, error)
// TryInteger converts Item to an integer.
TryInteger() (*big.Int, error)
// Equals checks if 2 StackItems are equal.
Equals(s Item) bool
// Type returns stack item type.
Type() Type
// Convert converts Item to another type.
Convert(Type) (Item, error)
}
// Convertible is something that can be converted to/from Item.
type Convertible interface {
ToStackItem() (Item, error)
FromStackItem(Item) error
}
// Equatable describes a special value of Interop that can be compared with
// value of some other Interop that implements Equatable.
type Equatable interface {
// Equals checks if two objects are equal.
Equals(other Equatable) bool
}
var (
// ErrInvalidConversion is returned upon an attempt to make an incorrect
// conversion between item types.
ErrInvalidConversion = errors.New("invalid conversion")
// ErrTooBig is returned when an item exceeds some size constraints, like
// the maximum allowed integer value of the number of elements in an array. It
// can also be returned by serialization functions if the resulting
// value exceeds MaxSize.
ErrTooBig = errors.New("too big")
// ErrReadOnly is returned on attempt to modify immutable stack item.
ErrReadOnly = errors.New("item is read-only")
errTooBigComparable = fmt.Errorf("%w: uncomparable", ErrTooBig)
errTooBigInteger = fmt.Errorf("%w: integer", ErrTooBig)
errTooBigKey = fmt.Errorf("%w: map key", ErrTooBig)
errTooBigSize = fmt.Errorf("%w: size", ErrTooBig)
errTooBigElements = fmt.Errorf("%w: many elements", ErrTooBig)
)
// mkInvConversion creates a conversion error with additional metadata (from and
// to types).
func mkInvConversion(from Item, to Type) error {
return fmt.Errorf("%w: %s/%s", ErrInvalidConversion, from, to)
}
// Make tries to make an appropriate stack item from the provided value.
// It will panic if it's not possible.
func Make(v any) Item {
switch val := v.(type) {
case int:
return (*BigInteger)(big.NewInt(int64(val)))
case int64:
return (*BigInteger)(big.NewInt(val))
case uint8:
return (*BigInteger)(big.NewInt(int64(val)))
case uint16:
return (*BigInteger)(big.NewInt(int64(val)))
case uint32:
return (*BigInteger)(big.NewInt(int64(val)))
case uint64:
return (*BigInteger)(new(big.Int).SetUint64(val))
case []byte:
return NewByteArray(val)
case string:
return NewByteArray([]byte(val))
case bool:
return Bool(val)
case []Item:
return &Array{
value: val,
}
case *big.Int:
return NewBigInteger(val)
case Item:
return val
case []int:
var a []Item
for _, i := range val {
a = append(a, Make(i))
}
return Make(a)
case []any:
res := make([]Item, len(val))
for i := range val {
res[i] = Make(val[i])
}
return Make(res)
case util.Uint160:
return Make(val.BytesBE())
case util.Uint256:
return Make(val.BytesBE())
case *util.Uint160:
if val == nil {
return Null{}
}
return Make(*val)
case *util.Uint256:
if val == nil {
return Null{}
}
return Make(*val)
case nil:
return Null{}
default:
i64T := reflect.TypeOf(int64(0))
if reflect.TypeOf(val).ConvertibleTo(i64T) {
i64Val := reflect.ValueOf(val).Convert(i64T).Interface()
return Make(i64Val)
}
panic(
fmt.Sprintf(
"invalid stack item type: %v (%v)",
val,
reflect.TypeOf(val),
),
)
}
}
// ToString converts an Item to a string if it is a valid UTF-8.
func ToString(item Item) (string, error) {
bs, err := item.TryBytes()
if err != nil {
return "", err
}
if !utf8.Valid(bs) {
return "", fmt.Errorf("%w: not UTF-8", ErrInvalidValue)
}
return string(bs), nil
}
// convertPrimitive converts a primitive item to the specified type.
func convertPrimitive(item Item, typ Type) (Item, error) {
if item.Type() == typ {
return item, nil
}
switch typ {
case IntegerT:
bi, err := item.TryInteger()
if err != nil {
return nil, err
}
return NewBigInteger(bi), nil
case ByteArrayT, BufferT:
b, err := item.TryBytes()
if err != nil {
return nil, err
}
if typ == BufferT {
return NewBuffer(bytes.Clone(b)), nil
}
// ByteArray can't really be changed, so it's OK to reuse `b`.
return NewByteArray(b), nil
case BooleanT:
b, err := item.TryBool()
if err != nil {
return nil, err
}
return NewBool(b), nil
default:
return nil, mkInvConversion(item, typ)
}
}
// Struct represents a struct on the stack.
type Struct struct {
value []Item
rc
ro
}
// NewStruct returns a new Struct object.
func NewStruct(items []Item) *Struct {
return &Struct{
value: items,
}
}
// Value implements the Item interface.
func (i *Struct) Value() any {
return i.value
}
// Remove removes the element at `pos` index from the Struct value.
// It will panic if a bad index given.
func (i *Struct) Remove(pos int) {
if i.IsReadOnly() {
panic(ErrReadOnly)
}
i.value = append(i.value[:pos], i.value[pos+1:]...)
}
// Append adds an Item to the end of the Struct value.
func (i *Struct) Append(item Item) {
if i.IsReadOnly() {
panic(ErrReadOnly)
}
i.value = append(i.value, item)
}
// Clear removes all elements from the Struct item value.
func (i *Struct) Clear() {
if i.IsReadOnly() {
panic(ErrReadOnly)
}
i.value = i.value[:0]
}
// Len returns the length of the Struct value.
func (i *Struct) Len() int {
return len(i.value)
}
// String implements the Item interface.
func (i *Struct) String() string {
return "Struct"
}
// Dup implements the Item interface.
func (i *Struct) Dup() Item {
// it's a reference type, so no copying here.
return i
}
// TryBool implements the Item interface.
func (i *Struct) TryBool() (bool, error) { return true, nil }
// TryBytes implements the Item interface.
func (i *Struct) TryBytes() ([]byte, error) {
return nil, mkInvConversion(i, ByteArrayT)
}
// TryInteger implements the Item interface.
func (i *Struct) TryInteger() (*big.Int, error) {
return nil, mkInvConversion(i, IntegerT)
}
// Equals implements the Item interface.
func (i *Struct) Equals(s Item) bool {
if s == nil {
return false
}
val, ok := s.(*Struct)
if !ok {
return false
}
var limit = MaxComparableNumOfItems - 1 // 1 for current element.
return i.equalStruct(val, &limit)
}
func (i *Struct) equalStruct(s *Struct, limit *int) bool {
if i == s {
return true
} else if len(i.value) != len(s.value) {
return false
}
var maxComparableSize = MaxByteArrayComparableSize
for j := range i.value {
*limit--
if *limit == 0 {
panic(errTooBigElements)
}
arr, ok := i.value[j].(*ByteArray)
if ok {
if !arr.equalsLimited(s.value[j], &maxComparableSize) {
return false
}
} else {
if maxComparableSize == 0 {
panic(errTooBigComparable)
}
maxComparableSize--
sa, oka := i.value[j].(*Struct)
sb, okb := s.value[j].(*Struct)
if oka && okb {
if !sa.equalStruct(sb, limit) {
return false
}
} else if !i.value[j].Equals(s.value[j]) {
return false
}
}
}
return true
}
// Type implements the Item interface.
func (i *Struct) Type() Type { return StructT }
// Convert implements the Item interface.
func (i *Struct) Convert(typ Type) (Item, error) {
switch typ {
case StructT:
return i, nil
case ArrayT:
arr := make([]Item, len(i.value))
copy(arr, i.value)
return NewArray(arr), nil
case BooleanT:
return NewBool(true), nil
default:
return nil, mkInvConversion(i, typ)
}
}
// Clone returns a Struct with all Struct fields copied by the value.
// Array fields are still copied by reference.
func (i *Struct) Clone() (*Struct, error) {
var limit = MaxClonableNumOfItems - 1 // For this struct itself.
return i.clone(&limit)
}
func (i *Struct) clone(limit *int) (*Struct, error) {
ret := &Struct{value: make([]Item, len(i.value))}
for j := range i.value {
*limit--
if *limit < 0 {
return nil, ErrTooBig
}
switch t := i.value[j].(type) {
case *Struct:
var err error
ret.value[j], err = t.clone(limit)
if err != nil {
return nil, err
}
default:
ret.value[j] = t
}
}
return ret, nil
}
// Null represents null on the stack.
type Null struct{}
// String implements the Item interface.
func (i Null) String() string {
return "Null"
}
// Value implements the Item interface.
func (i Null) Value() any {
return nil
}
// Dup implements the Item interface.
// There is no need to perform a real copy here
// since Null has no internal state.
func (i Null) Dup() Item {
return i
}
// TryBool implements the Item interface.
func (i Null) TryBool() (bool, error) { return false, nil }
// TryBytes implements the Item interface.
func (i Null) TryBytes() ([]byte, error) {
return nil, mkInvConversion(i, ByteArrayT)
}
// TryInteger implements the Item interface.
func (i Null) TryInteger() (*big.Int, error) {
return nil, mkInvConversion(i, IntegerT)
}
// Equals implements the Item interface.
func (i Null) Equals(s Item) bool {
_, ok := s.(Null)
return ok
}
// Type implements the Item interface.
func (i Null) Type() Type { return AnyT }
// Convert implements the Item interface.
func (i Null) Convert(typ Type) (Item, error) {
if typ == AnyT || !typ.IsValid() {
return nil, mkInvConversion(i, typ)
}
return i, nil
}
// BigInteger represents a big integer on the stack.
type BigInteger big.Int
// NewBigInteger returns an new BigInteger object.
func NewBigInteger(value *big.Int) *BigInteger {
if err := CheckIntegerSize(value); err != nil {
panic(err)
}
return (*BigInteger)(value)
}
// CheckIntegerSize checks that the value size doesn't exceed the VM limit for Interer.
func CheckIntegerSize(value *big.Int) error {
// There are 2 cases when `BitLen` differs from the actual size:
// 1. Positive integer with the highest bit on byte boundary = 1.
// 2. Negative integer with the highest bit on byte boundary = 1
// minus some value. (-0x80 -> 0x80, -0x7F -> 0x81, -0x81 -> 0x7FFF).
sz := value.BitLen()
// This check is not required, just an optimization for the common case.
if sz < MaxBigIntegerSizeBits {
return nil
}
if sz > MaxBigIntegerSizeBits {
return errTooBigInteger
}
if value.Sign() == 1 || value.TrailingZeroBits() != MaxBigIntegerSizeBits-1 {
return errTooBigInteger
}
return nil
}
// Big casts i to the big.Int type.
func (i *BigInteger) Big() *big.Int {
return (*big.Int)(i)
}
// Bytes converts i to a slice of bytes.
func (i *BigInteger) Bytes() []byte {
return bigint.ToBytes(i.Big())
}
// TryBool implements the Item interface.
func (i *BigInteger) TryBool() (bool, error) {
return i.Big().Sign() != 0, nil
}
// TryBytes implements the Item interface.
func (i *BigInteger) TryBytes() ([]byte, error) {
return i.Bytes(), nil
}
// TryInteger implements the Item interface.
func (i *BigInteger) TryInteger() (*big.Int, error) {
return i.Big(), nil
}
// Equals implements the Item interface.
func (i *BigInteger) Equals(s Item) bool {
if i == s {
return true
} else if s == nil {
return false
}
val, ok := s.(*BigInteger)
return ok && i.Big().Cmp(val.Big()) == 0
}
// Value implements the Item interface.
func (i *BigInteger) Value() any {
return i.Big()
}
func (i *BigInteger) String() string {
return "BigInteger"
}
// Dup implements the Item interface.
func (i *BigInteger) Dup() Item {
n := new(big.Int)
return (*BigInteger)(n.Set(i.Big()))
}
// Type implements the Item interface.
func (i *BigInteger) Type() Type { return IntegerT }
// Convert implements the Item interface.
func (i *BigInteger) Convert(typ Type) (Item, error) {
return convertPrimitive(i, typ)
}
// MarshalJSON implements the json.Marshaler interface.
func (i *BigInteger) MarshalJSON() ([]byte, error) {
return json.Marshal(i.Big())
}
// Bool represents a boolean Item.
type Bool bool
// NewBool returns an new Bool object.
func NewBool(val bool) Bool {
return Bool(val)
}
// Value implements the Item interface.
func (i Bool) Value() any {
return bool(i)
}
// MarshalJSON implements the json.Marshaler interface.
func (i Bool) MarshalJSON() ([]byte, error) {
return json.Marshal(bool(i))
}
func (i Bool) String() string {
return "Boolean"
}
// Dup implements the Item interface.
func (i Bool) Dup() Item {
return i
}
// TryBool implements the Item interface.
func (i Bool) TryBool() (bool, error) { return bool(i), nil }
// Bytes converts Bool to bytes.
func (i Bool) Bytes() []byte {
if i {
return []byte{1}
}
return []byte{0}
}
// TryBytes implements the Item interface.
func (i Bool) TryBytes() ([]byte, error) {
return i.Bytes(), nil
}
// TryInteger implements the Item interface.
func (i Bool) TryInteger() (*big.Int, error) {
if i {
return big.NewInt(1), nil
}
return big.NewInt(0), nil
}
// Equals implements the Item interface.
func (i Bool) Equals(s Item) bool {
if i == s {
return true
} else if s == nil {
return false
}
val, ok := s.(Bool)
return ok && i == val
}
// Type implements the Item interface.
func (i Bool) Type() Type { return BooleanT }
// Convert implements the Item interface.
func (i Bool) Convert(typ Type) (Item, error) {
return convertPrimitive(i, typ)
}
// ByteArray represents a byte array on the stack.
type ByteArray []byte
// NewByteArray returns an new ByteArray object.
func NewByteArray(b []byte) *ByteArray {
return (*ByteArray)(&b)
}
// Value implements the Item interface.
func (i *ByteArray) Value() any {
return []byte(*i)
}
// MarshalJSON implements the json.Marshaler interface.
func (i *ByteArray) MarshalJSON() ([]byte, error) {
return json.Marshal(hex.EncodeToString(*i))
}
func (i *ByteArray) String() string {
return "ByteString"
}
// TryBool implements the Item interface.
func (i *ByteArray) TryBool() (bool, error) {
if len(*i) > MaxBigIntegerSizeBits/8 {
return false, errTooBigInteger
}
for _, b := range *i {
if b != 0 {
return true, nil
}
}
return false, nil
}
// TryBytes implements the Item interface.
func (i ByteArray) TryBytes() ([]byte, error) {
return i, nil
}
// TryInteger implements the Item interface.
func (i ByteArray) TryInteger() (*big.Int, error) {
if len(i) > MaxBigIntegerSizeBits/8 {
return nil, errTooBigInteger
}
return bigint.FromBytes(i), nil
}
// Equals implements the Item interface.
func (i *ByteArray) Equals(s Item) bool {
var limit = MaxByteArrayComparableSize
return i.equalsLimited(s, &limit)
}
// equalsLimited compares ByteArray with provided stackitem using the limit.
func (i *ByteArray) equalsLimited(s Item, limit *int) bool {
if i == nil {
return s == nil
}
lCurr := len(*i)
if lCurr > *limit || *limit == 0 {
panic(errTooBigComparable)
}
var comparedSize = 1
defer func() { *limit -= comparedSize }()
if s == nil {
return false
}
val, ok := s.(*ByteArray)
if !ok {
return false
}
comparedSize = lCurr
lOther := len(*val)
if lOther > comparedSize {
comparedSize = lOther
}
if i == val {
return true
}
if lOther > *limit {
panic(errTooBigComparable)
}
return bytes.Equal(*i, *val)
}
// Dup implements the Item interface.
func (i *ByteArray) Dup() Item {
ba := bytes.Clone(*i)
return (*ByteArray)(&ba)
}
// Type implements the Item interface.
func (i *ByteArray) Type() Type { return ByteArrayT }
// Convert implements the Item interface.
func (i *ByteArray) Convert(typ Type) (Item, error) {
return convertPrimitive(i, typ)
}
// Array represents a new Array object.
type Array struct {
value []Item
rc
ro
}
// NewArray returns a new Array object.
func NewArray(items []Item) *Array {
return &Array{
value: items,
}
}
// Value implements the Item interface.
func (i *Array) Value() any {
return i.value
}
// Remove removes the element at `pos` index from Array value.
// It will panics on bad index.
func (i *Array) Remove(pos int) {
if i.IsReadOnly() {
panic(ErrReadOnly)
}
i.value = append(i.value[:pos], i.value[pos+1:]...)
}
// Append adds an Item to the end of the Array value.
func (i *Array) Append(item Item) {
if i.IsReadOnly() {
panic(ErrReadOnly)
}
i.value = append(i.value, item)
}
// Clear removes all elements from the Array item value.
func (i *Array) Clear() {
if i.IsReadOnly() {
panic(ErrReadOnly)
}
i.value = i.value[:0]
}
// Len returns length of Array value.
func (i *Array) Len() int {
return len(i.value)
}
// MarshalJSON implements the json.Marshaler interface.
func (i *Array) MarshalJSON() ([]byte, error) {
return json.Marshal(i.value)
}
func (i *Array) String() string {
return "Array"
}
// TryBool implements the Item interface.
func (i *Array) TryBool() (bool, error) { return true, nil }
// TryBytes implements the Item interface.
func (i *Array) TryBytes() ([]byte, error) {
return nil, mkInvConversion(i, ByteArrayT)
}
// TryInteger implements the Item interface.
func (i *Array) TryInteger() (*big.Int, error) {
return nil, mkInvConversion(i, IntegerT)
}
// Equals implements the Item interface.
func (i *Array) Equals(s Item) bool {
return i == s
}
// Dup implements the Item interface.
func (i *Array) Dup() Item {
// reference type
return i
}
// Type implements the Item interface.
func (i *Array) Type() Type { return ArrayT }
// Convert implements the Item interface.
func (i *Array) Convert(typ Type) (Item, error) {
switch typ {
case ArrayT:
return i, nil
case StructT:
arr := make([]Item, len(i.value))
copy(arr, i.value)
return NewStruct(arr), nil
case BooleanT:
return NewBool(true), nil
default:
return nil, mkInvConversion(i, typ)
}
}
// MapElement is a key-value pair of StackItems.
type MapElement struct {
Key Item
Value Item
}
// Map represents a Map object. It's ordered, so we use slice representation,
// which should be fine for maps with less than 32 or so elements. Given that
// our VM has quite low limit of overall stack items, it should be good enough,
// but it can be extended with a real map for fast random access in the future
// if needed.
type Map struct {
value []MapElement
rc
ro
}
// NewMap returns a new Map object.
func NewMap() *Map {
return &Map{
value: make([]MapElement, 0),
}
}
// NewMapWithValue returns a new Map object filled with the specified value.
func NewMapWithValue(value []MapElement) *Map {
if value != nil {
return &Map{
value: value,
}
}
return NewMap()
}
// Value implements the Item interface.
func (i *Map) Value() any {
return i.value
}
// Clear removes all elements from the Map item value.
func (i *Map) Clear() {
if i.IsReadOnly() {
panic(ErrReadOnly)
}
i.value = i.value[:0]
}
// Len returns the length of the Map value.
func (i *Map) Len() int {
return len(i.value)
}
// TryBool implements the Item interface.
func (i *Map) TryBool() (bool, error) { return true, nil }
// TryBytes implements the Item interface.
func (i *Map) TryBytes() ([]byte, error) {
return nil, mkInvConversion(i, ByteArrayT)
}
// TryInteger implements the Item interface.
func (i *Map) TryInteger() (*big.Int, error) {
return nil, mkInvConversion(i, IntegerT)
}
// Equals implements the Item interface.
func (i *Map) Equals(s Item) bool {
return i == s
}
func (i *Map) String() string {
return "Map"
}
// Index returns an index of the key in map.
func (i *Map) Index(key Item) int {
for k := range i.value {
if i.value[k].Key.Equals(key) {
return k
}
}
return -1
}
// Has checks if the map has the specified key.
func (i *Map) Has(key Item) bool {
return i.Index(key) >= 0
}
// Dup implements the Item interface.
func (i *Map) Dup() Item {
// reference type
return i
}
// Type implements the Item interface.
func (i *Map) Type() Type { return MapT }
// Convert implements the Item interface.
func (i *Map) Convert(typ Type) (Item, error) {
switch typ {
case MapT:
return i, nil
case BooleanT:
return NewBool(true), nil
default:
return nil, mkInvConversion(i, typ)
}
}
// Add adds a key-value pair to the map.
func (i *Map) Add(key, value Item) {
if err := IsValidMapKey(key); err != nil {
panic(err)
}
if i.IsReadOnly() {
panic(ErrReadOnly)
}
index := i.Index(key)
if index >= 0 {
i.value[index].Value = value
} else {
i.value = append(i.value, MapElement{key, value})
}
}
// Drop removes the given index from the map (no bounds check done here).
func (i *Map) Drop(index int) {
if i.IsReadOnly() {
panic(ErrReadOnly)
}
copy(i.value[index:], i.value[index+1:])
i.value = i.value[:len(i.value)-1]
}
// IsValidMapKey checks whether it's possible to use the given Item as a Map
// key.
func IsValidMapKey(key Item) error {
switch key.(type) {
case Bool, *BigInteger:
return nil
case *ByteArray:
size := len(key.Value().([]byte))
if size > MaxKeySize {
return errTooBigKey
}
return nil
default:
return fmt.Errorf("%w: %s map key", ErrInvalidType, key.Type())
}
}
// Interop represents interop data on the stack.
type Interop struct {
value any
}
// NewInterop returns a new Interop object.
func NewInterop(value any) *Interop {
return &Interop{
value: value,
}
}
// Value implements the Item interface.
func (i *Interop) Value() any {
return i.value
}
// String implements stringer interface.
func (i *Interop) String() string {
return "InteropInterface"
}
// Dup implements the Item interface.
func (i *Interop) Dup() Item {
// reference type
return i
}
// TryBool implements the Item interface.
func (i *Interop) TryBool() (bool, error) { return true, nil }
// TryBytes implements the Item interface.
func (i *Interop) TryBytes() ([]byte, error) {
return nil, mkInvConversion(i, ByteArrayT)
}
// TryInteger implements the Item interface.
func (i *Interop) TryInteger() (*big.Int, error) {
return nil, mkInvConversion(i, IntegerT)
}
// Equals implements the Item interface.
func (i *Interop) Equals(s Item) bool {
if i == s {
return true
} else if s == nil {
return false