validator_test.go 2.3 KB

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