-
Notifications
You must be signed in to change notification settings - Fork 170
/
access_node_builder.go
1887 lines (1719 loc) · 77.5 KB
/
access_node_builder.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 node_builder
import (
"context"
"errors"
"fmt"
"math"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/ipfs/boxo/bitswap"
badger "github.com/ipfs/go-ds-badger2"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/routing"
"github.com/onflow/crypto"
"github.com/onflow/flow/protobuf/go/flow/access"
"github.com/rs/zerolog"
"github.com/spf13/pflag"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"github.com/onflow/flow-go/admin/commands"
stateSyncCommands "github.com/onflow/flow-go/admin/commands/state_synchronization"
storageCommands "github.com/onflow/flow-go/admin/commands/storage"
"github.com/onflow/flow-go/cmd"
"github.com/onflow/flow-go/consensus"
"github.com/onflow/flow-go/consensus/hotstuff"
"github.com/onflow/flow-go/consensus/hotstuff/committees"
"github.com/onflow/flow-go/consensus/hotstuff/notifications"
consensuspubsub "github.com/onflow/flow-go/consensus/hotstuff/notifications/pubsub"
"github.com/onflow/flow-go/consensus/hotstuff/signature"
hotstuffvalidator "github.com/onflow/flow-go/consensus/hotstuff/validator"
"github.com/onflow/flow-go/consensus/hotstuff/verification"
recovery "github.com/onflow/flow-go/consensus/recovery/protocol"
"github.com/onflow/flow-go/engine"
"github.com/onflow/flow-go/engine/access/ingestion"
pingeng "github.com/onflow/flow-go/engine/access/ping"
"github.com/onflow/flow-go/engine/access/rest"
"github.com/onflow/flow-go/engine/access/rest/routes"
"github.com/onflow/flow-go/engine/access/rpc"
"github.com/onflow/flow-go/engine/access/rpc/backend"
rpcConnection "github.com/onflow/flow-go/engine/access/rpc/connection"
"github.com/onflow/flow-go/engine/access/state_stream"
statestreambackend "github.com/onflow/flow-go/engine/access/state_stream/backend"
followereng "github.com/onflow/flow-go/engine/common/follower"
"github.com/onflow/flow-go/engine/common/requester"
synceng "github.com/onflow/flow-go/engine/common/synchronization"
"github.com/onflow/flow-go/engine/execution/computation/query"
"github.com/onflow/flow-go/ledger"
"github.com/onflow/flow-go/ledger/complete/wal"
"github.com/onflow/flow-go/model/bootstrap"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/model/flow/filter"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/module/blobs"
"github.com/onflow/flow-go/module/chainsync"
"github.com/onflow/flow-go/module/execution"
"github.com/onflow/flow-go/module/executiondatasync/execution_data"
execdatacache "github.com/onflow/flow-go/module/executiondatasync/execution_data/cache"
finalizer "github.com/onflow/flow-go/module/finalizer/consensus"
"github.com/onflow/flow-go/module/grpcserver"
"github.com/onflow/flow-go/module/id"
"github.com/onflow/flow-go/module/mempool/herocache"
"github.com/onflow/flow-go/module/mempool/stdmap"
"github.com/onflow/flow-go/module/metrics"
"github.com/onflow/flow-go/module/metrics/unstaked"
"github.com/onflow/flow-go/module/state_synchronization"
"github.com/onflow/flow-go/module/state_synchronization/indexer"
edrequester "github.com/onflow/flow-go/module/state_synchronization/requester"
"github.com/onflow/flow-go/network"
alspmgr "github.com/onflow/flow-go/network/alsp/manager"
netcache "github.com/onflow/flow-go/network/cache"
"github.com/onflow/flow-go/network/channels"
cborcodec "github.com/onflow/flow-go/network/codec/cbor"
"github.com/onflow/flow-go/network/p2p"
"github.com/onflow/flow-go/network/p2p/blob"
p2pbuilder "github.com/onflow/flow-go/network/p2p/builder"
p2pbuilderconfig "github.com/onflow/flow-go/network/p2p/builder/config"
"github.com/onflow/flow-go/network/p2p/cache"
"github.com/onflow/flow-go/network/p2p/conduit"
"github.com/onflow/flow-go/network/p2p/connection"
"github.com/onflow/flow-go/network/p2p/dht"
"github.com/onflow/flow-go/network/p2p/subscription"
"github.com/onflow/flow-go/network/p2p/translator"
"github.com/onflow/flow-go/network/p2p/unicast/protocols"
relaynet "github.com/onflow/flow-go/network/relay"
"github.com/onflow/flow-go/network/slashing"
"github.com/onflow/flow-go/network/topology"
"github.com/onflow/flow-go/network/underlay"
"github.com/onflow/flow-go/network/validator"
"github.com/onflow/flow-go/state/protocol"
badgerState "github.com/onflow/flow-go/state/protocol/badger"
"github.com/onflow/flow-go/state/protocol/blocktimer"
"github.com/onflow/flow-go/storage"
bstorage "github.com/onflow/flow-go/storage/badger"
pStorage "github.com/onflow/flow-go/storage/pebble"
"github.com/onflow/flow-go/utils/grpcutils"
)
// AccessNodeBuilder extends cmd.NodeBuilder and declares additional functions needed to bootstrap an Access node.
// The private network allows the staked nodes to communicate among themselves, while the public network allows the
// Observers and an Access node to communicate.
//
// public network private network
// +------------------------+
// | Observer 1 |<--------------------------|
// +------------------------+ v
// +------------------------+ +--------------------+ +------------------------+
// | Observer 2 |<----------------------->| Staked Access Node |<--------------->| All other staked Nodes |
// +------------------------+ +--------------------+ +------------------------+
// +------------------------+ ^
// | Observer 3 |<--------------------------|
// +------------------------+
// AccessNodeConfig defines all the user defined parameters required to bootstrap an access node
// For a node running as a standalone process, the config fields will be populated from the command line params,
// while for a node running as a library, the config fields are expected to be initialized by the caller.
type AccessNodeConfig struct {
supportsObserver bool // True if this is an Access node that supports observers and consensus follower engines
collectionGRPCPort uint
executionGRPCPort uint
pingEnabled bool
nodeInfoFile string
apiRatelimits map[string]int
apiBurstlimits map[string]int
rpcConf rpc.Config
stateStreamConf statestreambackend.Config
stateStreamFilterConf map[string]int
ExecutionNodeAddress string // deprecated
HistoricalAccessRPCs []access.AccessAPIClient
logTxTimeToFinalized bool
logTxTimeToExecuted bool
logTxTimeToFinalizedExecuted bool
retryEnabled bool
rpcMetricsEnabled bool
executionDataSyncEnabled bool
publicNetworkExecutionDataEnabled bool
executionDataDir string
executionDataStartHeight uint64
executionDataConfig edrequester.ExecutionDataConfig
PublicNetworkConfig PublicNetworkConfig
TxResultCacheSize uint
TxErrorMessagesCacheSize uint
executionDataIndexingEnabled bool
registersDBPath string
checkpointFile string
scriptExecutorConfig query.QueryConfig
scriptExecMinBlock uint64
scriptExecMaxBlock uint64
}
type PublicNetworkConfig struct {
// NetworkKey crypto.PublicKey // TODO: do we need a different key for the public network?
BindAddress string
Network network.EngineRegistry
Metrics module.NetworkMetrics
}
// DefaultAccessNodeConfig defines all the default values for the AccessNodeConfig
func DefaultAccessNodeConfig() *AccessNodeConfig {
homedir, _ := os.UserHomeDir()
return &AccessNodeConfig{
supportsObserver: false,
collectionGRPCPort: 9000,
executionGRPCPort: 9000,
rpcConf: rpc.Config{
UnsecureGRPCListenAddr: "0.0.0.0:9000",
SecureGRPCListenAddr: "0.0.0.0:9001",
HTTPListenAddr: "0.0.0.0:8000",
CollectionAddr: "",
HistoricalAccessAddrs: "",
BackendConfig: backend.Config{
CollectionClientTimeout: 3 * time.Second,
ExecutionClientTimeout: 3 * time.Second,
ConnectionPoolSize: backend.DefaultConnectionPoolSize,
MaxHeightRange: backend.DefaultMaxHeightRange,
PreferredExecutionNodeIDs: nil,
FixedExecutionNodeIDs: nil,
CircuitBreakerConfig: rpcConnection.CircuitBreakerConfig{
Enabled: false,
RestoreTimeout: 60 * time.Second,
MaxFailures: 5,
MaxRequests: 1,
},
ScriptExecutionMode: backend.IndexQueryModeExecutionNodesOnly.String(), // default to ENs only for now
EventQueryMode: backend.IndexQueryModeExecutionNodesOnly.String(), // default to ENs only for now
TxResultQueryMode: backend.IndexQueryModeExecutionNodesOnly.String(), // default to ENs only for now
},
RestConfig: rest.Config{
ListenAddress: "",
WriteTimeout: rest.DefaultWriteTimeout,
ReadTimeout: rest.DefaultReadTimeout,
IdleTimeout: rest.DefaultIdleTimeout,
},
MaxMsgSize: grpcutils.DefaultMaxMsgSize,
CompressorName: grpcutils.NoCompressor,
},
stateStreamConf: statestreambackend.Config{
MaxExecutionDataMsgSize: grpcutils.DefaultMaxMsgSize,
ExecutionDataCacheSize: state_stream.DefaultCacheSize,
ClientSendTimeout: state_stream.DefaultSendTimeout,
ClientSendBufferSize: state_stream.DefaultSendBufferSize,
MaxGlobalStreams: state_stream.DefaultMaxGlobalStreams,
EventFilterConfig: state_stream.DefaultEventFilterConfig,
ResponseLimit: state_stream.DefaultResponseLimit,
HeartbeatInterval: state_stream.DefaultHeartbeatInterval,
RegisterIDsRequestLimit: state_stream.DefaultRegisterIDsRequestLimit,
},
stateStreamFilterConf: nil,
ExecutionNodeAddress: "localhost:9000",
logTxTimeToFinalized: false,
logTxTimeToExecuted: false,
logTxTimeToFinalizedExecuted: false,
pingEnabled: false,
retryEnabled: false,
rpcMetricsEnabled: false,
nodeInfoFile: "",
apiRatelimits: nil,
apiBurstlimits: nil,
TxResultCacheSize: 0,
TxErrorMessagesCacheSize: 1000,
PublicNetworkConfig: PublicNetworkConfig{
BindAddress: cmd.NotSet,
Metrics: metrics.NewNoopCollector(),
},
executionDataSyncEnabled: true,
publicNetworkExecutionDataEnabled: false,
executionDataDir: filepath.Join(homedir, ".flow", "execution_data"),
executionDataStartHeight: 0,
executionDataConfig: edrequester.ExecutionDataConfig{
InitialBlockHeight: 0,
MaxSearchAhead: edrequester.DefaultMaxSearchAhead,
FetchTimeout: edrequester.DefaultFetchTimeout,
MaxFetchTimeout: edrequester.DefaultMaxFetchTimeout,
RetryDelay: edrequester.DefaultRetryDelay,
MaxRetryDelay: edrequester.DefaultMaxRetryDelay,
},
executionDataIndexingEnabled: false,
registersDBPath: filepath.Join(homedir, ".flow", "execution_state"),
checkpointFile: cmd.NotSet,
scriptExecutorConfig: query.NewDefaultConfig(),
scriptExecMinBlock: 0,
scriptExecMaxBlock: math.MaxUint64,
}
}
// FlowAccessNodeBuilder provides the common functionality needed to bootstrap a Flow access node
// It is composed of the FlowNodeBuilder, the AccessNodeConfig and contains all the components and modules needed for the
// access nodes
type FlowAccessNodeBuilder struct {
*cmd.FlowNodeBuilder
*AccessNodeConfig
// components
FollowerState protocol.FollowerState
SyncCore *chainsync.Core
RpcEng *rpc.Engine
FollowerDistributor *consensuspubsub.FollowerDistributor
CollectionRPC access.AccessAPIClient
TransactionTimings *stdmap.TransactionTimings
CollectionsToMarkFinalized *stdmap.Times
CollectionsToMarkExecuted *stdmap.Times
BlocksToMarkExecuted *stdmap.Times
TransactionMetrics *metrics.TransactionCollector
RestMetrics *metrics.RestCollector
AccessMetrics module.AccessMetrics
PingMetrics module.PingMetrics
Committee hotstuff.DynamicCommittee
Finalized *flow.Header // latest finalized block that the node knows of at startup time
Pending []*flow.Header
FollowerCore module.HotStuffFollower
Validator hotstuff.Validator
ExecutionDataDownloader execution_data.Downloader
PublicBlobService network.BlobService
ExecutionDataRequester state_synchronization.ExecutionDataRequester
ExecutionDataStore execution_data.ExecutionDataStore
ExecutionDataCache *execdatacache.ExecutionDataCache
ExecutionIndexer *indexer.Indexer
ExecutionIndexerCore *indexer.IndexerCore
ScriptExecutor *backend.ScriptExecutor
RegistersAsyncStore *execution.RegistersAsyncStore
EventsIndex *backend.EventsIndex
TxResultsIndex *backend.TransactionResultsIndex
IndexerDependencies *cmd.DependencyList
collectionExecutedMetric module.CollectionExecutedMetric
// The sync engine participants provider is the libp2p peer store for the access node
// which is not available until after the network has started.
// Hence, a factory function that needs to be called just before creating the sync engine
SyncEngineParticipantsProviderFactory func() module.IdentifierProvider
// engines
IngestEng *ingestion.Engine
RequestEng *requester.Engine
FollowerEng *followereng.ComplianceEngine
SyncEng *synceng.Engine
StateStreamEng *statestreambackend.Engine
// grpc servers
secureGrpcServer *grpcserver.GrpcServer
unsecureGrpcServer *grpcserver.GrpcServer
stateStreamGrpcServer *grpcserver.GrpcServer
stateStreamBackend *statestreambackend.StateStreamBackend
}
func (builder *FlowAccessNodeBuilder) buildFollowerState() *FlowAccessNodeBuilder {
builder.Module("mutable follower state", func(node *cmd.NodeConfig) error {
// For now, we only support state implementations from package badger.
// If we ever support different implementations, the following can be replaced by a type-aware factory
state, ok := node.State.(*badgerState.State)
if !ok {
return fmt.Errorf("only implementations of type badger.State are currently supported but read-only state has type %T", node.State)
}
followerState, err := badgerState.NewFollowerState(
node.Logger,
node.Tracer,
node.ProtocolEvents,
state,
node.Storage.Index,
node.Storage.Payloads,
blocktimer.DefaultBlockTimer,
)
builder.FollowerState = followerState
return err
})
return builder
}
func (builder *FlowAccessNodeBuilder) buildSyncCore() *FlowAccessNodeBuilder {
builder.Module("sync core", func(node *cmd.NodeConfig) error {
syncCore, err := chainsync.New(node.Logger, node.SyncCoreConfig, metrics.NewChainSyncCollector(node.RootChainID), node.RootChainID)
builder.SyncCore = syncCore
return err
})
return builder
}
func (builder *FlowAccessNodeBuilder) buildCommittee() *FlowAccessNodeBuilder {
builder.Component("committee", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
// initialize consensus committee's membership state
// This committee state is for the HotStuff follower, which follows the MAIN CONSENSUS committee
// Note: node.Me.NodeID() is not part of the consensus committee
committee, err := committees.NewConsensusCommittee(node.State, node.Me.NodeID())
node.ProtocolEvents.AddConsumer(committee)
builder.Committee = committee
return committee, err
})
return builder
}
func (builder *FlowAccessNodeBuilder) buildLatestHeader() *FlowAccessNodeBuilder {
builder.Module("latest header", func(node *cmd.NodeConfig) error {
finalized, pending, err := recovery.FindLatest(node.State, node.Storage.Headers)
builder.Finalized, builder.Pending = finalized, pending
return err
})
return builder
}
func (builder *FlowAccessNodeBuilder) buildFollowerCore() *FlowAccessNodeBuilder {
builder.Component("follower core", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
// create a finalizer that will handle updating the protocol
// state when the follower detects newly finalized blocks
final := finalizer.NewFinalizer(node.DB, node.Storage.Headers, builder.FollowerState, node.Tracer)
packer := signature.NewConsensusSigDataPacker(builder.Committee)
// initialize the verifier for the protocol consensus
verifier := verification.NewCombinedVerifier(builder.Committee, packer)
builder.Validator = hotstuffvalidator.New(builder.Committee, verifier)
followerCore, err := consensus.NewFollower(
node.Logger,
node.Metrics.Mempool,
node.Storage.Headers,
final,
builder.FollowerDistributor,
node.FinalizedRootBlock.Header,
node.RootQC,
builder.Finalized,
builder.Pending,
)
if err != nil {
return nil, fmt.Errorf("could not initialize follower core: %w", err)
}
builder.FollowerCore = followerCore
return builder.FollowerCore, nil
})
return builder
}
func (builder *FlowAccessNodeBuilder) buildFollowerEngine() *FlowAccessNodeBuilder {
builder.Component("follower engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
var heroCacheCollector module.HeroCacheMetrics = metrics.NewNoopCollector()
if node.HeroCacheMetricsEnable {
heroCacheCollector = metrics.FollowerCacheMetrics(node.MetricsRegisterer)
}
core, err := followereng.NewComplianceCore(
node.Logger,
node.Metrics.Mempool,
heroCacheCollector,
builder.FollowerDistributor,
builder.FollowerState,
builder.FollowerCore,
builder.Validator,
builder.SyncCore,
node.Tracer,
)
if err != nil {
return nil, fmt.Errorf("could not create follower core: %w", err)
}
builder.FollowerEng, err = followereng.NewComplianceLayer(
node.Logger,
node.EngineRegistry,
node.Me,
node.Metrics.Engine,
node.Storage.Headers,
builder.Finalized,
core,
node.ComplianceConfig,
)
if err != nil {
return nil, fmt.Errorf("could not create follower engine: %w", err)
}
builder.FollowerDistributor.AddOnBlockFinalizedConsumer(builder.FollowerEng.OnFinalizedBlock)
return builder.FollowerEng, nil
})
return builder
}
func (builder *FlowAccessNodeBuilder) buildSyncEngine() *FlowAccessNodeBuilder {
builder.Component("sync engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
spamConfig, err := synceng.NewSpamDetectionConfig()
if err != nil {
return nil, fmt.Errorf("could not initialize spam detection config: %w", err)
}
sync, err := synceng.New(
node.Logger,
node.Metrics.Engine,
node.EngineRegistry,
node.Me,
node.State,
node.Storage.Blocks,
builder.FollowerEng,
builder.SyncCore,
builder.SyncEngineParticipantsProviderFactory(),
spamConfig,
)
if err != nil {
return nil, fmt.Errorf("could not create synchronization engine: %w", err)
}
builder.SyncEng = sync
builder.FollowerDistributor.AddFinalizationConsumer(sync)
return builder.SyncEng, nil
})
return builder
}
func (builder *FlowAccessNodeBuilder) BuildConsensusFollower() *FlowAccessNodeBuilder {
builder.
buildFollowerState().
buildSyncCore().
buildCommittee().
buildLatestHeader().
buildFollowerCore().
buildFollowerEngine().
buildSyncEngine()
return builder
}
func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccessNodeBuilder {
var ds *badger.Datastore
var bs network.BlobService
var processedBlockHeight storage.ConsumerProgress
var processedNotifications storage.ConsumerProgress
var bsDependable *module.ProxiedReadyDoneAware
var execDataDistributor *edrequester.ExecutionDataDistributor
var execDataCacheBackend *herocache.BlockExecutionData
var executionDataStoreCache *execdatacache.ExecutionDataCache
// setup dependency chain to ensure indexer starts after the requester
requesterDependable := module.NewProxiedReadyDoneAware()
builder.IndexerDependencies.Add(requesterDependable)
builder.
AdminCommand("read-execution-data", func(config *cmd.NodeConfig) commands.AdminCommand {
return stateSyncCommands.NewReadExecutionDataCommand(builder.ExecutionDataStore)
}).
Module("execution data datastore and blobstore", func(node *cmd.NodeConfig) error {
datastoreDir := filepath.Join(builder.executionDataDir, "blobstore")
err := os.MkdirAll(datastoreDir, 0700)
if err != nil {
return err
}
ds, err = badger.NewDatastore(datastoreDir, &badger.DefaultOptions)
if err != nil {
return err
}
builder.ShutdownFunc(func() error {
if err := ds.Close(); err != nil {
return fmt.Errorf("could not close execution data datastore: %w", err)
}
return nil
})
return nil
}).
Module("processed block height consumer progress", func(node *cmd.NodeConfig) error {
// Note: progress is stored in the datastore's DB since that is where the jobqueue
// writes execution data to.
processedBlockHeight = bstorage.NewConsumerProgress(ds.DB, module.ConsumeProgressExecutionDataRequesterBlockHeight)
return nil
}).
Module("processed notifications consumer progress", func(node *cmd.NodeConfig) error {
// Note: progress is stored in the datastore's DB since that is where the jobqueue
// writes execution data to.
processedNotifications = bstorage.NewConsumerProgress(ds.DB, module.ConsumeProgressExecutionDataRequesterNotification)
return nil
}).
Module("blobservice peer manager dependencies", func(node *cmd.NodeConfig) error {
bsDependable = module.NewProxiedReadyDoneAware()
builder.PeerManagerDependencies.Add(bsDependable)
return nil
}).
Module("execution datastore", func(node *cmd.NodeConfig) error {
blobstore := blobs.NewBlobstore(ds)
builder.ExecutionDataStore = execution_data.NewExecutionDataStore(blobstore, execution_data.DefaultSerializer)
return nil
}).
Module("execution data cache", func(node *cmd.NodeConfig) error {
var heroCacheCollector module.HeroCacheMetrics = metrics.NewNoopCollector()
if builder.HeroCacheMetricsEnable {
heroCacheCollector = metrics.AccessNodeExecutionDataCacheMetrics(builder.MetricsRegisterer)
}
execDataCacheBackend = herocache.NewBlockExecutionData(builder.stateStreamConf.ExecutionDataCacheSize, builder.Logger, heroCacheCollector)
// Execution Data cache that uses a blobstore as the backend (instead of a downloader)
// This ensures that it simply returns a not found error if the blob doesn't exist
// instead of attempting to download it from the network.
executionDataStoreCache = execdatacache.NewExecutionDataCache(
builder.ExecutionDataStore,
builder.Storage.Headers,
builder.Storage.Seals,
builder.Storage.Results,
execDataCacheBackend,
)
return nil
}).
Component("execution data service", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
opts := []network.BlobServiceOption{
blob.WithBitswapOptions(
// Only allow block requests from staked ENs and ANs
bitswap.WithPeerBlockRequestFilter(
blob.AuthorizedRequester(nil, builder.IdentityProvider, builder.Logger),
),
bitswap.WithTracer(
blob.NewTracer(node.Logger.With().Str("blob_service", channels.ExecutionDataService.String()).Logger()),
),
),
}
var err error
bs, err = node.EngineRegistry.RegisterBlobService(channels.ExecutionDataService, ds, opts...)
if err != nil {
return nil, fmt.Errorf("could not register blob service: %w", err)
}
// add blobservice into ReadyDoneAware dependency passed to peer manager
// this starts the blob service and configures peer manager to wait for the blobservice
// to be ready before starting
bsDependable.Init(bs)
builder.ExecutionDataDownloader = execution_data.NewDownloader(bs)
return builder.ExecutionDataDownloader, nil
}).
Component("execution data requester", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
// Validation of the start block height needs to be done after loading state
if builder.executionDataStartHeight > 0 {
if builder.executionDataStartHeight <= builder.FinalizedRootBlock.Header.Height {
return nil, fmt.Errorf(
"execution data start block height (%d) must be greater than the root block height (%d)",
builder.executionDataStartHeight, builder.FinalizedRootBlock.Header.Height)
}
latestSeal, err := builder.State.Sealed().Head()
if err != nil {
return nil, fmt.Errorf("failed to get latest sealed height")
}
// Note: since the root block of a spork is also sealed in the root protocol state, the
// latest sealed height is always equal to the root block height. That means that at the
// very beginning of a spork, this check will always fail. Operators should not specify
// an InitialBlockHeight when starting from the beginning of a spork.
if builder.executionDataStartHeight > latestSeal.Height {
return nil, fmt.Errorf(
"execution data start block height (%d) must be less than or equal to the latest sealed block height (%d)",
builder.executionDataStartHeight, latestSeal.Height)
}
// executionDataStartHeight is provided as the first block to sync, but the
// requester expects the initial last processed height, which is the first height - 1
builder.executionDataConfig.InitialBlockHeight = builder.executionDataStartHeight - 1
} else {
builder.executionDataConfig.InitialBlockHeight = builder.FinalizedRootBlock.Header.Height
}
execDataDistributor = edrequester.NewExecutionDataDistributor()
// Execution Data cache with a downloader as the backend. This is used by the requester
// to download and cache execution data for each block. It shares a cache backend instance
// with the datastore implementation.
executionDataCache := execdatacache.NewExecutionDataCache(
builder.ExecutionDataDownloader,
builder.Storage.Headers,
builder.Storage.Seals,
builder.Storage.Results,
execDataCacheBackend,
)
r, err := edrequester.New(
builder.Logger,
metrics.NewExecutionDataRequesterCollector(),
builder.ExecutionDataDownloader,
executionDataCache,
processedBlockHeight,
processedNotifications,
builder.State,
builder.Storage.Headers,
builder.executionDataConfig,
execDataDistributor,
)
if err != nil {
return nil, fmt.Errorf("failed to create execution data requester: %w", err)
}
builder.ExecutionDataRequester = r
builder.FollowerDistributor.AddOnBlockFinalizedConsumer(builder.ExecutionDataRequester.OnBlockFinalized)
// add requester into ReadyDoneAware dependency passed to indexer. This allows the indexer
// to wait for the requester to be ready before starting.
requesterDependable.Init(builder.ExecutionDataRequester)
return builder.ExecutionDataRequester, nil
})
if builder.publicNetworkExecutionDataEnabled {
var publicBsDependable *module.ProxiedReadyDoneAware
builder.Module("public blobservice peer manager dependencies", func(node *cmd.NodeConfig) error {
publicBsDependable = module.NewProxiedReadyDoneAware()
builder.PeerManagerDependencies.Add(publicBsDependable)
return nil
})
builder.Component("public network execution data service", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
opts := []network.BlobServiceOption{
blob.WithBitswapOptions(
bitswap.WithTracer(
blob.NewTracer(node.Logger.With().Str("public_blob_service", channels.PublicExecutionDataService.String()).Logger()),
),
),
}
net := builder.AccessNodeConfig.PublicNetworkConfig.Network
var err error
builder.PublicBlobService, err = net.RegisterBlobService(channels.PublicExecutionDataService, ds, opts...)
if err != nil {
return nil, fmt.Errorf("could not register blob service: %w", err)
}
// add blobservice into ReadyDoneAware dependency passed to peer manager
// this starts the blob service and configures peer manager to wait for the blobservice
// to be ready before starting
publicBsDependable.Init(builder.PublicBlobService)
return &module.NoopReadyDoneAware{}, nil
})
}
if builder.executionDataIndexingEnabled {
var indexedBlockHeight storage.ConsumerProgress
builder.
AdminCommand("execute-script", func(config *cmd.NodeConfig) commands.AdminCommand {
return stateSyncCommands.NewExecuteScriptCommand(builder.ScriptExecutor)
}).
Module("indexed block height consumer progress", func(node *cmd.NodeConfig) error {
// Note: progress is stored in the MAIN db since that is where indexed execution data is stored.
indexedBlockHeight = bstorage.NewConsumerProgress(builder.DB, module.ConsumeProgressExecutionDataIndexerBlockHeight)
return nil
}).
Module("transaction results storage", func(node *cmd.NodeConfig) error {
builder.Storage.LightTransactionResults = bstorage.NewLightTransactionResults(node.Metrics.Cache, node.DB, bstorage.DefaultCacheSize)
return nil
}).
DependableComponent("execution data indexer", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
// Note: using a DependableComponent here to ensure that the indexer does not block
// other components from starting while bootstrapping the register db since it may
// take hours to complete.
pdb, err := pStorage.OpenRegisterPebbleDB(builder.registersDBPath)
if err != nil {
return nil, fmt.Errorf("could not open registers db: %w", err)
}
builder.ShutdownFunc(func() error {
return pdb.Close()
})
bootstrapped, err := pStorage.IsBootstrapped(pdb)
if err != nil {
return nil, fmt.Errorf("could not check if registers db is bootstrapped: %w", err)
}
if !bootstrapped {
checkpointFile := builder.checkpointFile
if checkpointFile == cmd.NotSet {
checkpointFile = path.Join(builder.BootstrapDir, bootstrap.PathRootCheckpoint)
}
// currently, the checkpoint must be from the root block.
// read the root hash from the provided checkpoint and verify it matches the
// state commitment from the root snapshot.
err := wal.CheckpointHasRootHash(
node.Logger,
"", // checkpoint file already full path
checkpointFile,
ledger.RootHash(node.RootSeal.FinalState),
)
if err != nil {
return nil, fmt.Errorf("could not verify checkpoint file: %w", err)
}
checkpointHeight := builder.SealedRootBlock.Header.Height
if builder.SealedRootBlock.ID() != builder.RootSeal.BlockID {
return nil, fmt.Errorf("mismatching sealed root block and root seal: %v != %v",
builder.SealedRootBlock.ID(), builder.RootSeal.BlockID)
}
rootHash := ledger.RootHash(builder.RootSeal.FinalState)
bootstrap, err := pStorage.NewRegisterBootstrap(pdb, checkpointFile, checkpointHeight, rootHash, builder.Logger)
if err != nil {
return nil, fmt.Errorf("could not create registers bootstrap: %w", err)
}
// TODO: find a way to hook a context up to this to allow a graceful shutdown
workerCount := 10
err = bootstrap.IndexCheckpointFile(context.Background(), workerCount)
if err != nil {
return nil, fmt.Errorf("could not load checkpoint file: %w", err)
}
}
registers, err := pStorage.NewRegisters(pdb)
if err != nil {
return nil, fmt.Errorf("could not create registers storage: %w", err)
}
builder.Storage.RegisterIndex = registers
indexerCore, err := indexer.New(
builder.Logger,
metrics.NewExecutionStateIndexerCollector(),
builder.DB,
builder.Storage.RegisterIndex,
builder.Storage.Headers,
builder.Storage.Events,
builder.Storage.Collections,
builder.Storage.Transactions,
builder.Storage.LightTransactionResults,
builder.collectionExecutedMetric,
)
if err != nil {
return nil, err
}
builder.ExecutionIndexerCore = indexerCore
// execution state worker uses a jobqueue to process new execution data and indexes it by using the indexer.
builder.ExecutionIndexer, err = indexer.NewIndexer(
builder.Logger,
registers.FirstHeight(),
registers,
indexerCore,
executionDataStoreCache,
builder.ExecutionDataRequester.HighestConsecutiveHeight,
indexedBlockHeight,
)
if err != nil {
return nil, err
}
// setup requester to notify indexer when new execution data is received
execDataDistributor.AddOnExecutionDataReceivedConsumer(builder.ExecutionIndexer.OnExecutionData)
// create script execution module, this depends on the indexer being initialized and the
// having the register storage bootstrapped
scripts, err := execution.NewScripts(
builder.Logger,
metrics.NewExecutionCollector(builder.Tracer),
builder.RootChainID,
query.NewProtocolStateWrapper(builder.State),
builder.Storage.Headers,
builder.ExecutionIndexerCore.RegisterValue,
builder.scriptExecutorConfig,
)
if err != nil {
return nil, err
}
err = builder.ScriptExecutor.Initialize(builder.ExecutionIndexer, scripts)
if err != nil {
return nil, err
}
err = builder.EventsIndex.Initialize(builder.ExecutionIndexer)
if err != nil {
return nil, err
}
err = builder.TxResultsIndex.Initialize(builder.ExecutionIndexer)
if err != nil {
return nil, err
}
err = builder.RegistersAsyncStore.Initialize(registers)
if err != nil {
return nil, err
}
return builder.ExecutionIndexer, nil
}, builder.IndexerDependencies)
}
if builder.stateStreamConf.ListenAddr != "" {
builder.Component("exec state stream engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
for key, value := range builder.stateStreamFilterConf {
switch key {
case "EventTypes":
builder.stateStreamConf.MaxEventTypes = value
case "Addresses":
builder.stateStreamConf.MaxAddresses = value
case "Contracts":
builder.stateStreamConf.MaxContracts = value
}
}
builder.stateStreamConf.RpcMetricsEnabled = builder.rpcMetricsEnabled
highestAvailableHeight, err := builder.ExecutionDataRequester.HighestConsecutiveHeight()
if err != nil {
return nil, fmt.Errorf("could not get highest consecutive height: %w", err)
}
broadcaster := engine.NewBroadcaster()
eventQueryMode, err := backend.ParseIndexQueryMode(builder.rpcConf.BackendConfig.EventQueryMode)
if err != nil {
return nil, fmt.Errorf("could not parse event query mode: %w", err)
}
// use the events index for events if enabled and the node is configured to use it for
// regular event queries
useIndex := builder.executionDataIndexingEnabled &&
eventQueryMode != backend.IndexQueryModeExecutionNodesOnly
builder.stateStreamBackend, err = statestreambackend.New(
node.Logger,
builder.stateStreamConf,
node.State,
node.Storage.Headers,
node.Storage.Seals,
node.Storage.Results,
builder.ExecutionDataStore,
executionDataStoreCache,
broadcaster,
builder.executionDataConfig.InitialBlockHeight,
highestAvailableHeight,
builder.RegistersAsyncStore,
builder.EventsIndex,
useIndex,
)
if err != nil {
return nil, fmt.Errorf("could not create state stream backend: %w", err)
}
stateStreamEng, err := statestreambackend.NewEng(
node.Logger,
builder.stateStreamConf,
executionDataStoreCache,
node.Storage.Headers,
node.RootChainID,
builder.stateStreamGrpcServer,
builder.stateStreamBackend,
broadcaster,
)
if err != nil {
return nil, fmt.Errorf("could not create state stream engine: %w", err)
}
builder.StateStreamEng = stateStreamEng
execDataDistributor.AddOnExecutionDataReceivedConsumer(builder.StateStreamEng.OnExecutionData)
return builder.StateStreamEng, nil
})
}
return builder
}
func FlowAccessNode(nodeBuilder *cmd.FlowNodeBuilder) *FlowAccessNodeBuilder {
dist := consensuspubsub.NewFollowerDistributor()
dist.AddProposalViolationConsumer(notifications.NewSlashingViolationsConsumer(nodeBuilder.Logger))
return &FlowAccessNodeBuilder{
AccessNodeConfig: DefaultAccessNodeConfig(),
FlowNodeBuilder: nodeBuilder,
FollowerDistributor: dist,
IndexerDependencies: cmd.NewDependencyList(),
}
}
func (builder *FlowAccessNodeBuilder) ParseFlags() error {
builder.BaseFlags()
builder.extraFlags()
return builder.ParseAndPrintFlags()
}
func (builder *FlowAccessNodeBuilder) extraFlags() {
builder.ExtraFlags(func(flags *pflag.FlagSet) {
defaultConfig := DefaultAccessNodeConfig()
flags.UintVar(&builder.collectionGRPCPort, "collection-ingress-port", defaultConfig.collectionGRPCPort, "the grpc ingress port for all collection nodes")
flags.UintVar(&builder.executionGRPCPort, "execution-ingress-port", defaultConfig.executionGRPCPort, "the grpc ingress port for all execution nodes")
flags.StringVarP(&builder.rpcConf.UnsecureGRPCListenAddr,
"rpc-addr",
"r",
defaultConfig.rpcConf.UnsecureGRPCListenAddr,
"the address the unsecured gRPC server listens on")
flags.StringVar(&builder.rpcConf.SecureGRPCListenAddr,
"secure-rpc-addr",
defaultConfig.rpcConf.SecureGRPCListenAddr,
"the address the secure gRPC server listens on")
flags.StringVar(&builder.stateStreamConf.ListenAddr,
"state-stream-addr",
defaultConfig.stateStreamConf.ListenAddr,
"the address the state stream server listens on (if empty the server will not be started)")
flags.StringVarP(&builder.rpcConf.HTTPListenAddr, "http-addr", "h", defaultConfig.rpcConf.HTTPListenAddr, "the address the http proxy server listens on")
flags.StringVar(&builder.rpcConf.RestConfig.ListenAddress,
"rest-addr",
defaultConfig.rpcConf.RestConfig.ListenAddress,
"the address the REST server listens on (if empty the REST server will not be started)")
flags.DurationVar(&builder.rpcConf.RestConfig.WriteTimeout,
"rest-write-timeout",
defaultConfig.rpcConf.RestConfig.WriteTimeout,
"timeout to use when writing REST response")
flags.DurationVar(&builder.rpcConf.RestConfig.ReadTimeout,
"rest-read-timeout",
defaultConfig.rpcConf.RestConfig.ReadTimeout,
"timeout to use when reading REST request headers")
flags.DurationVar(&builder.rpcConf.RestConfig.IdleTimeout, "rest-idle-timeout", defaultConfig.rpcConf.RestConfig.IdleTimeout, "idle timeout for REST connections")
flags.StringVarP(&builder.rpcConf.CollectionAddr,
"static-collection-ingress-addr",
"",
defaultConfig.rpcConf.CollectionAddr,
"the address (of the collection node) to send transactions to")
flags.StringVarP(&builder.ExecutionNodeAddress,
"script-addr",
"s",
defaultConfig.ExecutionNodeAddress,
"the address (of the execution node) forward the script to")
flags.StringVarP(&builder.rpcConf.HistoricalAccessAddrs,
"historical-access-addr",
"",
defaultConfig.rpcConf.HistoricalAccessAddrs,
"comma separated rpc addresses for historical access nodes")