github.com/btcsuite/btcd@v0.24.0/connmgr/dynamicbanscore_test.go (about) 1 // Copyright (c) 2016 The btcsuite developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package connmgr 6 7 import ( 8 "math" 9 "testing" 10 "time" 11 ) 12 13 // TestDynamicBanScoreDecay tests the exponential decay implemented in 14 // DynamicBanScore. 15 func TestDynamicBanScoreDecay(t *testing.T) { 16 var bs DynamicBanScore 17 base := time.Now() 18 19 r := bs.increase(100, 50, base) 20 if r != 150 { 21 t.Errorf("Unexpected result %d after ban score increase.", r) 22 } 23 24 r = bs.int(base.Add(time.Minute)) 25 if r != 125 { 26 t.Errorf("Halflife check failed - %d instead of 125", r) 27 } 28 29 r = bs.int(base.Add(7 * time.Minute)) 30 if r != 100 { 31 t.Errorf("Decay after 7m - %d instead of 100", r) 32 } 33 } 34 35 // TestDynamicBanScoreLifetime tests that DynamicBanScore properly yields zero 36 // once the maximum age is reached. 37 func TestDynamicBanScoreLifetime(t *testing.T) { 38 var bs DynamicBanScore 39 base := time.Now() 40 41 r := bs.increase(0, math.MaxUint32, base) 42 r = bs.int(base.Add(Lifetime * time.Second)) 43 if r != 3 { // 3, not 4 due to precision loss and truncating 3.999... 44 t.Errorf("Pre max age check with MaxUint32 failed - %d", r) 45 } 46 r = bs.int(base.Add((Lifetime + 1) * time.Second)) 47 if r != 0 { 48 t.Errorf("Zero after max age check failed - %d instead of 0", r) 49 } 50 } 51 52 // TestDynamicBanScore tests exported functions of DynamicBanScore. Exponential 53 // decay or other time based behavior is tested by other functions. 54 func TestDynamicBanScoreReset(t *testing.T) { 55 var bs DynamicBanScore 56 if bs.Int() != 0 { 57 t.Errorf("Initial state is not zero.") 58 } 59 bs.Increase(100, 0) 60 r := bs.Int() 61 if r != 100 { 62 t.Errorf("Unexpected result %d after ban score increase.", r) 63 } 64 bs.Reset() 65 if bs.Int() != 0 { 66 t.Errorf("Failed to reset ban score.") 67 } 68 } 69 70 // TestDynamicBanScoreString 71 func TestDynamicBanScoreString(t *testing.T) { 72 var bs DynamicBanScore 73 base := time.Now() 74 75 r := bs.increase(100, 50, base) 76 if r != 150 { 77 t.Errorf("Unexpected result %d after ban score increase.", r) 78 } 79 t.Log(bs.String()) 80 }