github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/proxy/vmess/validator_test.go (about) 1 package vmess_test 2 3 import ( 4 "testing" 5 "time" 6 7 "v2ray.com/core/common" 8 "v2ray.com/core/common/protocol" 9 "v2ray.com/core/common/serial" 10 "v2ray.com/core/common/uuid" 11 . "v2ray.com/core/proxy/vmess" 12 ) 13 14 func toAccount(a *Account) protocol.Account { 15 account, err := a.AsAccount() 16 common.Must(err) 17 return account 18 } 19 20 func TestUserValidator(t *testing.T) { 21 hasher := protocol.DefaultIDHash 22 v := NewTimedUserValidator(hasher) 23 defer common.Close(v) 24 25 id := uuid.New() 26 user := &protocol.MemoryUser{ 27 Email: "test", 28 Account: toAccount(&Account{ 29 Id: id.String(), 30 AlterId: 8, 31 }), 32 } 33 common.Must(v.Add(user)) 34 35 { 36 testSmallLag := func(lag time.Duration) { 37 ts := protocol.Timestamp(time.Now().Add(time.Second * lag).Unix()) 38 idHash := hasher(id.Bytes()) 39 common.Must2(serial.WriteUint64(idHash, uint64(ts))) 40 userHash := idHash.Sum(nil) 41 42 euser, ets, found, _ := v.Get(userHash) 43 if !found { 44 t.Fatal("user not found") 45 } 46 if euser.Email != user.Email { 47 t.Error("unexpected user email: ", euser.Email, " want ", user.Email) 48 } 49 if ets != ts { 50 t.Error("unexpected timestamp: ", ets, " want ", ts) 51 } 52 } 53 54 testSmallLag(0) 55 testSmallLag(40) 56 testSmallLag(-40) 57 testSmallLag(80) 58 testSmallLag(-80) 59 testSmallLag(120) 60 testSmallLag(-120) 61 } 62 63 { 64 testBigLag := func(lag time.Duration) { 65 ts := protocol.Timestamp(time.Now().Add(time.Second * lag).Unix()) 66 idHash := hasher(id.Bytes()) 67 common.Must2(serial.WriteUint64(idHash, uint64(ts))) 68 userHash := idHash.Sum(nil) 69 70 euser, _, found, _ := v.Get(userHash) 71 if found || euser != nil { 72 t.Error("unexpected user") 73 } 74 } 75 76 testBigLag(121) 77 testBigLag(-121) 78 testBigLag(310) 79 testBigLag(-310) 80 testBigLag(500) 81 testBigLag(-500) 82 } 83 84 if v := v.Remove(user.Email); !v { 85 t.Error("unable to remove user") 86 } 87 if v := v.Remove(user.Email); v { 88 t.Error("remove user twice") 89 } 90 } 91 92 func BenchmarkUserValidator(b *testing.B) { 93 for i := 0; i < b.N; i++ { 94 hasher := protocol.DefaultIDHash 95 v := NewTimedUserValidator(hasher) 96 97 for j := 0; j < 1500; j++ { 98 id := uuid.New() 99 v.Add(&protocol.MemoryUser{ 100 Email: "test", 101 Account: toAccount(&Account{ 102 Id: id.String(), 103 AlterId: 16, 104 }), 105 }) 106 } 107 108 common.Close(v) 109 } 110 }