-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.go
1492 lines (1215 loc) · 40.5 KB
/
blockchain.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 emulator provides an emulated version of the Flow blockchain that can be used
// for development purposes.
//
// This package can be used as a library or as a standalone application.
//
// When used as a library, this package provides tools to write programmatic tests for
// Flow applications.
//
// When used as a standalone application, this package implements the Flow Access API
// and is fully-compatible with Flow gRPC client libraries.
package emulator
import (
"errors"
"fmt"
"math"
"sync"
"time"
"github.com/onflow/atree"
"github.com/onflow/cadence"
"github.com/onflow/cadence/runtime"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/interpreter"
sdk "github.com/onflow/flow-go-sdk"
sdkcrypto "github.com/onflow/flow-go-sdk/crypto"
"github.com/onflow/flow-go-sdk/templates"
"github.com/onflow/flow-go/access"
"github.com/onflow/flow-go/crypto"
"github.com/onflow/flow-go/crypto/hash"
"github.com/onflow/flow-go/engine/execution/state/delta"
"github.com/onflow/flow-go/fvm"
fvmcrypto "github.com/onflow/flow-go/fvm/crypto"
fvmerrors "github.com/onflow/flow-go/fvm/errors"
"github.com/onflow/flow-go/fvm/meter"
"github.com/onflow/flow-go/fvm/programs"
"github.com/onflow/flow-go/fvm/state"
flowgo "github.com/onflow/flow-go/model/flow"
"github.com/rs/zerolog"
"github.com/onflow/flow-emulator/convert"
sdkconvert "github.com/onflow/flow-emulator/convert/sdk"
"github.com/onflow/flow-emulator/storage"
"github.com/onflow/flow-emulator/storage/memstore"
"github.com/onflow/flow-emulator/types"
"github.com/opentracing/opentracing-go"
)
// Blockchain emulates the functionality of the Flow blockchain.
type Blockchain struct {
// committed chain state: blocks, transactions, registers, events
storage storage.Store
// mutex protecting pending block
mu sync.RWMutex
// pending block containing block info, register state, pending transactions
pendingBlock *pendingBlock
// used to execute transactions and scripts
vm *fvm.VirtualMachine
vmCtx fvm.Context
transactionValidator *access.TransactionValidator
serviceKey ServiceKey
}
type ServiceKey struct {
Index int
Address sdk.Address
SequenceNumber uint64
PrivateKey sdkcrypto.PrivateKey
PublicKey sdkcrypto.PublicKey
HashAlgo sdkcrypto.HashAlgorithm
SigAlgo sdkcrypto.SignatureAlgorithm
Weight int
}
func (s ServiceKey) Signer() (sdkcrypto.Signer, error) {
return sdkcrypto.NewInMemorySigner(s.PrivateKey, s.HashAlgo)
}
func (s ServiceKey) AccountKey() *sdk.AccountKey {
var publicKey sdkcrypto.PublicKey
if s.PublicKey != nil {
publicKey = s.PublicKey
}
if s.PrivateKey != nil {
publicKey = s.PrivateKey.PublicKey()
}
return &sdk.AccountKey{
Index: s.Index,
PublicKey: publicKey,
SigAlgo: s.SigAlgo,
HashAlgo: s.HashAlgo,
Weight: s.Weight,
SequenceNumber: s.SequenceNumber,
}
}
const defaultServiceKeyPrivateKeySeed = "elephant ears space cowboy octopus rodeo potato cannon pineapple"
const DefaultServiceKeySigAlgo = sdkcrypto.ECDSA_P256
const DefaultServiceKeyHashAlgo = sdkcrypto.SHA3_256
func DefaultServiceKey() ServiceKey {
return GenerateDefaultServiceKey(DefaultServiceKeySigAlgo, DefaultServiceKeyHashAlgo)
}
func GenerateDefaultServiceKey(
sigAlgo sdkcrypto.SignatureAlgorithm,
hashAlgo sdkcrypto.HashAlgorithm,
) ServiceKey {
privateKey, err := sdkcrypto.GeneratePrivateKey(
sigAlgo,
[]byte(defaultServiceKeyPrivateKeySeed),
)
if err != nil {
panic(fmt.Sprintf("Failed to generate default service key: %s", err.Error()))
}
return ServiceKey{
PrivateKey: privateKey,
SigAlgo: sigAlgo,
HashAlgo: hashAlgo,
}
}
// config is a set of configuration options for an emulated blockchain.
type config struct {
ServiceKey ServiceKey
Store storage.Store
SimpleAddresses bool
GenesisTokenSupply cadence.UFix64
TransactionMaxGasLimit uint64
ScriptGasLimit uint64
TransactionExpiry uint
StorageLimitEnabled bool
TransactionFeesEnabled bool
TransactionValidationEnabled bool
MinimumStorageReservation cadence.UFix64
StorageMBPerFLOW cadence.UFix64
Logger zerolog.Logger
}
func (conf config) GetStore() storage.Store {
// if no store is specified, use a memstore
// NOTE: we don't initialize this in defaultConfig because otherwise the same
// memstore is shared between Blockchain instances
if conf.Store == nil {
return memstore.New()
}
return conf.Store
}
func (conf config) GetChainID() flowgo.ChainID {
if conf.SimpleAddresses {
return flowgo.MonotonicEmulator
}
return flowgo.Emulator
}
func (conf config) GetServiceKey() ServiceKey {
// set up service key
serviceKey := conf.ServiceKey
serviceKey.Address = sdk.Address(conf.GetChainID().Chain().ServiceAddress())
serviceKey.Weight = sdk.AccountKeyWeightThreshold
return serviceKey
}
const defaultGenesisTokenSupply = "1000000000.0"
const defaultScriptGasLimit = 100000
const defaultTransactionMaxGasLimit = flowgo.DefaultMaxTransactionGasLimit
// defaultConfig is the default configuration for an emulated blockchain.
var defaultConfig = func() config {
genesisTokenSupply, err := cadence.NewUFix64(defaultGenesisTokenSupply)
if err != nil {
panic(fmt.Sprintf("Failed to parse default genesis token supply: %s", err.Error()))
}
return config{
ServiceKey: DefaultServiceKey(),
Store: nil,
SimpleAddresses: false,
GenesisTokenSupply: genesisTokenSupply,
ScriptGasLimit: defaultScriptGasLimit,
TransactionMaxGasLimit: defaultTransactionMaxGasLimit,
MinimumStorageReservation: fvm.DefaultMinimumStorageReservation,
StorageMBPerFLOW: fvm.DefaultStorageMBPerFLOW,
TransactionExpiry: 0, // TODO: replace with sensible default
StorageLimitEnabled: true,
TransactionValidationEnabled: true,
Logger: zerolog.Nop(),
}
}()
// Option is a function applying a change to the emulator config.
type Option func(*config)
//WithLogger sets the logger
func WithLogger(
logger zerolog.Logger,
) Option {
return func(c *config) {
c.Logger = logger
}
}
// WithServicePublicKey sets the service key from a public key.
func WithServicePublicKey(
servicePublicKey sdkcrypto.PublicKey,
sigAlgo sdkcrypto.SignatureAlgorithm,
hashAlgo sdkcrypto.HashAlgorithm,
) Option {
return func(c *config) {
c.ServiceKey = ServiceKey{
PublicKey: servicePublicKey,
SigAlgo: sigAlgo,
HashAlgo: hashAlgo,
}
}
}
// WithServicePrivateKey sets the service key from private key.
func WithServicePrivateKey(
privateKey sdkcrypto.PrivateKey,
sigAlgo sdkcrypto.SignatureAlgorithm,
hashAlgo sdkcrypto.HashAlgorithm,
) Option {
return func(c *config) {
c.ServiceKey = ServiceKey{
PrivateKey: privateKey,
PublicKey: privateKey.PublicKey(),
HashAlgo: hashAlgo,
SigAlgo: sigAlgo,
}
}
}
// WithStore sets the persistent storage provider.
func WithStore(store storage.Store) Option {
return func(c *config) {
c.Store = store
}
}
// WithSimpleAddresses enables simple addresses, which are sequential starting with 0x01.
func WithSimpleAddresses(enabled bool) Option {
return func(c *config) {
c.SimpleAddresses = enabled
}
}
// WithGenesisTokenSupply sets the genesis token supply.
func WithGenesisTokenSupply(supply cadence.UFix64) Option {
return func(c *config) {
c.GenesisTokenSupply = supply
}
}
// WithTransactionMaxGasLimit sets the maximum gas limit for transactions.
//
// Individual transactions will still be bounded by the limit they declare.
// This function sets the maximum limit that any transaction can declare.
//
// This limit does not affect script executions. Use WithScriptGasLimit
// to set the gas limit for script executions.
func WithTransactionMaxGasLimit(maxLimit uint64) Option {
return func(c *config) {
c.TransactionMaxGasLimit = maxLimit
}
}
// WithScriptGasLimit sets the gas limit for scripts.
//
// This limit does not affect transactions, which declare their own limit.
// Use WithTransactionMaxGasLimit to set the maximum gas limit for transactions.
func WithScriptGasLimit(limit uint64) Option {
return func(c *config) {
c.ScriptGasLimit = limit
}
}
// WithTransactionExpiry sets the transaction expiry measured in blocks.
//
// If set to zero, transaction expiry is disabled and the reference block ID field
// is not required.
func WithTransactionExpiry(expiry uint) Option {
return func(c *config) {
c.TransactionExpiry = expiry
}
}
// WithStorageLimitEnabled enables/disables limiting account storage used to their storage capacity.
//
// If set to false, accounts can store any amount of data,
// otherwise they can only store as much as their storage capacity.
// The default is true.
func WithStorageLimitEnabled(enabled bool) Option {
return func(c *config) {
c.StorageLimitEnabled = enabled
}
}
// WithMinimumStorageReservation sets the minimum account balance.
//
// The cost of creating new accounts is also set to this value.
// The default is taken from fvm.DefaultMinimumStorageReservation
func WithMinimumStorageReservation(minimumStorageReservation cadence.UFix64) Option {
return func(c *config) {
c.MinimumStorageReservation = minimumStorageReservation
}
}
// WithStorageMBPerFLOW sets the cost of a megabyte of storage in FLOW
//
// the default is taken from fvm.DefaultStorageMBPerFLOW
func WithStorageMBPerFLOW(storageMBPerFLOW cadence.UFix64) Option {
return func(c *config) {
c.StorageMBPerFLOW = storageMBPerFLOW
}
}
// WithTransactionFeesEnabled enables/disables transaction fees.
//
// If set to false transactions don't cost any flow.
// The default is false.
func WithTransactionFeesEnabled(enabled bool) Option {
return func(c *config) {
c.TransactionFeesEnabled = enabled
}
}
// WithTransactionValidationEnabled enables/disables transaction valudation.
//
// If set to false transactions don't check for signatures or sequence numbers.
// The default is true.
func WithTransactionValidationEnabled(enabled bool) Option {
return func(c *config) {
c.TransactionValidationEnabled = enabled
}
}
// NewBlockchain instantiates a new emulated blockchain with the provided options.
func NewBlockchain(opts ...Option) (*Blockchain, error) {
// apply options to the default config
conf := defaultConfig
for _, opt := range opts {
opt(&conf)
}
b := &Blockchain{
storage: conf.GetStore(),
serviceKey: conf.GetServiceKey(),
}
var err error
blocks := newBlocks(b)
b.vm, b.vmCtx, err = configureFVM(conf, blocks)
if err != nil {
return nil, err
}
latestBlock, latestLedgerView, err := configureLedger(conf, b.storage, b.vm, b.vmCtx)
if err != nil {
return nil, err
}
b.pendingBlock = newPendingBlock(latestBlock, latestLedgerView)
b.transactionValidator = configureTransactionValidator(conf, blocks)
return b, nil
}
func configureFVM(conf config, blocks *blocks) (*fvm.VirtualMachine, fvm.Context, error) {
rt := runtime.NewInterpreterRuntime()
vm := fvm.NewVirtualMachine(rt)
fvmOptions := []fvm.Option{
fvm.WithChain(conf.GetChainID().Chain()),
fvm.WithBlocks(blocks),
fvm.WithRestrictedDeployment(false),
fvm.WithGasLimit(conf.ScriptGasLimit),
fvm.WithCadenceLogging(true),
fvm.WithAccountStorageLimit(conf.StorageLimitEnabled),
fvm.WithTransactionFeesEnabled(conf.TransactionFeesEnabled),
}
if !conf.TransactionValidationEnabled {
fvmOptions = append(fvmOptions, fvm.WithTransactionProcessors(fvm.NewTransactionInvoker(zerolog.Nop())))
}
ctx := fvm.NewContext(
zerolog.Nop(),
fvmOptions...,
)
return vm, ctx, nil
}
func configureLedger(
conf config,
store storage.Store,
vm *fvm.VirtualMachine,
ctx fvm.Context,
) (*flowgo.Block, *delta.View, error) {
latestBlock, err := store.LatestBlock()
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
// storage is empty, bootstrap new ledger state
return configureNewLedger(conf, store, vm, ctx)
}
// internal storage error, fail fast
return nil, nil, err
}
// storage contains data, load state from storage
return configureExistingLedger(&latestBlock, store)
}
func configureNewLedger(
conf config,
store storage.Store,
vm *fvm.VirtualMachine,
ctx fvm.Context,
) (*flowgo.Block, *delta.View, error) {
genesisLedgerView := store.LedgerViewByHeight(0)
err := bootstrapLedger(
vm,
ctx,
genesisLedgerView,
conf,
)
if err != nil {
return nil, nil, fmt.Errorf("failed to bootstrap execution state: %w", err)
}
// commit the genesis block to storage
genesis := flowgo.Genesis(conf.GetChainID())
err = store.CommitBlock(
*genesis,
nil,
nil,
nil,
genesisLedgerView.Delta(),
nil,
)
if err != nil {
return nil, nil, err
}
// get empty ledger view
ledgerView := store.LedgerViewByHeight(0)
return genesis, ledgerView, nil
}
func configureExistingLedger(
latestBlock *flowgo.Block,
store storage.Store,
) (*flowgo.Block, *delta.View, error) {
latestLedgerView := store.LedgerViewByHeight(latestBlock.Header.Height)
return latestBlock, latestLedgerView, nil
}
func bootstrapLedger(
vm *fvm.VirtualMachine,
ctx fvm.Context,
ledger state.View,
conf config,
) error {
accountKey := conf.GetServiceKey().AccountKey()
publicKey, _ := crypto.DecodePublicKey(
accountKey.SigAlgo,
accountKey.PublicKey.Encode(),
)
ctx = fvm.NewContextFromParent(
ctx,
fvm.WithAccountStorageLimit(false),
)
flowAccountKey := flowgo.AccountPublicKey{
PublicKey: publicKey,
SignAlgo: accountKey.SigAlgo,
HashAlgo: accountKey.HashAlgo,
Weight: fvm.AccountKeyWeightThreshold,
}
bootstrap := configureBootstrapProcedure(conf, flowAccountKey, conf.GenesisTokenSupply)
err := vm.Run(ctx, bootstrap, ledger, programs.NewEmptyPrograms())
if err != nil {
return err
}
return nil
}
func configureBootstrapProcedure(conf config, flowAccountKey flowgo.AccountPublicKey, supply cadence.UFix64) *fvm.BootstrapProcedure {
options := make([]fvm.BootstrapProcedureOption, 0)
options = append(options,
fvm.WithInitialTokenSupply(supply),
fvm.WithRestrictedAccountCreationEnabled(false),
)
if conf.StorageLimitEnabled {
options = append(options,
fvm.WithAccountCreationFee(conf.MinimumStorageReservation),
fvm.WithMinimumStorageReservation(conf.MinimumStorageReservation),
fvm.WithStorageMBPerFLOW(conf.StorageMBPerFLOW),
)
}
if conf.TransactionFeesEnabled {
// This enables variable transaction fees AND execution effort metering
// as described in Variable Transaction Fees: Execution Effort FLIP: https://github.com/onflow/flow/pull/753)
// TODO: In the future this should be an injectable parameter. For now this is hard coded
// as this is the first iteration of variable execution fees.
options = append(options,
fvm.WithTransactionFee(fvm.BootstrapProcedureFeeParameters{
SurgeFactor: cadence.UFix64(100_000_000), // 1.0
InclusionEffortCost: cadence.UFix64(100), // 1E-6
ExecutionEffortCost: cadence.UFix64(499_000_000), // 4.99
}),
fvm.WithExecutionEffortWeights(map[common.ComputationKind]uint64{
common.ComputationKindStatement: 1569,
common.ComputationKindLoop: 1569,
common.ComputationKindFunctionInvocation: 1569,
meter.ComputationKindGetValue: 808,
meter.ComputationKindCreateAccount: 2837670,
meter.ComputationKindSetValue: 765,
}),
)
}
return fvm.Bootstrap(
flowAccountKey,
options...,
)
}
func configureTransactionValidator(conf config, blocks *blocks) *access.TransactionValidator {
return access.NewTransactionValidator(
blocks,
conf.GetChainID().Chain(),
access.TransactionValidationOptions{
Expiry: conf.TransactionExpiry,
ExpiryBuffer: 0,
AllowEmptyReferenceBlockID: conf.TransactionExpiry == 0,
AllowUnknownReferenceBlockID: false,
MaxGasLimit: conf.TransactionMaxGasLimit,
CheckScriptsParse: true,
MaxTransactionByteSize: flowgo.DefaultMaxTransactionByteSize,
MaxCollectionByteSize: flowgo.DefaultMaxCollectionByteSize,
},
)
}
// ServiceKey returns the service private key for this blockchain.
func (b *Blockchain) ServiceKey() ServiceKey {
serviceAccount, err := b.getAccount(sdkconvert.SDKAddressToFlow(b.serviceKey.Address))
if err != nil {
return b.serviceKey
}
if len(serviceAccount.Keys) > 0 {
b.serviceKey.Index = 0
b.serviceKey.SequenceNumber = serviceAccount.Keys[0].SeqNumber
b.serviceKey.Weight = serviceAccount.Keys[0].Weight
}
return b.serviceKey
}
// PendingBlockID returns the ID of the pending block.
func (b *Blockchain) PendingBlockID() flowgo.Identifier {
return b.pendingBlock.ID()
}
// PendingBlockView returns the view of the pending block.
func (b *Blockchain) PendingBlockView() uint64 {
return b.pendingBlock.view
}
// PendingBlockTimestamp returns the Timestamp of the pending block.
func (b *Blockchain) PendingBlockTimestamp() time.Time {
return b.pendingBlock.Block().Header.Timestamp
}
// GetLatestBlock gets the latest sealed block.
func (b *Blockchain) GetLatestBlock() (*flowgo.Block, error) {
block, err := b.storage.LatestBlock()
if err != nil {
return nil, &StorageError{err}
}
return &block, nil
}
// GetBlockByID gets a block by ID.
func (b *Blockchain) GetBlockByID(id sdk.Identifier) (*flowgo.Block, error) {
block, err := b.storage.BlockByID(sdkconvert.SDKIdentifierToFlow(id))
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, &BlockNotFoundByIDError{ID: id}
}
return nil, &StorageError{err}
}
return block, nil
}
// GetBlockByHeight gets a block by height.
func (b *Blockchain) GetBlockByHeight(height uint64) (*flowgo.Block, error) {
block, err := b.getBlockByHeight(height)
if err != nil {
return nil, err
}
return block, nil
}
func (b *Blockchain) getBlockByHeight(height uint64) (*flowgo.Block, error) {
block, err := b.storage.BlockByHeight(height)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, &BlockNotFoundByHeightError{Height: height}
}
return nil, err
}
return block, nil
}
func (b *Blockchain) GetChain() flowgo.Chain {
return b.vmCtx.Chain
}
func (b *Blockchain) GetCollection(colID sdk.Identifier) (*sdk.Collection, error) {
b.mu.RLock()
defer b.mu.RUnlock()
col, err := b.storage.CollectionByID(sdkconvert.SDKIdentifierToFlow(colID))
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, &CollectionNotFoundError{ID: colID}
}
return nil, &StorageError{err}
}
sdkCol := sdkconvert.FlowLightCollectionToSDK(col)
return &sdkCol, nil
}
// GetTransaction gets an existing transaction by ID.
//
// The function first looks in the pending block, then the current blockchain state.
func (b *Blockchain) GetTransaction(id sdk.Identifier) (*sdk.Transaction, error) {
b.mu.RLock()
defer b.mu.RUnlock()
txID := sdkconvert.SDKIdentifierToFlow(id)
pendingTx := b.pendingBlock.GetTransaction(txID)
if pendingTx != nil {
pendingSDKTx := sdkconvert.FlowTransactionToSDK(*pendingTx)
return &pendingSDKTx, nil
}
tx, err := b.storage.TransactionByID(txID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, &TransactionNotFoundError{ID: txID}
}
return nil, &StorageError{err}
}
sdkTx := sdkconvert.FlowTransactionToSDK(tx)
return &sdkTx, nil
}
func (b *Blockchain) GetTransactionResult(ID sdk.Identifier) (*sdk.TransactionResult, error) {
b.mu.RLock()
defer b.mu.RUnlock()
txID := sdkconvert.SDKIdentifierToFlow(ID)
if b.pendingBlock.ContainsTransaction(txID) {
return &sdk.TransactionResult{
Status: sdk.TransactionStatusPending,
}, nil
}
storedResult, err := b.storage.TransactionResultByID(txID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return &sdk.TransactionResult{
Status: sdk.TransactionStatusUnknown,
}, nil
}
return nil, &StorageError{err}
}
var errResult error
if storedResult.ErrorCode != 0 {
errResult = &ExecutionError{
Code: storedResult.ErrorCode,
Message: storedResult.ErrorMessage,
}
}
sdkEvents, err := sdkconvert.FlowEventsToSDK(storedResult.Events)
if err != nil {
return nil, err
}
result := sdk.TransactionResult{
Status: sdk.TransactionStatusSealed,
Error: errResult,
Events: sdkEvents,
}
return &result, nil
}
// GetAccount returns the account for the given address.
func (b *Blockchain) GetAccount(address sdk.Address) (*sdk.Account, error) {
b.mu.RLock()
defer b.mu.RUnlock()
flowAddress := sdkconvert.SDKAddressToFlow(address)
account, err := b.getAccount(flowAddress)
if err != nil {
return nil, err
}
sdkAccount, err := sdkconvert.FlowAccountToSDK(*account)
if err != nil {
return nil, err
}
return &sdkAccount, nil
}
// getAccount returns the account for the given address.
func (b *Blockchain) getAccount(address flowgo.Address) (*flowgo.Account, error) {
latestBlock, err := b.GetLatestBlock()
if err != nil {
return nil, err
}
return b.getAccountAtBlock(address, latestBlock.Header.Height)
}
// GetAccountAtBlock returns the account for the given address at specified block height.
func (b *Blockchain) GetAccountAtBlock(address sdk.Address, blockHeight uint64) (*sdk.Account, error) {
b.mu.RLock()
defer b.mu.RUnlock()
flowAddress := sdkconvert.SDKAddressToFlow(address)
account, err := b.getAccountAtBlock(flowAddress, blockHeight)
if err != nil {
return nil, err
}
sdkAccount, err := sdkconvert.FlowAccountToSDK(*account)
if err != nil {
return nil, err
}
return &sdkAccount, nil
}
// GetAccountAtBlock returns the account for the given address at specified block height.
func (b *Blockchain) getAccountAtBlock(address flowgo.Address, blockHeight uint64) (*flowgo.Account, error) {
account, err := b.vm.GetAccount(
b.vmCtx,
address,
b.storage.LedgerViewByHeight(blockHeight),
programs.NewEmptyPrograms(),
)
if fvmerrors.IsAccountNotFoundError(err) {
return nil, &AccountNotFoundError{Address: address}
}
return account, nil
}
// GetEventsByHeight returns the events in the block at the given height, optionally filtered by type.
func (b *Blockchain) GetEventsByHeight(blockHeight uint64, eventType string) ([]sdk.Event, error) {
flowEvents, err := b.storage.EventsByHeight(blockHeight, eventType)
if err != nil {
return nil, err
}
sdkEvents, err := sdkconvert.FlowEventsToSDK(flowEvents)
if err != nil {
return nil, fmt.Errorf("could not convert events: %w", err)
}
return sdkEvents, err
}
// AddTransaction validates a transaction and adds it to the current pending block.
func (b *Blockchain) AddTransaction(tx sdk.Transaction) error {
b.mu.Lock()
defer b.mu.Unlock()
return b.addTransaction(tx)
}
// AddTransaction validates a transaction and adds it to the current pending block.
func (b *Blockchain) addTransaction(sdkTx sdk.Transaction) error {
tx := sdkconvert.SDKTransactionToFlow(sdkTx)
// If index > 0, pending block has begun execution (cannot add more transactions)
if b.pendingBlock.ExecutionStarted() {
return &PendingBlockMidExecutionError{BlockID: b.pendingBlock.ID()}
}
if b.pendingBlock.ContainsTransaction(tx.ID()) {
return &DuplicateTransactionError{TxID: tx.ID()}
}
_, err := b.storage.TransactionByID(tx.ID())
if err == nil {
// Found the transaction, this is a duplicate
return &DuplicateTransactionError{TxID: tx.ID()}
} else if !errors.Is(err, storage.ErrNotFound) {
// Error in the storage provider
return fmt.Errorf("failed to check storage for transaction %w", err)
}
err = b.transactionValidator.Validate(tx)
if err != nil {
return convertAccessError(err)
}
// add transaction to pending block
b.pendingBlock.AddTransaction(*tx)
return nil
}
// ExecuteBlock executes the remaining transactions in pending block.
func (b *Blockchain) ExecuteBlock() ([]*types.TransactionResult, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.executeBlock()
}
func (b *Blockchain) executeBlock() ([]*types.TransactionResult, error) {
results := make([]*types.TransactionResult, 0)
// empty blocks do not require execution, treat as a no-op
if b.pendingBlock.Empty() {
return results, nil
}
header := b.pendingBlock.Block().Header
blockContext := fvm.NewContextFromParent(
b.vmCtx,
fvm.WithBlockHeader(header),
)
// cannot execute a block that has already executed
if b.pendingBlock.ExecutionComplete() {
return results, &PendingBlockTransactionsExhaustedError{
BlockID: b.pendingBlock.ID(),
}
}
// continue executing transactions until execution is complete
for !b.pendingBlock.ExecutionComplete() {
result, err := b.executeNextTransaction(blockContext)
if err != nil {
return results, err
}
results = append(results, result)
}
return results, nil
}
// ExecuteNextTransaction executes the next indexed transaction in pending block.
func (b *Blockchain) ExecuteNextTransaction() (*types.TransactionResult, error) {
b.mu.Lock()
defer b.mu.Unlock()
header := b.pendingBlock.Block().Header
blockContext := fvm.NewContextFromParent(
b.vmCtx,
fvm.WithBlockHeader(header),
)
return b.executeNextTransaction(blockContext)
}
// executeNextTransaction is a helper function for ExecuteBlock and ExecuteNextTransaction that
// executes the next transaction in the pending block.
func (b *Blockchain) executeNextTransaction(ctx fvm.Context) (*types.TransactionResult, error) {
// check if there are remaining txs to be executed
if b.pendingBlock.ExecutionComplete() {
return nil, &PendingBlockTransactionsExhaustedError{
BlockID: b.pendingBlock.ID(),
}
}
// use the computer to execute the next transaction
tp, err := b.pendingBlock.ExecuteNextTransaction(
func(
ledgerView state.View,
txIndex uint32,
txBody *flowgo.TransactionBody,
) (*fvm.TransactionProcedure, error) {
tx := fvm.Transaction(txBody, txIndex)
err := b.vm.Run(ctx, tx, ledgerView, programs.NewEmptyPrograms())
if err != nil {
return nil, err
}
return tx, nil
},
)
if err != nil {
// fail fast if fatal error occurs
return nil, err
}
tr, err := convert.VMTransactionResultToEmulator(tp)
if err != nil {
// fail fast if fatal error occurs
return nil, err
}
// if transaction error exist try to further debug what was the problem
if tr.Error != nil {
tr.Debug = b.debugSignatureError(tr.Error, tp.Transaction)
}
return tr, nil
}
// CommitBlock seals the current pending block and saves it to storage.
//
// This function clears the pending transaction pool and resets the pending block.
func (b *Blockchain) CommitBlock() (*flowgo.Block, error) {
b.mu.Lock()
defer b.mu.Unlock()
block, err := b.commitBlock()
if err != nil {
return nil, err
}
return block, nil
}
func (b *Blockchain) commitBlock() (*flowgo.Block, error) {
// pending block cannot be committed before execution starts (unless empty)
if !b.pendingBlock.ExecutionStarted() && !b.pendingBlock.Empty() {
return nil, &PendingBlockCommitBeforeExecutionError{BlockID: b.pendingBlock.ID()}
}
// pending block cannot be committed before execution completes
if b.pendingBlock.ExecutionStarted() && !b.pendingBlock.ExecutionComplete() {
return nil, &PendingBlockMidExecutionError{BlockID: b.pendingBlock.ID()}
}
block := b.pendingBlock.Block()
collections := b.pendingBlock.Collections()
transactions := b.pendingBlock.Transactions()
transactionResults, err := convertToSealedResults(b.pendingBlock.TransactionResults())
if err != nil {
return nil, err