-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathruntime.go
3672 lines (3146 loc) Β· 89.5 KB
/
runtime.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
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright 2019-2020 Dapper Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package runtime
import (
"errors"
"fmt"
"math"
goRuntime "runtime"
"time"
opentracing "github.com/opentracing/opentracing-go"
"golang.org/x/crypto/sha3"
"github.com/onflow/cadence"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
runtimeErrors "github.com/onflow/cadence/runtime/errors"
"github.com/onflow/cadence/runtime/interpreter"
"github.com/onflow/cadence/runtime/parser2"
"github.com/onflow/cadence/runtime/sema"
"github.com/onflow/cadence/runtime/stdlib"
)
type Script struct {
Source []byte
Arguments [][]byte
}
type importResolutionResults map[common.LocationID]bool
// Runtime is a runtime capable of executing Cadence.
type Runtime interface {
// ExecuteScript executes the given script.
//
// This function returns an error if the program has errors (e.g syntax errors, type errors),
// or if the execution fails.
ExecuteScript(Script, Context) (cadence.Value, error)
// ExecuteTransaction executes the given transaction.
//
// This function returns an error if the program has errors (e.g syntax errors, type errors),
// or if the execution fails.
ExecuteTransaction(Script, Context) error
// InvokeContractFunction invokes a contract function with the given arguments.
//
// This function returns an error if the execution fails.
// If the contract function accepts an AuthAccount as a parameter the corresponding argument can be an interpreter.Address.
// returns a cadence.Value
InvokeContractFunction(
contractLocation common.AddressLocation,
functionName string,
arguments []interpreter.Value,
argumentTypes []sema.Type,
context Context,
) (cadence.Value, error)
// ParseAndCheckProgram parses and checks the given code without executing the program.
//
// This function returns an error if the program contains any syntax or semantic errors.
ParseAndCheckProgram(source []byte, context Context) (*interpreter.Program, error)
// SetCoverageReport activates reporting coverage in the given report.
// Passing nil disables coverage reporting (default).
//
SetCoverageReport(coverageReport *CoverageReport)
// SetContractUpdateValidationEnabled configures if contract update validation is enabled.
//
SetContractUpdateValidationEnabled(enabled bool)
// SetAtreeValidationEnabled configures if atree validation is enabled.
SetAtreeValidationEnabled(enabled bool)
// SetTracingEnabled configures if tracing is enabled.
SetTracingEnabled(enabled bool)
// SetResourceOwnerChangeCallbackEnabled configures if the resource owner change callback is enabled.
SetResourceOwnerChangeHandlerEnabled(enabled bool)
// ReadStored reads the value stored at the given path
//
ReadStored(address common.Address, path cadence.Path, context Context) (cadence.Value, error)
// ReadLinked dereferences the path and returns the value stored at the target
//
ReadLinked(address common.Address, path cadence.Path, context Context) (cadence.Value, error)
}
var typeDeclarations = append(
stdlib.FlowBuiltInTypes,
stdlib.BuiltinTypes...,
).ToTypeDeclarations()
type ImportResolver = func(location common.Location) (program *ast.Program, e error)
var validTopLevelDeclarationsInTransaction = []common.DeclarationKind{
common.DeclarationKindImport,
common.DeclarationKindFunction,
common.DeclarationKindTransaction,
}
var validTopLevelDeclarationsInAccountCode = []common.DeclarationKind{
common.DeclarationKindPragma,
common.DeclarationKindImport,
common.DeclarationKindContract,
common.DeclarationKindContractInterface,
}
func validTopLevelDeclarations(location common.Location) []common.DeclarationKind {
switch location.(type) {
case common.TransactionLocation:
return validTopLevelDeclarationsInTransaction
case common.AddressLocation:
return validTopLevelDeclarationsInAccountCode
}
return nil
}
func reportMetric(
f func(),
runtimeInterface Interface,
report func(Metrics, time.Duration),
) {
metrics, ok := runtimeInterface.(Metrics)
if !ok {
f()
return
}
start := time.Now()
f()
elapsed := time.Since(start)
report(metrics, elapsed)
}
// interpreterRuntime is a interpreter-based version of the Flow runtime.
type interpreterRuntime struct {
coverageReport *CoverageReport
contractUpdateValidationEnabled bool
atreeValidationEnabled bool
tracingEnabled bool
resourceOwnerChangeHandlerEnabled bool
}
type Option func(Runtime)
// WithContractUpdateValidationEnabled returns a runtime option
// that configures if contract update validation is enabled.
//
func WithContractUpdateValidationEnabled(enabled bool) Option {
return func(runtime Runtime) {
runtime.SetContractUpdateValidationEnabled(enabled)
}
}
// WithAtreeValidationEnabled returns a runtime option
// that configures if atree validation is enabled.
//
func WithAtreeValidationEnabled(enabled bool) Option {
return func(runtime Runtime) {
runtime.SetAtreeValidationEnabled(enabled)
}
}
// WithTracingEnabled returns a runtime option
// that configures if tracing is enabled.
//
func WithTracingEnabled(enabled bool) Option {
return func(runtime Runtime) {
runtime.SetTracingEnabled(enabled)
}
}
// WithResourceOwnerChangeCallbackEnabled returns a runtime option
// that configures if the resource owner change callback is enabled.
//
func WithResourceOwnerChangeCallbackEnabled(enabled bool) Option {
return func(runtime Runtime) {
runtime.SetResourceOwnerChangeHandlerEnabled(enabled)
}
}
// NewInterpreterRuntime returns a interpreter-based version of the Flow runtime.
func NewInterpreterRuntime(options ...Option) Runtime {
runtime := &interpreterRuntime{}
for _, option := range options {
option(runtime)
}
return runtime
}
func (r *interpreterRuntime) Recover(onError func(error), context Context) {
recovered := recover()
if recovered == nil {
return
}
var err error
switch recovered := recovered.(type) {
case Error:
// avoid redundant wrapping
err = recovered
case error:
err = newError(recovered, context)
}
onError(err)
}
func (r *interpreterRuntime) SetCoverageReport(coverageReport *CoverageReport) {
r.coverageReport = coverageReport
}
func (r *interpreterRuntime) SetContractUpdateValidationEnabled(enabled bool) {
r.contractUpdateValidationEnabled = enabled
}
func (r *interpreterRuntime) SetAtreeValidationEnabled(enabled bool) {
r.atreeValidationEnabled = enabled
}
func (r *interpreterRuntime) SetTracingEnabled(enabled bool) {
r.tracingEnabled = enabled
}
func (r *interpreterRuntime) SetResourceOwnerChangeHandlerEnabled(enabled bool) {
r.resourceOwnerChangeHandlerEnabled = enabled
}
func (r *interpreterRuntime) ExecuteScript(script Script, context Context) (val cadence.Value, err error) {
defer r.Recover(
func(internalErr error) {
err = internalErr
},
context,
)
context.InitializeCodesAndPrograms()
storage := NewStorage(context.Interface)
var checkerOptions []sema.Option
var interpreterOptions []interpreter.Option
functions := r.standardLibraryFunctions(
context,
storage,
interpreterOptions,
checkerOptions,
)
program, err := r.parseAndCheckProgram(
script.Source,
context,
functions,
stdlib.BuiltinValues,
checkerOptions,
true,
importResolutionResults{},
)
if err != nil {
return nil, newError(err, context)
}
functionEntryPointType, err := program.Elaboration.FunctionEntryPointType()
if err != nil {
return nil, newError(err, context)
}
// Ensure the entry point's parameter types are importable
if len(functionEntryPointType.Parameters) > 0 {
for _, param := range functionEntryPointType.Parameters {
if !param.TypeAnnotation.Type.IsImportable(map[*sema.Member]bool{}) {
err = &ScriptParameterTypeNotImportableError{
Type: param.TypeAnnotation.Type,
}
return nil, newError(err, context)
}
}
}
// Ensure the entry point's return type is valid
if !functionEntryPointType.ReturnTypeAnnotation.Type.IsExternallyReturnable(map[*sema.Member]bool{}) {
err = &InvalidScriptReturnTypeError{
Type: functionEntryPointType.ReturnTypeAnnotation.Type,
}
return nil, newError(err, context)
}
interpret := scriptExecutionFunction(
functionEntryPointType.Parameters,
script.Arguments,
context.Interface,
)
value, inter, err := r.interpret(
program,
context,
storage,
functions,
stdlib.BuiltinValues,
interpreterOptions,
checkerOptions,
interpret,
)
if err != nil {
return nil, newError(err, context)
}
// Export before committing storage
result, err := exportValue(value)
if err != nil {
return nil, newError(err, context)
}
// Write back all stored values, which were actually just cached, back into storage.
// Even though this function is `ExecuteScript`, that doesn't imply the changes
// to storage will be actually persisted
err = r.commitStorage(storage, inter)
if err != nil {
return nil, newError(err, context)
}
return result, nil
}
func (r *interpreterRuntime) commitStorage(storage *Storage, inter *interpreter.Interpreter) error {
const commitContractUpdates = true
err := storage.Commit(inter, commitContractUpdates)
if err != nil {
return err
}
if r.atreeValidationEnabled {
err = storage.CheckHealth()
if err != nil {
return err
}
}
return nil
}
type interpretFunc func(inter *interpreter.Interpreter) (interpreter.Value, error)
func scriptExecutionFunction(
parameters []*sema.Parameter,
arguments [][]byte,
runtimeInterface Interface,
) interpretFunc {
return func(inter *interpreter.Interpreter) (value interpreter.Value, err error) {
// Recover internal panics and return them as an error.
// For example, the argument validation might attempt to
// load contract code for non-existing types
defer inter.RecoverErrors(func(internalErr error) {
err = internalErr
})
values, err := validateArgumentParams(
inter,
runtimeInterface,
arguments,
parameters)
if err != nil {
return nil, err
}
return inter.Invoke("main", values...)
}
}
func (r *interpreterRuntime) interpret(
program *interpreter.Program,
context Context,
storage *Storage,
functions stdlib.StandardLibraryFunctions,
values stdlib.StandardLibraryValues,
interpreterOptions []interpreter.Option,
checkerOptions []sema.Option,
f interpretFunc,
) (
exportableValue,
*interpreter.Interpreter,
error,
) {
inter, err := r.newInterpreter(
program,
context,
functions,
values,
storage,
interpreterOptions,
checkerOptions,
)
if err != nil {
return exportableValue{}, nil, err
}
var result interpreter.Value
reportMetric(
func() {
err = inter.Interpret()
if err != nil || f == nil {
return
}
result, err = f(inter)
},
context.Interface,
func(metrics Metrics, duration time.Duration) {
metrics.ProgramInterpreted(context.Location, duration)
},
)
if err != nil {
return exportableValue{}, nil, err
}
var exportedValue exportableValue
if f != nil {
exportedValue = newExportableValue(result, inter)
}
if inter.ExitHandler != nil {
err = inter.ExitHandler()
}
return exportedValue, inter, err
}
func (r *interpreterRuntime) newAuthAccountValue(
addressValue interpreter.AddressValue,
context Context,
storage *Storage,
interpreterOptions []interpreter.Option,
checkerOptions []sema.Option,
) interpreter.Value {
return interpreter.NewAuthAccountValue(
addressValue,
accountBalanceGetFunction(addressValue, context.Interface),
accountAvailableBalanceGetFunction(addressValue, context.Interface),
storageUsedGetFunction(addressValue, context.Interface, storage),
storageCapacityGetFunction(addressValue, context.Interface),
r.newAddPublicKeyFunction(addressValue, context.Interface),
r.newRemovePublicKeyFunction(addressValue, context.Interface),
func() interpreter.Value {
return r.newAuthAccountContracts(
addressValue,
context,
storage,
interpreterOptions,
checkerOptions,
)
},
func() interpreter.Value {
return r.newAuthAccountKeys(
addressValue,
context.Interface,
)
},
)
}
func (r *interpreterRuntime) InvokeContractFunction(
contractLocation common.AddressLocation,
functionName string,
arguments []interpreter.Value,
argumentTypes []sema.Type,
context Context,
) (val cadence.Value, err error) {
defer r.Recover(
func(internalErr error) {
err = internalErr
},
context,
)
context.InitializeCodesAndPrograms()
storage := NewStorage(context.Interface)
var interpreterOptions []interpreter.Option
var checkerOptions []sema.Option
functions := r.standardLibraryFunctions(
context,
storage,
interpreterOptions,
checkerOptions,
)
// create interpreter
_, inter, err := r.interpret(
nil,
context,
storage,
functions,
stdlib.BuiltinValues,
interpreterOptions,
checkerOptions,
nil,
)
if err != nil {
return nil, newError(err, context)
}
// ensure the contract is loaded
inter = inter.EnsureLoaded(contractLocation)
for i, argumentType := range argumentTypes {
arguments[i] = r.convertArgument(
arguments[i],
argumentType,
context,
storage,
interpreterOptions,
checkerOptions,
)
}
contractValue, err := inter.GetContractComposite(contractLocation)
if err != nil {
return nil, newError(err, context)
}
// prepare invocation
invocation := interpreter.Invocation{
Self: contractValue,
Arguments: arguments,
ArgumentTypes: argumentTypes,
TypeParameterTypes: nil,
GetLocationRange: func() interpreter.LocationRange {
return interpreter.LocationRange{
Location: context.Location,
}
},
Interpreter: inter,
}
contractMember := contractValue.GetMember(inter, invocation.GetLocationRange, functionName)
contractFunction, ok := contractMember.(interpreter.FunctionValue)
if !ok {
return nil, newError(
interpreter.NotInvokableError{
Value: contractFunction,
},
context)
}
value, err := inter.InvokeFunction(contractFunction, invocation)
if err != nil {
return nil, newError(err, context)
}
// Write back all stored values, which were actually just cached, back into storage
err = r.commitStorage(storage, inter)
if err != nil {
return nil, newError(err, context)
}
var exportedValue cadence.Value
exportedValue, err = ExportValue(value, inter)
if err != nil {
return nil, newError(err, context)
}
return exportedValue, nil
}
func (r *interpreterRuntime) convertArgument(
argument interpreter.Value,
argumentType sema.Type,
context Context,
storage *Storage,
interpreterOptions []interpreter.Option,
checkerOptions []sema.Option,
) interpreter.Value {
switch argumentType {
case sema.AuthAccountType:
// convert addresses to auth accounts so there is no need to construct an auth account value for the caller
if addressValue, ok := argument.(interpreter.AddressValue); ok {
return r.newAuthAccountValue(
interpreter.NewAddressValue(addressValue.ToAddress()),
context,
storage,
interpreterOptions,
checkerOptions,
)
}
case sema.PublicAccountType:
// convert addresses to public accounts so there is no need to construct a public account value for the caller
if addressValue, ok := argument.(interpreter.AddressValue); ok {
return r.getPublicAccount(
interpreter.NewAddressValue(addressValue.ToAddress()),
context.Interface,
storage,
)
}
}
return argument
}
func (r *interpreterRuntime) ExecuteTransaction(script Script, context Context) (err error) {
defer r.Recover(
func(internalErr error) {
err = internalErr
},
context,
)
context.InitializeCodesAndPrograms()
storage := NewStorage(context.Interface)
var interpreterOptions []interpreter.Option
var checkerOptions []sema.Option
functions := r.standardLibraryFunctions(
context,
storage,
interpreterOptions,
checkerOptions,
)
program, err := r.parseAndCheckProgram(
script.Source,
context,
functions,
stdlib.BuiltinValues,
checkerOptions,
true,
importResolutionResults{},
)
if err != nil {
return newError(err, context)
}
transactions := program.Elaboration.TransactionTypes
transactionCount := len(transactions)
if transactionCount != 1 {
err = InvalidTransactionCountError{
Count: transactionCount,
}
return newError(err, context)
}
transactionType := transactions[0]
var authorizers []Address
wrapPanic(func() {
authorizers, err = context.Interface.GetSigningAccounts()
})
if err != nil {
return newError(err, context)
}
// check parameter count
argumentCount := len(script.Arguments)
authorizerCount := len(authorizers)
transactionParameterCount := len(transactionType.Parameters)
if argumentCount != transactionParameterCount {
err = InvalidEntryPointParameterCountError{
Expected: transactionParameterCount,
Actual: argumentCount,
}
return newError(err, context)
}
transactionAuthorizerCount := len(transactionType.PrepareParameters)
if authorizerCount != transactionAuthorizerCount {
err = InvalidTransactionAuthorizerCountError{
Expected: transactionAuthorizerCount,
Actual: authorizerCount,
}
return newError(err, context)
}
// gather authorizers
authorizerValues := func(inter *interpreter.Interpreter) []interpreter.Value {
authorizerValues := make([]interpreter.Value, authorizerCount)
for i, address := range authorizers {
authorizerValues[i] = r.newAuthAccountValue(
interpreter.NewAddressValue(address),
context,
storage,
interpreterOptions,
checkerOptions,
)
}
return authorizerValues
}
_, inter, err := r.interpret(
program,
context,
storage,
functions,
stdlib.BuiltinValues,
interpreterOptions,
checkerOptions,
r.transactionExecutionFunction(
transactionType.Parameters,
script.Arguments,
context.Interface,
authorizerValues,
),
)
if err != nil {
return newError(err, context)
}
// Write back all stored values, which were actually just cached, back into storage
err = r.commitStorage(storage, inter)
if err != nil {
return newError(err, context)
}
return nil
}
func wrapPanic(f func()) {
defer func() {
if r := recover(); r != nil {
var ok bool
// don't recover Go errors
goErr, ok := r.(goRuntime.Error)
if ok {
panic(goErr)
}
panic(interpreter.ExternalError{
Recovered: r,
})
}
}()
f()
}
// Executes `f`. On panic, the panic is returned as an error.
// Wraps any non-`error` panics so panic is never propagated.
func panicToError(f func()) (returnedError error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok := r.(error)
if ok {
returnedError = err
} else {
returnedError = fmt.Errorf("%s", r)
}
}
}()
f()
return nil
}
// Executes `f`. On panic, the panic is returned as an error.
// Exception: panics when error is `goRuntime.Error` or `ExternalError`.
func userPanicToError(f func()) error {
err := panicToError(f)
switch err := err.(type) {
case goRuntime.Error, interpreter.ExternalError:
panic(err)
default:
return err
}
}
func (r *interpreterRuntime) transactionExecutionFunction(
parameters []*sema.Parameter,
arguments [][]byte,
runtimeInterface Interface,
authorizerValues func(*interpreter.Interpreter) []interpreter.Value,
) interpretFunc {
return func(inter *interpreter.Interpreter) (value interpreter.Value, err error) {
// Recover internal panics and return them as an error.
// For example, the argument validation might attempt to
// load contract code for non-existing types
defer inter.RecoverErrors(func(internalErr error) {
err = internalErr
})
values, err := validateArgumentParams(
inter,
runtimeInterface,
arguments,
parameters,
)
if err != nil {
return nil, err
}
values = append(values, authorizerValues(inter)...)
err = inter.InvokeTransaction(0, values...)
return nil, err
}
}
func validateArgumentParams(
inter *interpreter.Interpreter,
runtimeInterface Interface,
arguments [][]byte,
parameters []*sema.Parameter,
) (
[]interpreter.Value,
error,
) {
argumentCount := len(arguments)
parameterCount := len(parameters)
if argumentCount != parameterCount {
return nil, InvalidEntryPointParameterCountError{
Expected: parameterCount,
Actual: argumentCount,
}
}
argumentValues := make([]interpreter.Value, len(arguments))
// Decode arguments against parameter types
for i, parameter := range parameters {
parameterType := parameter.TypeAnnotation.Type
argument := arguments[i]
exportedParameterType := ExportType(parameterType, map[sema.TypeID]cadence.Type{})
var value cadence.Value
var err error
wrapPanic(func() {
value, err = runtimeInterface.DecodeArgument(
argument,
exportedParameterType,
)
})
if err != nil {
return nil, &InvalidEntryPointArgumentError{
Index: i,
Err: err,
}
}
var arg interpreter.Value
panicError := userPanicToError(func() {
// if importing an invalid public key, this call panics
arg, err = importValue(inter, value, parameterType)
})
if panicError != nil {
return nil, &InvalidEntryPointArgumentError{
Index: i,
Err: panicError,
}
}
if err != nil {
return nil, &InvalidEntryPointArgumentError{
Index: i,
Err: err,
}
}
dynamicType := arg.DynamicType(inter, interpreter.SeenReferences{})
// Ensure the argument is of an importable type
if !dynamicType.IsImportable() {
return nil, &ArgumentNotImportableError{
Type: dynamicType,
}
}
// Check that decoded value is a subtype of static parameter type
if !inter.IsSubType(dynamicType, parameterType) {
return nil, &InvalidEntryPointArgumentError{
Index: i,
Err: &InvalidValueTypeError{
ExpectedType: parameterType,
},
}
}
// Check whether the decoded value conforms to the type associated with the value
conformanceResults := interpreter.TypeConformanceResults{}
if !arg.ConformsToDynamicType(
inter,
interpreter.ReturnEmptyLocationRange,
dynamicType,
conformanceResults,
) {
return nil, &InvalidEntryPointArgumentError{
Index: i,
Err: &MalformedValueError{
ExpectedType: parameterType,
},
}
}
// Ensure static type info is available for all values
interpreter.InspectValue(arg, func(value interpreter.Value) bool {
if value == nil {
return true
}
if !hasValidStaticType(value) {
panic(fmt.Errorf("invalid static type for argument: %d", i))
}
return true
})
argumentValues[i] = arg
}
return argumentValues, nil
}
func hasValidStaticType(value interpreter.Value) bool {
switch value := value.(type) {
case *interpreter.ArrayValue:
return value.Type != nil
case *interpreter.DictionaryValue:
return value.Type.KeyType != nil &&
value.Type.ValueType != nil
default:
// For other values, static type is NOT inferred.
// Hence no need to validate it here.
return value.StaticType() != nil
}
}
// ParseAndCheckProgram parses the given code and checks it.
// Returns a program that can be interpreted (AST + elaboration).
//
func (r *interpreterRuntime) ParseAndCheckProgram(
code []byte,
context Context,
) (
program *interpreter.Program,
err error,
) {
defer r.Recover(
func(internalErr error) {
err = internalErr
},
context,
)
context.InitializeCodesAndPrograms()
storage := NewStorage(context.Interface)
var interpreterOptions []interpreter.Option
var checkerOptions []sema.Option
functions := r.standardLibraryFunctions(
context,
storage,
interpreterOptions,
checkerOptions,
)
program, err = r.parseAndCheckProgram(
code,
context,
functions,
stdlib.BuiltinValues,
checkerOptions,