Debian Codegraph @

generator.go

raw symbols SCIP
1 // Copyright (C) 2013-2018 by Maxim Bublis <[email protected]>
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
22 package uuid
23
24 import (
25 "crypto/md5"
26 "crypto/rand"
27 "crypto/sha1"
28 "encoding/binary"
29 "fmt"
30 "io"
31 "net"
32 "sync"
33 "time"
34 )
35
36 // Difference in 100-nanosecond intervals between
37 // UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
38 const epochStart = 122192928000000000
39
40 // V7 carries its monotonic counter in rand_a, the 12 bits sitting between the
41 // version nibble and the variant.
42 const maxV7Counter = 0x0fff
43
44 // V7 timestamps are an unsigned 48 bit count of milliseconds since the Unix
45 // epoch, a range that runs from 1970 into the year 10889.
46 const maxV7Timestamp = 1<<48 - 1
47
48 // The counter is seeded with 11 random bits at the start of every timestamp
49 // tick, as described by RFC 9562 section 6.2 under "Fixed Bit-Length Dedicated
50 // Counter Seeding". The leading bit is left zero to act as a rollover guard, so
51 // at least 2048 increments are always available within a tick.
52 const v7CounterSeedMask = 0x07ff
53
54 // EpochFunc is the function type used to provide the current time.
55 type EpochFunc func() time.Time
56
57 // HWAddrFunc is the function type used to provide hardware (MAC) addresses.
58 type HWAddrFunc func() (net.HardwareAddr, error)
59
60 // DefaultGenerator is the default UUID Generator used by this package.
61 var DefaultGenerator Generator = NewGen()
62
63 // NewV1 returns a UUID based on the current timestamp and MAC address.
64 func NewV1() (UUID, error) {
65 return DefaultGenerator.NewV1()
66 }
67
68 // NewV1 returns a UUID based on the provided timestamp and MAC address.
69 func NewV1AtTime(atTime time.Time) (UUID, error) {
70 return DefaultGenerator.NewV1AtTime(atTime)
71 }
72
73 // NewV3 returns a UUID based on the MD5 hash of the namespace UUID and name.
74 func NewV3(ns UUID, name string) UUID {
75 return DefaultGenerator.NewV3(ns, name)
76 }
77
78 // NewV4 returns a randomly generated UUID.
79 func NewV4() (UUID, error) {
80 return DefaultGenerator.NewV4()
81 }
82
83 // NewV5 returns a UUID based on SHA-1 hash of the namespace UUID and name.
84 func NewV5(ns UUID, name string) UUID {
85 return DefaultGenerator.NewV5(ns, name)
86 }
87
88 // NewV6 returns a k-sortable UUID based on the current timestamp and 48 bits of
89 // pseudorandom data. The timestamp in a V6 UUID is the same as V1, with the bit
90 // order being adjusted to allow the UUID to be k-sortable.
91 func NewV6() (UUID, error) {
92 return DefaultGenerator.NewV6()
93 }
94
95 // NewV6 returns a k-sortable UUID based on the provided timestamp and 48 bits of
96 // pseudorandom data. The timestamp in a V6 UUID is the same as V1, with the bit
97 // order being adjusted to allow the UUID to be k-sortable.
98 func NewV6AtTime(atTime time.Time) (UUID, error) {
99 return DefaultGenerator.NewV6AtTime(atTime)
100 }
101
102 // NewV7 returns a k-sortable UUID based on the current millisecond-precision
103 // UNIX epoch and 74 bits of pseudorandom data. It supports single-node batch
104 // generation (multiple UUIDs in the same timestamp) with a 12-bit monotonic
105 // counter in rand_a, as described by RFC 9562 section 6.2, Method 1.
106 //
107 // UUIDs returned by a single generator are strictly increasing: each one sorts
108 // above the one before it, even within a millisecond and even if the system
109 // clock moves backwards. The counter is reseeded with each millisecond, leaving
110 // room for at least 2048 UUIDs within that millisecond. Beyond that the
111 // embedded timestamp is incremented ahead of the actual time, so generating
112 // UUIDs faster than roughly two million per second trades timestamp accuracy
113 // for ordering.
114 func NewV7() (UUID, error) {
115 return DefaultGenerator.NewV7()
116 }
117
118 // NewV7AtTime returns a k-sortable UUID based on the provided
119 // millisecond-precision UNIX epoch and 74 bits of pseudorandom data. It supports
120 // single-node batch generation (multiple UUIDs in the same timestamp) with a
121 // 12-bit monotonic counter in rand_a, as described by RFC 9562 section 6.2,
122 // Method 1.
123 //
124 // The provided timestamp is used as the starting point for generation, so unlike
125 // NewV7 the ordering guarantee only holds for timestamps that do not move
126 // backwards. Timestamps that repeat or advance behave as they do for NewV7,
127 // including the embedded timestamp being incremented once the counter is exhausted.
128 // Providing a timestamp ahead of the clock therefore holds later NewV7 UUIDs at
129 // that timestamp, since going back below it would break their ordering. Times
130 // outside the range the 48-bit millisecond field can represent are pinned to the
131 // nearest end of it.
132 func NewV7AtTime(atTime time.Time) (UUID, error) {
133 return DefaultGenerator.NewV7AtTime(atTime)
134 }
135
136 // NewV8 returns a custom UUID based on user-provided data as specified in RFC 9562.
137 // The UUID is constructed from three fields:
138 // - customA: exactly 6 bytes (48 bits) - occupies bits 0-47
139 // - customB: exactly 2 bytes (only lower 12 bits used) - occupies bits 52-63
140 // - customC: exactly 8 bytes (only lower 62 bits used) - occupies bits 66-127
141 //
142 // Version (4 bits) and variant (2 bits) are set automatically.
143 // Returns ErrV8FieldLength if any field is not exactly the required length.
144 func NewV8(customA []byte, customB []byte, customC []byte) (UUID, error) {
145 return DefaultGenerator.NewV8(customA, customB, customC)
146 }
147
148 // Generator provides an interface for generating UUIDs.
149 type Generator interface {
150 NewV1() (UUID, error)
151 NewV1AtTime(time.Time) (UUID, error)
152 NewV3(ns UUID, name string) UUID
153 NewV4() (UUID, error)
154 NewV5(ns UUID, name string) UUID
155 NewV6() (UUID, error)
156 NewV6AtTime(time.Time) (UUID, error)
157 NewV7() (UUID, error)
158 NewV7AtTime(time.Time) (UUID, error)
159 NewV8([]byte, []byte, []byte) (UUID, error)
160 }
161
162 // Gen is a reference UUID generator based on the specifications laid out in
163 // RFC-9562 and DCE 1.1: Authentication and Security Services. This type
164 // satisfies the Generator interface as defined in this package.
165 //
166 // For consumers who are generating V1 UUIDs, but don't want to expose the MAC
167 // address of the node generating the UUIDs, the NewGenWithHWAF() function has been
168 // provided as a convenience. See the function's documentation for more info.
169 //
170 // The authors of this package do not feel that the majority of users will need
171 // to obfuscate their MAC address, and so we recommend using NewGen() to create
172 // a new generator.
173 type Gen struct {
174 clockSequenceOnce sync.Once
175 hardwareAddrOnce sync.Once
176 storageMutex sync.Mutex
177
178 rand io.Reader
179
180 epochFunc EpochFunc
181 hwAddrFunc HWAddrFunc
182 lastTime uint64
183 clockSequence uint16
184 hardwareAddr [6]byte
185
186 // V7 keeps its own counter state, separate from the V1/V6 clock sequence:
187 // the two measure time in different units and the counters have different
188 // usable widths.
189 v7LastRequestedMs uint64
190 v7LastMs uint64
191 v7Counter uint16
192 v7Seeded bool
193 }
194
195 // GenOption is a function type that can be used to configure a Gen generator.
196 type GenOption func(*Gen)
197
198 // interface check -- build will fail if *Gen doesn't satisfy Generator
199 var _ Generator = (*Gen)(nil)
200
201 // NewGen returns a new instance of Gen with some default values set. Most
202 // people should use this.
203 func NewGen() *Gen {
204 return NewGenWithHWAF(defaultHWAddrFunc)
205 }
206
207 // NewGenWithHWAF builds a new UUID generator with the HWAddrFunc provided. Most
208 // consumers should use NewGen() instead.
209 //
210 // This is used so that consumers can generate their own MAC addresses, for use
211 // in the generated UUIDs, if there is some concern about exposing the physical
212 // address of the machine generating the UUID.
213 //
214 // The Gen generator will only invoke the HWAddrFunc once, and cache that MAC
215 // address for all the future UUIDs generated by it. If you'd like to switch the
216 // MAC address being used, you'll need to create a new generator using this
217 // function.
218 func NewGenWithHWAF(hwaf HWAddrFunc) *Gen {
219 return NewGenWithOptions(WithHWAddrFunc(hwaf))
220 }
221
222 // NewGenWithOptions returns a new instance of Gen with the options provided.
223 // Most people should use NewGen() or NewGenWithHWAF() instead.
224 //
225 // To customize the generator, you can pass in one or more GenOption functions.
226 // For example:
227 //
228 // gen := NewGenWithOptions(
229 // WithHWAddrFunc(myHWAddrFunc),
230 // WithEpochFunc(myEpochFunc),
231 // WithRandomReader(myRandomReader),
232 // )
233 //
234 // NewGenWithOptions(WithHWAddrFunc(myHWAddrFunc)) is equivalent to calling
235 // NewGenWithHWAF(myHWAddrFunc)
236 // NewGenWithOptions() is equivalent to calling NewGen()
237 func NewGenWithOptions(opts ...GenOption) *Gen {
238 gen := &Gen{
239 epochFunc: time.Now,
240 hwAddrFunc: defaultHWAddrFunc,
241 rand: rand.Reader,
242 }
243
244 for _, opt := range opts {
245 opt(gen)
246 }
247
248 return gen
249 }
250
251 // WithHWAddrFunc is a GenOption that allows you to provide your own HWAddrFunc
252 // function.
253 // When this option is nil, the defaultHWAddrFunc is used.
254 func WithHWAddrFunc(hwaf HWAddrFunc) GenOption {
255 return func(gen *Gen) {
256 if hwaf == nil {
257 hwaf = defaultHWAddrFunc
258 }
259
260 gen.hwAddrFunc = hwaf
261 }
262 }
263
264 // WithEpochFunc is a GenOption that allows you to provide your own EpochFunc
265 // function.
266 // When this option is nil, time.Now is used.
267 func WithEpochFunc(epochf EpochFunc) GenOption {
268 return func(gen *Gen) {
269 if epochf == nil {
270 epochf = time.Now
271 }
272
273 gen.epochFunc = epochf
274 }
275 }
276
277 // WithRandomReader is a GenOption that allows you to provide your own random
278 // reader.
279 // When this option is nil, the default rand.Reader is used.
280 func WithRandomReader(reader io.Reader) GenOption {
281 return func(gen *Gen) {
282 if reader == nil {
283 reader = rand.Reader
284 }
285
286 gen.rand = reader
287 }
288 }
289
290 // NewV1 returns a UUID based on the current timestamp and MAC address.
291 func (g *Gen) NewV1() (UUID, error) {
292 return g.NewV1AtTime(g.epochFunc())
293 }
294
295 // NewV1AtTime returns a UUID based on the provided timestamp and current MAC address.
296 func (g *Gen) NewV1AtTime(atTime time.Time) (UUID, error) {
297 u := UUID{}
298
299 timeNow, clockSeq, err := g.getClockSequence(atTime)
300 if err != nil {
301 return Nil, err
302 }
303 binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
304 binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
305 binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
306 binary.BigEndian.PutUint16(u[8:], clockSeq)
307
308 hardwareAddr, err := g.getHardwareAddr()
309 if err != nil {
310 return Nil, err
311 }
312 copy(u[10:], hardwareAddr)
313
314 u.SetVersion(V1)
315 u.SetVariant(VariantRFC9562)
316
317 return u, nil
318 }
319
320 // NewV3 returns a UUID based on the MD5 hash of the namespace UUID and name.
321 func (g *Gen) NewV3(ns UUID, name string) (u UUID) {
322 h := md5.New()
323 h.Write(ns[:])
324 h.Write([]byte(name))
325 copy(u[:], h.Sum(make([]byte, 0, md5.Size)))
326
327 u.SetVersion(V3)
328 u.SetVariant(VariantRFC9562)
329
330 return u
331 }
332
333 // NewV4 returns a randomly generated UUID.
334 func (g *Gen) NewV4() (UUID, error) {
335 u := UUID{}
336 if _, err := io.ReadFull(g.rand, u[:]); err != nil {
337 return Nil, err
338 }
339 u.SetVersion(V4)
340 u.SetVariant(VariantRFC9562)
341
342 return u, nil
343 }
344
345 // NewV5 returns a UUID based on SHA-1 hash of the namespace UUID and name.
346 func (g *Gen) NewV5(ns UUID, name string) (u UUID) {
347 h := sha1.New()
348 h.Write(ns[:])
349 h.Write([]byte(name))
350 copy(u[:], h.Sum(make([]byte, 0, sha1.Size)))
351
352 u.SetVersion(V5)
353 u.SetVariant(VariantRFC9562)
354
355 return u
356 }
357
358 // NewV6 returns a k-sortable UUID based on the current timestamp and 48 bits of
359 // pseudorandom data. The timestamp in a V6 UUID is the same as V1, with the bit
360 // order being adjusted to allow the UUID to be k-sortable.
361 func (g *Gen) NewV6() (UUID, error) {
362 return g.NewV6AtTime(g.epochFunc())
363 }
364
365 // NewV6 returns a k-sortable UUID based on the provided timestamp and 48 bits of
366 // pseudorandom data. The timestamp in a V6 UUID is the same as V1, with the bit
367 // order being adjusted to allow the UUID to be k-sortable.
368 func (g *Gen) NewV6AtTime(atTime time.Time) (UUID, error) {
369 /* https://datatracker.ietf.org/doc/html/rfc9562#name-uuid-version-6
370 0 1 2 3
371 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
372 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
373 | time_high |
374 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
375 | time_mid | ver | time_low |
376 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
377 |var| clock_seq | node |
378 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
379 | node |
380 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
381 var u UUID
382
383 timeNow, _, err := g.getClockSequence(atTime)
384 if err != nil {
385 return Nil, err
386 }
387
388 binary.BigEndian.PutUint32(u[0:], uint32(timeNow>>28)) // set time_high
389 binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>12)) // set time_mid
390 binary.BigEndian.PutUint16(u[6:], uint16(timeNow&0xfff)) // set time_low (minus four version bits)
391
392 // Based on the RFC 9562 recommendation that this data be fully random and not a monotonic counter,
393 //we do NOT support batching version 6 UUIDs.
394 //set clock_seq (14 bits) and node (48 bits) pseudo-random bits (first 2 bits will be overridden)
395 if _, err = io.ReadFull(g.rand, u[8:]); err != nil {
396 return Nil, err
397 }
398
399 u.SetVersion(V6)
400
401 //overwrite first 2 bits of byte[8] for the variant
402 u.SetVariant(VariantRFC9562)
403
404 return u, nil
405 }
406
407 // NewV7 returns a k-sortable UUID based on the current millisecond-precision
408 // UNIX epoch and 74 bits of pseudorandom data. UUIDs returned by a single
409 // generator are strictly increasing; see the package-level NewV7 for the
410 // details of that guarantee.
411 func (g *Gen) NewV7() (UUID, error) {
412 return g.newV7(g.epochFunc(), true)
413 }
414
415 // NewV7AtTime returns a k-sortable UUID based on the provided
416 // millisecond-precision UNIX epoch and 74 bits of pseudorandom data. See the
417 // package-level NewV7AtTime for how the provided timestamp interacts with the
418 // monotonic counter.
419 func (g *Gen) NewV7AtTime(atTime time.Time) (UUID, error) {
420 return g.newV7(atTime, false)
421 }
422
423 // newV7 builds a V7 UUID for atTime. When clampBackwards is set, a timestamp
424 // older than the last one seen is replaced by that last timestamp so a
425 // backwards-moving clock cannot produce out-of-order UUIDs. Callers that pass a
426 // timestamp explicitly leave it unset, so that a deliberately older timestamp is
427 // encoded as given.
428 func (g *Gen) newV7(atTime time.Time, clampBackwards bool) (UUID, error) {
429 var u UUID
430 /* https://datatracker.ietf.org/doc/html/rfc9562#name-uuid-version-7
431 0 1 2 3
432 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
433 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
434 | unix_ts_ms |
435 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
436 | unix_ts_ms | ver | rand_a |
437 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
438 |var| rand_b |
439 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
440 | rand_b |
441 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
442
443 // A time outside the range the timestamp field can hold has no
444 // representation, so the nearest end of that range stands in for it rather
445 // than the unrelated value the field would otherwise wrap to.
446 atMs := min(uint64(max(atTime.UnixMilli(), 0)), maxV7Timestamp)
447
448 ms, counter, err := g.nextV7Sequence(atMs, clampBackwards)
449 if err != nil {
450 return Nil, err
451 }
452 //UUIDv7 features a 48 bit timestamp. First 32bit (4bytes) represents seconds since 1970, followed by 2 bytes for the ms granularity.
453 u[0] = byte(ms >> 40) //1-6 bytes: big-endian unsigned number of Unix epoch timestamp
454 u[1] = byte(ms >> 32)
455 u[2] = byte(ms >> 24)
456 u[3] = byte(ms >> 16)
457 u[4] = byte(ms >> 8)
458 u[5] = byte(ms)
459
460 //Support batching by using a dedicated counter in rand_a,
461 //as described in RFC 9562 section 6.2, Method 1.
462 //The 6th byte contains the version and the top 4 bits of rand_a, so the
463 //counter is 12 bits wide and fits entirely below the version nibble.
464 binary.BigEndian.PutUint16(u[6:8], counter) // set rand_a with the monotonic counter
465
466 //override first 4bits of u[6].
467 u.SetVersion(V7)
468
469 //set rand_b 64bits of pseudo-random bits (first 2 will be overridden)
470 if _, err = io.ReadFull(g.rand, u[8:16]); err != nil {
471 return Nil, err
472 }
473 //override first 2 bits of byte[8] for the variant
474 u.SetVariant(VariantRFC9562)
475
476 return u, nil
477 }
478
479 // NewV8 returns a UUID based on user-provided data as specified in RFC 9562.
480 // See the package-level NewV8 function for documentation.
481 func (g *Gen) NewV8(customA []byte, customB []byte, customC []byte) (UUID, error) {
482 var u UUID
483 /* https://datatracker.ietf.org/doc/html/rfc9562#name-uuid-version-8
484 0 1 2 3
485 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
486 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
487 | custom_a |
488 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
489 | custom_a | ver | custom_b |
490 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
491 |var| custom_c |
492 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
493 | custom_c |
494 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
495
496 // Validate input lengths
497 if len(customA) != 6 {
498 return Nil, fmt.Errorf("%w: customA must be exactly 6 bytes (48 bits), got %d", ErrV8FieldLength, len(customA))
499 }
500 if len(customB) != 2 {
501 return Nil, fmt.Errorf("%w: customB must be exactly 2 bytes (16 bits, where 12 bits are used per RFC9562), got %d", ErrV8FieldLength, len(customB))
502 }
503 if len(customC) != 8 {
504 return Nil, fmt.Errorf("%w: customC must be exactly 8 bytes (64 bits, where 62 bits are used per RFC9562), got %d", ErrV8FieldLength, len(customC))
505 }
506
507 // Copy customA (48 bits = 6 bytes) into u[0:6]
508 copy(u[0:6], customA)
509
510 // Copy customB (16 bits from 2 bytes) into u[6:8]
511 // the high 4 bits of u[6] will be overwritten by version
512 copy(u[6:8], customB)
513
514 // Copy customC (62 bits from 8 bytes) into u[8:16]
515 // The high 2 bits of u[8] will be overwritten by variant
516 copy(u[8:16], customC)
517
518 u.SetVersion(V8)
519 u.SetVariant(VariantRFC9562)
520
521 return u, nil
522 }
523
524 // nextV7Sequence returns the millisecond timestamp and the 12-bit counter to
525 // encode into a V7 UUID. The pair strictly increases from one call to the next,
526 // which is what makes the resulting UUIDs sortable in generation order.
527 //
528 // The counter is reseeded whenever the timestamp ticks over and incremented
529 // otherwise. Once it runs out of room within a tick, the timestamp is
530 // incremented ahead of the actual time and the counter reseeded, one of the two
531 // rollover strategies allowed by RFC 9562 section 6.2. The alternative, waiting
532 // for the clock to catch up, is not open to us: the timestamp can be supplied by
533 // the caller and is then under no obligation to advance.
534 func (g *Gen) nextV7Sequence(ms uint64, clampBackwards bool) (uint64, uint16, error) {
535 g.storageMutex.Lock()
536 defer g.storageMutex.Unlock()
537
538 // The counter starts over on a new tick. A provided timestamp that predates
539 // the one provided last also starts it over, since that is a request for an
540 // older UUID rather than a clock to be corrected for. The comparison for a
541 // new tick is against the timestamp last encoded, which a rollover may have
542 // pushed ahead of the one last provided.
543 if !g.v7Seeded || ms > g.v7LastMs || (!clampBackwards && ms < g.v7LastRequestedMs) {
544 counter, err := g.seedV7Counter()
545 if err != nil {
546 return 0, 0, err
547 }
548 g.v7Seeded = true
549 g.v7LastMs, g.v7LastRequestedMs, g.v7Counter = ms, ms, counter
550
551 return ms, counter, nil
552 }
553
554 // Still within the tick last encoded, either because the timestamp repeats
555 // or because it moved backwards and is being held at the last value.
556 if g.v7Counter >= maxV7Counter {
557 counter, err := g.seedV7Counter()
558 if err != nil {
559 return 0, 0, err
560 }
561 g.v7LastMs, g.v7Counter = g.v7LastMs+1, counter
562 } else {
563 g.v7Counter++
564 }
565 g.v7LastRequestedMs = ms
566
567 return g.v7LastMs, g.v7Counter, nil
568 }
569
570 // seedV7Counter draws a fresh value for the start of a timestamp tick, leaving
571 // the counter's leading bit clear as a rollover guard.
572 func (g *Gen) seedV7Counter() (uint16, error) {
573 var buf [2]byte
574 if _, err := io.ReadFull(g.rand, buf[:]); err != nil {
575 return 0, err
576 }
577
578 return binary.BigEndian.Uint16(buf[:]) & v7CounterSeedMask, nil
579 }
580
581 // getClockSequence returns the epoch and clock sequence of the provided time,
582 // used for generating V1 and V6 UUIDs.
583 //
584 // The epoch is the Coordinated Universal Time (UTC) as a count of 100-nanosecond
585 // intervals since 00:00:00.00, 15 October 1582 (the date of Gregorian reform to
586 // the Christian calendar).
587 func (g *Gen) getClockSequence(atTime time.Time) (uint64, uint16, error) {
588 var err error
589 g.clockSequenceOnce.Do(func() {
590 buf := make([]byte, 2)
591 if _, err = io.ReadFull(g.rand, buf); err != nil {
592 return
593 }
594 g.clockSequence = binary.BigEndian.Uint16(buf)
595 })
596 if err != nil {
597 return 0, 0, err
598 }
599
600 g.storageMutex.Lock()
601 defer g.storageMutex.Unlock()
602
603 timeNow := g.getEpoch(atTime)
604 // Clock didn't change since last UUID generation.
605 // Should increase clock sequence.
606 if timeNow <= g.lastTime {
607 g.clockSequence++
608 }
609 g.lastTime = timeNow
610
611 return timeNow, g.clockSequence, nil
612 }
613
614 // Returns the hardware address.
615 func (g *Gen) getHardwareAddr() ([]byte, error) {
616 var err error
617 g.hardwareAddrOnce.Do(func() {
618 var hwAddr net.HardwareAddr
619 if hwAddr, err = g.hwAddrFunc(); err == nil {
620 copy(g.hardwareAddr[:], hwAddr)
621 return
622 }
623
624 // Initialize hardwareAddr randomly in case
625 // of real network interfaces absence.
626 if _, err = io.ReadFull(g.rand, g.hardwareAddr[:]); err != nil {
627 return
628 }
629 // Set multicast bit as recommended by RFC-9562
630 g.hardwareAddr[0] |= 0x01
631 })
632 if err != nil {
633 return []byte{}, err
634 }
635 return g.hardwareAddr[:], nil
636 }
637
638 // Returns the difference between UUID epoch (October 15, 1582)
639 // and the provided time in 100-nanosecond intervals.
640 func (g *Gen) getEpoch(atTime time.Time) uint64 {
641 return epochStart + uint64(atTime.UnixNano()/100)
642 }
643
644 var netInterfaces = net.Interfaces
645
646 // Returns the hardware address.
647 func defaultHWAddrFunc() (net.HardwareAddr, error) {
648 ifaces, err := netInterfaces()
649 if err != nil {
650 return []byte{}, err
651 }
652 for _, iface := range ifaces {
653 if len(iface.HardwareAddr) >= 6 {
654 return iface.HardwareAddr, nil
655 }
656 }
657 return []byte{}, ErrNoHwAddressFound
658 }