github.com/MetalBlockchain/metalgo@v1.11.9/network/tracked_ip_test.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  	"net/netip"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/stretchr/testify/require"
    12  
    13  	"github.com/MetalBlockchain/metalgo/staking"
    14  	"github.com/MetalBlockchain/metalgo/utils/ips"
    15  )
    16  
    17  var (
    18  	ip      *ips.ClaimedIPPort
    19  	otherIP *ips.ClaimedIPPort
    20  
    21  	defaultLoopbackAddrPort = netip.AddrPortFrom(
    22  		netip.AddrFrom4([4]byte{127, 0, 0, 1}),
    23  		9651,
    24  	)
    25  )
    26  
    27  func init() {
    28  	{
    29  		cert, err := staking.NewTLSCert()
    30  		if err != nil {
    31  			panic(err)
    32  		}
    33  		stakingCert, err := staking.ParseCertificate(cert.Leaf.Raw)
    34  		if err != nil {
    35  			panic(err)
    36  		}
    37  		ip = ips.NewClaimedIPPort(
    38  			stakingCert,
    39  			defaultLoopbackAddrPort,
    40  			1,   // timestamp
    41  			nil, // signature
    42  		)
    43  	}
    44  
    45  	{
    46  		cert, err := staking.NewTLSCert()
    47  		if err != nil {
    48  			panic(err)
    49  		}
    50  		stakingCert, err := staking.ParseCertificate(cert.Leaf.Raw)
    51  		if err != nil {
    52  			panic(err)
    53  		}
    54  		otherIP = ips.NewClaimedIPPort(
    55  			stakingCert,
    56  			defaultLoopbackAddrPort,
    57  			1,   // timestamp
    58  			nil, // signature
    59  		)
    60  	}
    61  }
    62  
    63  func TestTrackedIP(t *testing.T) {
    64  	require := require.New(t)
    65  
    66  	ip := trackedIP{
    67  		onStopTracking: make(chan struct{}),
    68  	}
    69  
    70  	require.Equal(time.Duration(0), ip.getDelay())
    71  
    72  	ip.increaseDelay(time.Second, time.Minute)
    73  	require.LessOrEqual(ip.getDelay(), 2*time.Second)
    74  
    75  	ip.increaseDelay(time.Second, time.Minute)
    76  	require.LessOrEqual(ip.getDelay(), 4*time.Second)
    77  
    78  	ip.increaseDelay(time.Second, time.Minute)
    79  	require.LessOrEqual(ip.getDelay(), 8*time.Second)
    80  
    81  	ip.increaseDelay(time.Second, time.Minute)
    82  	require.LessOrEqual(ip.getDelay(), 16*time.Second)
    83  
    84  	ip.increaseDelay(time.Second, time.Minute)
    85  	require.LessOrEqual(ip.getDelay(), 32*time.Second)
    86  
    87  	for i := 0; i < 100; i++ {
    88  		ip.increaseDelay(time.Second, time.Minute)
    89  		require.LessOrEqual(ip.getDelay(), time.Minute)
    90  	}
    91  	require.GreaterOrEqual(ip.getDelay(), 45*time.Second)
    92  
    93  	ip.stopTracking()
    94  	<-ip.onStopTracking
    95  
    96  	ip.stopTracking()
    97  	<-ip.onStopTracking
    98  }