validator_test.go 2.2 KB

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