-
Notifications
You must be signed in to change notification settings - Fork 179
/
staked_access_node_builder.go
389 lines (334 loc) · 13.3 KB
/
staked_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
package node_builder
import (
"context"
"fmt"
"strings"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/routing"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/onflow/flow/protobuf/go/flow/access"
"github.com/onflow/flow-go/cmd"
"github.com/onflow/flow-go/crypto"
"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/rpc"
"github.com/onflow/flow-go/engine/access/rpc/backend"
"github.com/onflow/flow-go/engine/common/requester"
synceng "github.com/onflow/flow-go/engine/common/synchronization"
"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/id"
"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/network"
"github.com/onflow/flow-go/network/p2p"
"github.com/onflow/flow-go/network/p2p/unicast"
relaynet "github.com/onflow/flow-go/network/relay"
"github.com/onflow/flow-go/network/topology"
"github.com/onflow/flow-go/utils/grpcutils"
)
// StakedAccessNodeBuilder builds a staked access node. The staked access node can optionally participate in the
// unstaked network publishing data for the unstaked access node downstream.
type StakedAccessNodeBuilder struct {
*FlowAccessNodeBuilder
}
func NewStakedAccessNodeBuilder(builder *FlowAccessNodeBuilder) *StakedAccessNodeBuilder {
return &StakedAccessNodeBuilder{
FlowAccessNodeBuilder: builder,
}
}
func (builder *StakedAccessNodeBuilder) InitIDProviders() {
builder.Module("id providers", func(node *cmd.NodeConfig) error {
idCache, err := p2p.NewProtocolStateIDCache(node.Logger, node.State, node.ProtocolEvents)
if err != nil {
return err
}
builder.IdentityProvider = idCache
builder.SyncEngineParticipantsProviderFactory = func() id.IdentifierProvider {
return id.NewIdentityFilterIdentifierProvider(
filter.And(
filter.HasRole(flow.RoleConsensus),
filter.Not(filter.HasNodeID(node.Me.NodeID())),
p2p.NotEjectedFilter,
),
idCache,
)
}
builder.IDTranslator = p2p.NewHierarchicalIDTranslator(idCache, p2p.NewUnstakedNetworkIDTranslator())
return nil
})
}
func (builder *StakedAccessNodeBuilder) Initialize() error {
builder.InitIDProviders()
builder.EnqueueResolver()
// enqueue the regular network
builder.EnqueueNetworkInit()
// if this is an access node that supports unstaked followers, enqueue the unstaked network
if builder.supportsUnstakedFollower {
builder.enqueueUnstakedNetworkInit()
builder.enqueueRelayNetwork()
}
builder.EnqueuePingService()
builder.EnqueueMetricsServerInit()
if err := builder.RegisterBadgerMetrics(); err != nil {
return err
}
builder.EnqueueAdminServerInit()
builder.EnqueueTracer()
builder.PreInit(cmd.DynamicStartPreInit)
return nil
}
func (builder *StakedAccessNodeBuilder) enqueueRelayNetwork() {
builder.Component("relay network", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
relayNet := relaynet.NewRelayNetwork(
node.Network,
builder.AccessNodeConfig.PublicNetworkConfig.Network,
node.Logger,
[]network.Channel{engine.ReceiveBlocks},
)
node.Network = relayNet
return relayNet, nil
})
}
func (builder *StakedAccessNodeBuilder) Build() (cmd.Node, error) {
builder.
BuildConsensusFollower().
Module("collection node client", func(node *cmd.NodeConfig) error {
// collection node address is optional (if not specified, collection nodes will be chosen at random)
if strings.TrimSpace(builder.rpcConf.CollectionAddr) == "" {
node.Logger.Info().Msg("using a dynamic collection node address")
return nil
}
node.Logger.Info().
Str("collection_node", builder.rpcConf.CollectionAddr).
Msg("using the static collection node address")
collectionRPCConn, err := grpc.Dial(
builder.rpcConf.CollectionAddr,
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(grpcutils.DefaultMaxMsgSize)),
grpc.WithInsecure(), //nolint:staticcheck
backend.WithClientUnaryInterceptor(builder.rpcConf.CollectionClientTimeout))
if err != nil {
return err
}
builder.CollectionRPC = access.NewAccessAPIClient(collectionRPCConn)
return nil
}).
Module("historical access node clients", func(node *cmd.NodeConfig) error {
addrs := strings.Split(builder.rpcConf.HistoricalAccessAddrs, ",")
for _, addr := range addrs {
if strings.TrimSpace(addr) == "" {
continue
}
node.Logger.Info().Str("access_nodes", addr).Msg("historical access node addresses")
historicalAccessRPCConn, err := grpc.Dial(
addr,
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(grpcutils.DefaultMaxMsgSize)),
grpc.WithInsecure()) //nolint:staticcheck
if err != nil {
return err
}
builder.HistoricalAccessRPCs = append(builder.HistoricalAccessRPCs, access.NewAccessAPIClient(historicalAccessRPCConn))
}
return nil
}).
Module("transaction timing mempools", func(node *cmd.NodeConfig) error {
var err error
builder.TransactionTimings, err = stdmap.NewTransactionTimings(1500 * 300) // assume 1500 TPS * 300 seconds
if err != nil {
return err
}
builder.CollectionsToMarkFinalized, err = stdmap.NewTimes(50 * 300) // assume 50 collection nodes * 300 seconds
if err != nil {
return err
}
builder.CollectionsToMarkExecuted, err = stdmap.NewTimes(50 * 300) // assume 50 collection nodes * 300 seconds
if err != nil {
return err
}
builder.BlocksToMarkExecuted, err = stdmap.NewTimes(1 * 300) // assume 1 block per second * 300 seconds
return err
}).
Module("transaction metrics", func(node *cmd.NodeConfig) error {
builder.TransactionMetrics = metrics.NewTransactionCollector(builder.TransactionTimings, node.Logger, builder.logTxTimeToFinalized,
builder.logTxTimeToExecuted, builder.logTxTimeToFinalizedExecuted)
return nil
}).
Module("ping metrics", func(node *cmd.NodeConfig) error {
builder.PingMetrics = metrics.NewPingCollector()
return nil
}).
Module("server certificate", func(node *cmd.NodeConfig) error {
// generate the server certificate that will be served by the GRPC server
x509Certificate, err := grpcutils.X509Certificate(node.NetworkKey)
if err != nil {
return err
}
tlsConfig := grpcutils.DefaultServerTLSConfig(x509Certificate)
builder.rpcConf.TransportCredentials = credentials.NewTLS(tlsConfig)
return nil
}).
Component("RPC engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
builder.RpcEng = rpc.New(
node.Logger,
node.State,
builder.rpcConf,
builder.CollectionRPC,
builder.HistoricalAccessRPCs,
node.Storage.Blocks,
node.Storage.Headers,
node.Storage.Collections,
node.Storage.Transactions,
node.Storage.Receipts,
node.Storage.Results,
node.RootChainID,
builder.TransactionMetrics,
builder.collectionGRPCPort,
builder.executionGRPCPort,
builder.retryEnabled,
builder.rpcMetricsEnabled,
builder.apiRatelimits,
builder.apiBurstlimits,
)
return builder.RpcEng, nil
}).
Component("ingestion engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
var err error
builder.RequestEng, err = requester.New(
node.Logger,
node.Metrics.Engine,
node.Network,
node.Me,
node.State,
engine.RequestCollections,
filter.HasRole(flow.RoleCollection),
func() flow.Entity { return &flow.Collection{} },
)
if err != nil {
return nil, fmt.Errorf("could not create requester engine: %w", err)
}
builder.IngestEng, err = ingestion.New(node.Logger, node.Network, node.State, node.Me, builder.RequestEng, node.Storage.Blocks, node.Storage.Headers, node.Storage.Collections, node.Storage.Transactions, node.Storage.Results, node.Storage.Receipts, builder.TransactionMetrics,
builder.CollectionsToMarkFinalized, builder.CollectionsToMarkExecuted, builder.BlocksToMarkExecuted, builder.RpcEng)
if err != nil {
return nil, err
}
builder.RequestEng.WithHandle(builder.IngestEng.OnCollection)
builder.FinalizationDistributor.AddConsumer(builder.IngestEng)
return builder.IngestEng, nil
}).
Component("requester engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
// We initialize the requester engine inside the ingestion engine due to the mutual dependency. However, in
// order for it to properly start and shut down, we should still return it as its own engine here, so it can
// be handled by the scaffold.
return builder.RequestEng, nil
})
if builder.supportsUnstakedFollower {
builder.Component("unstaked sync request handler", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
syncRequestHandler, err := synceng.NewRequestHandlerEngine(
node.Logger.With().Bool("unstaked", true).Logger(),
unstaked.NewUnstakedEngineCollector(node.Metrics.Engine),
builder.AccessNodeConfig.PublicNetworkConfig.Network,
node.Me,
node.Storage.Blocks,
builder.SyncCore,
builder.FinalizedHeader,
)
if err != nil {
return nil, fmt.Errorf("could not create unstaked sync request handler: %w", err)
}
return syncRequestHandler, nil
})
}
builder.Component("ping engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
ping, err := pingeng.New(
node.Logger,
node.IdentityProvider,
node.IDTranslator,
node.Me,
builder.PingMetrics,
builder.pingEnabled,
builder.nodeInfoFile,
node.PingService,
)
if err != nil {
return nil, fmt.Errorf("could not create ping engine: %w", err)
}
return ping, nil
})
return builder.FlowAccessNodeBuilder.Build()
}
// enqueueUnstakedNetworkInit enqueues the unstaked network component initialized for the staked node
func (builder *StakedAccessNodeBuilder) enqueueUnstakedNetworkInit() {
builder.Component("unstaked network", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
builder.PublicNetworkConfig.Metrics = metrics.NewNetworkCollector(metrics.WithNetworkPrefix("unstaked"))
libP2PFactory := builder.initLibP2PFactory(builder.NodeConfig.NetworkKey)
msgValidators := unstakedNetworkMsgValidators(node.Logger.With().Bool("unstaked", true).Logger(), node.IdentityProvider, builder.NodeID)
middleware := builder.initMiddleware(builder.NodeID, builder.PublicNetworkConfig.Metrics, libP2PFactory, msgValidators...)
// topology returns empty list since peers are not known upfront
top := topology.EmptyListTopology{}
network, err := builder.initNetwork(builder.Me, builder.PublicNetworkConfig.Metrics, middleware, top)
if err != nil {
return nil, err
}
builder.AccessNodeConfig.PublicNetworkConfig.Network = network
node.Logger.Info().Msgf("network will run on address: %s", builder.PublicNetworkConfig.BindAddress)
return network, nil
})
}
// initLibP2PFactory creates the LibP2P factory function for the given node ID and network key.
// The factory function is later passed into the initMiddleware function to eventually instantiate the p2p.LibP2PNode instance
// The LibP2P host is created with the following options:
// DHT as server
// The address from the node config or the specified bind address as the listen address
// The passed in private key as the libp2p key
// No connection gater
// Default Flow libp2p pubsub options
func (builder *StakedAccessNodeBuilder) initLibP2PFactory(networkKey crypto.PrivateKey) p2p.LibP2PFactoryFunc {
return func(ctx context.Context) (*p2p.Node, error) {
connManager := p2p.NewConnManager(builder.Logger, builder.PublicNetworkConfig.Metrics)
libp2pNode, err := p2p.NewNodeBuilder(builder.Logger, builder.PublicNetworkConfig.BindAddress, networkKey, builder.SporkID).
SetBasicResolver(builder.Resolver).
SetSubscriptionFilter(
p2p.NewRoleBasedFilter(
flow.RoleAccess, builder.IdentityProvider,
),
).
SetConnectionManager(connManager).
SetRoutingSystem(func(ctx context.Context, h host.Host) (routing.Routing, error) {
return p2p.NewDHT(ctx, h, unicast.FlowPublicDHTProtocolID(builder.SporkID), p2p.AsServer())
}).
SetPubSub(pubsub.NewGossipSub).
Build(ctx)
if err != nil {
return nil, fmt.Errorf("could not build libp2p node for staked access node: %w", err)
}
builder.LibP2PNode = libp2pNode
return builder.LibP2PNode, nil
}
}
// initMiddleware creates the network.Middleware implementation with the libp2p factory function, metrics, peer update
// interval, and validators. The network.Middleware is then passed into the initNetwork function.
func (builder *StakedAccessNodeBuilder) initMiddleware(nodeID flow.Identifier,
networkMetrics module.NetworkMetrics,
factoryFunc p2p.LibP2PFactoryFunc,
validators ...network.MessageValidator) network.Middleware {
// disable connection pruning for the staked AN which supports the unstaked AN
peerManagerFactory := p2p.PeerManagerFactory([]p2p.Option{p2p.WithInterval(builder.PeerUpdateInterval)}, p2p.WithConnectionPruning(false))
builder.Middleware = p2p.NewMiddleware(
builder.Logger.With().Bool("staked", false).Logger(),
factoryFunc,
nodeID,
networkMetrics,
builder.SporkID,
p2p.DefaultUnicastTimeout,
builder.IDTranslator,
p2p.WithMessageValidators(validators...),
p2p.WithPeerManager(peerManagerFactory),
// use default identifier provider
)
return builder.Middleware
}