This repository has been archived by the owner on Jan 23, 2022. It is now read-only.
/
peer_id.go
81 lines (72 loc) · 2.11 KB
/
peer_id.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package ident
import (
"fmt"
"math"
"math/rand"
"time"
)
// PeerID uniquely identifies a peer within a network.
//
// Peer IDs contain a clock component and a random 16-bit integer component.
// They are rendered in hexadecimal encoding, with a hypen separating the two
// components, such as "58AEE146-191C".
//
// For a given network, the random component is guaranteed to be unique at any
// given time; and, assuming a stable system clock it is highly likely that the
// ID is unique across time. This makes peer IDs useful for tracking peer
// behavior in logs.
//
// All other IDs generated by a peer, such as SessionID and MessageID are
// derived from the peer ID.
type PeerID struct {
// Clock is a time-based portion of the ID, this helps uniquely identify
// peer IDs over longer time-scales, such as when looking back through
// logs, etc.
Clock uint64
// Rand is a unique number identifying this peer within a network at any
// given time. It is generated randomly and then reserved when the peer
// connects to the network.
Rand uint16
}
// NewPeerID creates a new ID struct. There is no guarantee that the ID is
// unique until the peer is connected to a network.
func NewPeerID() PeerID {
return PeerID{
uint64(time.Now().Unix()),
uint16(rand.Intn(math.MaxUint16-1)) + 1,
}
}
// Validate returns an error if the peer ID is not valid.
//
// Neither the Clock nor Rand component may be zero.
func (id PeerID) Validate() error {
if id.Clock != 0 && id.Rand != 0 {
return nil
}
return fmt.Errorf("peer ID %s is invalid", id)
}
// Session returns a new session ID for this peer with seq as the sequence
// number.
func (id PeerID) Session(seq uint32) SessionID {
return SessionID{
Peer: id,
Seq: seq,
}
}
// ShortString returns a string representation of the peer ID without the clock
// component (e.g. "191C").
func (id PeerID) ShortString() string {
return fmt.Sprintf(
"%04X",
id.Rand,
)
}
// String returns a string representation including both the Clock and Rand
// components (e.g. "58AEE146-191C").
func (id PeerID) String() string {
return fmt.Sprintf(
"%X-%04X",
id.Clock,
id.Rand,
)
}