generator.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. // Copyright (C) 2013-2018 by Maxim Bublis <b@codemonkey.ru>
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining
  4. // a copy of this software and associated documentation files (the
  5. // "Software"), to deal in the Software without restriction, including
  6. // without limitation the rights to use, copy, modify, merge, publish,
  7. // distribute, sublicense, and/or sell copies of the Software, and to
  8. // permit persons to whom the Software is furnished to do so, subject to
  9. // the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be
  12. // included in all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  18. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  19. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. package uuid
  22. import (
  23. "crypto/md5"
  24. "crypto/rand"
  25. "crypto/sha1"
  26. "encoding/binary"
  27. "errors"
  28. "fmt"
  29. "hash"
  30. "io"
  31. "net"
  32. "sync"
  33. "time"
  34. )
  35. // Difference in 100-nanosecond intervals between
  36. // UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
  37. const epochStart = 122192928000000000
  38. type epochFunc func() time.Time
  39. // HWAddrFunc is the function type used to provide hardware (MAC) addresses.
  40. type HWAddrFunc func() (net.HardwareAddr, error)
  41. // DefaultGenerator is the default UUID Generator used by this package.
  42. var DefaultGenerator Generator = NewGen()
  43. // NewV1 returns a UUID based on the current timestamp and MAC address.
  44. func NewV1() (UUID, error) {
  45. return DefaultGenerator.NewV1()
  46. }
  47. // NewV3 returns a UUID based on the MD5 hash of the namespace UUID and name.
  48. func NewV3(ns UUID, name string) UUID {
  49. return DefaultGenerator.NewV3(ns, name)
  50. }
  51. // NewV4 returns a randomly generated UUID.
  52. func NewV4() (UUID, error) {
  53. return DefaultGenerator.NewV4()
  54. }
  55. // NewV5 returns a UUID based on SHA-1 hash of the namespace UUID and name.
  56. func NewV5(ns UUID, name string) UUID {
  57. return DefaultGenerator.NewV5(ns, name)
  58. }
  59. // NewV6 returns a k-sortable UUID based on a timestamp and 48 bits of
  60. // pseudorandom data. The timestamp in a V6 UUID is the same as V1, with the bit
  61. // order being adjusted to allow the UUID to be k-sortable.
  62. //
  63. // This is implemented based on revision 02 of the Peabody UUID draft, and may
  64. // be subject to change pending further revisions. Until the final specification
  65. // revision is finished, changes required to implement updates to the spec will
  66. // not be considered a breaking change. They will happen as a minor version
  67. // releases until the spec is final.
  68. func NewV6() (UUID, error) {
  69. return DefaultGenerator.NewV6()
  70. }
  71. // NewV7 returns a k-sortable UUID based on the current UNIX epoch, with the
  72. // ability to configure the timestamp's precision from millisecond all the way
  73. // to nanosecond. The additional precision is supported by reducing the amount
  74. // of pseudorandom data that makes up the rest of the UUID.
  75. //
  76. // If an unknown Precision argument is passed to this method it will panic. As
  77. // such it's strongly encouraged to use the package-provided constants for this
  78. // value.
  79. //
  80. // This is implemented based on revision 02 of the Peabody UUID draft, and may
  81. // be subject to change pending further revisions. Until the final specification
  82. // revision is finished, changes required to implement updates to the spec will
  83. // not be considered a breaking change. They will happen as a minor version
  84. // releases until the spec is final.
  85. func NewV7(p Precision) (UUID, error) {
  86. return DefaultGenerator.NewV7(p)
  87. }
  88. // Generator provides an interface for generating UUIDs.
  89. type Generator interface {
  90. NewV1() (UUID, error)
  91. NewV3(ns UUID, name string) UUID
  92. NewV4() (UUID, error)
  93. NewV5(ns UUID, name string) UUID
  94. NewV6() (UUID, error)
  95. NewV7(Precision) (UUID, error)
  96. }
  97. // Gen is a reference UUID generator based on the specifications laid out in
  98. // RFC-4122 and DCE 1.1: Authentication and Security Services. This type
  99. // satisfies the Generator interface as defined in this package.
  100. //
  101. // For consumers who are generating V1 UUIDs, but don't want to expose the MAC
  102. // address of the node generating the UUIDs, the NewGenWithHWAF() function has been
  103. // provided as a convenience. See the function's documentation for more info.
  104. //
  105. // The authors of this package do not feel that the majority of users will need
  106. // to obfuscate their MAC address, and so we recommend using NewGen() to create
  107. // a new generator.
  108. type Gen struct {
  109. clockSequenceOnce sync.Once
  110. hardwareAddrOnce sync.Once
  111. storageMutex sync.Mutex
  112. rand io.Reader
  113. epochFunc epochFunc
  114. hwAddrFunc HWAddrFunc
  115. lastTime uint64
  116. clockSequence uint16
  117. hardwareAddr [6]byte
  118. v7LastTime uint64
  119. v7LastSubsec uint64
  120. v7ClockSequence uint16
  121. }
  122. // interface check -- build will fail if *Gen doesn't satisfy Generator
  123. var _ Generator = (*Gen)(nil)
  124. // NewGen returns a new instance of Gen with some default values set. Most
  125. // people should use this.
  126. func NewGen() *Gen {
  127. return NewGenWithHWAF(defaultHWAddrFunc)
  128. }
  129. // NewGenWithHWAF builds a new UUID generator with the HWAddrFunc provided. Most
  130. // consumers should use NewGen() instead.
  131. //
  132. // This is used so that consumers can generate their own MAC addresses, for use
  133. // in the generated UUIDs, if there is some concern about exposing the physical
  134. // address of the machine generating the UUID.
  135. //
  136. // The Gen generator will only invoke the HWAddrFunc once, and cache that MAC
  137. // address for all the future UUIDs generated by it. If you'd like to switch the
  138. // MAC address being used, you'll need to create a new generator using this
  139. // function.
  140. func NewGenWithHWAF(hwaf HWAddrFunc) *Gen {
  141. return &Gen{
  142. epochFunc: time.Now,
  143. hwAddrFunc: hwaf,
  144. rand: rand.Reader,
  145. }
  146. }
  147. // NewV1 returns a UUID based on the current timestamp and MAC address.
  148. func (g *Gen) NewV1() (UUID, error) {
  149. u := UUID{}
  150. timeNow, clockSeq, err := g.getClockSequence()
  151. if err != nil {
  152. return Nil, err
  153. }
  154. binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
  155. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  156. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  157. binary.BigEndian.PutUint16(u[8:], clockSeq)
  158. hardwareAddr, err := g.getHardwareAddr()
  159. if err != nil {
  160. return Nil, err
  161. }
  162. copy(u[10:], hardwareAddr)
  163. u.SetVersion(V1)
  164. u.SetVariant(VariantRFC4122)
  165. return u, nil
  166. }
  167. // NewV3 returns a UUID based on the MD5 hash of the namespace UUID and name.
  168. func (g *Gen) NewV3(ns UUID, name string) UUID {
  169. u := newFromHash(md5.New(), ns, name)
  170. u.SetVersion(V3)
  171. u.SetVariant(VariantRFC4122)
  172. return u
  173. }
  174. // NewV4 returns a randomly generated UUID.
  175. func (g *Gen) NewV4() (UUID, error) {
  176. u := UUID{}
  177. if _, err := io.ReadFull(g.rand, u[:]); err != nil {
  178. return Nil, err
  179. }
  180. u.SetVersion(V4)
  181. u.SetVariant(VariantRFC4122)
  182. return u, nil
  183. }
  184. // NewV5 returns a UUID based on SHA-1 hash of the namespace UUID and name.
  185. func (g *Gen) NewV5(ns UUID, name string) UUID {
  186. u := newFromHash(sha1.New(), ns, name)
  187. u.SetVersion(V5)
  188. u.SetVariant(VariantRFC4122)
  189. return u
  190. }
  191. // NewV6 returns a k-sortable UUID based on a timestamp and 48 bits of
  192. // pseudorandom data. The timestamp in a V6 UUID is the same as V1, with the bit
  193. // order being adjusted to allow the UUID to be k-sortable.
  194. //
  195. // This is implemented based on revision 02 of the Peabody UUID draft, and may
  196. // be subject to change pending further revisions. Until the final specification
  197. // revision is finished, changes required to implement updates to the spec will
  198. // not be considered a breaking change. They will happen as a minor version
  199. // releases until the spec is final.
  200. func (g *Gen) NewV6() (UUID, error) {
  201. var u UUID
  202. if _, err := io.ReadFull(g.rand, u[10:]); err != nil {
  203. return Nil, err
  204. }
  205. timeNow, clockSeq, err := g.getClockSequence()
  206. if err != nil {
  207. return Nil, err
  208. }
  209. binary.BigEndian.PutUint32(u[0:], uint32(timeNow>>28)) // set time_high
  210. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>12)) // set time_mid
  211. binary.BigEndian.PutUint16(u[6:], uint16(timeNow&0xfff)) // set time_low (minus four version bits)
  212. binary.BigEndian.PutUint16(u[8:], clockSeq&0x3fff) // set clk_seq_hi_res (minus two variant bits)
  213. u.SetVersion(V6)
  214. u.SetVariant(VariantRFC4122)
  215. return u, nil
  216. }
  217. // getClockSequence returns the epoch and clock sequence for V1 and V6 UUIDs.
  218. func (g *Gen) getClockSequence() (uint64, uint16, error) {
  219. var err error
  220. g.clockSequenceOnce.Do(func() {
  221. buf := make([]byte, 2)
  222. if _, err = io.ReadFull(g.rand, buf); err != nil {
  223. return
  224. }
  225. g.clockSequence = binary.BigEndian.Uint16(buf)
  226. })
  227. if err != nil {
  228. return 0, 0, err
  229. }
  230. g.storageMutex.Lock()
  231. defer g.storageMutex.Unlock()
  232. timeNow := g.getEpoch()
  233. // Clock didn't change since last UUID generation.
  234. // Should increase clock sequence.
  235. if timeNow <= g.lastTime {
  236. g.clockSequence++
  237. }
  238. g.lastTime = timeNow
  239. return timeNow, g.clockSequence, nil
  240. }
  241. // Precision is used to configure the V7 generator, to specify how precise the
  242. // timestamp within the UUID should be.
  243. type Precision byte
  244. const (
  245. NanosecondPrecision Precision = iota
  246. MicrosecondPrecision
  247. MillisecondPrecision
  248. )
  249. func (p Precision) String() string {
  250. switch p {
  251. case NanosecondPrecision:
  252. return "nanosecond"
  253. case MicrosecondPrecision:
  254. return "microsecond"
  255. case MillisecondPrecision:
  256. return "millisecond"
  257. default:
  258. return "unknown"
  259. }
  260. }
  261. // Duration returns the time.Duration for a specific precision. If the Precision
  262. // value is not known, this returns 0.
  263. func (p Precision) Duration() time.Duration {
  264. switch p {
  265. case NanosecondPrecision:
  266. return time.Nanosecond
  267. case MicrosecondPrecision:
  268. return time.Microsecond
  269. case MillisecondPrecision:
  270. return time.Millisecond
  271. default:
  272. return 0
  273. }
  274. }
  275. // NewV7 returns a k-sortable UUID based on the current UNIX epoch, with the
  276. // ability to configure the timestamp's precision from millisecond all the way
  277. // to nanosecond. The additional precision is supported by reducing the amount
  278. // of pseudorandom data that makes up the rest of the UUID.
  279. //
  280. // If an unknown Precision argument is passed to this method it will panic. As
  281. // such it's strongly encouraged to use the package-provided constants for this
  282. // value.
  283. //
  284. // This is implemented based on revision 02 of the Peabody UUID draft, and may
  285. // be subject to change pending further revisions. Until the final specification
  286. // revision is finished, changes required to implement updates to the spec will
  287. // not be considered a breaking change. They will happen as a minor version
  288. // releases until the spec is final.
  289. func (g *Gen) NewV7(p Precision) (UUID, error) {
  290. var u UUID
  291. var err error
  292. switch p {
  293. case NanosecondPrecision:
  294. u, err = g.newV7Nano()
  295. case MicrosecondPrecision:
  296. u, err = g.newV7Micro()
  297. case MillisecondPrecision:
  298. u, err = g.newV7Milli()
  299. default:
  300. panic(fmt.Sprintf("unknown precision value %d", p))
  301. }
  302. if err != nil {
  303. return Nil, err
  304. }
  305. u.SetVersion(V7)
  306. u.SetVariant(VariantRFC4122)
  307. return u, nil
  308. }
  309. func (g *Gen) newV7Milli() (UUID, error) {
  310. var u UUID
  311. if _, err := io.ReadFull(g.rand, u[8:]); err != nil {
  312. return Nil, err
  313. }
  314. sec, nano, seq, err := g.getV7ClockSequence(MillisecondPrecision)
  315. if err != nil {
  316. return Nil, err
  317. }
  318. msec := (nano / 1000000) & 0xfff
  319. d := (sec << 28) // set unixts field
  320. d |= (msec << 16) // set msec field
  321. d |= (uint64(seq) & 0xfff) // set seq field
  322. binary.BigEndian.PutUint64(u[:], d)
  323. return u, nil
  324. }
  325. func (g *Gen) newV7Micro() (UUID, error) {
  326. var u UUID
  327. if _, err := io.ReadFull(g.rand, u[10:]); err != nil {
  328. return Nil, err
  329. }
  330. sec, nano, seq, err := g.getV7ClockSequence(MicrosecondPrecision)
  331. if err != nil {
  332. return Nil, err
  333. }
  334. usec := nano / 1000
  335. usech := (usec << 4) & 0xfff0000
  336. usecl := usec & 0xfff
  337. d := (sec << 28) // set unixts field
  338. d |= usech | usecl // set usec fields
  339. binary.BigEndian.PutUint64(u[:], d)
  340. binary.BigEndian.PutUint16(u[8:], seq)
  341. return u, nil
  342. }
  343. func (g *Gen) newV7Nano() (UUID, error) {
  344. var u UUID
  345. if _, err := io.ReadFull(g.rand, u[11:]); err != nil {
  346. return Nil, err
  347. }
  348. sec, nano, seq, err := g.getV7ClockSequence(NanosecondPrecision)
  349. if err != nil {
  350. return Nil, err
  351. }
  352. nano &= 0x3fffffffff
  353. nanoh := nano >> 26
  354. nanom := (nano >> 14) & 0xfff
  355. nanol := uint16(nano & 0x3fff)
  356. d := (sec << 28) // set unixts field
  357. d |= (nanoh << 16) | nanom // set nsec high and med fields
  358. binary.BigEndian.PutUint64(u[:], d)
  359. binary.BigEndian.PutUint16(u[8:], nanol) // set nsec low field
  360. u[10] = byte(seq) // set seq field
  361. return u, nil
  362. }
  363. const (
  364. maxSeq14 = (1 << 14) - 1
  365. maxSeq12 = (1 << 12) - 1
  366. maxSeq8 = (1 << 8) - 1
  367. )
  368. // getV7ClockSequence returns the unix epoch, nanoseconds of current second, and
  369. // the sequence for V7 UUIDs.
  370. func (g *Gen) getV7ClockSequence(p Precision) (epoch uint64, nano uint64, seq uint16, err error) {
  371. g.storageMutex.Lock()
  372. defer g.storageMutex.Unlock()
  373. tn := g.epochFunc()
  374. unix := uint64(tn.Unix())
  375. nsec := uint64(tn.Nanosecond())
  376. // V7 UUIDs have more precise requirements around how the clock sequence
  377. // value is generated and used. Specifically they require that the sequence
  378. // be zero, unless we've already generated a UUID within this unit of time
  379. // (millisecond, microsecond, or nanosecond) at which point you should
  380. // increment the sequence. Likewise if time has warped backwards for some reason (NTP
  381. // adjustment?), we also increment the clock sequence to reduce the risk of a
  382. // collision.
  383. switch {
  384. case unix < g.v7LastTime:
  385. g.v7ClockSequence++
  386. case unix > g.v7LastTime:
  387. g.v7ClockSequence = 0
  388. case unix == g.v7LastTime:
  389. switch p {
  390. case NanosecondPrecision:
  391. if nsec <= g.v7LastSubsec {
  392. if g.v7ClockSequence >= maxSeq8 {
  393. return 0, 0, 0, errors.New("generating nanosecond precision UUIDv7s too fast: internal clock sequence would roll over")
  394. }
  395. g.v7ClockSequence++
  396. } else {
  397. g.v7ClockSequence = 0
  398. }
  399. case MicrosecondPrecision:
  400. if nsec/1000 <= g.v7LastSubsec/1000 {
  401. if g.v7ClockSequence >= maxSeq14 {
  402. return 0, 0, 0, errors.New("generating microsecond precision UUIDv7s too fast: internal clock sequence would roll over")
  403. }
  404. g.v7ClockSequence++
  405. } else {
  406. g.v7ClockSequence = 0
  407. }
  408. case MillisecondPrecision:
  409. if nsec/1000000 <= g.v7LastSubsec/1000000 {
  410. if g.v7ClockSequence >= maxSeq12 {
  411. return 0, 0, 0, errors.New("generating millisecond precision UUIDv7s too fast: internal clock sequence would roll over")
  412. }
  413. g.v7ClockSequence++
  414. } else {
  415. g.v7ClockSequence = 0
  416. }
  417. default:
  418. panic(fmt.Sprintf("unknown precision value %d", p))
  419. }
  420. }
  421. g.v7LastTime = unix
  422. g.v7LastSubsec = nsec
  423. return unix, nsec, g.v7ClockSequence, nil
  424. }
  425. // Returns the hardware address.
  426. func (g *Gen) getHardwareAddr() ([]byte, error) {
  427. var err error
  428. g.hardwareAddrOnce.Do(func() {
  429. var hwAddr net.HardwareAddr
  430. if hwAddr, err = g.hwAddrFunc(); err == nil {
  431. copy(g.hardwareAddr[:], hwAddr)
  432. return
  433. }
  434. // Initialize hardwareAddr randomly in case
  435. // of real network interfaces absence.
  436. if _, err = io.ReadFull(g.rand, g.hardwareAddr[:]); err != nil {
  437. return
  438. }
  439. // Set multicast bit as recommended by RFC-4122
  440. g.hardwareAddr[0] |= 0x01
  441. })
  442. if err != nil {
  443. return []byte{}, err
  444. }
  445. return g.hardwareAddr[:], nil
  446. }
  447. // Returns the difference between UUID epoch (October 15, 1582)
  448. // and current time in 100-nanosecond intervals.
  449. func (g *Gen) getEpoch() uint64 {
  450. return epochStart + uint64(g.epochFunc().UnixNano()/100)
  451. }
  452. // Returns the UUID based on the hashing of the namespace UUID and name.
  453. func newFromHash(h hash.Hash, ns UUID, name string) UUID {
  454. u := UUID{}
  455. h.Write(ns[:])
  456. h.Write([]byte(name))
  457. copy(u[:], h.Sum(nil))
  458. return u
  459. }
  460. // Returns the hardware address.
  461. func defaultHWAddrFunc() (net.HardwareAddr, error) {
  462. ifaces, err := net.Interfaces()
  463. if err != nil {
  464. return []byte{}, err
  465. }
  466. for _, iface := range ifaces {
  467. if len(iface.HardwareAddr) >= 6 {
  468. return iface.HardwareAddr, nil
  469. }
  470. }
  471. return []byte{}, fmt.Errorf("uuid: no HW address found")
  472. }