forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.go
1756 lines (1534 loc) · 51.9 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-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package node
import (
"context"
"crypto"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/netip"
"os"
"path/filepath"
"strconv"
"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"
"github.com/ava-labs/avalanchego/api/admin"
"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/memdb"
"github.com/ava-labs/avalanchego/database/meterdb"
"github.com/ava-labs/avalanchego/database/pebbledb"
"github.com/ava-labs/avalanchego/database/prefixdb"
"github.com/ava-labs/avalanchego/database/versiondb"
"github.com/ava-labs/avalanchego/genesis"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/indexer"
"github.com/ava-labs/avalanchego/message"
"github.com/ava-labs/avalanchego/nat"
"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/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/staking"
"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/dynamicip"
"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/metric"
"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/version"
"github.com/ava-labs/avalanchego/vms"
"github.com/ava-labs/avalanchego/vms/avm"
"github.com/ava-labs/avalanchego/vms/platformvm"
"github.com/ava-labs/avalanchego/vms/platformvm/signer"
"github.com/ava-labs/avalanchego/vms/platformvm/upgrade"
"github.com/ava-labs/avalanchego/vms/registry"
"github.com/ava-labs/avalanchego/vms/rpcchainvm/runtime"
avmconfig "github.com/ava-labs/avalanchego/vms/avm/config"
platformconfig "github.com/ava-labs/avalanchego/vms/platformvm/config"
coreth "github.com/ava-labs/coreth/plugin/evm"
)
const (
stakingPortName = constants.AppName + "-staking"
httpPortName = constants.AppName + "-http"
ipResolutionTimeout = 30 * time.Second
apiNamespace = constants.PlatformName + metric.NamespaceSeparator + "api"
benchlistNamespace = constants.PlatformName + metric.NamespaceSeparator + "benchlist"
dbNamespace = constants.PlatformName + metric.NamespaceSeparator + "db"
healthNamespace = constants.PlatformName + metric.NamespaceSeparator + "health"
meterDBNamespace = constants.PlatformName + metric.NamespaceSeparator + "meterdb"
networkNamespace = constants.PlatformName + metric.NamespaceSeparator + "network"
processNamespace = constants.PlatformName + metric.NamespaceSeparator + "process"
requestsNamespace = constants.PlatformName + metric.NamespaceSeparator + "requests"
resourceTrackerNamespace = constants.PlatformName + metric.NamespaceSeparator + "resource_tracker"
responsesNamespace = constants.PlatformName + metric.NamespaceSeparator + "responses"
systemResourcesNamespace = constants.PlatformName + metric.NamespaceSeparator + "system_resources"
)
var (
genesisHashKey = []byte("genesisID")
ungracefulShutdown = []byte("ungracefulShutdown")
indexerDBPrefix = []byte{0x00}
keystoreDBPrefix = []byte("keystore")
errInvalidTLSKey = errors.New("invalid TLS key")
errShuttingDown = errors.New("server shutting down")
)
// New returns an instance of Node
func New(
config *Config,
logFactory logging.Factory,
logger logging.Logger,
) (*Node, error) {
tlsCert := config.StakingTLSCert.Leaf
stakingCert, err := staking.ParseCertificate(tlsCert.Raw)
if err != nil {
return nil, fmt.Errorf("invalid staking certificate: %w", err)
}
n := &Node{
Log: logger,
LogFactory: logFactory,
StakingTLSSigner: config.StakingTLSCert.PrivateKey.(crypto.Signer),
StakingTLSCert: stakingCert,
ID: ids.NodeIDFromCert(stakingCert),
Config: config,
}
n.DoneShuttingDown.Add(1)
pop := signer.NewProofOfPossession(n.Config.StakingSigningKey)
logger.Info("initializing node",
zap.Stringer("version", version.CurrentApp),
zap.Stringer("nodeID", n.ID),
zap.Stringer("stakingKeyType", tlsCert.PublicKeyAlgorithm),
zap.Reflect("nodePOP", pop),
zap.Reflect("providedFlags", n.Config.ProvidedFlags),
zap.Reflect("config", n.Config),
)
n.VMFactoryLog, err = logFactory.Make("vm-factory")
if err != nil {
return nil, fmt.Errorf("problem creating vm logger: %w", err)
}
n.VMAliaser = ids.NewAliaser()
for vmID, aliases := range config.VMAliases {
for _, alias := range aliases {
if err := n.VMAliaser.Alias(vmID, alias); err != nil {
return nil, err
}
}
}
n.VMManager = vms.NewManager(n.VMFactoryLog, n.VMAliaser)
if err := n.initBootstrappers(); err != nil { // Configure the bootstrappers
return nil, fmt.Errorf("problem initializing node beacons: %w", err)
}
// Set up tracer
n.tracer, err = trace.New(n.Config.TraceConfig)
if err != nil {
return nil, fmt.Errorf("couldn't initialize tracer: %w", err)
}
if err := n.initMetrics(); err != nil {
return nil, fmt.Errorf("couldn't initialize metrics: %w", err)
}
n.initNAT()
if err := n.initAPIServer(); err != nil { // Start the API Server
return nil, fmt.Errorf("couldn't initialize API server: %w", err)
}
if err := n.initMetricsAPI(); err != nil { // Start the Metrics API
return nil, fmt.Errorf("couldn't initialize metrics API: %w", err)
}
if err := n.initDatabase(); err != nil { // Set up the node's database
return nil, fmt.Errorf("problem initializing database: %w", err)
}
if err := n.initKeystoreAPI(); err != nil { // Start the Keystore API
return nil, fmt.Errorf("couldn't initialize keystore API: %w", err)
}
n.initSharedMemory() // Initialize shared memory
// message.Creator is shared between networking, chainManager and the engine.
// It must be initiated before networking (initNetworking), chain manager (initChainManager)
// and the engine (initChains) but after the metrics (initMetricsAPI)
// message.Creator currently record metrics under network namespace
networkRegisterer, err := metrics.MakeAndRegister(
n.MetricsGatherer,
networkNamespace,
)
if err != nil {
return nil, err
}
n.msgCreator, err = message.NewCreator(
n.Log,
networkRegisterer,
n.Config.NetworkConfig.CompressionType,
n.Config.NetworkConfig.MaximumInboundMessageTimeout,
)
if err != nil {
return nil, fmt.Errorf("problem initializing message creator: %w", err)
}
n.vdrs = validators.NewManager()
if !n.Config.SybilProtectionEnabled {
logger.Warn("sybil control is not enforced")
n.vdrs = newOverriddenManager(constants.PrimaryNetworkID, n.vdrs)
}
if err := n.initResourceManager(); err != nil {
return nil, fmt.Errorf("problem initializing resource manager: %w", err)
}
n.initCPUTargeter(&config.CPUTargeterConfig)
n.initDiskTargeter(&config.DiskTargeterConfig)
if err := n.initNetworking(networkRegisterer); err != nil { // Set up networking layer.
return nil, fmt.Errorf("problem initializing networking: %w", err)
}
n.initEventDispatchers()
// Start the Health API
// Has to be initialized before chain manager
// [n.Net] must already be set
if err := n.initHealthAPI(); err != nil {
return nil, fmt.Errorf("couldn't initialize health API: %w", err)
}
if err := n.addDefaultVMAliases(); err != nil {
return nil, fmt.Errorf("couldn't initialize API aliases: %w", err)
}
if err := n.initChainManager(n.Config.AvaxAssetID); err != nil { // Set up the chain manager
return nil, fmt.Errorf("couldn't initialize chain manager: %w", err)
}
if err := n.initVMs(); err != nil { // Initialize the VM registry.
return nil, fmt.Errorf("couldn't initialize VM registry: %w", err)
}
if err := n.initAdminAPI(); err != nil { // Start the Admin API
return nil, fmt.Errorf("couldn't initialize admin API: %w", err)
}
if err := n.initInfoAPI(); err != nil { // Start the Info API
return nil, fmt.Errorf("couldn't initialize info API: %w", err)
}
if err := n.initChainAliases(n.Config.GenesisBytes); err != nil {
return nil, fmt.Errorf("couldn't initialize chain aliases: %w", err)
}
if err := n.initAPIAliases(n.Config.GenesisBytes); err != nil {
return nil, fmt.Errorf("couldn't initialize API aliases: %w", err)
}
if err := n.initIndexer(); err != nil {
return nil, fmt.Errorf("couldn't initialize indexer: %w", err)
}
n.health.Start(context.TODO(), n.Config.HealthCheckFreq)
n.initProfiler()
// Start the Platform chain
if err := n.initChains(n.Config.GenesisBytes); err != nil {
return nil, fmt.Errorf("couldn't initialize chains: %w", err)
}
return n, nil
}
// 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
StakingTLSSigner crypto.Signer
StakingTLSCert *staking.Certificate
// Storage for this node
DB database.Database
router nat.Router
portMapper *nat.Mapper
ipUpdater dynamicip.Updater
chainRouter router.Router
// 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 network timeouts
timeoutManager timeout.Manager
// 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
// Net runs the networking stack
Net network.Network
// The staking address will optionally be written to a process context
// file to enable other nodes to be configured to use this node as a
// beacon.
stakingAddress string
// 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
bootstrappers validators.Manager
// current validators of the network
vdrs validators.Manager
apiURI string
// 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
MetricsGatherer metrics.MultiGatherer
MeterDBMetricsGatherer metrics.MultiGatherer
VMAliaser ids.Aliaser
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
// Closed when a sufficient amount of bootstrap nodes are connected to
onSufficientlyConnected chan struct{}
}
/*
******************************************************************************
*************************** P2P Networking Section ***************************
******************************************************************************
*/
// Initialize the networking layer.
// Assumes [n.vdrs], [n.CPUTracker], and [n.CPUTargeter] have been initialized.
func (n *Node) initNetworking(reg prometheus.Registerer) error {
// Providing either loopback address - `::1` for ipv6 and `127.0.0.1` for ipv4 - as the listen
// host will avoid the need for a firewall exception on recent MacOS:
//
// - MacOS requires a manually-approved firewall exception [1] for each version of a given
// binary that wants to bind to all interfaces (i.e. with an address of `:[port]`). Each
// compiled version of avalanchego requires a separate exception to be allowed to bind to all
// interfaces.
//
// - A firewall exception is not required to bind to a loopback interface, but the only way for
// Listen() to bind to loopback for both ipv4 and ipv6 is to bind to all interfaces [2] which
// requires an exception.
//
// - Thus, the only way to start a node on MacOS without approving a firewall exception for the
// avalanchego binary is to bind to loopback by specifying the host to be `::1` or `127.0.0.1`.
//
// 1: https://apple.stackexchange.com/questions/393715/do-you-want-the-application-main-to-accept-incoming-network-connections-pop
// 2: https://github.com/golang/go/issues/56998
listenAddress := net.JoinHostPort(n.Config.ListenHost, strconv.FormatUint(uint64(n.Config.ListenPort), 10))
listener, err := net.Listen(constants.NetworkType, listenAddress)
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)
// Record the bound address to enable inclusion in process context file.
n.stakingAddress = listener.Addr().String()
stakingAddrPort, err := ips.ParseAddrPort(n.stakingAddress)
if err != nil {
return err
}
var (
publicAddr netip.Addr
atomicIP *utils.Atomic[netip.AddrPort]
)
switch {
case n.Config.PublicIP != "":
// Use the specified public IP.
publicAddr, err = ips.ParseAddr(n.Config.PublicIP)
if err != nil {
return fmt.Errorf("invalid public IP address %q: %w", n.Config.PublicIP, err)
}
atomicIP = utils.NewAtomic(netip.AddrPortFrom(
publicAddr,
stakingAddrPort.Port(),
))
n.ipUpdater = dynamicip.NewNoUpdater()
case n.Config.PublicIPResolutionService != "":
// Use dynamic IP resolution.
resolver, err := dynamicip.NewResolver(n.Config.PublicIPResolutionService)
if err != nil {
return fmt.Errorf("couldn't create IP resolver: %w", err)
}
// Use that to resolve our public IP.
ctx, cancel := context.WithTimeout(context.Background(), ipResolutionTimeout)
publicAddr, err = resolver.Resolve(ctx)
cancel()
if err != nil {
return fmt.Errorf("couldn't resolve public IP: %w", err)
}
atomicIP = utils.NewAtomic(netip.AddrPortFrom(
publicAddr,
stakingAddrPort.Port(),
))
n.ipUpdater = dynamicip.NewUpdater(atomicIP, resolver, n.Config.PublicIPResolutionFreq)
default:
publicAddr, err = n.router.ExternalIP()
if err != nil {
return fmt.Errorf("public IP / IP resolution service not given and failed to resolve IP with NAT: %w", err)
}
atomicIP = utils.NewAtomic(netip.AddrPortFrom(
publicAddr,
stakingAddrPort.Port(),
))
n.ipUpdater = dynamicip.NewNoUpdater()
}
if !ips.IsPublic(publicAddr) {
n.Log.Warn("P2P IP is private, you will not be publicly discoverable",
zap.Stringer("ip", publicAddr),
)
}
// Regularly update our public IP and port mappings.
n.portMapper.Map(
stakingAddrPort.Port(),
stakingAddrPort.Port(),
stakingPortName,
atomicIP,
n.Config.PublicIPResolutionFreq,
)
go n.ipUpdater.Dispatch(n.Log)
n.Log.Info("initializing networking",
zap.Stringer("ip", atomicIP.Get()),
)
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),
)
}
// We allow nodes to gossip unknown ACPs in case the current ACPs constant
// becomes out of date.
var unknownACPs set.Set[uint32]
for acp := range n.Config.NetworkConfig.SupportedACPs {
if !constants.CurrentACPs.Contains(acp) {
unknownACPs.Add(acp)
}
}
for acp := range n.Config.NetworkConfig.ObjectedACPs {
if !constants.CurrentACPs.Contains(acp) {
unknownACPs.Add(acp)
}
}
if unknownACPs.Len() > 0 {
n.Log.Warn("gossiping unknown ACPs",
zap.Reflect("acps", unknownACPs),
)
}
tlsConfig := peer.TLSConfig(n.Config.StakingTLSCert, n.tlsKeyLogWriterCloser)
// Create chain router
n.chainRouter = &router.ChainRouter{}
if n.Config.TraceConfig.Enabled {
n.chainRouter = router.Trace(n.chainRouter, n.tracer)
}
// Configure benchlist
n.Config.BenchlistConfig.Validators = n.vdrs
n.Config.BenchlistConfig.Benchable = n.chainRouter
n.Config.BenchlistConfig.BenchlistRegisterer = metrics.NewLabelGatherer(chains.ChainLabel)
err = n.MetricsGatherer.Register(
benchlistNamespace,
n.Config.BenchlistConfig.BenchlistRegisterer,
)
if err != nil {
return err
}
n.benchlistManager = benchlist.NewManager(&n.Config.BenchlistConfig)
n.uptimeCalculator = uptime.NewLockedCalculator()
consensusRouter := n.chainRouter
if !n.Config.SybilProtectionEnabled {
// Sybil protection 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.Bytes())
err := n.vdrs.AddStaker(
constants.PrimaryNetworkID,
n.ID,
bls.PublicFromSecretKey(n.Config.StakingSigningKey),
dummyTxID,
n.Config.SybilProtectionDisabledWeight,
)
if err != nil {
return err
}
consensusRouter = &insecureValidatorManager{
log: n.Log,
Router: consensusRouter,
vdrs: n.vdrs,
weight: n.Config.SybilProtectionDisabledWeight,
}
}
n.onSufficientlyConnected = make(chan struct{})
numBootstrappers := n.bootstrappers.Count(constants.PrimaryNetworkID)
requiredConns := (3*numBootstrappers + 3) / 4
if requiredConns > 0 {
consensusRouter = &beaconManager{
Router: consensusRouter,
beacons: n.bootstrappers,
requiredConns: int64(requiredConns),
onSufficientlyConnected: n.onSufficientlyConnected,
}
} else {
close(n.onSufficientlyConnected)
}
// add node configs to network config
n.Config.NetworkConfig.MyNodeID = n.ID
n.Config.NetworkConfig.MyIPPort = atomicIP
n.Config.NetworkConfig.NetworkID = n.Config.NetworkID
n.Config.NetworkConfig.Validators = n.vdrs
n.Config.NetworkConfig.Beacons = n.bootstrappers
n.Config.NetworkConfig.TLSConfig = tlsConfig
n.Config.NetworkConfig.TLSKey = tlsKey
n.Config.NetworkConfig.BLSKey = n.Config.StakingSigningKey
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.Net, err = network.NewNetwork(
&n.Config.NetworkConfig,
n.msgCreator,
reg,
n.Log,
listener,
dialer.NewDialer(constants.NetworkType, n.Config.NetworkConfig.DialerConfig, n.Log),
consensusRouter,
)
return err
}
type NodeProcessContext struct {
// The process id of the node
PID int `json:"pid"`
// URI to access the node API
// Format: [https|http]://[host]:[port]
URI string `json:"uri"`
// Address other nodes can use to communicate with this node
// Format: [host]:[port]
StakingAddress string `json:"stakingAddress"`
}
// Write process context to the configured path. Supports the use of
// dynamically chosen network ports with local network orchestration.
func (n *Node) writeProcessContext() error {
n.Log.Info("writing process context", zap.String("path", n.Config.ProcessContextFilePath))
// Write the process context to disk
processContext := &NodeProcessContext{
PID: os.Getpid(),
URI: n.apiURI,
StakingAddress: n.stakingAddress, // Set by network initialization
}
bytes, err := json.MarshalIndent(processContext, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal process context: %w", err)
}
if err := perms.WriteFile(n.Config.ProcessContextFilePath, bytes, perms.ReadWrite); err != nil {
return fmt.Errorf("failed to write process context: %w", err)
}
return nil
}
// Dispatch starts the node's servers.
// Returns when the node exits.
func (n *Node) Dispatch() error {
if err := n.writeProcessContext(); err != nil {
return err
}
// Start the HTTP API server
go n.Log.RecoverAndPanic(func() {
n.Log.Info("API server listening",
zap.String("uri", n.apiURI),
)
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)
})
// Log a warning if we aren't able to connect to a sufficient portion of
// nodes.
go func() {
timer := time.NewTimer(n.Config.BootstrapBeaconConnectionTimeout)
defer timer.Stop()
select {
case <-timer.C:
if n.shuttingDown.Get() {
return
}
n.Log.Warn("failed to connect to bootstrap nodes",
zap.Stringer("bootstrappers", n.bootstrappers),
zap.Duration("duration", n.Config.BootstrapBeaconConnectionTimeout),
)
case <-n.onSufficientlyConnected:
}
}()
// 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 _, bootstrapper := range n.Config.Bootstrappers {
n.Net.ManuallyTrack(bootstrapper.ID, bootstrapper.IP)
}
// 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()
// Remove the process context file to communicate to an orchestrator
// that the node is no longer running.
if err := os.Remove(n.Config.ProcessContextFilePath); err != nil && !errors.Is(err, fs.ErrNotExist) {
n.Log.Error("removal of process context file failed",
zap.String("path", n.Config.ProcessContextFilePath),
zap.Error(err),
)
}
return err
}
/*
******************************************************************************
*********************** End P2P Networking Section ***************************
******************************************************************************
*/
func (n *Node) initDatabase() error {
dbRegisterer, err := metrics.MakeAndRegister(
n.MetricsGatherer,
dbNamespace,
)
if err != nil {
return err
}
// start the db
switch n.Config.DatabaseConfig.Name {
case leveldb.Name:
// Prior to v1.10.15, the only on-disk database was leveldb, and its
// files went to [dbPath]/[networkID]/v1.4.5.
dbPath := filepath.Join(n.Config.DatabaseConfig.Path, version.CurrentDatabase.String())
n.DB, err = leveldb.New(dbPath, n.Config.DatabaseConfig.Config, n.Log, dbRegisterer)
if err != nil {
return fmt.Errorf("couldn't create %s at %s: %w", leveldb.Name, dbPath, err)
}
case memdb.Name:
n.DB = memdb.New()
case pebbledb.Name:
dbPath := filepath.Join(n.Config.DatabaseConfig.Path, "pebble")
n.DB, err = pebbledb.New(dbPath, n.Config.DatabaseConfig.Config, n.Log, dbRegisterer)
if err != nil {
return fmt.Errorf("couldn't create %s at %s: %w", pebbledb.Name, dbPath, err)
}
default:
return fmt.Errorf(
"db-type was %q but should have been one of {%s, %s, %s}",
n.Config.DatabaseConfig.Name,
leveldb.Name,
memdb.Name,
pebbledb.Name,
)
}
if n.Config.ReadOnly && n.Config.DatabaseConfig.Name != memdb.Name {
n.DB = versiondb.New(n.DB)
}
meterDBReg, err := metrics.MakeAndRegister(
n.MeterDBMetricsGatherer,
"all",
)
if err != nil {
return err
}
n.DB, err = meterdb.New(meterDBReg, n.DB)
if err != nil {
return err
}
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)
}
n.Log.Info("initializing database",
zap.Stringer("genesisHash", genesisHash),
)
ok, err := n.DB.Has(ungracefulShutdown)
if err != nil {
return fmt.Errorf("failed to read ungraceful shutdown key: %w", err)
}
if ok {
n.Log.Warn("detected previous ungraceful shutdown")
}
if err := n.DB.Put(ungracefulShutdown, nil); err != nil {
return fmt.Errorf(
"failed to write ungraceful shutdown key at: %w",
err,
)
}
return nil
}
// Set the node IDs of the peers this node should first connect to
func (n *Node) initBootstrappers() error {
n.bootstrappers = validators.NewManager()
for _, bootstrapper := range n.Config.Bootstrappers {
// 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.bootstrappers.AddStaker(constants.PrimaryNetworkID, bootstrapper.ID, 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)
}
// 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.bootstrappers,
}
// Start the chain creator with the Platform Chain
return n.chainManager.StartChainCreator(platformChain)
}
func (n *Node) initMetrics() error {
n.MetricsGatherer = metrics.NewPrefixGatherer()
n.MeterDBMetricsGatherer = metrics.NewLabelGatherer(chains.ChainLabel)
return n.MetricsGatherer.Register(
meterDBNamespace,
n.MeterDBMetricsGatherer,
)
}
func (n *Node) initNAT() {
n.Log.Info("initializing NAT")
if n.Config.PublicIP == "" && n.Config.PublicIPResolutionService == "" {
n.router = nat.GetRouter()
if !n.router.SupportsNAT() {
n.Log.Warn("UPnP and NAT-PMP router attach failed, " +
"you may not be listening publicly. " +
"Please confirm the settings in your router")
}
} else {
n.router = nat.NewNoRouter()
}
n.portMapper = nat.NewPortMapper(n.Log, n.router)
}
// initAPIServer initializes the server that handles HTTP calls
func (n *Node) initAPIServer() error {
n.Log.Info("initializing API server")
// An empty host is treated as a wildcard to match all addresses, so it is
// considered public.
hostIsPublic := n.Config.HTTPHost == ""
if !hostIsPublic {
ip, err := ips.Lookup(n.Config.HTTPHost)
if err != nil {
n.Log.Fatal("failed to lookup HTTP host",
zap.String("host", n.Config.HTTPHost),
zap.Error(err),
)
return err
}
hostIsPublic = ips.IsPublic(ip)
n.Log.Debug("finished HTTP host lookup",
zap.String("host", n.Config.HTTPHost),
zap.Stringer("ip", ip),
zap.Bool("isPublic", hostIsPublic),
)
}
listenAddress := net.JoinHostPort(n.Config.HTTPHost, strconv.FormatUint(uint64(n.Config.HTTPPort), 10))
listener, err := net.Listen("tcp", listenAddress)
if err != nil {
return err
}
addrStr := listener.Addr().String()
addrPort, err := ips.ParseAddrPort(addrStr)
if err != nil {