github.com/imannamdari/v2ray-core/v5@v5.0.5/common/protocol/id.go (about) 1 package protocol 2 3 import ( 4 "crypto/hmac" 5 "crypto/md5" 6 "hash" 7 8 "github.com/imannamdari/v2ray-core/v5/common" 9 "github.com/imannamdari/v2ray-core/v5/common/uuid" 10 ) 11 12 const ( 13 IDBytesLen = 16 14 ) 15 16 type IDHash func(key []byte) hash.Hash 17 18 func DefaultIDHash(key []byte) hash.Hash { 19 return hmac.New(md5.New, key) 20 } 21 22 // The ID of en entity, in the form of a UUID. 23 type ID struct { 24 uuid uuid.UUID 25 cmdKey [IDBytesLen]byte 26 } 27 28 // Equals returns true if this ID equals to the other one. 29 func (id *ID) Equals(another *ID) bool { 30 return id.uuid.Equals(&(another.uuid)) 31 } 32 33 func (id *ID) Bytes() []byte { 34 return id.uuid.Bytes() 35 } 36 37 func (id *ID) String() string { 38 return id.uuid.String() 39 } 40 41 func (id *ID) UUID() uuid.UUID { 42 return id.uuid 43 } 44 45 func (id ID) CmdKey() []byte { 46 return id.cmdKey[:] 47 } 48 49 // NewID returns an ID with given UUID. 50 func NewID(uuid uuid.UUID) *ID { 51 id := &ID{uuid: uuid} 52 md5hash := md5.New() 53 common.Must2(md5hash.Write(uuid.Bytes())) 54 common.Must2(md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))) 55 md5hash.Sum(id.cmdKey[:0]) 56 return id 57 } 58 59 func nextID(u *uuid.UUID) uuid.UUID { 60 md5hash := md5.New() 61 common.Must2(md5hash.Write(u.Bytes())) 62 common.Must2(md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81"))) 63 var newid uuid.UUID 64 for { 65 md5hash.Sum(newid[:0]) 66 if !newid.Equals(u) { 67 return newid 68 } 69 common.Must2(md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2"))) 70 } 71 } 72 73 func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID { 74 alterIDs := make([]*ID, alterIDCount) 75 prevID := primary.UUID() 76 for idx := range alterIDs { 77 newid := nextID(&prevID) 78 alterIDs[idx] = NewID(newid) 79 prevID = newid 80 } 81 return alterIDs 82 }