-
Notifications
You must be signed in to change notification settings - Fork 13
/
node_id.go
66 lines (53 loc) · 1.77 KB
/
node_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
package types
import (
"encoding/hex"
"errors"
"fmt"
"regexp"
"strings"
"github.com/dashpay/tenderdash/crypto"
)
// NodeIDByteLength is the length of a crypto.Address. Currently only 20.
// FIXME: support other length addresses?
const NodeIDByteLength = crypto.AddressSize
// reNodeID is a regexp for valid node IDs.
var reNodeID = regexp.MustCompile(`^[0-9a-f]{40}$`)
// NodeID is a hex-encoded crypto.Address. It must be lowercased
// (for uniqueness) and of length 2*NodeIDByteLength.
type NodeID string
// NewNodeID returns a lowercased (normalized) NodeID, or errors if the
// node ID is invalid.
func NewNodeID(nodeID string) (NodeID, error) {
n := NodeID(strings.ToLower(nodeID))
return n, n.Validate()
}
// IDAddressString returns id@hostPort. It strips the leading
// protocol from protocolHostPort if it exists.
func (id NodeID) AddressString(protocolHostPort string) string {
return fmt.Sprintf("%s@%s", id, removeProtocolIfDefined(protocolHostPort))
}
// NodeIDFromPubKey creates a node ID from a given PubKey address.
func NodeIDFromPubKey(pubKey crypto.PubKey) NodeID {
return NodeID(hex.EncodeToString(pubKey.Address()))
}
// Bytes converts the node ID to its binary byte representation.
func (id NodeID) Bytes() ([]byte, error) {
bz, err := hex.DecodeString(string(id))
if err != nil {
return nil, fmt.Errorf("invalid node ID encoding: %w", err)
}
return bz, nil
}
// Validate validates the NodeID.
func (id NodeID) Validate() error {
switch {
case len(id) == 0:
return errors.New("empty node ID")
case len(id) != 2*NodeIDByteLength:
return fmt.Errorf("invalid node ID length %d, expected %d", len(id), 2*NodeIDByteLength)
case !reNodeID.MatchString(string(id)):
return fmt.Errorf("node ID can only contain lowercased hex digits")
default:
return nil
}
}