validator_test.go 2.2 KB

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