-
Notifications
You must be signed in to change notification settings - Fork 670
/
manager.go
1583 lines (1386 loc) · 47.6 KB
/
manager.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package chains
import (
"context"
"crypto"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"go.uber.org/zap"
"github.com/ava-labs/avalanchego/api/health"
"github.com/ava-labs/avalanchego/api/keystore"
"github.com/ava-labs/avalanchego/api/metrics"
"github.com/ava-labs/avalanchego/api/server"
"github.com/ava-labs/avalanchego/chains/atomic"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/database/meterdb"
"github.com/ava-labs/avalanchego/database/prefixdb"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/message"
"github.com/ava-labs/avalanchego/network"
"github.com/ava-labs/avalanchego/network/p2p"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/snow/engine/avalanche/bootstrap/queue"
"github.com/ava-labs/avalanchego/snow/engine/avalanche/state"
"github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex"
"github.com/ava-labs/avalanchego/snow/engine/common"
"github.com/ava-labs/avalanchego/snow/engine/common/tracker"
"github.com/ava-labs/avalanchego/snow/engine/snowman/block"
"github.com/ava-labs/avalanchego/snow/engine/snowman/syncer"
"github.com/ava-labs/avalanchego/snow/networking/handler"
"github.com/ava-labs/avalanchego/snow/networking/router"
"github.com/ava-labs/avalanchego/snow/networking/sender"
"github.com/ava-labs/avalanchego/snow/networking/timeout"
"github.com/ava-labs/avalanchego/snow/validators"
"github.com/ava-labs/avalanchego/staking"
"github.com/ava-labs/avalanchego/subnets"
"github.com/ava-labs/avalanchego/trace"
"github.com/ava-labs/avalanchego/upgrade"
"github.com/ava-labs/avalanchego/utils/buffer"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/utils/metric"
"github.com/ava-labs/avalanchego/utils/perms"
"github.com/ava-labs/avalanchego/utils/set"
"github.com/ava-labs/avalanchego/vms"
"github.com/ava-labs/avalanchego/vms/fx"
"github.com/ava-labs/avalanchego/vms/metervm"
"github.com/ava-labs/avalanchego/vms/nftfx"
"github.com/ava-labs/avalanchego/vms/platformvm/warp"
"github.com/ava-labs/avalanchego/vms/propertyfx"
"github.com/ava-labs/avalanchego/vms/proposervm"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
"github.com/ava-labs/avalanchego/vms/tracedvm"
p2ppb "github.com/ava-labs/avalanchego/proto/pb/p2p"
smcon "github.com/ava-labs/avalanchego/snow/consensus/snowman"
aveng "github.com/ava-labs/avalanchego/snow/engine/avalanche"
avbootstrap "github.com/ava-labs/avalanchego/snow/engine/avalanche/bootstrap"
avagetter "github.com/ava-labs/avalanchego/snow/engine/avalanche/getter"
smeng "github.com/ava-labs/avalanchego/snow/engine/snowman"
smbootstrap "github.com/ava-labs/avalanchego/snow/engine/snowman/bootstrap"
snowgetter "github.com/ava-labs/avalanchego/snow/engine/snowman/getter"
timetracker "github.com/ava-labs/avalanchego/snow/networking/tracker"
)
const (
ChainLabel = "chain"
defaultChannelSize = 1
initialQueueSize = 3
avalancheNamespace = constants.PlatformName + metric.NamespaceSeparator + "avalanche"
handlerNamespace = constants.PlatformName + metric.NamespaceSeparator + "handler"
meterchainvmNamespace = constants.PlatformName + metric.NamespaceSeparator + "meterchainvm"
meterdagvmNamespace = constants.PlatformName + metric.NamespaceSeparator + "meterdagvm"
proposervmNamespace = constants.PlatformName + metric.NamespaceSeparator + "proposervm"
p2pNamespace = constants.PlatformName + metric.NamespaceSeparator + "p2p"
snowmanNamespace = constants.PlatformName + metric.NamespaceSeparator + "snowman"
stakeNamespace = constants.PlatformName + metric.NamespaceSeparator + "stake"
)
var (
// Commonly shared VM DB prefix
VMDBPrefix = []byte("vm")
// Bootstrapping prefixes for LinearizableVMs
VertexDBPrefix = []byte("vertex")
VertexBootstrappingDBPrefix = []byte("vertex_bs")
TxBootstrappingDBPrefix = []byte("tx_bs")
BlockBootstrappingDBPrefix = []byte("interval_block_bs")
// Bootstrapping prefixes for ChainVMs
ChainBootstrappingDBPrefix = []byte("interval_bs")
errUnknownVMType = errors.New("the vm should have type avalanche.DAGVM or snowman.ChainVM")
errCreatePlatformVM = errors.New("attempted to create a chain running the PlatformVM")
errNotBootstrapped = errors.New("subnets not bootstrapped")
errPartialSyncAsAValidator = errors.New("partial sync should not be configured for a validator")
fxs = map[ids.ID]fx.Factory{
secp256k1fx.ID: &secp256k1fx.Factory{},
nftfx.ID: &nftfx.Factory{},
propertyfx.ID: &propertyfx.Factory{},
}
_ Manager = (*manager)(nil)
)
// Manager manages the chains running on this node.
// It can:
// - Create a chain
// - Add a registrant. When a chain is created, each registrant calls
// RegisterChain with the new chain as the argument.
// - Manage the aliases of chains
type Manager interface {
ids.Aliaser
// Queues a chain to be created in the future after chain creator is unblocked.
// This is only called from the P-chain thread to create other chains
// Queued chains are created only after P-chain is bootstrapped.
// This assumes only chains in tracked subnets are queued.
QueueChainCreation(ChainParameters)
// Add a registrant [r]. Every time a chain is
// created, [r].RegisterChain([new chain]) is called.
AddRegistrant(Registrant)
// Given an alias, return the ID of the chain associated with that alias
Lookup(string) (ids.ID, error)
// Given an alias, return the ID of the VM associated with that alias
LookupVM(string) (ids.ID, error)
// Returns true iff the chain with the given ID exists and is finished bootstrapping
IsBootstrapped(ids.ID) bool
// Starts the chain creator with the initial platform chain parameters, must
// be called once.
StartChainCreator(platformChain ChainParameters) error
Shutdown()
}
// ChainParameters defines the chain being created
type ChainParameters struct {
// The ID of the chain being created.
ID ids.ID
// ID of the subnet that validates this chain.
SubnetID ids.ID
// The genesis data of this chain's ledger.
GenesisData []byte
// The ID of the vm this chain is running.
VMID ids.ID
// The IDs of the feature extensions this chain is running.
FxIDs []ids.ID
// Invariant: Only used when [ID] is the P-chain ID.
CustomBeacons validators.Manager
}
type chain struct {
Name string
Context *snow.ConsensusContext
VM common.VM
Handler handler.Handler
}
// ChainConfig is configuration settings for the current execution.
// [Config] is the user-provided config blob for the chain.
// [Upgrade] is a chain-specific blob for coordinating upgrades.
type ChainConfig struct {
Config []byte
Upgrade []byte
}
type ManagerConfig struct {
SybilProtectionEnabled bool
StakingTLSSigner crypto.Signer
StakingTLSCert *staking.Certificate
StakingBLSKey *bls.SecretKey
TracingEnabled bool
// Must not be used unless [TracingEnabled] is true as this may be nil.
Tracer trace.Tracer
Log logging.Logger
LogFactory logging.Factory
VMManager vms.Manager // Manage mappings from vm ID --> vm
BlockAcceptorGroup snow.AcceptorGroup
TxAcceptorGroup snow.AcceptorGroup
VertexAcceptorGroup snow.AcceptorGroup
DB database.Database
MsgCreator message.OutboundMsgBuilder // message creator, shared with network
Router router.Router // Routes incoming messages to the appropriate chain
Net network.Network // Sends consensus messages to other validators
Validators validators.Manager // Validators validating on this chain
NodeID ids.NodeID // The ID of this node
NetworkID uint32 // ID of the network this node is connected to
PartialSyncPrimaryNetwork bool
Server server.Server // Handles HTTP API calls
Keystore keystore.Keystore
AtomicMemory *atomic.Memory
AVAXAssetID ids.ID
XChainID ids.ID // ID of the X-Chain,
CChainID ids.ID // ID of the C-Chain,
CriticalChains set.Set[ids.ID] // Chains that can't exit gracefully
TimeoutManager timeout.Manager // Manages request timeouts when sending messages to other validators
Health health.Registerer
SubnetConfigs map[ids.ID]subnets.Config // ID -> SubnetConfig
ChainConfigs map[string]ChainConfig // alias -> ChainConfig
// ShutdownNodeFunc allows the chain manager to issue a request to shutdown the node
ShutdownNodeFunc func(exitCode int)
MeterVMEnabled bool // Should each VM be wrapped with a MeterVM
Metrics metrics.MultiGatherer
MeterDBMetrics metrics.MultiGatherer
FrontierPollFrequency time.Duration
ConsensusAppConcurrency int
// Max Time to spend fetching a container and its
// ancestors when responding to a GetAncestors
BootstrapMaxTimeGetAncestors time.Duration
// Max number of containers in an ancestors message sent by this node.
BootstrapAncestorsMaxContainersSent int
// This node will only consider the first [AncestorsMaxContainersReceived]
// containers in an ancestors message it receives.
BootstrapAncestorsMaxContainersReceived int
Upgrades upgrade.Config
// Tracks CPU/disk usage caused by each peer.
ResourceTracker timetracker.ResourceTracker
StateSyncBeacons []ids.NodeID
ChainDataDir string
Subnets *Subnets
}
type manager struct {
// Note: The string representation of a chain's ID is also considered to be an alias of the chain
// That is, [chainID].String() is an alias for the chain, too
ids.Aliaser
ManagerConfig
// Those notified when a chain is created
registrants []Registrant
// queue that holds chain create requests
chainsQueue buffer.BlockingDeque[ChainParameters]
// unblocks chain creator to start processing the queue
unblockChainCreatorCh chan struct{}
// shutdown the chain creator goroutine if the queue hasn't started to be
// processed.
chainCreatorShutdownCh chan struct{}
chainCreatorExited sync.WaitGroup
chainsLock sync.Mutex
// Key: Chain's ID
// Value: The chain
chains map[ids.ID]handler.Handler
// snowman++ related interface to allow validators retrieval
validatorState validators.State
avalancheGatherer metrics.MultiGatherer // chainID
handlerGatherer metrics.MultiGatherer // chainID
meterChainVMGatherer metrics.MultiGatherer // chainID
meterDAGVMGatherer metrics.MultiGatherer // chainID
proposervmGatherer metrics.MultiGatherer // chainID
p2pGatherer metrics.MultiGatherer // chainID
snowmanGatherer metrics.MultiGatherer // chainID
stakeGatherer metrics.MultiGatherer // chainID
vmGatherer map[ids.ID]metrics.MultiGatherer // vmID -> chainID
}
// New returns a new Manager
func New(config *ManagerConfig) (Manager, error) {
avalancheGatherer := metrics.NewLabelGatherer(ChainLabel)
if err := config.Metrics.Register(avalancheNamespace, avalancheGatherer); err != nil {
return nil, err
}
handlerGatherer := metrics.NewLabelGatherer(ChainLabel)
if err := config.Metrics.Register(handlerNamespace, handlerGatherer); err != nil {
return nil, err
}
meterChainVMGatherer := metrics.NewLabelGatherer(ChainLabel)
if err := config.Metrics.Register(meterchainvmNamespace, meterChainVMGatherer); err != nil {
return nil, err
}
meterDAGVMGatherer := metrics.NewLabelGatherer(ChainLabel)
if err := config.Metrics.Register(meterdagvmNamespace, meterDAGVMGatherer); err != nil {
return nil, err
}
proposervmGatherer := metrics.NewLabelGatherer(ChainLabel)
if err := config.Metrics.Register(proposervmNamespace, proposervmGatherer); err != nil {
return nil, err
}
p2pGatherer := metrics.NewLabelGatherer(ChainLabel)
if err := config.Metrics.Register(p2pNamespace, p2pGatherer); err != nil {
return nil, err
}
snowmanGatherer := metrics.NewLabelGatherer(ChainLabel)
if err := config.Metrics.Register(snowmanNamespace, snowmanGatherer); err != nil {
return nil, err
}
stakeGatherer := metrics.NewLabelGatherer(ChainLabel)
if err := config.Metrics.Register(stakeNamespace, stakeGatherer); err != nil {
return nil, err
}
return &manager{
Aliaser: ids.NewAliaser(),
ManagerConfig: *config,
chains: make(map[ids.ID]handler.Handler),
chainsQueue: buffer.NewUnboundedBlockingDeque[ChainParameters](initialQueueSize),
unblockChainCreatorCh: make(chan struct{}),
chainCreatorShutdownCh: make(chan struct{}),
avalancheGatherer: avalancheGatherer,
handlerGatherer: handlerGatherer,
meterChainVMGatherer: meterChainVMGatherer,
meterDAGVMGatherer: meterDAGVMGatherer,
proposervmGatherer: proposervmGatherer,
p2pGatherer: p2pGatherer,
snowmanGatherer: snowmanGatherer,
stakeGatherer: stakeGatherer,
vmGatherer: make(map[ids.ID]metrics.MultiGatherer),
}, nil
}
// QueueChainCreation queues a chain creation request
// Invariant: Tracked Subnet must be checked before calling this function
func (m *manager) QueueChainCreation(chainParams ChainParameters) {
if sb, _ := m.Subnets.GetOrCreate(chainParams.SubnetID); !sb.AddChain(chainParams.ID) {
m.Log.Debug("skipping chain creation",
zap.String("reason", "chain already staged"),
zap.Stringer("subnetID", chainParams.SubnetID),
zap.Stringer("chainID", chainParams.ID),
zap.Stringer("vmID", chainParams.VMID),
)
return
}
if ok := m.chainsQueue.PushRight(chainParams); !ok {
m.Log.Warn("skipping chain creation",
zap.String("reason", "couldn't enqueue chain"),
zap.Stringer("subnetID", chainParams.SubnetID),
zap.Stringer("chainID", chainParams.ID),
zap.Stringer("vmID", chainParams.VMID),
)
}
}
// createChain creates and starts the chain
//
// Note: it is expected for the subnet to already have the chain registered as
// bootstrapping before this function is called
func (m *manager) createChain(chainParams ChainParameters) {
m.Log.Info("creating chain",
zap.Stringer("subnetID", chainParams.SubnetID),
zap.Stringer("chainID", chainParams.ID),
zap.Stringer("vmID", chainParams.VMID),
)
sb, _ := m.Subnets.GetOrCreate(chainParams.SubnetID)
// Note: buildChain builds all chain's relevant objects (notably engine and handler)
// but does not start their operations. Starting of the handler (which could potentially
// issue some internal messages), is delayed until chain dispatching is started and
// the chain is registered in the manager. This ensures that no message generated by handler
// upon start is dropped.
chain, err := m.buildChain(chainParams, sb)
if err != nil {
if m.CriticalChains.Contains(chainParams.ID) {
// Shut down if we fail to create a required chain (i.e. X, P or C)
m.Log.Fatal("error creating required chain",
zap.Stringer("subnetID", chainParams.SubnetID),
zap.Stringer("chainID", chainParams.ID),
zap.Stringer("vmID", chainParams.VMID),
zap.Error(err),
)
go m.ShutdownNodeFunc(1)
return
}
chainAlias := m.PrimaryAliasOrDefault(chainParams.ID)
m.Log.Error("error creating chain",
zap.Stringer("subnetID", chainParams.SubnetID),
zap.Stringer("chainID", chainParams.ID),
zap.String("chainAlias", chainAlias),
zap.Stringer("vmID", chainParams.VMID),
zap.Error(err),
)
// Register the health check for this chain regardless of if it was
// created or not. This attempts to notify the node operator that their
// node may not be properly validating the subnet they expect to be
// validating.
healthCheckErr := fmt.Errorf("failed to create chain on subnet %s: %w", chainParams.SubnetID, err)
err := m.Health.RegisterHealthCheck(
chainAlias,
health.CheckerFunc(func(context.Context) (interface{}, error) {
return nil, healthCheckErr
}),
chainParams.SubnetID.String(),
)
if err != nil {
m.Log.Error("failed to register failing health check",
zap.Stringer("subnetID", chainParams.SubnetID),
zap.Stringer("chainID", chainParams.ID),
zap.String("chainAlias", chainAlias),
zap.Stringer("vmID", chainParams.VMID),
zap.Error(err),
)
}
return
}
m.chainsLock.Lock()
m.chains[chainParams.ID] = chain.Handler
m.chainsLock.Unlock()
// Associate the newly created chain with its default alias
if err := m.Alias(chainParams.ID, chainParams.ID.String()); err != nil {
m.Log.Error("failed to alias the new chain with itself",
zap.Stringer("subnetID", chainParams.SubnetID),
zap.Stringer("chainID", chainParams.ID),
zap.Stringer("vmID", chainParams.VMID),
zap.Error(err),
)
}
// Notify those who registered to be notified when a new chain is created
m.notifyRegistrants(chain.Name, chain.Context, chain.VM)
// Allows messages to be routed to the new chain. If the handler hasn't been
// started and a message is forwarded, then the message will block until the
// handler is started.
m.ManagerConfig.Router.AddChain(context.TODO(), chain.Handler)
// Register bootstrapped health checks after P chain has been added to
// chains.
//
// Note: Registering this after the chain has been tracked prevents a race
// condition between the health check and adding the first chain to
// the manager.
if chainParams.ID == constants.PlatformChainID {
if err := m.registerBootstrappedHealthChecks(); err != nil {
chain.Handler.StopWithError(context.TODO(), err)
}
}
// Tell the chain to start processing messages.
// If the X, P, or C Chain panics, do not attempt to recover
chain.Handler.Start(context.TODO(), !m.CriticalChains.Contains(chainParams.ID))
}
// Create a chain
func (m *manager) buildChain(chainParams ChainParameters, sb subnets.Subnet) (*chain, error) {
if chainParams.ID != constants.PlatformChainID && chainParams.VMID == constants.PlatformVMID {
return nil, errCreatePlatformVM
}
primaryAlias := m.PrimaryAliasOrDefault(chainParams.ID)
// Create this chain's data directory
chainDataDir := filepath.Join(m.ChainDataDir, chainParams.ID.String())
if err := os.MkdirAll(chainDataDir, perms.ReadWriteExecute); err != nil {
return nil, fmt.Errorf("error while creating chain data directory %w", err)
}
// Create the log and context of the chain
chainLog, err := m.LogFactory.MakeChain(primaryAlias)
if err != nil {
return nil, fmt.Errorf("error while creating chain's log %w", err)
}
snowmanMetrics, err := metrics.MakeAndRegister(
m.snowmanGatherer,
primaryAlias,
)
if err != nil {
return nil, err
}
vmMetrics, err := m.getOrMakeVMRegisterer(chainParams.VMID, primaryAlias)
if err != nil {
return nil, err
}
ctx := &snow.ConsensusContext{
Context: &snow.Context{
NetworkID: m.NetworkID,
SubnetID: chainParams.SubnetID,
ChainID: chainParams.ID,
NodeID: m.NodeID,
PublicKey: bls.PublicFromSecretKey(m.StakingBLSKey),
NetworkUpgrades: m.Upgrades,
XChainID: m.XChainID,
CChainID: m.CChainID,
AVAXAssetID: m.AVAXAssetID,
Log: chainLog,
Keystore: m.Keystore.NewBlockchainKeyStore(chainParams.ID),
SharedMemory: m.AtomicMemory.NewSharedMemory(chainParams.ID),
BCLookup: m,
Metrics: vmMetrics,
WarpSigner: warp.NewSigner(m.StakingBLSKey, m.NetworkID, chainParams.ID),
ValidatorState: m.validatorState,
ChainDataDir: chainDataDir,
},
PrimaryAlias: primaryAlias,
Registerer: snowmanMetrics,
BlockAcceptor: m.BlockAcceptorGroup,
TxAcceptor: m.TxAcceptorGroup,
VertexAcceptor: m.VertexAcceptorGroup,
}
// Get a factory for the vm we want to use on our chain
vmFactory, err := m.VMManager.GetFactory(chainParams.VMID)
if err != nil {
return nil, fmt.Errorf("error while getting vmFactory: %w", err)
}
// Create the chain
vm, err := vmFactory.New(chainLog)
if err != nil {
return nil, fmt.Errorf("error while creating vm: %w", err)
}
// TODO: Shutdown VM if an error occurs
chainFxs := make([]*common.Fx, len(chainParams.FxIDs))
for i, fxID := range chainParams.FxIDs {
fxFactory, ok := fxs[fxID]
if !ok {
return nil, fmt.Errorf("fx %s not found", fxID)
}
chainFxs[i] = &common.Fx{
ID: fxID,
Fx: fxFactory.New(),
}
}
var chain *chain
switch vm := vm.(type) {
case vertex.LinearizableVMWithEngine:
chain, err = m.createAvalancheChain(
ctx,
chainParams.GenesisData,
m.Validators,
vm,
chainFxs,
sb,
)
if err != nil {
return nil, fmt.Errorf("error while creating new avalanche vm %w", err)
}
case block.ChainVM:
beacons := m.Validators
if chainParams.ID == constants.PlatformChainID {
beacons = chainParams.CustomBeacons
}
chain, err = m.createSnowmanChain(
ctx,
chainParams.GenesisData,
m.Validators,
beacons,
vm,
chainFxs,
sb,
)
if err != nil {
return nil, fmt.Errorf("error while creating new snowman vm %w", err)
}
default:
return nil, errUnknownVMType
}
// Register the chain with the timeout manager
if err := m.TimeoutManager.RegisterChain(ctx); err != nil {
return nil, err
}
return chain, nil
}
func (m *manager) AddRegistrant(r Registrant) {
m.registrants = append(m.registrants, r)
}
// Create a DAG-based blockchain that uses Avalanche
func (m *manager) createAvalancheChain(
ctx *snow.ConsensusContext,
genesisData []byte,
vdrs validators.Manager,
vm vertex.LinearizableVMWithEngine,
fxs []*common.Fx,
sb subnets.Subnet,
) (*chain, error) {
ctx.Lock.Lock()
defer ctx.Lock.Unlock()
ctx.State.Set(snow.EngineState{
Type: p2ppb.EngineType_ENGINE_TYPE_AVALANCHE,
State: snow.Initializing,
})
primaryAlias := m.PrimaryAliasOrDefault(ctx.ChainID)
meterDBReg, err := metrics.MakeAndRegister(
m.MeterDBMetrics,
primaryAlias,
)
if err != nil {
return nil, err
}
meterDB, err := meterdb.New(meterDBReg, m.DB)
if err != nil {
return nil, err
}
prefixDB := prefixdb.New(ctx.ChainID[:], meterDB)
vmDB := prefixdb.New(VMDBPrefix, prefixDB)
vertexDB := prefixdb.New(VertexDBPrefix, prefixDB)
vertexBootstrappingDB := prefixdb.New(VertexBootstrappingDBPrefix, prefixDB)
txBootstrappingDB := prefixdb.New(TxBootstrappingDBPrefix, prefixDB)
blockBootstrappingDB := prefixdb.New(BlockBootstrappingDBPrefix, prefixDB)
avalancheMetrics, err := metrics.MakeAndRegister(
m.avalancheGatherer,
primaryAlias,
)
if err != nil {
return nil, err
}
vtxBlocker, err := queue.NewWithMissing(vertexBootstrappingDB, "vtx", avalancheMetrics)
if err != nil {
return nil, err
}
txBlocker, err := queue.New(txBootstrappingDB, "tx", avalancheMetrics)
if err != nil {
return nil, err
}
// Passes messages from the avalanche engines to the network
avalancheMessageSender, err := sender.New(
ctx,
m.MsgCreator,
m.Net,
m.ManagerConfig.Router,
m.TimeoutManager,
p2ppb.EngineType_ENGINE_TYPE_AVALANCHE,
sb,
avalancheMetrics,
)
if err != nil {
return nil, fmt.Errorf("couldn't initialize avalanche sender: %w", err)
}
if m.TracingEnabled {
avalancheMessageSender = sender.Trace(avalancheMessageSender, m.Tracer)
}
// Passes messages from the snowman engines to the network
snowmanMessageSender, err := sender.New(
ctx,
m.MsgCreator,
m.Net,
m.ManagerConfig.Router,
m.TimeoutManager,
p2ppb.EngineType_ENGINE_TYPE_SNOWMAN,
sb,
ctx.Registerer,
)
if err != nil {
return nil, fmt.Errorf("couldn't initialize avalanche sender: %w", err)
}
if m.TracingEnabled {
snowmanMessageSender = sender.Trace(snowmanMessageSender, m.Tracer)
}
chainConfig, err := m.getChainConfig(ctx.ChainID)
if err != nil {
return nil, fmt.Errorf("error while fetching chain config: %w", err)
}
dagVM := vm
if m.MeterVMEnabled {
meterdagvmReg, err := metrics.MakeAndRegister(
m.meterDAGVMGatherer,
primaryAlias,
)
if err != nil {
return nil, err
}
dagVM = metervm.NewVertexVM(dagVM, meterdagvmReg)
}
if m.TracingEnabled {
dagVM = tracedvm.NewVertexVM(dagVM, m.Tracer)
}
// Handles serialization/deserialization of vertices and also the
// persistence of vertices
vtxManager := state.NewSerializer(
state.SerializerConfig{
ChainID: ctx.ChainID,
VM: dagVM,
DB: vertexDB,
Log: ctx.Log,
},
)
// The channel through which a VM may send messages to the consensus engine
// VM uses this channel to notify engine that a block is ready to be made
msgChan := make(chan common.Message, defaultChannelSize)
// The only difference between using avalancheMessageSender and
// snowmanMessageSender here is where the metrics will be placed. Because we
// end up using this sender after the linearization, we pass in
// snowmanMessageSender here.
err = dagVM.Initialize(
context.TODO(),
ctx.Context,
vmDB,
genesisData,
chainConfig.Upgrade,
chainConfig.Config,
msgChan,
fxs,
snowmanMessageSender,
)
if err != nil {
return nil, fmt.Errorf("error during vm's Initialize: %w", err)
}
// Initialize the ProposerVM and the vm wrapped inside it
var (
minBlockDelay = proposervm.DefaultMinBlockDelay
numHistoricalBlocks = proposervm.DefaultNumHistoricalBlocks
)
if subnetCfg, ok := m.SubnetConfigs[ctx.SubnetID]; ok {
minBlockDelay = subnetCfg.ProposerMinBlockDelay
numHistoricalBlocks = subnetCfg.ProposerNumHistoricalBlocks
}
m.Log.Info("creating proposervm wrapper",
zap.Time("activationTime", m.Upgrades.ApricotPhase4Time),
zap.Uint64("minPChainHeight", m.Upgrades.ApricotPhase4MinPChainHeight),
zap.Duration("minBlockDelay", minBlockDelay),
zap.Uint64("numHistoricalBlocks", numHistoricalBlocks),
)
// Note: this does not use [dagVM] to ensure we use the [vm]'s height index.
untracedVMWrappedInsideProposerVM := NewLinearizeOnInitializeVM(vm)
var vmWrappedInsideProposerVM block.ChainVM = untracedVMWrappedInsideProposerVM
if m.TracingEnabled {
vmWrappedInsideProposerVM = tracedvm.NewBlockVM(vmWrappedInsideProposerVM, primaryAlias, m.Tracer)
}
proposervmReg, err := metrics.MakeAndRegister(
m.proposervmGatherer,
primaryAlias,
)
if err != nil {
return nil, err
}
proposerVM := proposervm.New(
vmWrappedInsideProposerVM,
proposervm.Config{
Upgrades: m.Upgrades,
MinBlkDelay: minBlockDelay,
NumHistoricalBlocks: numHistoricalBlocks,
StakingLeafSigner: m.StakingTLSSigner,
StakingCertLeaf: m.StakingTLSCert,
Registerer: proposervmReg,
},
)
// Note: vmWrappingProposerVM is the VM that the Snowman engines should be
// using.
var vmWrappingProposerVM block.ChainVM = proposerVM
if m.MeterVMEnabled {
meterchainvmReg, err := metrics.MakeAndRegister(
m.meterChainVMGatherer,
primaryAlias,
)
if err != nil {
return nil, err
}
vmWrappingProposerVM = metervm.NewBlockVM(vmWrappingProposerVM, meterchainvmReg)
}
if m.TracingEnabled {
vmWrappingProposerVM = tracedvm.NewBlockVM(vmWrappingProposerVM, "proposervm", m.Tracer)
}
// Note: linearizableVM is the VM that the Avalanche engines should be
// using.
linearizableVM := &initializeOnLinearizeVM{
DAGVM: dagVM,
vmToInitialize: vmWrappingProposerVM,
vmToLinearize: untracedVMWrappedInsideProposerVM,
ctx: ctx.Context,
db: vmDB,
genesisBytes: genesisData,
upgradeBytes: chainConfig.Upgrade,
configBytes: chainConfig.Config,
toEngine: msgChan,
fxs: fxs,
appSender: snowmanMessageSender,
}
bootstrapWeight, err := vdrs.TotalWeight(ctx.SubnetID)
if err != nil {
return nil, fmt.Errorf("error while fetching weight for subnet %s: %w", ctx.SubnetID, err)
}
consensusParams := sb.Config().ConsensusParameters
sampleK := consensusParams.K
if uint64(sampleK) > bootstrapWeight {
sampleK = int(bootstrapWeight)
}
stakeReg, err := metrics.MakeAndRegister(
m.stakeGatherer,
primaryAlias,
)
if err != nil {
return nil, err
}
connectedValidators, err := tracker.NewMeteredPeers(stakeReg)
if err != nil {
return nil, fmt.Errorf("error creating peer tracker: %w", err)
}
vdrs.RegisterSetCallbackListener(ctx.SubnetID, connectedValidators)
p2pReg, err := metrics.MakeAndRegister(
m.p2pGatherer,
primaryAlias,
)
if err != nil {
return nil, err
}
peerTracker, err := p2p.NewPeerTracker(
ctx.Log,
"peer_tracker",
p2pReg,
set.Of(ctx.NodeID),
nil,
)
if err != nil {
return nil, fmt.Errorf("error creating peer tracker: %w", err)
}
handlerReg, err := metrics.MakeAndRegister(
m.handlerGatherer,
primaryAlias,
)
if err != nil {
return nil, err
}
var halter common.Halter
// Asynchronously passes messages from the network to the consensus engine
h, err := handler.New(
ctx,
vdrs,
msgChan,
m.FrontierPollFrequency,
m.ConsensusAppConcurrency,
m.ResourceTracker,
sb,
connectedValidators,
peerTracker,
handlerReg,
halter.Halt,
)
if err != nil {
return nil, fmt.Errorf("error initializing network handler: %w", err)
}
connectedBeacons := tracker.NewPeers()
startupTracker := tracker.NewStartup(connectedBeacons, (3*bootstrapWeight+3)/4)
vdrs.RegisterSetCallbackListener(ctx.SubnetID, startupTracker)
snowGetHandler, err := snowgetter.New(
vmWrappingProposerVM,
snowmanMessageSender,
ctx.Log,
m.BootstrapMaxTimeGetAncestors,
m.BootstrapAncestorsMaxContainersSent,
ctx.Registerer,
)
if err != nil {
return nil, fmt.Errorf("couldn't initialize snow base message handler: %w", err)
}
var snowmanConsensus smcon.Consensus = &smcon.Topological{}
if m.TracingEnabled {
snowmanConsensus = smcon.Trace(snowmanConsensus, m.Tracer)
}
// Create engine, bootstrapper and state-syncer in this order,
// to make sure start callbacks are duly initialized
snowmanEngineConfig := smeng.Config{
Ctx: ctx,
AllGetsServer: snowGetHandler,
VM: vmWrappingProposerVM,
Sender: snowmanMessageSender,
Validators: vdrs,
ConnectedValidators: connectedValidators,
Params: consensusParams,
Consensus: snowmanConsensus,
}
var snowmanEngine common.Engine
snowmanEngine, err = smeng.New(snowmanEngineConfig)
if err != nil {
return nil, fmt.Errorf("error initializing snowman engine: %w", err)
}
if m.TracingEnabled {
snowmanEngine = common.TraceEngine(snowmanEngine, m.Tracer)
}
// create bootstrap gear
bootstrapCfg := smbootstrap.Config{
ShouldHalt: halter.Halted,
NonVerifyingParse: block.ParseFunc(proposerVM.ParseLocalBlock),
AllGetsServer: snowGetHandler,
Ctx: ctx,
Beacons: vdrs,
SampleK: sampleK,
StartupTracker: startupTracker,
Sender: snowmanMessageSender,
BootstrapTracker: sb,
Timer: h,
PeerTracker: peerTracker,
AncestorsMaxContainersReceived: m.BootstrapAncestorsMaxContainersReceived,
DB: blockBootstrappingDB,
VM: vmWrappingProposerVM,
}
var snowmanBootstrapper common.BootstrapableEngine
snowmanBootstrapper, err = smbootstrap.New(
bootstrapCfg,
snowmanEngine.Start,
)
if err != nil {
return nil, fmt.Errorf("error initializing snowman bootstrapper: %w", err)
}
if m.TracingEnabled {
snowmanBootstrapper = common.TraceBootstrapableEngine(snowmanBootstrapper, m.Tracer)
}
avaGetHandler, err := avagetter.New(
vtxManager,
avalancheMessageSender,
ctx.Log,
m.BootstrapMaxTimeGetAncestors,
m.BootstrapAncestorsMaxContainersSent,
avalancheMetrics,
)
if err != nil {
return nil, fmt.Errorf("couldn't initialize avalanche base message handler: %w", err)
}
// create engine gear
avalancheEngine := aveng.New(ctx, avaGetHandler, linearizableVM)
if m.TracingEnabled {
avalancheEngine = common.TraceEngine(avalancheEngine, m.Tracer)
}