github.com/ava-labs/avalanchego@v1.11.11/network/test_network.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package network
     5  
     6  import (
     7  	"crypto"
     8  	"errors"
     9  	"math"
    10  	"net"
    11  	"net/netip"
    12  	"runtime"
    13  	"sync"
    14  
    15  	"github.com/prometheus/client_golang/prometheus"
    16  
    17  	"github.com/ava-labs/avalanchego/ids"
    18  	"github.com/ava-labs/avalanchego/message"
    19  	"github.com/ava-labs/avalanchego/network/dialer"
    20  	"github.com/ava-labs/avalanchego/network/peer"
    21  	"github.com/ava-labs/avalanchego/network/throttling"
    22  	"github.com/ava-labs/avalanchego/snow/networking/router"
    23  	"github.com/ava-labs/avalanchego/snow/networking/tracker"
    24  	"github.com/ava-labs/avalanchego/snow/uptime"
    25  	"github.com/ava-labs/avalanchego/snow/validators"
    26  	"github.com/ava-labs/avalanchego/staking"
    27  	"github.com/ava-labs/avalanchego/subnets"
    28  	"github.com/ava-labs/avalanchego/upgrade"
    29  	"github.com/ava-labs/avalanchego/utils"
    30  	"github.com/ava-labs/avalanchego/utils/constants"
    31  	"github.com/ava-labs/avalanchego/utils/crypto/bls"
    32  	"github.com/ava-labs/avalanchego/utils/logging"
    33  	"github.com/ava-labs/avalanchego/utils/math/meter"
    34  	"github.com/ava-labs/avalanchego/utils/resource"
    35  	"github.com/ava-labs/avalanchego/utils/set"
    36  	"github.com/ava-labs/avalanchego/utils/units"
    37  )
    38  
    39  var (
    40  	errClosed = errors.New("closed")
    41  
    42  	_ net.Listener    = (*noopListener)(nil)
    43  	_ subnets.Allower = (*nodeIDConnector)(nil)
    44  )
    45  
    46  type noopListener struct {
    47  	once   sync.Once
    48  	closed chan struct{}
    49  }
    50  
    51  func newNoopListener() net.Listener {
    52  	return &noopListener{
    53  		closed: make(chan struct{}),
    54  	}
    55  }
    56  
    57  func (l *noopListener) Accept() (net.Conn, error) {
    58  	<-l.closed
    59  	return nil, errClosed
    60  }
    61  
    62  func (l *noopListener) Close() error {
    63  	l.once.Do(func() {
    64  		close(l.closed)
    65  	})
    66  	return nil
    67  }
    68  
    69  func (*noopListener) Addr() net.Addr {
    70  	return &net.TCPAddr{
    71  		IP:   net.IPv4zero,
    72  		Port: 1,
    73  	}
    74  }
    75  
    76  func NewTestNetwork(
    77  	log logging.Logger,
    78  	networkID uint32,
    79  	currentValidators validators.Manager,
    80  	trackedSubnets set.Set[ids.ID],
    81  	router router.ExternalHandler,
    82  ) (Network, error) {
    83  	metrics := prometheus.NewRegistry()
    84  	msgCreator, err := message.NewCreator(
    85  		logging.NoLog{},
    86  		metrics,
    87  		constants.DefaultNetworkCompressionType,
    88  		constants.DefaultNetworkMaximumInboundTimeout,
    89  	)
    90  	if err != nil {
    91  		return nil, err
    92  	}
    93  
    94  	tlsCert, err := staking.NewTLSCert()
    95  	if err != nil {
    96  		return nil, err
    97  	}
    98  
    99  	blsKey, err := bls.NewSecretKey()
   100  	if err != nil {
   101  		return nil, err
   102  	}
   103  
   104  	// TODO actually monitor usage
   105  	// TestNetwork doesn't use disk so we don't need to track it, but we should
   106  	// still have guardrails around cpu/memory usage.
   107  	resourceTracker, err := tracker.NewResourceTracker(
   108  		metrics,
   109  		resource.NoUsage,
   110  		&meter.ContinuousFactory{},
   111  		constants.DefaultHealthCheckAveragerHalflife,
   112  	)
   113  	if err != nil {
   114  		return nil, err
   115  	}
   116  
   117  	return NewNetwork(
   118  		&Config{
   119  			HealthConfig: HealthConfig{
   120  				Enabled:                      true,
   121  				MinConnectedPeers:            constants.DefaultNetworkHealthMinPeers,
   122  				MaxTimeSinceMsgReceived:      constants.DefaultNetworkHealthMaxTimeSinceMsgReceived,
   123  				MaxTimeSinceMsgSent:          constants.DefaultNetworkHealthMaxTimeSinceMsgSent,
   124  				MaxPortionSendQueueBytesFull: constants.DefaultNetworkHealthMaxPortionSendQueueFill,
   125  				MaxSendFailRate:              constants.DefaultNetworkHealthMaxSendFailRate,
   126  				SendFailRateHalflife:         constants.DefaultHealthCheckAveragerHalflife,
   127  			},
   128  			PeerListGossipConfig: PeerListGossipConfig{
   129  				PeerListNumValidatorIPs: constants.DefaultNetworkPeerListNumValidatorIPs,
   130  				PeerListPullGossipFreq:  constants.DefaultNetworkPeerListPullGossipFreq,
   131  				PeerListBloomResetFreq:  constants.DefaultNetworkPeerListBloomResetFreq,
   132  			},
   133  			TimeoutConfig: TimeoutConfig{
   134  				PingPongTimeout:      constants.DefaultPingPongTimeout,
   135  				ReadHandshakeTimeout: constants.DefaultNetworkReadHandshakeTimeout,
   136  			},
   137  			DelayConfig: DelayConfig{
   138  				InitialReconnectDelay: constants.DefaultNetworkInitialReconnectDelay,
   139  				MaxReconnectDelay:     constants.DefaultNetworkMaxReconnectDelay,
   140  			},
   141  			ThrottlerConfig: ThrottlerConfig{
   142  				InboundConnUpgradeThrottlerConfig: throttling.InboundConnUpgradeThrottlerConfig{
   143  					UpgradeCooldown:        constants.DefaultInboundConnUpgradeThrottlerCooldown,
   144  					MaxRecentConnsUpgraded: int(math.Ceil(constants.DefaultInboundThrottlerMaxConnsPerSec * constants.DefaultInboundConnUpgradeThrottlerCooldown.Seconds())),
   145  				},
   146  				InboundMsgThrottlerConfig: throttling.InboundMsgThrottlerConfig{
   147  					MsgByteThrottlerConfig: throttling.MsgByteThrottlerConfig{
   148  						VdrAllocSize:        constants.DefaultInboundThrottlerVdrAllocSize,
   149  						AtLargeAllocSize:    constants.DefaultInboundThrottlerAtLargeAllocSize,
   150  						NodeMaxAtLargeBytes: constants.DefaultInboundThrottlerNodeMaxAtLargeBytes,
   151  					},
   152  					BandwidthThrottlerConfig: throttling.BandwidthThrottlerConfig{
   153  						RefillRate:   constants.DefaultInboundThrottlerBandwidthRefillRate,
   154  						MaxBurstSize: constants.DefaultInboundThrottlerBandwidthMaxBurstSize,
   155  					},
   156  					CPUThrottlerConfig: throttling.SystemThrottlerConfig{
   157  						MaxRecheckDelay: constants.DefaultInboundThrottlerCPUMaxRecheckDelay,
   158  					},
   159  					DiskThrottlerConfig: throttling.SystemThrottlerConfig{
   160  						MaxRecheckDelay: constants.DefaultInboundThrottlerDiskMaxRecheckDelay,
   161  					},
   162  					MaxProcessingMsgsPerNode: constants.DefaultInboundThrottlerMaxProcessingMsgsPerNode,
   163  				},
   164  				OutboundMsgThrottlerConfig: throttling.MsgByteThrottlerConfig{
   165  					VdrAllocSize:        constants.DefaultOutboundThrottlerVdrAllocSize,
   166  					AtLargeAllocSize:    constants.DefaultOutboundThrottlerAtLargeAllocSize,
   167  					NodeMaxAtLargeBytes: constants.DefaultOutboundThrottlerNodeMaxAtLargeBytes,
   168  				},
   169  				MaxInboundConnsPerSec: constants.DefaultInboundThrottlerMaxConnsPerSec,
   170  			},
   171  			ProxyEnabled:           constants.DefaultNetworkTCPProxyEnabled,
   172  			ProxyReadHeaderTimeout: constants.DefaultNetworkTCPProxyReadTimeout,
   173  			DialerConfig: dialer.Config{
   174  				ThrottleRps:       constants.DefaultOutboundConnectionThrottlingRps,
   175  				ConnectionTimeout: constants.DefaultOutboundConnectionTimeout,
   176  			},
   177  			TLSConfig: peer.TLSConfig(*tlsCert, nil),
   178  			MyIPPort: utils.NewAtomic(netip.AddrPortFrom(
   179  				netip.IPv4Unspecified(),
   180  				1,
   181  			)),
   182  			NetworkID:                    networkID,
   183  			MaxClockDifference:           constants.DefaultNetworkMaxClockDifference,
   184  			PingFrequency:                constants.DefaultPingFrequency,
   185  			AllowPrivateIPs:              !constants.ProductionNetworkIDs.Contains(networkID),
   186  			CompressionType:              constants.DefaultNetworkCompressionType,
   187  			TLSKey:                       tlsCert.PrivateKey.(crypto.Signer),
   188  			BLSKey:                       blsKey,
   189  			TrackedSubnets:               trackedSubnets,
   190  			Beacons:                      validators.NewManager(),
   191  			Validators:                   currentValidators,
   192  			UptimeCalculator:             uptime.NoOpCalculator,
   193  			UptimeMetricFreq:             constants.DefaultUptimeMetricFreq,
   194  			RequireValidatorToConnect:    constants.DefaultNetworkRequireValidatorToConnect,
   195  			MaximumInboundMessageTimeout: constants.DefaultNetworkMaximumInboundTimeout,
   196  			PeerReadBufferSize:           constants.DefaultNetworkPeerReadBufferSize,
   197  			PeerWriteBufferSize:          constants.DefaultNetworkPeerWriteBufferSize,
   198  			ResourceTracker:              resourceTracker,
   199  			CPUTargeter: tracker.NewTargeter(
   200  				logging.NoLog{},
   201  				&tracker.TargeterConfig{
   202  					VdrAlloc:           float64(runtime.NumCPU()),
   203  					MaxNonVdrUsage:     .8 * float64(runtime.NumCPU()),
   204  					MaxNonVdrNodeUsage: float64(runtime.NumCPU()) / 8,
   205  				},
   206  				currentValidators,
   207  				resourceTracker.CPUTracker(),
   208  			),
   209  			DiskTargeter: tracker.NewTargeter(
   210  				logging.NoLog{},
   211  				&tracker.TargeterConfig{
   212  					VdrAlloc:           1000 * units.GiB,
   213  					MaxNonVdrUsage:     1000 * units.GiB,
   214  					MaxNonVdrNodeUsage: 1000 * units.GiB,
   215  				},
   216  				currentValidators,
   217  				resourceTracker.DiskTracker(),
   218  			),
   219  		},
   220  		upgrade.InitiallyActiveTime,
   221  		msgCreator,
   222  		metrics,
   223  		log,
   224  		newNoopListener(),
   225  		dialer.NewDialer(
   226  			constants.NetworkType,
   227  			dialer.Config{
   228  				ThrottleRps:       constants.DefaultOutboundConnectionThrottlingRps,
   229  				ConnectionTimeout: constants.DefaultOutboundConnectionTimeout,
   230  			},
   231  			log,
   232  		),
   233  		router,
   234  	)
   235  }
   236  
   237  type nodeIDConnector struct {
   238  	nodeID ids.NodeID
   239  }
   240  
   241  func newNodeIDConnector(nodeID ids.NodeID) *nodeIDConnector {
   242  	return &nodeIDConnector{nodeID: nodeID}
   243  }
   244  
   245  func (f *nodeIDConnector) IsAllowed(nodeID ids.NodeID, _ bool) bool {
   246  	return nodeID == f.nodeID
   247  }