-
Notifications
You must be signed in to change notification settings - Fork 479
/
eval.go
5998 lines (5271 loc) · 170 KB
/
eval.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
// Copyright (C) 2019-2024 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package logic
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"math/bits"
"runtime"
"slices"
"strconv"
"strings"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/protocol"
)
// The constants below control opcode evaluation and MAY NOT be changed without
// gating them by version. Old programs need to retain their old behavior.
// maxStringSize is the limit of byte string length in an AVM value
const maxStringSize = 4096
// maxByteMathSize is the limit of byte strings supplied as input to byte math opcodes
const maxByteMathSize = 64
// maxLogSize is the limit of total log size from n log calls in a program
const maxLogSize = config.MaxEvalDeltaTotalLogSize
// maxLogCalls is the limit of total log calls during a program execution
const maxLogCalls = 32
// maxAppCallDepth is the limit on inner appl call depth
// To be clear, 0 would prevent inner appls, 1 would mean inner app calls cannot
// make inner appls. So the total app depth can be 1 higher than this number, if
// you count the top-level app call.
var maxAppCallDepth = 8
// maxStackDepth should not change unless controlled by an AVM version change
const maxStackDepth = 1000
// maxTxGroupSize is the same as config.MaxTxGroupSize, but is a constant so
// that we can declare an array of this size. A unit test confirms that they
// match.
const maxTxGroupSize = 16
// stackValue is the type for the operand stack.
// Each stackValue is either a valid []byte value or a uint64 value.
// If (.Bytes != nil) the stackValue is a []byte value, otherwise uint64 value.
type stackValue struct {
Uint uint64
Bytes []byte
}
func (sv stackValue) avmType() avmType {
if sv.Bytes != nil {
return avmBytes
}
return avmUint64
}
func (sv stackValue) stackType() StackType {
if sv.Bytes != nil {
return NewStackType(sv.avmType(), static(uint64(len(sv.Bytes))))
}
return NewStackType(sv.avmType(), static(sv.Uint))
}
func (sv stackValue) typeName() string {
if sv.Bytes != nil {
return "[]byte"
}
return "uint64"
}
func (sv stackValue) String() string {
if sv.Bytes != nil {
return hex.EncodeToString(sv.Bytes)
}
return fmt.Sprintf("%d 0x%x", sv.Uint, sv.Uint)
}
func (sv stackValue) asAny() any {
if sv.Bytes != nil {
return sv.Bytes
}
return sv.Uint
}
func (sv stackValue) isEmpty() bool {
return sv.Bytes == nil && sv.Uint == 0
}
func (sv stackValue) address() (addr basics.Address, err error) {
if len(sv.Bytes) != len(addr) {
return basics.Address{}, errors.New("not an address")
}
copy(addr[:], sv.Bytes)
return
}
func (sv stackValue) uint() (uint64, error) {
if sv.Bytes != nil {
return 0, fmt.Errorf("%#v is not a uint64", sv.Bytes)
}
return sv.Uint, nil
}
func (sv stackValue) uintMaxed(max uint64) (uint64, error) {
if sv.Bytes != nil {
return 0, fmt.Errorf("%#v is not a uint64", sv.Bytes)
}
if sv.Uint > max {
return 0, fmt.Errorf("%d is larger than max=%d", sv.Uint, max)
}
return sv.Uint, nil
}
func (sv stackValue) bool() (bool, error) {
u64, err := sv.uint()
if err != nil {
return false, err
}
switch u64 {
case 0:
return false, nil
case 1:
return true, nil
default:
return false, fmt.Errorf("boolean is neither 1 nor 0: %d", u64)
}
}
func (sv stackValue) string(limit int) (string, error) {
if sv.Bytes == nil {
return "", errors.New("not a byte array")
}
if len(sv.Bytes) > limit {
return "", errors.New("value is too long")
}
return string(sv.Bytes), nil
}
// ToTealValue converts a stack value instance into a basics.TealValue instance
func (sv stackValue) ToTealValue() basics.TealValue {
if sv.avmType() == avmBytes {
return basics.TealValue{Type: basics.TealBytesType, Bytes: string(sv.Bytes)}
}
return basics.TealValue{Type: basics.TealUintType, Uint: sv.Uint}
}
func stackValueFromTealValue(tv basics.TealValue) (sv stackValue, err error) {
switch tv.Type {
case basics.TealBytesType:
sv.Bytes = []byte(tv.Bytes)
case basics.TealUintType:
sv.Uint = tv.Uint
default:
err = fmt.Errorf("invalid TealValue type: %d", tv.Type)
}
return
}
// computeMinAvmVersion calculates the minimum safe AVM version that may be
// used by a transaction in this group. It is important to prevent
// newly-introduced transaction fields from breaking assumptions made by older
// versions of the AVM. If one of the transactions in a group will execute a TEAL
// program whose version predates a given field, that field must not be set
// anywhere in the transaction group, or the group will be rejected.
func computeMinAvmVersion(group []transactions.SignedTxnWithAD) uint64 {
var minVersion uint64
for _, txn := range group {
if !txn.Txn.RekeyTo.IsZero() {
if minVersion < rekeyingEnabledVersion {
minVersion = rekeyingEnabledVersion
}
}
if txn.Txn.Type == protocol.ApplicationCallTx {
if minVersion < appsEnabledVersion {
minVersion = appsEnabledVersion
}
}
}
return minVersion
}
// LedgerForSignature represents the parts of Ledger that LogicSigs can see. It
// only exposes things that consensus has already agreed upon, so it is
// "stateless" for signature purposes.
type LedgerForSignature interface {
BlockHdr(basics.Round) (bookkeeping.BlockHeader, error)
GenesisHash() crypto.Digest
}
// NoHeaderLedger is intended for debugging TEAL in isolation(no real ledger) in
// which it is reasonable to preclude the use of `block`, `txn
// LastValidTime`. Also `global GenesisHash` is just a static value.
type NoHeaderLedger struct {
}
// BlockHdr always errors
func (NoHeaderLedger) BlockHdr(basics.Round) (bookkeeping.BlockHeader, error) {
return bookkeeping.BlockHeader{}, fmt.Errorf("no block header access")
}
// GenesisHash returns a fixed value
func (NoHeaderLedger) GenesisHash() crypto.Digest {
return crypto.Digest{
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
}
}
// LedgerForLogic represents ledger API for Stateful TEAL program
type LedgerForLogic interface {
AccountData(addr basics.Address) (ledgercore.AccountData, error)
Authorizer(addr basics.Address) (basics.Address, error)
Round() basics.Round
PrevTimestamp() int64
// These are simplifications of the underlying Ledger methods that take a
// round argument. They implicitly use agreement's BalanceRound (320 back).
AgreementData(addr basics.Address) (basics.OnlineAccountData, error)
OnlineStake() (basics.MicroAlgos, error)
AssetHolding(addr basics.Address, assetIdx basics.AssetIndex) (basics.AssetHolding, error)
AssetParams(aidx basics.AssetIndex) (basics.AssetParams, basics.Address, error)
AppParams(aidx basics.AppIndex) (basics.AppParams, basics.Address, error)
OptedIn(addr basics.Address, appIdx basics.AppIndex) (bool, error)
GetLocal(addr basics.Address, appIdx basics.AppIndex, key string, accountIdx uint64) (value basics.TealValue, exists bool, err error)
SetLocal(addr basics.Address, appIdx basics.AppIndex, key string, value basics.TealValue, accountIdx uint64) error
DelLocal(addr basics.Address, appIdx basics.AppIndex, key string, accountIdx uint64) error
GetGlobal(appIdx basics.AppIndex, key string) (value basics.TealValue, exists bool, err error)
SetGlobal(appIdx basics.AppIndex, key string, value basics.TealValue) error
DelGlobal(appIdx basics.AppIndex, key string) error
NewBox(appIdx basics.AppIndex, key string, value []byte, appAddr basics.Address) error
GetBox(appIdx basics.AppIndex, key string) ([]byte, bool, error)
SetBox(appIdx basics.AppIndex, key string, value []byte) error
DelBox(appIdx basics.AppIndex, key string, appAddr basics.Address) (bool, error)
Perform(gi int, ep *EvalParams) error
Counter() uint64
}
// BoxRef is the "hydrated" form of a transactions.BoxRef - it has the actual app id, not an index
type BoxRef struct {
App basics.AppIndex
Name string
}
// UnnamedResourcePolicy is an interface that defines the policy for allowing unnamed resources.
// This should only be used during simulation or debugging.
type UnnamedResourcePolicy interface {
AvailableAccount(addr basics.Address) bool
AvailableAsset(asset basics.AssetIndex) bool
AvailableApp(app basics.AppIndex) bool
AllowsHolding(addr basics.Address, asset basics.AssetIndex) bool
AllowsLocal(addr basics.Address, app basics.AppIndex) bool
AvailableBox(app basics.AppIndex, name string, operation BoxOperation, createSize uint64) bool
}
// EvalConstants contains constant parameters that are used by opcodes during evaluation (including both real-execution and simulation).
type EvalConstants struct {
// MaxLogSize is the limit of total log size from n log calls in a program
MaxLogSize uint64
// MaxLogCalls is the limit of total log calls during a program execution
MaxLogCalls uint64
// UnnamedResources, if provided, allows resources to be used without being named according to
// this policy.
UnnamedResources UnnamedResourcePolicy
}
// RuntimeEvalConstants gives a set of const params used in normal runtime of opcodes
func RuntimeEvalConstants() EvalConstants {
return EvalConstants{
MaxLogSize: uint64(maxLogSize),
MaxLogCalls: uint64(maxLogCalls),
}
}
// EvalParams contains data that comes into condition evaluation.
type EvalParams struct {
runMode RunMode
Proto *config.ConsensusParams
Trace *strings.Builder
TxnGroup []transactions.SignedTxnWithAD
pastScratch [maxTxGroupSize]*scratchSpace
logger logging.Logger
SigLedger LedgerForSignature
Ledger LedgerForLogic
// optional tracer
Tracer EvalTracer
// minAvmVersion is the minimum allowed AVM version of a program to be
// evaluated in TxnGroup.
minAvmVersion uint64
// Amount "overpaid" by the transactions of the group. Often 0. When
// positive, it can be spent by inner transactions. Shared across a group's
// txns, so that it can be updated (including upward, by overpaying inner
// transactions). nil is treated as 0 (used before fee pooling is enabled).
FeeCredit *uint64
Specials *transactions.SpecialAddresses
// Total pool of app call budget in a group transaction (nil before budget pooling enabled)
PooledApplicationBudget *int
// Total pool of logicsig budget in a group transaction (nil before lsig pooling enabled)
PooledLogicSigBudget *int
// Total allowable inner txns in a group transaction (nil before inner pooling enabled)
pooledAllowedInners *int
// available contains resources that may be used even though they are not
// necessarily directly in the txn's "static arrays". Apps and ASAs go in if
// the app or asa was created earlier in the txgroup (empty until
// createdResourcesVersion). Boxes go in when the ep is created, to share
// availability across all txns in the group.
available *resources
// ioBudget is the number of bytes that the box ref'd boxes can sum to, and
// the number of bytes that created or written boxes may sum to.
ioBudget uint64
// readBudgetChecked allows us to only check the read budget once
readBudgetChecked bool
// SurplusReadBudget is the number of bytes from the IO budget that were not used for reading
// in boxes before evaluation began. In other words, the txn group could have read in
// SurplusReadBudget more box bytes, but did not.
SurplusReadBudget uint64
EvalConstants
// Caching these here means the hashes can be shared across the TxnGroup
// (and inners, because the cache is shared with the inner EvalParams)
appAddrCache map[basics.AppIndex]basics.Address
// Cache the txid hashing, but do *not* share this into inner EvalParams, as
// the key is just the index in the txgroup.
txidCache map[int]transactions.Txid
innerTxidCache map[int]transactions.Txid
// The calling context, if this is an inner app call
caller *EvalContext
}
// GetCaller returns the calling EvalContext if this is an inner transaction evaluation. Otherwise,
// this returns nil.
func (ep *EvalParams) GetCaller() *EvalContext {
return ep.caller
}
// GetIOBudget returns the current IO budget for the group.
func (ep *EvalParams) GetIOBudget() uint64 {
return ep.ioBudget
}
// SetIOBudget sets the IO budget for the group.
func (ep *EvalParams) SetIOBudget(ioBudget uint64) {
ep.ioBudget = ioBudget
}
// BoxDirtyBytes returns the number of bytes that have been written to boxes
func (ep *EvalParams) BoxDirtyBytes() uint64 {
return ep.available.dirtyBytes
}
func copyWithClearAD(txgroup []transactions.SignedTxnWithAD) []transactions.SignedTxnWithAD {
copy := make([]transactions.SignedTxnWithAD, len(txgroup))
for i := range txgroup {
copy[i].SignedTxn = txgroup[i].SignedTxn
// leave copy[i].ApplyData clear
}
return copy
}
// NewSigEvalParams creates an EvalParams to be used while evaluating a group's logicsigs
func NewSigEvalParams(txgroup []transactions.SignedTxn, proto *config.ConsensusParams, ls LedgerForSignature) *EvalParams {
lsigs := 0
for _, tx := range txgroup {
if !tx.Lsig.Blank() {
lsigs++
}
}
var pooledLogicBudget *int
if lsigs > 0 { // don't allocate if no lsigs
if proto.EnableLogicSigCostPooling {
pooledLogicBudget = new(int)
*pooledLogicBudget = len(txgroup) * int(proto.LogicSigMaxCost)
}
}
withADs := transactions.WrapSignedTxnsWithAD(txgroup)
return &EvalParams{
runMode: ModeSig,
TxnGroup: withADs,
Proto: proto,
minAvmVersion: computeMinAvmVersion(withADs),
SigLedger: ls,
PooledLogicSigBudget: pooledLogicBudget,
}
}
// NewAppEvalParams creates an EvalParams to use while evaluating a top-level txgroup.
func NewAppEvalParams(txgroup []transactions.SignedTxnWithAD, proto *config.ConsensusParams, specials *transactions.SpecialAddresses) *EvalParams {
apps := 0
for _, tx := range txgroup {
if tx.Txn.Type == protocol.ApplicationCallTx {
apps++
}
}
var pooledApplicationBudget *int
var pooledAllowedInners *int
var credit *uint64
if apps > 0 { // none of these allocations needed if no apps
credit = new(uint64)
*credit = feeCredit(txgroup, proto.MinTxnFee)
if proto.EnableAppCostPooling {
pooledApplicationBudget = new(int)
*pooledApplicationBudget = apps * proto.MaxAppProgramCost
}
if proto.EnableInnerTransactionPooling {
pooledAllowedInners = new(int)
*pooledAllowedInners = proto.MaxTxGroupSize * proto.MaxInnerTransactions
}
}
ep := &EvalParams{
runMode: ModeApp,
TxnGroup: copyWithClearAD(txgroup),
Proto: proto,
Specials: specials,
minAvmVersion: computeMinAvmVersion(txgroup),
FeeCredit: credit,
PooledApplicationBudget: pooledApplicationBudget,
pooledAllowedInners: pooledAllowedInners,
appAddrCache: make(map[basics.AppIndex]basics.Address),
EvalConstants: RuntimeEvalConstants(),
}
return ep
}
func (ep *EvalParams) computeAvailability() *resources {
available := &resources{
sharedAccounts: make(map[basics.Address]struct{}),
sharedAsas: make(map[basics.AssetIndex]struct{}),
sharedApps: make(map[basics.AppIndex]struct{}),
sharedHoldings: make(map[ledgercore.AccountAsset]struct{}),
sharedLocals: make(map[ledgercore.AccountApp]struct{}),
boxes: make(map[BoxRef]bool),
}
for i := range ep.TxnGroup {
available.fill(&ep.TxnGroup[i].Txn, ep)
}
return available
}
// feeCredit returns the extra fee supplied in this top-level txgroup compared
// to required minfee. It can make assumptions about overflow because the group
// is known OK according to txnGroupBatchPrep. (The group is "WellFormed")
func feeCredit(txgroup []transactions.SignedTxnWithAD, minFee uint64) uint64 {
minFeeCount := uint64(0)
feesPaid := uint64(0)
for _, stxn := range txgroup {
if stxn.Txn.Type != protocol.StateProofTx {
minFeeCount++
}
feesPaid = basics.AddSaturate(feesPaid, stxn.Txn.Fee.Raw)
}
// Overflow is impossible, because txnGroupBatchPrep checked.
feeNeeded := minFee * minFeeCount
return basics.SubSaturate(feesPaid, feeNeeded)
}
// NewInnerEvalParams creates an EvalParams to be used while evaluating an inner group txgroup
func NewInnerEvalParams(txg []transactions.SignedTxnWithAD, caller *EvalContext) *EvalParams {
minAvmVersion := computeMinAvmVersion(txg)
// Can't happen currently, since earliest inner callable version is higher
// than any minimum imposed otherwise. But is correct to inherit a stronger
// restriction from above, in case of future restriction.
if minAvmVersion < caller.minAvmVersion {
minAvmVersion = caller.minAvmVersion
}
// Unlike NewEvalParams, do not add fee credit here. opTxSubmit has already done so.
if caller.Proto.EnableAppCostPooling {
for _, tx := range txg {
if tx.Txn.Type == protocol.ApplicationCallTx {
*caller.PooledApplicationBudget += caller.Proto.MaxAppProgramCost
}
}
}
ep := &EvalParams{
runMode: ModeApp,
Proto: caller.Proto,
Trace: caller.Trace,
TxnGroup: txg,
logger: caller.logger,
SigLedger: caller.SigLedger,
Ledger: caller.Ledger,
Tracer: caller.Tracer,
minAvmVersion: minAvmVersion,
FeeCredit: caller.FeeCredit,
Specials: caller.Specials,
PooledApplicationBudget: caller.PooledApplicationBudget,
pooledAllowedInners: caller.pooledAllowedInners,
available: caller.available,
ioBudget: caller.ioBudget,
readBudgetChecked: true, // don't check for inners
appAddrCache: caller.appAddrCache,
EvalConstants: caller.EvalConstants,
// read comment in EvalParams declaration about txid caches
caller: caller,
}
return ep
}
type evalFunc func(cx *EvalContext) error
type checkFunc func(cx *EvalContext) error
// RunMode is a bitset of logic evaluation modes.
// There are currently two such modes: Signature and Application.
type RunMode uint64
const (
// ModeSig is LogicSig execution
ModeSig RunMode = 1 << iota
// ModeApp is application/contract execution
ModeApp
// local constant, run in any mode
modeAny = ModeSig | ModeApp
)
// Any checks if this mode bitset represents any evaluation mode
func (r RunMode) Any() bool {
return r == modeAny
}
func (r RunMode) String() string {
switch r {
case ModeSig:
return "Signature"
case ModeApp:
return "Application"
case modeAny:
return "Any"
default:
}
return "Unknown"
}
func (ep *EvalParams) log() logging.Logger {
if ep.logger != nil {
return ep.logger
}
return logging.Base()
}
// RecordAD notes ApplyData information that was derived outside of the logic
// package. For example, after a acfg transaction is processed, the AD created
// by the acfg is added to the EvalParams this way.
func (ep *EvalParams) RecordAD(gi int, ad transactions.ApplyData) {
if ep.runMode == ModeSig {
// We should not be touching a signature mode EvalParams as it shares
// memory with its caller. LogicSigs are supposed to be stateless!
panic("RecordAD called in signature mode")
}
ep.TxnGroup[gi].ApplyData = ad
if aid := ad.ConfigAsset; aid != 0 {
if ep.available == nil { // here, and below, we may need to make `ep.available`
ep.available = ep.computeAvailability()
}
if ep.available.createdAsas == nil {
ep.available.createdAsas = make(map[basics.AssetIndex]struct{})
}
ep.available.createdAsas[aid] = struct{}{}
}
if aid := ad.ApplicationID; aid != 0 {
if ep.available == nil {
ep.available = ep.computeAvailability()
}
if ep.available.createdApps == nil {
ep.available.createdApps = make(map[basics.AppIndex]struct{})
}
ep.available.createdApps[aid] = struct{}{}
}
}
type frame struct {
retpc int
height int
clear bool // perform "shift and clear" in retsub
args int
returns int
}
type scratchSpace [256]stackValue
// EvalContext is the execution context of AVM bytecode. It contains the full
// state of the running program, and tracks some of the things that the program
// has done, like log messages and inner transactions.
type EvalContext struct {
*EvalParams
// determines eval mode: ModeSig or ModeApp
runMode RunMode
// the index of the transaction being evaluated
groupIndex int
// the transaction being evaluated (initialized from groupIndex + ep.TxnGroup)
txn *transactions.SignedTxnWithAD
// Txn.EvalDelta maintains a summary of changes as we go. We used to
// compute this from the ledger after a full eval. But now apps can call
// apps. When they do, all of the changes accumulate into the parent's
// ledger, but Txn.EvalDelta should only have the changes from *this*
// call. (The changes caused by children are deeper inside - in the
// EvalDeltas of the InnerTxns inside this EvalDelta) Nice bonus - by
// keeping the running changes, the debugger can be changed to display them
// as the app runs.
Stack []stackValue
callstack []frame
fromCallsub bool
appID basics.AppIndex
program []byte
pc int
nextpc int
intc []uint64
bytec [][]byte
version uint64
Scratch scratchSpace
subtxns []transactions.SignedTxnWithAD // place to build for itxn_submit
cost int // cost incurred so far
logSize int // total log size so far
// Set of PC values that branches we've seen so far might
// go. So, if checkStep() skips one, that branch is trying to
// jump into the middle of a multibyte instruction
branchTargets []bool
// Set of PC values that we have begun a checkStep() with. So
// if a back jump is going to a value that isn't here, it's
// jumping into the middle of multibyte instruction.
instructionStarts []bool
programHashCached crypto.Digest
}
// GroupIndex returns the group index of the transaction being evaluated
func (cx *EvalContext) GroupIndex() int {
return cx.groupIndex
}
// RunMode returns the evaluation context's mode (signature or application)
func (cx *EvalContext) RunMode() RunMode {
return cx.runMode
}
// ProgramVersion returns the AVM version of the current program.
func (cx *EvalContext) ProgramVersion() uint64 {
return cx.version
}
// PC returns the program counter of the current application being evaluated
func (cx *EvalContext) PC() int { return cx.pc }
// GetOpSpec queries for the OpSpec w.r.t. current program byte.
func (cx *EvalContext) GetOpSpec() OpSpec { return opsByOpcode[cx.version][cx.program[cx.pc]] }
// GetProgram queries for the current program
func (cx *EvalContext) GetProgram() []byte { return cx.program }
// avmType describes the type of a value on the operand stack
// avmTypes are a subset of StackTypes
type avmType byte
const (
// avmNone in an OpSpec shows that the op pops or yields nothing
avmNone avmType = iota
// avmAny in an OpSpec shows that the op pops or yield any type
avmAny
// avmUint64 in an OpSpec shows that the op pops or yields a uint64
avmUint64
// avmBytes in an OpSpec shows that the op pops or yields a []byte
avmBytes
)
func (at avmType) String() string {
switch at {
case avmNone:
return "none"
case avmAny:
return "any"
case avmUint64:
return "uint64"
case avmBytes:
return "[]byte"
}
return "internal error, unknown type"
}
var (
// StackUint64 is any valid uint64
StackUint64 = NewStackType(avmUint64, bound(0, math.MaxUint64))
// StackBytes is any valid bytestring
StackBytes = NewStackType(avmBytes, bound(0, maxStringSize))
// StackAny could be Bytes or Uint64
StackAny = StackType{
Name: avmAny.String(),
AVMType: avmAny,
Bound: [2]uint64{0, 0},
}
// StackNone is used when there is no input or output to
// an opcode
StackNone = StackType{
Name: avmNone.String(),
AVMType: avmNone,
}
// StackBoolean constrains the int to 1 or 0, representing True or False
StackBoolean = NewStackType(avmUint64, bound(0, 1), "bool")
// StackAddress represents an address
StackAddress = NewStackType(avmBytes, static(32), "address")
// StackBytes32 represents a bytestring that should have exactly 32 bytes
StackBytes32 = NewStackType(avmBytes, static(32), "[32]byte")
// StackBytes64 represents a bytestring that should have exactly 64 bytes
StackBytes64 = NewStackType(avmBytes, static(64), "[64]byte")
// StackBytes80 represents a bytestring that should have exactly 80 bytes
StackBytes80 = NewStackType(avmBytes, static(80), "[80]byte")
// StackBigInt represents a bytestring that should be treated like an int
StackBigInt = NewStackType(avmBytes, bound(0, maxByteMathSize), "bigint")
// StackMethodSelector represents a bytestring that should be treated like a method selector
StackMethodSelector = NewStackType(avmBytes, static(4), "method")
// StackStateKey represents a bytestring that can be used as a key to some storage (global/local/box)
StackStateKey = NewStackType(avmBytes, bound(0, 64), "stateKey")
// StackBoxName represents a bytestring that can be used as a key to a box
StackBoxName = NewStackType(avmBytes, bound(1, 64), "boxName")
// StackZeroUint64 is a StackUint64 with a minimum value of 0 and a maximum value of 0
StackZeroUint64 = NewStackType(avmUint64, bound(0, 0), "0")
// StackZeroBytes is a StackBytes with a minimum length of 0 and a maximum length of 0
StackZeroBytes = NewStackType(avmUint64, bound(0, 0), "''")
// AllStackTypes is a map of all the stack types we recognize
// so that we can iterate over them in doc prep
// and use them for opcode proto shorthand
AllStackTypes = map[byte]StackType{
'a': StackAny,
'b': StackBytes,
'i': StackUint64,
'x': StackNone,
'A': StackAddress,
'I': StackBigInt,
'T': StackBoolean,
'M': StackMethodSelector,
'K': StackStateKey,
'N': StackBoxName,
}
)
func bound(min, max uint64) [2]uint64 {
return [2]uint64{min, max}
}
func static(size uint64) [2]uint64 {
return bound(size, size)
}
func union(a, b [2]uint64) [2]uint64 {
u := [2]uint64{a[0], a[1]}
if b[0] < u[0] {
u[0] = b[0]
}
if b[1] > u[1] {
u[1] = b[1]
}
return u
}
// StackType describes the type of a value on the operand stack
type StackType struct {
Name string // alias (address, boolean, ...) or derived name [5]byte
AVMType avmType
Bound [2]uint64 // represents max/min value for uint64 or max/min length for byte[]
}
// NewStackType Initializes a new StackType with fields passed
func NewStackType(at avmType, bounds [2]uint64, stname ...string) StackType {
name := at.String()
// It's static, set the name to show
// the static value
if bounds[0] == bounds[1] {
switch at {
case avmBytes:
name = fmt.Sprintf("[%d]byte", bounds[0])
case avmUint64:
name = fmt.Sprintf("%d", bounds[0])
}
}
if len(stname) > 0 {
name = stname[0]
}
return StackType{Name: name, AVMType: at, Bound: bounds}
}
func (st StackType) union(b StackType) StackType {
// TODO: Can we ever receive one or the other
// as None? should that be a panic?
if st.AVMType != b.AVMType {
return StackAny
}
// Same type now, so we can just take the union of the bounds
return NewStackType(st.AVMType, union(st.Bound, b.Bound))
}
func (st StackType) narrowed(bounds [2]uint64) StackType {
return NewStackType(st.AVMType, bounds)
}
func (st StackType) widened() StackType {
// Take only the avm type
switch st.AVMType {
case avmBytes:
return StackBytes
case avmUint64:
return StackUint64
case avmAny:
return StackAny
default:
panic(fmt.Sprintf("What are you tyring to widen?: %+v", st))
}
}
func (st StackType) constInt() (uint64, bool) {
if st.AVMType != avmUint64 || st.Bound[0] != st.Bound[1] {
return 0, false
}
return st.Bound[0], true
}
// overlaps checks if there is enough overlap
// between the given types that the receiver can
// possible fit in the expected type
func (st StackType) overlaps(expected StackType) bool {
if st.AVMType == avmNone || expected.AVMType == avmNone {
return false
}
if st.AVMType == avmAny || expected.AVMType == avmAny {
return true
}
// By now, both are either uint or bytes
// and must match
if st.AVMType != expected.AVMType {
return false
}
// Same type now
// Check if our constraints will satisfy the other type
smin, smax := st.Bound[0], st.Bound[1]
emin, emax := expected.Bound[0], expected.Bound[1]
return smin <= emax && smax >= emin
}
func (st StackType) String() string {
return st.Name
}
// Typed tells whether the StackType is a specific concrete type.
func (st StackType) Typed() bool {
switch st.AVMType {
case avmUint64, avmBytes:
return true
}
return false
}
// StackTypes is an alias for a list of StackType with syntactic sugar
type StackTypes []StackType
func parseStackTypes(spec string) StackTypes {
if spec == "" {
return nil
}
types := make(StackTypes, 0, len(spec))
for i := 0; i < len(spec); i++ {
letter := spec[i]
if letter == '{' {
if types[len(types)-1] != StackBytes {
panic("{ after non-bytes " + spec)
}
end := strings.IndexByte(spec[i:], '}')
if end == -1 {
panic("No } after b{ " + spec)
}
size, err := strconv.Atoi(spec[i+1 : i+end])
if err != nil {
panic("b{} does not contain a number " + spec)
}
// replace the generic type with the constrained type
types[len(types)-1] = NewStackType(avmBytes, static(uint64(size)), fmt.Sprintf("[%d]byte", size))
i += end
continue
}
st, ok := AllStackTypes[letter]
if !ok {
panic(spec)
}
types = append(types, st)
}
return types
}
func filterNoneTypes(sts StackTypes) StackTypes {
var filteredSts = make(StackTypes, 0, len(sts))
for i := range sts {
if sts[i].AVMType != avmNone {
filteredSts = append(filteredSts, sts[i])
}
}
return filteredSts
}
// panicError wraps a recover() catching a panic()
type panicError struct {
PanicValue interface{}
StackTrace string
}
func (pe panicError) Error() string {
return fmt.Sprintf("panic in TEAL Eval: %v\n%s", pe.PanicValue, pe.StackTrace)
}
var errLogicSigNotSupported = errors.New("LogicSig not supported")