forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
1467 lines (1284 loc) · 44.3 KB
/
node.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-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package node
import (
"context"
"crypto"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
coreth "github.com/ava-labs/coreth/plugin/evm"
"github.com/ava-labs/avalanchego/api/admin"
"github.com/ava-labs/avalanchego/api/auth"
"github.com/ava-labs/avalanchego/api/health"
"github.com/ava-labs/avalanchego/api/info"
"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"
"github.com/ava-labs/avalanchego/chains/atomic"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/database/leveldb"
"github.com/ava-labs/avalanchego/database/manager"
"github.com/ava-labs/avalanchego/database/memdb"
"github.com/ava-labs/avalanchego/database/prefixdb"
"github.com/ava-labs/avalanchego/genesis"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/indexer"
"github.com/ava-labs/avalanchego/ipcs"
"github.com/ava-labs/avalanchego/message"
"github.com/ava-labs/avalanchego/network"
"github.com/ava-labs/avalanchego/network/dialer"
"github.com/ava-labs/avalanchego/network/peer"
"github.com/ava-labs/avalanchego/network/throttling"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/snow/engine/common"
"github.com/ava-labs/avalanchego/snow/networking/benchlist"
"github.com/ava-labs/avalanchego/snow/networking/router"
"github.com/ava-labs/avalanchego/snow/networking/timeout"
"github.com/ava-labs/avalanchego/snow/networking/tracker"
"github.com/ava-labs/avalanchego/snow/uptime"
"github.com/ava-labs/avalanchego/snow/validators"
"github.com/ava-labs/avalanchego/trace"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
"github.com/ava-labs/avalanchego/utils/filesystem"
"github.com/ava-labs/avalanchego/utils/hashing"
"github.com/ava-labs/avalanchego/utils/ips"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/utils/math/meter"
"github.com/ava-labs/avalanchego/utils/perms"
"github.com/ava-labs/avalanchego/utils/profiler"
"github.com/ava-labs/avalanchego/utils/resource"
"github.com/ava-labs/avalanchego/utils/set"
"github.com/ava-labs/avalanchego/utils/timer"
"github.com/ava-labs/avalanchego/utils/wrappers"
"github.com/ava-labs/avalanchego/version"
"github.com/ava-labs/avalanchego/vms"
"github.com/ava-labs/avalanchego/vms/avm"
"github.com/ava-labs/avalanchego/vms/nftfx"
"github.com/ava-labs/avalanchego/vms/platformvm"
"github.com/ava-labs/avalanchego/vms/platformvm/signer"
"github.com/ava-labs/avalanchego/vms/propertyfx"
"github.com/ava-labs/avalanchego/vms/registry"
"github.com/ava-labs/avalanchego/vms/rpcchainvm/runtime"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
ipcsapi "github.com/ava-labs/avalanchego/api/ipcs"
avmconfig "github.com/ava-labs/avalanchego/vms/avm/config"
platformconfig "github.com/ava-labs/avalanchego/vms/platformvm/config"
)
var (
genesisHashKey = []byte("genesisID")
indexerDBPrefix = []byte{0x00}
errInvalidTLSKey = errors.New("invalid TLS key")
errShuttingDown = errors.New("server shutting down")
)
// Node is an instance of an Avalanche node.
type Node struct {
Log logging.Logger
VMFactoryLog logging.Logger
LogFactory logging.Factory
// This node's unique ID used when communicating with other nodes
// (in consensus, for example)
ID ids.NodeID
// Storage for this node
DBManager manager.Manager
DB database.Database
// Profiles the process. Nil if continuous profiling is disabled.
profiler profiler.ContinuousProfiler
// Indexes blocks, transactions and blocks
indexer indexer.Indexer
// Handles calls to Keystore API
keystore keystore.Keystore
// Manages shared memory
sharedMemory *atomic.Memory
// Monitors node health and runs health checks
health health.Health
// Build and parse messages, for both network layer and chain manager
msgCreator message.Creator
// Manages creation of blockchains and routing messages to them
chainManager chains.Manager
// Manages validator benching
benchlistManager benchlist.Manager
uptimeCalculator uptime.LockedCalculator
// dispatcher for events as they happen in consensus
BlockAcceptorGroup snow.AcceptorGroup
TxAcceptorGroup snow.AcceptorGroup
VertexAcceptorGroup snow.AcceptorGroup
IPCs *ipcs.ChainIPCs
// Net runs the networking stack
networkNamespace string
Net network.Network
// tlsKeyLogWriterCloser is a debug file handle that writes all the TLS
// session keys. This value should only be non-nil during debugging.
tlsKeyLogWriterCloser io.WriteCloser
// this node's initial connections to the network
beacons validators.Set
// current validators of the network
vdrs validators.Manager
// Handles HTTP API calls
APIServer server.Server
// This node's configuration
Config *Config
tracer trace.Tracer
// ensures that we only close the node once.
shutdownOnce sync.Once
// True if node is shutting down or is done shutting down
shuttingDown utils.Atomic[bool]
// Sets the exit code
shuttingDownExitCode utils.Atomic[int]
// Incremented only once on initialization.
// Decremented when node is done shutting down.
DoneShuttingDown sync.WaitGroup
// Metrics Registerer
MetricsRegisterer *prometheus.Registry
MetricsGatherer metrics.MultiGatherer
VMManager vms.Manager
// VM endpoint registry
VMRegistry registry.VMRegistry
// Manages shutdown of a VM process
runtimeManager runtime.Manager
resourceManager resource.Manager
// Tracks the CPU/disk usage caused by processing
// messages of each peer.
resourceTracker tracker.ResourceTracker
// Specifies how much CPU usage each peer can cause before
// we rate-limit them.
cpuTargeter tracker.Targeter
// Specifies how much disk usage each peer can cause before
// we rate-limit them.
diskTargeter tracker.Targeter
}
/*
******************************************************************************
*************************** P2P Networking Section ***************************
******************************************************************************
*/
// Initialize the networking layer.
// Assumes [n.CPUTracker] and [n.CPUTargeter] have been initialized.
func (n *Node) initNetworking(primaryNetVdrs validators.Set) error {
currentIPPort := n.Config.IPPort.IPPort()
listener, err := net.Listen(constants.NetworkType, fmt.Sprintf(":%d", currentIPPort.Port))
if err != nil {
return err
}
// Wrap listener so it will only accept a certain number of incoming connections per second
listener = throttling.NewThrottledListener(listener, n.Config.NetworkConfig.ThrottlerConfig.MaxInboundConnsPerSec)
ipPort, err := ips.ToIPPort(listener.Addr().String())
if err != nil {
n.Log.Info("initializing networking",
zap.Stringer("currentNodeIP", currentIPPort),
)
} else {
ipPort = ips.IPPort{
IP: currentIPPort.IP,
Port: ipPort.Port,
}
n.Log.Info("initializing networking",
zap.Stringer("currentNodeIP", ipPort),
)
}
tlsKey, ok := n.Config.StakingTLSCert.PrivateKey.(crypto.Signer)
if !ok {
return errInvalidTLSKey
}
if n.Config.NetworkConfig.TLSKeyLogFile != "" {
n.tlsKeyLogWriterCloser, err = perms.Create(n.Config.NetworkConfig.TLSKeyLogFile, perms.ReadWrite)
if err != nil {
return err
}
n.Log.Warn("TLS key logging is enabled",
zap.String("filename", n.Config.NetworkConfig.TLSKeyLogFile),
)
}
tlsConfig := peer.TLSConfig(n.Config.StakingTLSCert, n.tlsKeyLogWriterCloser)
// Configure benchlist
n.Config.BenchlistConfig.Validators = n.vdrs
n.Config.BenchlistConfig.Benchable = n.Config.ConsensusRouter
n.Config.BenchlistConfig.StakingEnabled = n.Config.EnableStaking
n.benchlistManager = benchlist.NewManager(&n.Config.BenchlistConfig)
n.uptimeCalculator = uptime.NewLockedCalculator()
consensusRouter := n.Config.ConsensusRouter
if !n.Config.EnableStaking {
// Staking is disabled so we don't have a txID that added us as a
// validator. Because each validator needs a txID associated with it, we
// hack one together by just padding our nodeID with zeroes.
dummyTxID := ids.Empty
copy(dummyTxID[:], n.ID[:])
err := primaryNetVdrs.Add(
n.ID,
bls.PublicFromSecretKey(n.Config.StakingSigningKey),
dummyTxID,
n.Config.DisabledStakingWeight,
)
if err != nil {
return err
}
consensusRouter = &insecureValidatorManager{
Router: consensusRouter,
vdrs: primaryNetVdrs,
weight: n.Config.DisabledStakingWeight,
}
}
numBeacons := n.beacons.Len()
requiredConns := (3*numBeacons + 3) / 4
if requiredConns > 0 {
// Set a timer that will fire after a given timeout unless we connect
// to a sufficient portion of nodes. If the timeout fires, the node will
// shutdown.
timer := timer.NewTimer(func() {
// If the timeout fires and we're already shutting down, nothing to do.
if !n.shuttingDown.Get() {
n.Log.Warn("failed to connect to bootstrap nodes",
zap.Stringer("beacons", n.beacons),
zap.Duration("duration", n.Config.BootstrapBeaconConnectionTimeout),
)
}
})
go timer.Dispatch()
timer.SetTimeoutIn(n.Config.BootstrapBeaconConnectionTimeout)
consensusRouter = &beaconManager{
Router: consensusRouter,
timer: timer,
beacons: n.beacons,
requiredConns: int64(requiredConns),
}
}
// initialize gossip tracker
gossipTracker, err := peer.NewGossipTracker(n.MetricsRegisterer, n.networkNamespace)
if err != nil {
return err
}
// keep gossip tracker synchronized with the validator set
primaryNetVdrs.RegisterCallbackListener(&peer.GossipTrackerCallback{
Log: n.Log,
GossipTracker: gossipTracker,
})
// add node configs to network config
n.Config.NetworkConfig.Namespace = n.networkNamespace
n.Config.NetworkConfig.MyNodeID = n.ID
n.Config.NetworkConfig.MyIPPort = n.Config.IPPort
n.Config.NetworkConfig.NetworkID = n.Config.NetworkID
n.Config.NetworkConfig.Validators = n.vdrs
n.Config.NetworkConfig.Beacons = n.beacons
n.Config.NetworkConfig.TLSConfig = tlsConfig
n.Config.NetworkConfig.TLSKey = tlsKey
n.Config.NetworkConfig.TrackedSubnets = n.Config.TrackedSubnets
n.Config.NetworkConfig.UptimeCalculator = n.uptimeCalculator
n.Config.NetworkConfig.UptimeRequirement = n.Config.UptimeRequirement
n.Config.NetworkConfig.ResourceTracker = n.resourceTracker
n.Config.NetworkConfig.CPUTargeter = n.cpuTargeter
n.Config.NetworkConfig.DiskTargeter = n.diskTargeter
n.Config.NetworkConfig.GossipTracker = gossipTracker
n.Net, err = network.NewNetwork(
&n.Config.NetworkConfig,
n.msgCreator,
n.MetricsRegisterer,
n.Log,
listener,
dialer.NewDialer(constants.NetworkType, n.Config.NetworkConfig.DialerConfig, n.Log),
consensusRouter,
)
return err
}
// Dispatch starts the node's servers.
// Returns when the node exits.
func (n *Node) Dispatch() error {
// Start the HTTP API server
go n.Log.RecoverAndPanic(func() {
var err error
if n.Config.HTTPSEnabled {
n.Log.Debug("initializing API server with TLS")
err = n.APIServer.DispatchTLS(n.Config.HTTPSCert, n.Config.HTTPSKey)
} else {
n.Log.Debug("initializing API server without TLS")
err = n.APIServer.Dispatch()
}
// When [n].Shutdown() is called, [n.APIServer].Close() is called.
// This causes [n.APIServer].Dispatch() to return an error.
// If that happened, don't log/return an error here.
if !n.shuttingDown.Get() {
n.Log.Fatal("API server dispatch failed",
zap.Error(err),
)
}
// If the API server isn't running, shut down the node.
// If node is already shutting down, this does nothing.
n.Shutdown(1)
})
// Add state sync nodes to the peer network
for i, peerIP := range n.Config.StateSyncIPs {
n.Net.ManuallyTrack(n.Config.StateSyncIDs[i], peerIP)
}
// Add bootstrap nodes to the peer network
for i, peerIP := range n.Config.BootstrapIPs {
n.Net.ManuallyTrack(n.Config.BootstrapIDs[i], peerIP)
}
// Start P2P connections
err := n.Net.Dispatch()
// If the P2P server isn't running, shut down the node.
// If node is already shutting down, this does nothing.
n.Shutdown(1)
if n.tlsKeyLogWriterCloser != nil {
err := n.tlsKeyLogWriterCloser.Close()
if err != nil {
n.Log.Error("closing TLS key log file failed",
zap.String("filename", n.Config.NetworkConfig.TLSKeyLogFile),
zap.Error(err),
)
}
}
// Wait until the node is done shutting down before returning
n.DoneShuttingDown.Wait()
return err
}
/*
******************************************************************************
*********************** End P2P Networking Section ***************************
******************************************************************************
*/
func (n *Node) initDatabase() error {
// start the db manager
var (
dbManager manager.Manager
err error
)
switch n.Config.DatabaseConfig.Name {
case leveldb.Name:
dbManager, err = manager.NewLevelDB(n.Config.DatabaseConfig.Path, n.Config.DatabaseConfig.Config, n.Log, version.CurrentDatabase, "db_internal", n.MetricsRegisterer)
case memdb.Name:
dbManager = manager.NewMemDB(version.CurrentDatabase)
default:
err = fmt.Errorf(
"db-type was %q but should have been one of {%s, %s}",
n.Config.DatabaseConfig.Name,
leveldb.Name,
memdb.Name,
)
}
if err != nil {
return err
}
meterDBManager, err := dbManager.NewMeterDBManager("db", n.MetricsRegisterer)
if err != nil {
return err
}
n.DBManager = meterDBManager
currentDB := dbManager.Current()
n.Log.Info("initializing database",
zap.Stringer("dbVersion", currentDB.Version),
)
n.DB = currentDB.Database
rawExpectedGenesisHash := hashing.ComputeHash256(n.Config.GenesisBytes)
rawGenesisHash, err := n.DB.Get(genesisHashKey)
if err == database.ErrNotFound {
rawGenesisHash = rawExpectedGenesisHash
err = n.DB.Put(genesisHashKey, rawGenesisHash)
}
if err != nil {
return err
}
genesisHash, err := ids.ToID(rawGenesisHash)
if err != nil {
return err
}
expectedGenesisHash, err := ids.ToID(rawExpectedGenesisHash)
if err != nil {
return err
}
if genesisHash != expectedGenesisHash {
return fmt.Errorf("db contains invalid genesis hash. DB Genesis: %s Generated Genesis: %s", genesisHash, expectedGenesisHash)
}
return nil
}
// Set the node IDs of the peers this node should first connect to
func (n *Node) initBeacons() error {
n.beacons = validators.NewSet()
for _, peerID := range n.Config.BootstrapIDs {
// Note: The beacon connection manager will treat all beaconIDs as
// equal.
// Invariant: We never use the TxID or BLS keys populated here.
if err := n.beacons.Add(peerID, nil, ids.Empty, 1); err != nil {
return err
}
}
return nil
}
// Create the EventDispatcher used for hooking events
// into the general process flow.
func (n *Node) initEventDispatchers() {
n.BlockAcceptorGroup = snow.NewAcceptorGroup(n.Log)
n.TxAcceptorGroup = snow.NewAcceptorGroup(n.Log)
n.VertexAcceptorGroup = snow.NewAcceptorGroup(n.Log)
}
func (n *Node) initIPCs() error {
chainIDs := make([]ids.ID, len(n.Config.IPCDefaultChainIDs))
for i, chainID := range n.Config.IPCDefaultChainIDs {
id, err := ids.FromString(chainID)
if err != nil {
return err
}
chainIDs[i] = id
}
var err error
n.IPCs, err = ipcs.NewChainIPCs(
n.Log,
n.Config.IPCPath,
n.Config.NetworkID,
n.BlockAcceptorGroup,
n.TxAcceptorGroup,
n.VertexAcceptorGroup,
chainIDs,
)
return err
}
// Initialize [n.indexer].
// Should only be called after [n.DB], [n.DecisionAcceptorGroup],
// [n.ConsensusAcceptorGroup], [n.Log], [n.APIServer], [n.chainManager] are
// initialized
func (n *Node) initIndexer() error {
txIndexerDB := prefixdb.New(indexerDBPrefix, n.DB)
var err error
n.indexer, err = indexer.NewIndexer(indexer.Config{
IndexingEnabled: n.Config.IndexAPIEnabled,
AllowIncompleteIndex: n.Config.IndexAllowIncomplete,
DB: txIndexerDB,
Log: n.Log,
BlockAcceptorGroup: n.BlockAcceptorGroup,
TxAcceptorGroup: n.TxAcceptorGroup,
VertexAcceptorGroup: n.VertexAcceptorGroup,
APIServer: n.APIServer,
ShutdownF: func() {
n.Shutdown(0) // TODO put exit code here
},
})
if err != nil {
return fmt.Errorf("couldn't create index for txs: %w", err)
}
// Chain manager will notify indexer when a chain is created
n.chainManager.AddRegistrant(n.indexer)
return nil
}
// Initializes the Platform chain.
// Its genesis data specifies the other chains that should be created.
func (n *Node) initChains(genesisBytes []byte) error {
n.Log.Info("initializing chains")
platformChain := chains.ChainParameters{
ID: constants.PlatformChainID,
SubnetID: constants.PrimaryNetworkID,
GenesisData: genesisBytes, // Specifies other chains to create
VMID: constants.PlatformVMID,
CustomBeacons: n.beacons,
}
// Start the chain creator with the Platform Chain
return n.chainManager.StartChainCreator(platformChain)
}
func (n *Node) initMetrics() {
n.MetricsRegisterer = prometheus.NewRegistry()
n.MetricsGatherer = metrics.NewMultiGatherer()
}
// initAPIServer initializes the server that handles HTTP calls
func (n *Node) initAPIServer() error {
n.Log.Info("initializing API server")
if !n.Config.APIRequireAuthToken {
var err error
n.APIServer, err = server.New(
n.Log,
n.LogFactory,
n.Config.HTTPHost,
n.Config.HTTPPort,
n.Config.APIAllowedOrigins,
n.Config.ShutdownTimeout,
n.ID,
n.Config.TraceConfig.Enabled,
n.tracer,
"api",
n.MetricsRegisterer,
n.Config.HTTPConfig.HTTPConfig,
)
return err
}
a, err := auth.New(n.Log, "auth", n.Config.APIAuthPassword)
if err != nil {
return err
}
n.APIServer, err = server.New(
n.Log,
n.LogFactory,
n.Config.HTTPHost,
n.Config.HTTPPort,
n.Config.APIAllowedOrigins,
n.Config.ShutdownTimeout,
n.ID,
n.Config.TraceConfig.Enabled,
n.tracer,
"api",
n.MetricsRegisterer,
n.Config.HTTPConfig.HTTPConfig,
a,
)
if err != nil {
return err
}
// only create auth service if token authorization is required
n.Log.Info("API authorization is enabled. Auth tokens must be passed in the header of API requests, except requests to the auth service.")
authService, err := a.CreateHandler()
if err != nil {
return err
}
handler := &common.HTTPHandler{
LockOptions: common.NoLock,
Handler: authService,
}
return n.APIServer.AddRoute(handler, &sync.RWMutex{}, "auth", "")
}
// Add the default VM aliases
func (n *Node) addDefaultVMAliases() error {
n.Log.Info("adding the default VM aliases")
vmAliases := genesis.GetVMAliases()
for vmID, aliases := range vmAliases {
for _, alias := range aliases {
if err := n.Config.VMAliaser.Alias(vmID, alias); err != nil {
return err
}
}
}
return nil
}
// Create the chainManager and register the following VMs:
// AVM, Simple Payments DAG, Simple Payments Chain, and Platform VM
// Assumes n.DBManager, n.vdrs all initialized (non-nil)
func (n *Node) initChainManager(avaxAssetID ids.ID) error {
createAVMTx, err := genesis.VMGenesis(n.Config.GenesisBytes, constants.AVMID)
if err != nil {
return err
}
xChainID := createAVMTx.ID()
createEVMTx, err := genesis.VMGenesis(n.Config.GenesisBytes, constants.EVMID)
if err != nil {
return err
}
cChainID := createEVMTx.ID()
// If any of these chains die, the node shuts down
criticalChains := set.Set[ids.ID]{}
criticalChains.Add(
constants.PlatformChainID,
xChainID,
cChainID,
)
// Manages network timeouts
timeoutManager, err := timeout.NewManager(
&n.Config.AdaptiveTimeoutConfig,
n.benchlistManager,
"requests",
n.MetricsRegisterer,
)
if err != nil {
return err
}
go n.Log.RecoverAndPanic(timeoutManager.Dispatch)
// Routes incoming messages from peers to the appropriate chain
err = n.Config.ConsensusRouter.Initialize(
n.ID,
n.Log,
timeoutManager,
n.Config.ConsensusShutdownTimeout,
criticalChains,
n.Config.EnableStaking,
n.Config.TrackedSubnets,
n.Shutdown,
n.Config.RouterHealthConfig,
"requests",
n.MetricsRegisterer,
)
if err != nil {
return fmt.Errorf("couldn't initialize chain router: %w", err)
}
n.chainManager = chains.New(&chains.ManagerConfig{
StakingEnabled: n.Config.EnableStaking,
StakingCert: n.Config.StakingTLSCert,
StakingBLSKey: n.Config.StakingSigningKey,
Log: n.Log,
LogFactory: n.LogFactory,
VMManager: n.VMManager,
BlockAcceptorGroup: n.BlockAcceptorGroup,
TxAcceptorGroup: n.TxAcceptorGroup,
VertexAcceptorGroup: n.VertexAcceptorGroup,
DBManager: n.DBManager,
MsgCreator: n.msgCreator,
Router: n.Config.ConsensusRouter,
Net: n.Net,
Validators: n.vdrs,
NodeID: n.ID,
NetworkID: n.Config.NetworkID,
Server: n.APIServer,
Keystore: n.keystore,
AtomicMemory: n.sharedMemory,
AVAXAssetID: avaxAssetID,
XChainID: xChainID,
CChainID: cChainID,
CriticalChains: criticalChains,
TimeoutManager: timeoutManager,
Health: n.health,
RetryBootstrap: n.Config.RetryBootstrap,
RetryBootstrapWarnFrequency: n.Config.RetryBootstrapWarnFrequency,
ShutdownNodeFunc: n.Shutdown,
MeterVMEnabled: n.Config.MeterVMEnabled,
Metrics: n.MetricsGatherer,
SubnetConfigs: n.Config.SubnetConfigs,
ChainConfigs: n.Config.ChainConfigs,
ConsensusGossipFrequency: n.Config.ConsensusGossipFrequency,
ConsensusAppConcurrency: n.Config.ConsensusAppConcurrency,
BootstrapMaxTimeGetAncestors: n.Config.BootstrapMaxTimeGetAncestors,
BootstrapAncestorsMaxContainersSent: n.Config.BootstrapAncestorsMaxContainersSent,
BootstrapAncestorsMaxContainersReceived: n.Config.BootstrapAncestorsMaxContainersReceived,
ApricotPhase4Time: version.GetApricotPhase4Time(n.Config.NetworkID),
ApricotPhase4MinPChainHeight: version.GetApricotPhase4MinPChainHeight(n.Config.NetworkID),
ResourceTracker: n.resourceTracker,
StateSyncBeacons: n.Config.StateSyncIDs,
TracingEnabled: n.Config.TraceConfig.Enabled,
Tracer: n.tracer,
ChainDataDir: n.Config.ChainDataDir,
})
// Notify the API server when new chains are created
n.chainManager.AddRegistrant(n.APIServer)
return nil
}
// initVMs initializes the VMs Avalanche supports + any additional vms installed as plugins.
func (n *Node) initVMs() error {
n.Log.Info("initializing VMs")
vdrs := n.vdrs
// If staking is disabled, ignore updates to Subnets' validator sets
// Instead of updating node's validator manager, platform chain makes changes
// to its own local validator manager (which isn't used for sampling)
if !n.Config.EnableStaking {
vdrs = validators.NewManager()
primaryVdrs := validators.NewSet()
_ = vdrs.Add(constants.PrimaryNetworkID, primaryVdrs)
}
vmRegisterer := registry.NewVMRegisterer(registry.VMRegistererConfig{
APIServer: n.APIServer,
Log: n.Log,
VMFactoryLog: n.VMFactoryLog,
VMManager: n.VMManager,
})
// Register the VMs that Avalanche supports
errs := wrappers.Errs{}
errs.Add(
vmRegisterer.Register(context.TODO(), constants.PlatformVMID, &platformvm.Factory{
Config: platformconfig.Config{
Chains: n.chainManager,
Validators: vdrs,
UptimeLockedCalculator: n.uptimeCalculator,
StakingEnabled: n.Config.EnableStaking,
TrackedSubnets: n.Config.TrackedSubnets,
TxFee: n.Config.TxFee,
CreateAssetTxFee: n.Config.CreateAssetTxFee,
CreateSubnetTxFee: n.Config.CreateSubnetTxFee,
TransformSubnetTxFee: n.Config.TransformSubnetTxFee,
CreateBlockchainTxFee: n.Config.CreateBlockchainTxFee,
AddPrimaryNetworkValidatorFee: n.Config.AddPrimaryNetworkValidatorFee,
AddPrimaryNetworkDelegatorFee: n.Config.AddPrimaryNetworkDelegatorFee,
AddSubnetValidatorFee: n.Config.AddSubnetValidatorFee,
AddSubnetDelegatorFee: n.Config.AddSubnetDelegatorFee,
UptimePercentage: n.Config.UptimeRequirement,
MinValidatorStake: n.Config.MinValidatorStake,
MaxValidatorStake: n.Config.MaxValidatorStake,
MinDelegatorStake: n.Config.MinDelegatorStake,
MinDelegationFee: n.Config.MinDelegationFee,
MinStakeDuration: n.Config.MinStakeDuration,
MaxStakeDuration: n.Config.MaxStakeDuration,
RewardConfig: n.Config.RewardConfig,
ApricotPhase3Time: version.GetApricotPhase3Time(n.Config.NetworkID),
ApricotPhase5Time: version.GetApricotPhase5Time(n.Config.NetworkID),
BanffTime: version.GetBanffTime(n.Config.NetworkID),
CortinaTime: version.GetCortinaTime(n.Config.NetworkID),
MinPercentConnectedStakeHealthy: n.Config.MinPercentConnectedStakeHealthy,
UseCurrentHeight: n.Config.UseCurrentHeight,
},
}),
vmRegisterer.Register(context.TODO(), constants.AVMID, &avm.Factory{
Config: avmconfig.Config{
TxFee: n.Config.TxFee,
CreateAssetTxFee: n.Config.CreateAssetTxFee,
},
}),
vmRegisterer.Register(context.TODO(), constants.EVMID, &coreth.Factory{}),
n.VMManager.RegisterFactory(context.TODO(), secp256k1fx.ID, &secp256k1fx.Factory{}),
n.VMManager.RegisterFactory(context.TODO(), nftfx.ID, &nftfx.Factory{}),
n.VMManager.RegisterFactory(context.TODO(), propertyfx.ID, &propertyfx.Factory{}),
)
if errs.Errored() {
return errs.Err
}
// initialize vm runtime manager
n.runtimeManager = runtime.NewManager()
// initialize the vm registry
n.VMRegistry = registry.NewVMRegistry(registry.VMRegistryConfig{
VMGetter: registry.NewVMGetter(registry.VMGetterConfig{
FileReader: filesystem.NewReader(),
Manager: n.VMManager,
PluginDirectory: n.Config.PluginDir,
CPUTracker: n.resourceManager,
RuntimeTracker: n.runtimeManager,
}),
VMRegisterer: vmRegisterer,
})
// register any vms that need to be installed as plugins from disk
_, failedVMs, err := n.VMRegistry.Reload(context.TODO())
for failedVM, err := range failedVMs {
n.Log.Error("failed to register VM",
zap.Stringer("vmID", failedVM),
zap.Error(err),
)
}
return err
}
// initSharedMemory initializes the shared memory for cross chain interation
func (n *Node) initSharedMemory() {
n.Log.Info("initializing SharedMemory")
sharedMemoryDB := prefixdb.New([]byte("shared memory"), n.DB)
n.sharedMemory = atomic.NewMemory(sharedMemoryDB)
}
// initKeystoreAPI initializes the keystore service, which is an on-node wallet.
// Assumes n.APIServer is already set
func (n *Node) initKeystoreAPI() error {
n.Log.Info("initializing keystore")
keystoreDB := n.DBManager.NewPrefixDBManager([]byte("keystore"))
n.keystore = keystore.New(n.Log, keystoreDB)
keystoreHandler, err := n.keystore.CreateHandler()
if err != nil {
return err
}
if !n.Config.KeystoreAPIEnabled {
n.Log.Info("skipping keystore API initialization because it has been disabled")
return nil
}
n.Log.Warn("initializing deprecated keystore API")
handler := &common.HTTPHandler{
LockOptions: common.NoLock,
Handler: keystoreHandler,
}
return n.APIServer.AddRoute(handler, &sync.RWMutex{}, "keystore", "")
}
// initMetricsAPI initializes the Metrics API
// Assumes n.APIServer is already set
func (n *Node) initMetricsAPI() error {
if !n.Config.MetricsAPIEnabled {
n.Log.Info("skipping metrics API initialization because it has been disabled")
return nil
}
if err := n.MetricsGatherer.Register(constants.PlatformName, n.MetricsRegisterer); err != nil {
return err
}
// Current state of process metrics.
processCollector := collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})
if err := n.MetricsRegisterer.Register(processCollector); err != nil {
return err
}
// Go process metrics using debug.GCStats.
goCollector := collectors.NewGoCollector()
if err := n.MetricsRegisterer.Register(goCollector); err != nil {
return err
}
n.Log.Info("initializing metrics API")
return n.APIServer.AddRoute(
&common.HTTPHandler{
LockOptions: common.NoLock,
Handler: promhttp.HandlerFor(
n.MetricsGatherer,
promhttp.HandlerOpts{},
),
},
&sync.RWMutex{},
"metrics",
"",
)
}
// initAdminAPI initializes the Admin API service
// Assumes n.log, n.chainManager, and n.ValidatorAPI already initialized
func (n *Node) initAdminAPI() error {
if !n.Config.AdminAPIEnabled {
n.Log.Info("skipping admin API initialization because it has been disabled")
return nil
}
n.Log.Info("initializing admin API")
service, err := admin.NewService(
admin.Config{
Log: n.Log,
ChainManager: n.chainManager,
HTTPServer: n.APIServer,
ProfileDir: n.Config.ProfilerConfig.Dir,
LogFactory: n.LogFactory,
NodeConfig: n.Config,
VMManager: n.VMManager,
VMRegistry: n.VMRegistry,
},
)
if err != nil {
return err
}
return n.APIServer.AddRoute(service, &sync.RWMutex{}, "admin", "")
}
// initProfiler initializes the continuous profiling
func (n *Node) initProfiler() {
if !n.Config.ProfilerConfig.Enabled {
n.Log.Info("skipping profiler initialization because it has been disabled")
return
}
n.Log.Info("initializing continuous profiler")
n.profiler = profiler.NewContinuous(
filepath.Join(n.Config.ProfilerConfig.Dir, "continuous"),
n.Config.ProfilerConfig.Freq,
n.Config.ProfilerConfig.MaxNumFiles,
)
go n.Log.RecoverAndPanic(func() {
err := n.profiler.Dispatch()
if err != nil {
n.Log.Fatal("continuous profiler failed",
zap.Error(err),
)
}
n.Shutdown(1)
})
}
func (n *Node) initInfoAPI() error {
if !n.Config.InfoAPIEnabled {
n.Log.Info("skipping info API initialization because it has been disabled")
return nil
}
n.Log.Info("initializing info API")
primaryValidators, _ := n.vdrs.Get(constants.PrimaryNetworkID)
service, err := info.NewService(
info.Parameters{
Version: version.CurrentApp,
NodeID: n.ID,
NodePOP: signer.NewProofOfPossession(n.Config.StakingSigningKey),
NetworkID: n.Config.NetworkID,
TxFee: n.Config.TxFee,
CreateAssetTxFee: n.Config.CreateAssetTxFee,
CreateSubnetTxFee: n.Config.CreateSubnetTxFee,
TransformSubnetTxFee: n.Config.TransformSubnetTxFee,
CreateBlockchainTxFee: n.Config.CreateBlockchainTxFee,
AddPrimaryNetworkValidatorFee: n.Config.AddPrimaryNetworkValidatorFee,
AddPrimaryNetworkDelegatorFee: n.Config.AddPrimaryNetworkDelegatorFee,
AddSubnetValidatorFee: n.Config.AddSubnetValidatorFee,