id.go 1.2 KB

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