-
Notifications
You must be signed in to change notification settings - Fork 669
/
node_id.go
86 lines (67 loc) · 1.82 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package ids
import (
"bytes"
"crypto/x509"
"fmt"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/hashing"
)
const NodeIDPrefix = "NodeID-"
var (
EmptyNodeID = NodeID{}
_ utils.Sortable[NodeID] = NodeID{}
)
type NodeID ShortID
func (id NodeID) String() string {
return ShortID(id).PrefixedString(NodeIDPrefix)
}
func (id NodeID) Bytes() []byte {
return id[:]
}
func (id NodeID) MarshalJSON() ([]byte, error) {
return []byte("\"" + id.String() + "\""), nil
}
func (id NodeID) MarshalText() ([]byte, error) {
return []byte(id.String()), nil
}
func (id *NodeID) UnmarshalJSON(b []byte) error {
str := string(b)
if str == nullStr { // If "null", do nothing
return nil
} else if len(str) <= 2+len(NodeIDPrefix) {
return fmt.Errorf("expected NodeID length to be > %d", 2+len(NodeIDPrefix))
}
lastIndex := len(str) - 1
if str[0] != '"' || str[lastIndex] != '"' {
return errMissingQuotes
}
var err error
*id, err = NodeIDFromString(str[1:lastIndex])
return err
}
func (id *NodeID) UnmarshalText(text []byte) error {
return id.UnmarshalJSON(text)
}
func (id NodeID) Less(other NodeID) bool {
return bytes.Compare(id[:], other[:]) == -1
}
// ToNodeID attempt to convert a byte slice into a node id
func ToNodeID(bytes []byte) (NodeID, error) {
nodeID, err := ToShortID(bytes)
return NodeID(nodeID), err
}
func NodeIDFromCert(cert *x509.Certificate) NodeID {
return hashing.ComputeHash160Array(
hashing.ComputeHash256(cert.Raw),
)
}
// NodeIDFromString is the inverse of NodeID.String()
func NodeIDFromString(nodeIDStr string) (NodeID, error) {
asShort, err := ShortFromPrefixedString(nodeIDStr, NodeIDPrefix)
if err != nil {
return NodeID{}, err
}
return NodeID(asShort), nil
}