-
Notifications
You must be signed in to change notification settings - Fork 175
/
transactionEnv.go
1274 lines (1066 loc) · 38.3 KB
/
transactionEnv.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 fvm
import (
"encoding/binary"
"encoding/hex"
"fmt"
"math/rand"
"time"
"github.com/onflow/atree"
"github.com/onflow/cadence"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/onflow/cadence/runtime"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/interpreter"
"github.com/opentracing/opentracing-go"
traceLog "github.com/opentracing/opentracing-go/log"
"github.com/onflow/flow-go/fvm/blueprints"
"github.com/onflow/flow-go/fvm/crypto"
"github.com/onflow/flow-go/fvm/errors"
"github.com/onflow/flow-go/fvm/handler"
"github.com/onflow/flow-go/fvm/meter"
"github.com/onflow/flow-go/fvm/meter/weighted"
"github.com/onflow/flow-go/fvm/programs"
"github.com/onflow/flow-go/fvm/state"
"github.com/onflow/flow-go/fvm/utils"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module/trace"
"github.com/onflow/flow-go/storage"
)
var _ runtime.Interface = &TransactionEnv{}
// TransactionEnv is a read-write environment used for executing flow transactions.
type TransactionEnv struct {
vm *VirtualMachine
ctx Context
sth *state.StateHolder
programs *handler.ProgramsHandler
accounts state.Accounts
uuidGenerator *state.UUIDGenerator
contracts *handler.ContractHandler
accountKeys *handler.AccountKeyHandler
metrics *handler.MetricsHandler
eventHandler handler.EventHandler
addressGenerator flow.AddressGenerator
rng *rand.Rand
logs []string
tx *flow.TransactionBody
txIndex uint32
txID flow.Identifier
traceSpan opentracing.Span
authorizers []runtime.Address
}
func NewTransactionEnvironment(
ctx Context,
vm *VirtualMachine,
sth *state.StateHolder,
programs *programs.Programs,
tx *flow.TransactionBody,
txIndex uint32,
traceSpan opentracing.Span,
eventHandlerOptions ...handler.FlowEventHandlerOption,
) (*TransactionEnv, error) {
accounts := state.NewAccounts(sth)
generator := state.NewStateBoundAddressGenerator(sth, ctx.Chain)
uuidGenerator := state.NewUUIDGenerator(sth)
programsHandler := handler.NewProgramsHandler(programs, sth)
// TODO set the flags on context
eventHandler := handler.NewFlowEventHandler(ctx.Chain,
ctx.EventCollectionEnabled,
ctx.ServiceEventCollectionEnabled,
ctx.EventCollectionByteSizeLimit,
eventHandlerOptions...,
)
accountKeys := handler.NewAccountKeyHandler(accounts)
metrics := handler.NewMetricsHandler(ctx.Metrics)
env := &TransactionEnv{
vm: vm,
ctx: ctx,
sth: sth,
metrics: metrics,
programs: programsHandler,
accounts: accounts,
accountKeys: accountKeys,
addressGenerator: generator,
uuidGenerator: uuidGenerator,
eventHandler: eventHandler,
tx: tx,
txIndex: txIndex,
txID: tx.ID(),
traceSpan: traceSpan,
}
env.contracts = handler.NewContractHandler(accounts,
func() bool {
enabled, defined := env.GetIsContractDeploymentRestricted()
if !defined {
// If the contract deployment bool is not set by the state
// fallback to the default value set by the configuration
// after the contract deployment bool is set by the state on all chains, this logic can be simplified
return ctx.RestrictedDeploymentEnabled
}
return enabled
},
func() bool {
// TODO read this from the chain similar to the contract deployment
// but for now we would honor the fallback context flag
return ctx.RestrictedContractRemovalEnabled
},
env.GetAccountsAuthorizedForContractUpdate,
env.GetAccountsAuthorizedForContractRemoval,
env.useContractAuditVoucher,
)
if ctx.BlockHeader != nil {
env.seedRNG(ctx.BlockHeader)
}
// set the execution parameters from the state
err := env.setExecutionParameters()
return env, err
}
func (e *TransactionEnv) setExecutionParameters() error {
// Check that the service account exists because all the settings are stored in it
serviceAddress := e.Context().Chain.ServiceAddress()
service := runtime.Address(serviceAddress)
// set the property if no error, but if the error is a fatal error then return it
setIfOk := func(prop string, err error, setter func()) (fatal error) {
err, fatal = errors.SplitErrorTypes(err)
if fatal != nil {
// this is a fatal error. return it
e.ctx.Logger.
Error().
Err(fatal).
Msgf("error getting %s", prop)
return fatal
}
if err != nil {
// this is a general error.
// could be that no setting was present in the state,
// or that the setting was not parseable,
// or some other deterministic thing.
e.ctx.Logger.
Debug().
Err(err).
Msgf("could not set %s. Using defaults", prop)
return nil
}
// everything is ok. do the setting
setter()
return nil
}
var ok bool
var m *weighted.Meter
// only set the weights if the meter is a weighted.Meter
if m, ok = e.sth.State().Meter().(*weighted.Meter); !ok {
return nil
}
computationWeights, err := getExecutionEffortWeights(e, service)
err = setIfOk(
"execution effort weights",
err,
func() { m.SetComputationWeights(computationWeights) })
if err != nil {
return err
}
memoryWeights, err := getExecutionMemoryWeights(e, service)
err = setIfOk(
"execution memory weights",
err,
func() { m.SetMemoryWeights(memoryWeights) })
if err != nil {
return err
}
memoryLimit, err := getExecutionMemoryLimit(e, service)
err = setIfOk(
"execution memory limit",
err,
func() { m.SetTotalMemoryLimit(memoryLimit) })
if err != nil {
return err
}
return nil
}
func (e *TransactionEnv) TxIndex() uint32 {
return e.txIndex
}
func (e *TransactionEnv) TxID() flow.Identifier {
return e.txID
}
func (e *TransactionEnv) Context() *Context {
return &e.ctx
}
func (e *TransactionEnv) VM() *VirtualMachine {
return e.vm
}
func (e *TransactionEnv) seedRNG(header *flow.Header) {
// Seed the random number generator with entropy created from the block header ID. The random number generator will
// be used by the UnsafeRandom function.
id := header.ID()
source := rand.NewSource(int64(binary.BigEndian.Uint64(id[:])))
e.rng = rand.New(source)
}
func (e *TransactionEnv) isTraceable() bool {
return e.ctx.Tracer != nil && e.traceSpan != nil
}
// GetAccountsAuthorizedForContractUpdate returns a list of addresses authorized to update/deploy contracts
func (e *TransactionEnv) GetAccountsAuthorizedForContractUpdate() []common.Address {
return e.GetAuthorizedAccounts(
cadence.Path{
Domain: blueprints.ContractDeploymentAuthorizedAddressesPathDomain,
Identifier: blueprints.ContractDeploymentAuthorizedAddressesPathIdentifier,
})
}
// GetAccountsAuthorizedForContractRemoval returns a list of addresses authorized to remove contracts
func (e *TransactionEnv) GetAccountsAuthorizedForContractRemoval() []common.Address {
return e.GetAuthorizedAccounts(
cadence.Path{
Domain: blueprints.ContractRemovalAuthorizedAddressesPathDomain,
Identifier: blueprints.ContractRemovalAuthorizedAddressesPathIdentifier,
})
}
// GetAuthorizedAccounts returns a list of addresses authorized by the service account.
// Used to determine which accounts are permitted to deploy, update, or remove contracts.
//
// It reads a storage path from service account and parse the addresses.
// If any issue occurs on the process (missing registers, stored value properly not set),
// it gracefully handles it and falls back to default behaviour (only service account be authorized).
func (e *TransactionEnv) GetAuthorizedAccounts(path cadence.Path) []common.Address {
// set default to service account only
service := runtime.Address(e.ctx.Chain.ServiceAddress())
defaultAccounts := []runtime.Address{service}
value, err := e.vm.Runtime.ReadStored(
service,
path,
runtime.Context{Interface: e},
)
const warningMsg = "failed to read contract authorized accounts from service account. using default behaviour instead."
if err != nil {
e.ctx.Logger.Warn().Msg(warningMsg)
return defaultAccounts
}
addresses, ok := utils.CadenceValueToAddressSlice(value)
if !ok {
e.ctx.Logger.Warn().Msg(warningMsg)
return defaultAccounts
}
return addresses
}
// GetIsContractDeploymentRestricted returns if contract deployment restriction is defined in the state and the value of it
func (e *TransactionEnv) GetIsContractDeploymentRestricted() (restricted bool, defined bool) {
restricted, defined = false, false
service := runtime.Address(e.ctx.Chain.ServiceAddress())
value, err := e.vm.Runtime.ReadStored(
service,
cadence.Path{
Domain: blueprints.IsContractDeploymentRestrictedPathDomain,
Identifier: blueprints.IsContractDeploymentRestrictedPathIdentifier,
},
runtime.Context{Interface: e},
)
if err != nil {
e.ctx.Logger.
Debug().
Msg("Failed to read IsContractDeploymentRestricted from the service account. Using value from context instead.")
return restricted, defined
}
restrictedCadence, ok := value.(cadence.Bool)
if !ok {
e.ctx.Logger.
Debug().
Msg("Failed to parse IsContractDeploymentRestricted from the service account. Using value from context instead.")
return restricted, defined
}
defined = true
restricted = restrictedCadence.ToGoValue().(bool)
return restricted, defined
}
func (e *TransactionEnv) useContractAuditVoucher(address runtime.Address, code []byte) (bool, error) {
useVoucher := UseContractAuditVoucherInvocation(e, e.traceSpan)
return useVoucher(address, string(code[:]))
}
func (e *TransactionEnv) isAuthorizerServiceAccount() bool {
return e.isAuthorizer(runtime.Address(e.ctx.Chain.ServiceAddress()))
}
func (e *TransactionEnv) isAuthorizer(address runtime.Address) bool {
for _, accountAddress := range e.getSigningAccounts() {
if accountAddress == address {
return true
}
}
return false
}
func (e *TransactionEnv) GetValue(owner, key []byte) ([]byte, error) {
var valueByteSize int
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetValue)
defer func() {
sp.LogFields(
traceLog.String("owner", hex.EncodeToString(owner)),
traceLog.String("key", string(key)),
traceLog.Int("valueByteSize", valueByteSize),
)
sp.Finish()
}()
}
v, err := e.accounts.GetValue(
flow.BytesToAddress(owner),
string(key),
)
if err != nil {
return nil, fmt.Errorf("get value failed: %w", err)
}
valueByteSize = len(v)
err = e.meterComputation(meter.ComputationKindGetValue, uint(valueByteSize))
if err != nil {
return nil, fmt.Errorf("get value failed: %w", err)
}
return v, nil
}
func (e *TransactionEnv) SetValue(owner, key, value []byte) error {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvSetValue)
sp.LogFields(
traceLog.String("owner", hex.EncodeToString(owner)),
traceLog.String("key", string(key)),
)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindSetValue, uint(len(value)))
if err != nil {
return fmt.Errorf("set value failed: %w", err)
}
err = e.accounts.SetValue(
flow.BytesToAddress(owner),
string(key),
value,
)
if err != nil {
return fmt.Errorf("set value failed: %w", err)
}
return nil
}
func (e *TransactionEnv) ValueExists(owner, key []byte) (exists bool, err error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvValueExists)
defer sp.Finish()
}
err = e.meterComputation(meter.ComputationKindValueExists, 1)
if err != nil {
return false, fmt.Errorf("checking value existence failed: %w", err)
}
v, err := e.GetValue(owner, key)
if err != nil {
return false, fmt.Errorf("checking value existence failed: %w", err)
}
return len(v) > 0, nil
}
// AllocateStorageIndex allocates new storage index under the owner accounts to store a new register
func (e *TransactionEnv) AllocateStorageIndex(owner []byte) (atree.StorageIndex, error) {
err := e.meterComputation(meter.ComputationKindAllocateStorageIndex, 1)
if err != nil {
return atree.StorageIndex{}, fmt.Errorf("allocate storage index failed: %w", err)
}
v, err := e.accounts.AllocateStorageIndex(flow.BytesToAddress(owner))
if err != nil {
return atree.StorageIndex{}, fmt.Errorf("storage address allocation failed: %w", err)
}
return v, nil
}
func (e *TransactionEnv) GetStorageUsed(address common.Address) (value uint64, err error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetStorageUsed)
defer sp.Finish()
}
err = e.meterComputation(meter.ComputationKindGetStorageUsed, 1)
if err != nil {
return value, fmt.Errorf("get storage used failed: %w", err)
}
value, err = e.accounts.GetStorageUsed(flow.Address(address))
if err != nil {
return value, fmt.Errorf("get storage used failed: %w", err)
}
return value, nil
}
func (e *TransactionEnv) GetStorageCapacity(address common.Address) (value uint64, err error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetStorageCapacity)
defer sp.Finish()
}
err = e.meterComputation(meter.ComputationKindGetStorageCapacity, 1)
if err != nil {
return value, fmt.Errorf("get storage capacity failed: %w", err)
}
accountStorageCapacity := AccountStorageCapacityInvocation(e, e.traceSpan)
result, invokeErr := accountStorageCapacity(address)
// TODO: Figure out how to handle this error. Currently if a runtime error occurs, storage capacity will be 0.
// 1. An error will occur if user has removed their FlowToken.Vault -- should this be allowed?
// 2. There will also be an error in case the accounts balance times megabytesPerFlow constant overflows,
// which shouldn't happen unless the the price of storage is reduced at least 100 fold
// 3. Any other error indicates a bug in our implementation. How can we reliably check the Cadence error?
if invokeErr != nil {
return 0, nil
}
return storageMBUFixToBytesUInt(result), nil
}
// storageMBUFixToBytesUInt converts the return type of storage capacity which is a UFix64 with the unit of megabytes to
// UInt with the unit of bytes
func storageMBUFixToBytesUInt(result cadence.Value) uint64 {
// Divide the unsigned int by (1e8 (the scale of Fix64) / 1e6 (for mega)) to get bytes (rounded down)
return result.ToGoValue().(uint64) / 100
}
func (e *TransactionEnv) GetAccountBalance(address common.Address) (value uint64, err error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetAccountBalance)
defer sp.Finish()
}
err = e.meterComputation(meter.ComputationKindGetAccountBalance, 1)
if err != nil {
return value, fmt.Errorf("get account balance failed: %w", err)
}
accountBalance := AccountBalanceInvocation(e, e.traceSpan)
result, invokeErr := accountBalance(address)
// TODO: Figure out how to handle this error. Currently if a runtime error occurs, balance will be 0.
if invokeErr != nil {
return 0, nil
}
return result.ToGoValue().(uint64), nil
}
func (e *TransactionEnv) GetAccountAvailableBalance(address common.Address) (value uint64, err error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetAccountBalance)
defer sp.Finish()
}
err = e.meterComputation(meter.ComputationKindGetAccountAvailableBalance, 1)
if err != nil {
return value, fmt.Errorf("get account available balance failed: %w", err)
}
accountAvailableBalance := AccountAvailableBalanceInvocation(e, e.traceSpan)
result, invokeErr := accountAvailableBalance(address)
// TODO: Figure out how to handle this error. Currently if a runtime error occurs, available balance will be 0.
// 1. An error will occur if user has removed their FlowToken.Vault -- should this be allowed?
// 2. Any other error indicates a bug in our implementation. How can we reliably check the Cadence error?
if invokeErr != nil {
return 0, nil
}
return result.ToGoValue().(uint64), nil
}
func (e *TransactionEnv) ResolveLocation(
identifiers []runtime.Identifier,
location runtime.Location,
) ([]runtime.ResolvedLocation, error) {
if e.isTraceable() && e.ctx.ExtensiveTracing {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvResolveLocation)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindResolveLocation, 1)
if err != nil {
return nil, fmt.Errorf("resolve location failed: %w", err)
}
addressLocation, isAddress := location.(common.AddressLocation)
// if the location is not an address location, e.g. an identifier location (`import Crypto`),
// then return a single resolved location which declares all identifiers.
if !isAddress {
return []runtime.ResolvedLocation{
{
Location: location,
Identifiers: identifiers,
},
}, nil
}
// if the location is an address,
// and no specific identifiers where requested in the import statement,
// then fetch all identifiers at this address
if len(identifiers) == 0 {
address := flow.Address(addressLocation.Address)
err := e.accounts.CheckAccountNotFrozen(address)
if err != nil {
return nil, fmt.Errorf("resolving location failed: %w", err)
}
contractNames, err := e.contracts.GetContractNames(addressLocation.Address)
if err != nil {
return nil, fmt.Errorf("resolving location failed: %w", err)
}
// if there are no contractNames deployed,
// then return no resolved locations
if len(contractNames) == 0 {
return nil, nil
}
identifiers = make([]ast.Identifier, len(contractNames))
for i := range identifiers {
identifiers[i] = runtime.Identifier{
Identifier: contractNames[i],
}
}
}
// return one resolved location per identifier.
// each resolved location is an address contract location
resolvedLocations := make([]runtime.ResolvedLocation, len(identifiers))
for i := range resolvedLocations {
identifier := identifiers[i]
resolvedLocations[i] = runtime.ResolvedLocation{
Location: common.AddressLocation{
Address: addressLocation.Address,
Name: identifier.Identifier,
},
Identifiers: []runtime.Identifier{identifier},
}
}
return resolvedLocations, nil
}
func (e *TransactionEnv) GetCode(location runtime.Location) ([]byte, error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetCode)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindGetCode, 1)
if err != nil {
return nil, fmt.Errorf("get code failed: %w", err)
}
contractLocation, ok := location.(common.AddressLocation)
if !ok {
return nil, errors.NewInvalidLocationErrorf(location, "expecting an AddressLocation, but other location types are passed")
}
address := flow.Address(contractLocation.Address)
err = e.accounts.CheckAccountNotFrozen(address)
if err != nil {
return nil, fmt.Errorf("get code failed: %w", err)
}
add, err := e.contracts.GetContract(contractLocation.Address, contractLocation.Name)
if err != nil {
return nil, fmt.Errorf("get code failed: %w", err)
}
return add, nil
}
func (e *TransactionEnv) GetAccountContractNames(address runtime.Address) ([]string, error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetAccountContractNames)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindGetAccountContractNames, 1)
if err != nil {
return nil, fmt.Errorf("get account contract names failed: %w", err)
}
a := flow.Address(address)
freezeError := e.accounts.CheckAccountNotFrozen(a)
if freezeError != nil {
return nil, fmt.Errorf("get account contract names failed: %w", freezeError)
}
return e.accounts.GetContractNames(a)
}
func (e *TransactionEnv) GetProgram(location common.Location) (*interpreter.Program, error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetProgram)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindGetProgram, 1)
if err != nil {
return nil, fmt.Errorf("get program failed: %w", err)
}
if addressLocation, ok := location.(common.AddressLocation); ok {
address := flow.Address(addressLocation.Address)
freezeError := e.accounts.CheckAccountNotFrozen(address)
if freezeError != nil {
return nil, fmt.Errorf("get program failed: %w", freezeError)
}
}
program, has := e.programs.Get(location)
if has {
return program, nil
}
return nil, nil
}
func (e *TransactionEnv) SetProgram(location common.Location, program *interpreter.Program) error {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvSetProgram)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindSetProgram, 1)
if err != nil {
return fmt.Errorf("set program failed: %w", err)
}
err = e.programs.Set(location, program)
if err != nil {
return fmt.Errorf("set program failed: %w", err)
}
return nil
}
func (e *TransactionEnv) ProgramLog(message string) error {
if e.isTraceable() && e.ctx.ExtensiveTracing {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvProgramLog)
defer sp.Finish()
}
if e.ctx.CadenceLoggingEnabled {
e.logs = append(e.logs, message)
}
return nil
}
func (e *TransactionEnv) Logs() []string {
return e.logs
}
func (e *TransactionEnv) EmitEvent(event cadence.Event) error {
// only trace when extensive tracing
if e.isTraceable() && e.ctx.ExtensiveTracing {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvEmitEvent)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindEmitEvent, 1)
if err != nil {
return fmt.Errorf("emit event failed: %w", err)
}
return e.eventHandler.EmitEvent(event, e.txID, e.txIndex, e.tx.Payer)
}
func (e *TransactionEnv) Events() []flow.Event {
return e.eventHandler.Events()
}
func (e *TransactionEnv) ServiceEvents() []flow.Event {
return e.eventHandler.ServiceEvents()
}
func (e *TransactionEnv) GenerateUUID() (uint64, error) {
if e.isTraceable() && e.ctx.ExtensiveTracing {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGenerateUUID)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindGenerateUUID, 1)
if err != nil {
return 0, fmt.Errorf("generate uuid failed: %w", err)
}
if e.uuidGenerator == nil {
return 0, errors.NewOperationNotSupportedError("GenerateUUID")
}
uuid, err := e.uuidGenerator.GenerateUUID()
if err != nil {
return 0, fmt.Errorf("generate uuid failed: %w", err)
}
return uuid, err
}
func (e *TransactionEnv) meterComputation(kind common.ComputationKind, intensity uint) error {
if e.sth.EnforceComputationLimits {
return e.sth.State().MeterComputation(kind, intensity)
}
return nil
}
func (e *TransactionEnv) MeterComputation(kind common.ComputationKind, intensity uint) error {
return e.meterComputation(kind, intensity)
}
func (e *TransactionEnv) ComputationUsed() uint64 {
return uint64(e.sth.State().TotalComputationUsed())
}
func (e *TransactionEnv) meterMemory(kind common.MemoryKind, intensity uint) error {
if e.sth.EnforceMemoryLimits() {
return e.sth.State().MeterMemory(kind, intensity)
}
return nil
}
func (e *TransactionEnv) MeterMemory(usage common.MemoryUsage) error {
return e.meterMemory(usage.Kind, uint(usage.Amount))
}
func (e *TransactionEnv) MemoryUsed() uint64 {
return uint64(e.sth.State().TotalMemoryUsed())
}
func (e *TransactionEnv) SetAccountFrozen(address common.Address, frozen bool) error {
flowAddress := flow.Address(address)
if flowAddress == e.ctx.Chain.ServiceAddress() {
err := errors.NewValueErrorf(flowAddress.String(), "cannot freeze service account")
return fmt.Errorf("setting account frozen failed: %w", err)
}
if !e.isAuthorizerServiceAccount() {
err := errors.NewOperationAuthorizationErrorf("SetAccountFrozen", "accounts can be frozen only by transactions authorized by the service account")
return fmt.Errorf("setting account frozen failed: %w", err)
}
err := e.accounts.SetAccountFrozen(flowAddress, frozen)
if err != nil {
return fmt.Errorf("setting account frozen failed: %w", err)
}
return nil
}
func (e *TransactionEnv) DecodeArgument(b []byte, _ cadence.Type) (cadence.Value, error) {
if e.isTraceable() && e.ctx.ExtensiveTracing {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvDecodeArgument)
defer sp.Finish()
}
v, err := jsoncdc.Decode(e, b)
if err != nil {
err = errors.NewInvalidArgumentErrorf("argument is not json decodable: %w", err)
return nil, fmt.Errorf("decodeing argument failed: %w", err)
}
return v, err
}
func (e *TransactionEnv) Hash(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm) ([]byte, error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvHash)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindHash, 1)
if err != nil {
return nil, fmt.Errorf("hash failed: %w", err)
}
hashAlgo := crypto.RuntimeToCryptoHashingAlgorithm(hashAlgorithm)
return crypto.HashWithTag(hashAlgo, tag, data)
}
func (e *TransactionEnv) VerifySignature(
signature []byte,
tag string,
signedData []byte,
publicKey []byte,
signatureAlgorithm runtime.SignatureAlgorithm,
hashAlgorithm runtime.HashAlgorithm,
) (bool, error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvVerifySignature)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindVerifySignature, 1)
if err != nil {
return false, fmt.Errorf("verify signature failed: %w", err)
}
valid, err := crypto.VerifySignatureFromRuntime(
signature,
tag,
signedData,
publicKey,
signatureAlgorithm,
hashAlgorithm,
)
if err != nil {
return false, fmt.Errorf("verify signature failed: %w", err)
}
return valid, nil
}
func (e *TransactionEnv) ValidatePublicKey(pk *runtime.PublicKey) error {
err := e.meterComputation(meter.ComputationKindValidatePublicKey, 1)
if err != nil {
return fmt.Errorf("validate public key failed: %w", err)
}
return crypto.ValidatePublicKey(pk.SignAlgo, pk.PublicKey)
}
// Block Environment Functions
// GetCurrentBlockHeight returns the current block height.
func (e *TransactionEnv) GetCurrentBlockHeight() (uint64, error) {
if e.isTraceable() && e.ctx.ExtensiveTracing {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetCurrentBlockHeight)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindGetCurrentBlockHeight, 1)
if err != nil {
return 0, fmt.Errorf("get current block height failed: %w", err)
}
if e.ctx.BlockHeader == nil {
return 0, errors.NewOperationNotSupportedError("GetCurrentBlockHeight")
}
return e.ctx.BlockHeader.Height, nil
}
// UnsafeRandom returns a random uint64, where the process of random number derivation is not cryptographically
// secure.
func (e *TransactionEnv) UnsafeRandom() (uint64, error) {
if e.isTraceable() && e.ctx.ExtensiveTracing {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvUnsafeRandom)
defer sp.Finish()
}
if e.rng == nil {
return 0, errors.NewOperationNotSupportedError("UnsafeRandom")
}
// TODO (ramtin) return errors this assumption that this always succeeds might not be true
buf := make([]byte, 8)
_, _ = e.rng.Read(buf) // Always succeeds, no need to check error
return binary.LittleEndian.Uint64(buf), nil
}
// GetBlockAtHeight returns the block at the given height.
func (e *TransactionEnv) GetBlockAtHeight(height uint64) (runtime.Block, bool, error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvGetBlockAtHeight)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindGetBlockAtHeight, 1)
if err != nil {
return runtime.Block{}, false, fmt.Errorf("get block at height failed: %w", err)
}
if e.ctx.Blocks == nil {
return runtime.Block{}, false, errors.NewOperationNotSupportedError("GetBlockAtHeight")
}
if e.ctx.BlockHeader != nil && height == e.ctx.BlockHeader.Height {
return runtimeBlockFromHeader(e.ctx.BlockHeader), true, nil
}
header, err := e.ctx.Blocks.ByHeightFrom(height, e.ctx.BlockHeader)
// TODO (ramtin): remove dependency on storage and move this if condition to blockfinder
if errors.Is(err, storage.ErrNotFound) {
return runtime.Block{}, false, nil
} else if err != nil {
return runtime.Block{}, false, fmt.Errorf("get block at height failed for height %v: %w", height, err)
}
return runtimeBlockFromHeader(header), true, nil
}
func (e *TransactionEnv) CreateAccount(payer runtime.Address) (address runtime.Address, err error) {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvCreateAccount)
defer sp.Finish()
}
err = e.meterComputation(meter.ComputationKindCreateAccount, 1)
if err != nil {
return address, err
}
e.sth.DisableAllLimitEnforcements() // don't enforce limit during account creation
defer e.sth.EnableAllLimitEnforcements()
flowAddress, err := e.addressGenerator.NextAddress()
if err != nil {
return address, err
}
err = e.accounts.Create(nil, flowAddress)
if err != nil {
return address, fmt.Errorf("create account failed: %w", err)
}
if e.ctx.ServiceAccountEnabled {
setupNewAccount := SetupNewAccountInvocation(e, e.traceSpan)
_, invokeErr := setupNewAccount(flowAddress, payer)
if invokeErr != nil {
return address, errors.HandleRuntimeError(invokeErr)
}
}
e.ctx.Metrics.RuntimeSetNumberOfAccounts(e.addressGenerator.AddressCount())
return runtime.Address(flowAddress), nil
}
// AddEncodedAccountKey adds an encoded public key to an existing account.
//
// This function returns an error if the specified account does not exist or
// if the key insertion fails.
func (e *TransactionEnv) AddEncodedAccountKey(address runtime.Address, publicKey []byte) error {
if e.isTraceable() {
sp := e.ctx.Tracer.StartSpanFromParent(e.traceSpan, trace.FVMEnvAddAccountKey)
defer sp.Finish()
}
err := e.meterComputation(meter.ComputationKindAddEncodedAccountKey, 1)
if err != nil {
return fmt.Errorf("add encoded account key failed: %w", err)
}
// TODO do a call to track the computation usage and memory usage
e.sth.DisableAllLimitEnforcements() // don't enforce limit during adding a key
defer e.sth.EnableAllLimitEnforcements()
err = e.accounts.CheckAccountNotFrozen(flow.Address(address))
if err != nil {
return fmt.Errorf("add encoded account key failed: %w", err)
}
err = e.accountKeys.AddEncodedAccountKey(address, publicKey)