id.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package protocol
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "hash"
  6. "v2ray.com/core/common/uuid"
  7. )
  8. const (
  9. IDBytesLen = 16
  10. )
  11. type IDHash func(key []byte) hash.Hash
  12. func DefaultIDHash(key []byte) hash.Hash {
  13. return hmac.New(md5.New, key)
  14. }
  15. // The ID of en entity, in the form of an UUID.
  16. type ID struct {
  17. uuid *uuid.UUID
  18. cmdKey [IDBytesLen]byte
  19. }
  20. // Equals returns true if this ID equals to the other one.
  21. func (v *ID) Equals(another *ID) bool {
  22. return v.uuid.Equals(another.uuid)
  23. }
  24. func (v *ID) Bytes() []byte {
  25. return v.uuid.Bytes()
  26. }
  27. func (v *ID) String() string {
  28. return v.uuid.String()
  29. }
  30. func (v *ID) UUID() *uuid.UUID {
  31. return v.uuid
  32. }
  33. func (v ID) CmdKey() []byte {
  34. return v.cmdKey[:]
  35. }
  36. func NewID(uuid *uuid.UUID) *ID {
  37. id := &ID{uuid: uuid}
  38. md5hash := md5.New()
  39. md5hash.Write(uuid.Bytes())
  40. md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))
  41. md5hash.Sum(id.cmdKey[:0])
  42. return id
  43. }
  44. func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID {
  45. alterIDs := make([]*ID, alterIDCount)
  46. prevID := primary.UUID()
  47. for idx := range alterIDs {
  48. newid := prevID.Next()
  49. // TODO: check duplicates
  50. alterIDs[idx] = NewID(newid)
  51. prevID = newid
  52. }
  53. return alterIDs
  54. }