-
Notifications
You must be signed in to change notification settings - Fork 175
/
main.go
481 lines (433 loc) · 18 KB
/
main.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
package main
import (
"fmt"
"time"
"github.com/spf13/pflag"
"google.golang.org/grpc"
"github.com/onflow/flow-go-sdk/client"
sdkcrypto "github.com/onflow/flow-go-sdk/crypto"
"github.com/onflow/flow-go/cmd"
"github.com/onflow/flow-go/consensus"
"github.com/onflow/flow-go/consensus/hotstuff/committees"
"github.com/onflow/flow-go/consensus/hotstuff/notifications/pubsub"
"github.com/onflow/flow-go/consensus/hotstuff/pacemaker/timeout"
"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/collection/epochmgr"
"github.com/onflow/flow-go/engine/collection/epochmgr/factories"
"github.com/onflow/flow-go/engine/collection/ingest"
"github.com/onflow/flow-go/engine/collection/pusher"
followereng "github.com/onflow/flow-go/engine/common/follower"
"github.com/onflow/flow-go/engine/common/provider"
consync "github.com/onflow/flow-go/engine/common/synchronization"
"github.com/onflow/flow-go/fvm/systemcontracts"
"github.com/onflow/flow-go/model/encodable"
"github.com/onflow/flow-go/model/encoding"
"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/buffer"
builder "github.com/onflow/flow-go/module/builder/collection"
"github.com/onflow/flow-go/module/epochs"
confinalizer "github.com/onflow/flow-go/module/finalizer/consensus"
"github.com/onflow/flow-go/module/ingress"
"github.com/onflow/flow-go/module/mempool"
epochpool "github.com/onflow/flow-go/module/mempool/epochs"
"github.com/onflow/flow-go/module/mempool/stdmap"
"github.com/onflow/flow-go/module/metrics"
"github.com/onflow/flow-go/module/signature"
"github.com/onflow/flow-go/module/synchronization"
"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/state/protocol/events/gadgets"
storagekv "github.com/onflow/flow-go/storage/badger"
)
func main() {
var (
txLimit uint
maxCollectionSize uint
maxCollectionByteSize uint64
maxCollectionTotalGas uint64
builderExpiryBuffer uint
builderPayerRateLimit float64
builderUnlimitedPayers []string
hotstuffTimeout time.Duration
hotstuffMinTimeout time.Duration
hotstuffTimeoutIncreaseFactor float64
hotstuffTimeoutDecreaseFactor float64
hotstuffTimeoutVoteAggregationFraction float64
blockRateDelay time.Duration
followerState protocol.MutableState
ingestConf ingest.Config
ingressConf ingress.Config
pools *epochpool.TransactionPools // epoch-scoped transaction pools
followerBuffer *buffer.PendingBlocks // pending block cache for follower
finalizationDistributor *pubsub.FinalizationDistributor
push *pusher.Engine
ing *ingest.Engine
mainChainSyncCore *synchronization.Core
followerEng *followereng.Engine
colMetrics module.CollectionMetrics
err error
// epoch qc contract client
accessAddress string
)
cmd.FlowNode(flow.RoleCollection.String()).
ExtraFlags(func(flags *pflag.FlagSet) {
flags.UintVar(&txLimit, "tx-limit", 50000,
"maximum number of transactions in the memory pool")
flags.StringVarP(&ingressConf.ListenAddr, "ingress-addr", "i", "localhost:9000",
"the address the ingress server listens on")
flags.BoolVar(&ingressConf.RpcMetricsEnabled, "rpc-metrics-enabled", false,
"whether to enable the rpc metrics")
flags.Uint64Var(&ingestConf.MaxGasLimit, "ingest-max-gas-limit", flow.DefaultMaxTransactionGasLimit,
"maximum per-transaction computation limit (gas limit)")
flags.Uint64Var(&ingestConf.MaxTransactionByteSize, "ingest-max-tx-byte-size", flow.DefaultMaxTransactionByteSize,
"maximum per-transaction byte size")
flags.Uint64Var(&ingestConf.MaxCollectionByteSize, "ingest-max-col-byte-size", flow.DefaultMaxCollectionByteSize,
"maximum per-collection byte size")
flags.BoolVar(&ingestConf.CheckScriptsParse, "ingest-check-scripts-parse", true,
"whether we check that inbound transactions are parse-able")
flags.UintVar(&ingestConf.ExpiryBuffer, "ingest-expiry-buffer", 30,
"expiry buffer for inbound transactions")
flags.UintVar(&ingestConf.PropagationRedundancy, "ingest-tx-propagation-redundancy", 10,
"how many additional cluster members we propagate transactions to")
flags.Uint64Var(&ingestConf.MaxAddressIndex, "ingest-max-address-index", 10_000_000,
"the maximum address index allowed in transactions")
flags.UintVar(&builderExpiryBuffer, "builder-expiry-buffer", builder.DefaultExpiryBuffer,
"expiry buffer for transactions in proposed collections")
flags.Float64Var(&builderPayerRateLimit, "builder-rate-limit", builder.DefaultMaxPayerTransactionRate, // no rate limiting
"rate limit for each payer (transactions/collection)")
flags.StringSliceVar(&builderUnlimitedPayers, "builder-unlimited-payers", []string{}, // no unlimited payers
"set of payer addresses which are omitted from rate limiting")
flags.UintVar(&maxCollectionSize, "builder-max-collection-size", flow.DefaultMaxCollectionSize,
"maximum number of transactions in proposed collections")
flags.Uint64Var(&maxCollectionByteSize, "builder-max-collection-byte-size", flow.DefaultMaxCollectionByteSize,
"maximum byte size of the proposed collection")
flags.Uint64Var(&maxCollectionTotalGas, "builder-max-collection-total-gas", flow.DefaultMaxCollectionTotalGas,
"maximum total amount of maxgas of transactions in proposed collections")
flags.DurationVar(&hotstuffTimeout, "hotstuff-timeout", 60*time.Second,
"the initial timeout for the hotstuff pacemaker")
flags.DurationVar(&hotstuffMinTimeout, "hotstuff-min-timeout", 2500*time.Millisecond,
"the lower timeout bound for the hotstuff pacemaker")
flags.Float64Var(&hotstuffTimeoutIncreaseFactor, "hotstuff-timeout-increase-factor",
timeout.DefaultConfig.TimeoutIncrease,
"multiplicative increase of timeout value in case of time out event")
flags.Float64Var(&hotstuffTimeoutDecreaseFactor, "hotstuff-timeout-decrease-factor",
timeout.DefaultConfig.TimeoutDecrease,
"multiplicative decrease of timeout value in case of progress")
flags.Float64Var(&hotstuffTimeoutVoteAggregationFraction, "hotstuff-timeout-vote-aggregation-fraction",
timeout.DefaultConfig.VoteAggregationTimeoutFraction,
"additional fraction of replica timeout that the primary will wait for votes")
flags.DurationVar(&blockRateDelay, "block-rate-delay", 250*time.Millisecond,
"the delay to broadcast block proposal in order to control block production rate")
// epoch qc contract flags
flags.StringVar(&accessAddress, "access-address", "", "the address of an access node")
}).
Initialize().
Module("mutable follower state", func(builder cmd.NodeBuilder, 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 currenlty supported but read-only state has type %T", node.State)
}
followerState, err = badgerState.NewFollowerState(
state,
node.Storage.Index,
node.Storage.Payloads,
node.Tracer,
node.ProtocolEvents,
blocktimer.DefaultBlockTimer,
)
return err
}).
Module("transactions mempool", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) error {
create := func() mempool.Transactions { return stdmap.NewTransactions(txLimit) }
pools = epochpool.NewTransactionPools(create)
err := node.Metrics.Mempool.Register(metrics.ResourceTransaction, pools.CombinedSize)
return err
}).
Module("pending block cache", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) error {
followerBuffer = buffer.NewPendingBlocks()
return nil
}).
Module("metrics", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) error {
colMetrics = metrics.NewCollectionCollector(node.Tracer)
return nil
}).
Module("main chain sync core", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) error {
mainChainSyncCore, err = synchronization.New(node.Logger, synchronization.DefaultConfig())
return err
}).
Component("follower engine", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
// initialize cleaner for DB
cleaner := storagekv.NewCleaner(node.Logger, node.DB, metrics.NewCleanerCollector(), flow.DefaultValueLogGCFrequency)
// create a finalizer that will handling updating the protocol
// state when the follower detects newly finalized blocks
finalizer := confinalizer.NewFinalizer(node.DB, node.Storage.Headers, followerState)
// initialize the staking & beacon verifiers, signature joiner
staking := signature.NewAggregationVerifier(encoding.ConsensusVoteTag)
beacon := signature.NewThresholdVerifier(encoding.RandomBeaconTag)
merger := signature.NewCombiner(encodable.ConsensusVoteSigLen, encodable.RandomBeaconSigLen)
// 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
mainConsensusCommittee, err := committees.NewConsensusCommittee(node.State, node.Me.NodeID())
if err != nil {
return nil, fmt.Errorf("could not create Committee state for main consensus: %w", err)
}
// initialize the verifier for the protocol consensus
verifier := verification.NewCombinedVerifier(mainConsensusCommittee, staking, beacon, merger)
finalizationDistributor = pubsub.NewFinalizationDistributor()
finalized, pending, err := recovery.FindLatest(node.State, node.Storage.Headers)
if err != nil {
return nil, fmt.Errorf("could not find latest finalized block and pending blocks to recover consensus follower: %w", err)
}
// creates a consensus follower with noop consumer as the notifier
followerCore, err := consensus.NewFollower(
node.Logger,
mainConsensusCommittee,
node.Storage.Headers,
finalizer,
verifier,
finalizationDistributor,
node.RootBlock.Header,
node.RootQC,
finalized,
pending,
)
if err != nil {
return nil, fmt.Errorf("could not create follower core logic: %w", err)
}
followerEng, err = followereng.New(
node.Logger,
node.Network,
node.Me,
node.Metrics.Engine,
node.Metrics.Mempool,
cleaner,
node.Storage.Headers,
node.Storage.Payloads,
followerState,
followerBuffer,
followerCore,
mainChainSyncCore,
)
if err != nil {
return nil, fmt.Errorf("could not create follower engine: %w", err)
}
return followerEng, nil
}).
Component("main chain sync engine", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
// create a block synchronization engine to handle follower getting out of sync
sync, err := consync.New(
node.Logger,
node.Metrics.Engine,
node.Network,
node.Me,
node.State,
node.Storage.Blocks,
followerEng,
mainChainSyncCore,
)
if err != nil {
return nil, fmt.Errorf("could not create synchronization engine: %w", err)
}
finalizationDistributor.AddOnBlockFinalizedConsumer(sync.OnFinalizedBlock)
return sync, nil
}).
Component("ingestion engine", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
ing, err = ingest.New(
node.Logger,
node.Network,
node.State,
node.Metrics.Engine,
colMetrics,
node.Me,
node.RootChainID.Chain(),
pools,
ingestConf,
)
return ing, err
}).
Component("transaction ingress server", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
server := ingress.New(ingressConf, ing, node.RootChainID)
return server, nil
}).
Component("provider engine", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
retrieve := func(collID flow.Identifier) (flow.Entity, error) {
coll, err := node.Storage.Collections.ByID(collID)
return coll, err
}
return provider.New(node.Logger, node.Metrics.Engine, node.Network, node.Me, node.State,
engine.ProvideCollections,
filter.HasRole(flow.RoleAccess, flow.RoleExecution),
retrieve,
)
}).
Component("pusher engine", func(builder cmd.NodeBuilder, node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
push, err = pusher.New(
node.Logger,
node.Network,
node.State,
node.Metrics.Engine,
colMetrics,
node.Me,
node.Storage.Collections,
node.Storage.Transactions,
)
return push, err
}).
// Epoch manager encapsulates and manages epoch-dependent engines as we
// transition between epochs
Component("epoch manager", func(_ cmd.NodeBuilder, node *cmd.NodeConfig) (module.ReadyDoneAware, error) {
clusterStateFactory, err := factories.NewClusterStateFactory(node.DB, node.Metrics.Cache, node.Tracer)
if err != nil {
return nil, err
}
// convert hex string flag values to addresses
unlimitedPayers := make([]flow.Address, 0, len(builderUnlimitedPayers))
for _, payerStr := range builderUnlimitedPayers {
payerAddr := flow.HexToAddress(payerStr)
unlimitedPayers = append(unlimitedPayers, payerAddr)
}
builderFactory, err := factories.NewBuilderFactory(
node.DB,
node.Storage.Headers,
node.Tracer,
colMetrics,
push,
builder.WithMaxCollectionSize(maxCollectionSize),
builder.WithMaxCollectionByteSize(maxCollectionByteSize),
builder.WithMaxCollectionTotalGas(maxCollectionTotalGas),
builder.WithExpiryBuffer(builderExpiryBuffer),
builder.WithMaxPayerTransactionRate(builderPayerRateLimit),
builder.WithUnlimitedPayers(unlimitedPayers...),
)
if err != nil {
return nil, err
}
proposalFactory, err := factories.NewProposalEngineFactory(
node.Logger,
node.Network,
node.Me,
colMetrics,
node.Metrics.Engine,
node.Metrics.Mempool,
node.State,
node.Storage.Transactions,
)
if err != nil {
return nil, err
}
syncFactory, err := factories.NewSyncEngineFactory(
node.Logger,
node.Metrics.Engine,
node.Network,
node.Me,
synchronization.DefaultConfig(),
)
if err != nil {
return nil, err
}
createMetrics := func(chainID flow.ChainID) module.HotstuffMetrics {
return metrics.NewHotstuffCollector(chainID)
}
staking := signature.NewAggregationProvider(encoding.CollectorVoteTag, node.Me)
hotstuffFactory, err := factories.NewHotStuffFactory(
node.Logger,
node.Me,
staking,
node.DB,
node.State,
createMetrics,
consensus.WithBlockRateDelay(blockRateDelay),
consensus.WithInitialTimeout(hotstuffTimeout),
consensus.WithMinTimeout(hotstuffMinTimeout),
consensus.WithVoteAggregationTimeoutFraction(hotstuffTimeoutVoteAggregationFraction),
consensus.WithTimeoutIncreaseFactor(hotstuffTimeoutIncreaseFactor),
consensus.WithTimeoutDecreaseFactor(hotstuffTimeoutDecreaseFactor),
)
if err != nil {
return nil, err
}
signer := verification.NewSingleSigner(staking, node.Me.NodeID())
// construct QC contract client
qcContractClient, err := createQCContractClient(node, accessAddress)
if err != nil {
return nil, fmt.Errorf("could not create qc contract client %w", err)
}
rootQCVoter := epochs.NewRootQCVoter(
node.Logger,
node.Me,
signer,
node.State,
qcContractClient,
)
factory := factories.NewEpochComponentsFactory(
node.Me,
pools,
builderFactory,
clusterStateFactory,
hotstuffFactory,
proposalFactory,
syncFactory,
)
heightEvents := gadgets.NewHeights()
node.ProtocolEvents.AddConsumer(heightEvents)
manager, err := epochmgr.New(
node.Logger,
node.Me,
node.State,
pools,
rootQCVoter,
factory,
heightEvents,
)
if err != nil {
return nil, fmt.Errorf("could not create epoch manager: %w", err)
}
// register the manager for protocol events
node.ProtocolEvents.AddConsumer(manager)
return manager, err
}).
Run()
}
// TEMPORARY: The functionality to allow starting up a node without a properly configured
// machine account is very much intended to be temporary.
// Implemented by: https://github.com/dapperlabs/flow-go/issues/5585
// Will be reverted by: https://github.com/dapperlabs/flow-go/issues/5619
func createQCContractClient(node *cmd.NodeConfig, accessAddress string) (module.QCContractClient, error) {
var qcContractClient module.QCContractClient
contracts, err := systemcontracts.SystemContractsForChain(node.RootChainID)
if err != nil {
return nil, err
}
qcContractAddress := contracts.ClusterQC.Address.Hex()
// if not valid return a mock qc contract client
if valid := cmd.IsValidNodeMachineAccountConfig(node, accessAddress); !valid {
return epochs.NewMockQCContractClient(node.Logger), nil
}
// attempt to read NodeMachineAccountInfo
info, err := cmd.LoadNodeMachineAccountInfoFile(node.BaseConfig.BootstrapDir, node.Me.NodeID())
if err != nil {
return nil, fmt.Errorf("could not load node machine account info file: %w", err)
}
// construct signer from private key
sk, err := sdkcrypto.DecodePrivateKey(info.SigningAlgorithm, info.EncodedPrivateKey)
if err != nil {
return nil, fmt.Errorf("could not decode private key from hex: %w", err)
}
txSigner := sdkcrypto.NewInMemorySigner(sk, info.HashAlgorithm)
// create flow client
flowClient, err := client.New(accessAddress, grpc.WithInsecure())
if err != nil {
return nil, err
}
// create actual qc contract client, all flags and machine account info file found
qcContractClient = epochs.NewQCContractClient(node.Logger, flowClient, node.Me.NodeID(), info.Address, info.KeyIndex, qcContractAddress, txSigner)
return qcContractClient, nil
}