forked from weaveworks/mesh
-
Notifications
You must be signed in to change notification settings - Fork 1
/
peer_name_hash.go
58 lines (46 loc) · 1.44 KB
/
peer_name_hash.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
// +build peer_name_hash
package mesh
// Let peer names be SHA256 hashes of anything, provided they are unique.
import (
"crypto/sha256"
"encoding/hex"
)
// PeerName must be globally unique and usable as a map key.
type PeerName string
const (
// PeerNameFlavour is the type of peer names we use.
PeerNameFlavour = "hash"
// NameSize is the number of bytes in a peer name.
NameSize = sha256.Size >> 1
// UnknownPeerName is used as a sentinel value.
UnknownPeerName = PeerName("")
)
// PeerNameFromUserInput parses PeerName from a user-provided string.
func PeerNameFromUserInput(userInput string) (PeerName, error) {
// fixed-length identity
nameByteAry := sha256.Sum256([]byte(userInput))
return PeerNameFromBin(nameByteAry[:NameSize]), nil
}
// PeerNameFromString parses PeerName from a generic string.
func PeerNameFromString(nameStr string) (PeerName, error) {
if _, err := hex.DecodeString(nameStr); err != nil {
return UnknownPeerName, err
}
return PeerName(nameStr), nil
}
// PeerNameFromBin parses PeerName from a byte slice.
func PeerNameFromBin(nameByte []byte) PeerName {
return PeerName(hex.EncodeToString(nameByte))
}
// bytes encodes PeerName as a byte slice.
func (name PeerName) bytes() []byte {
res, err := hex.DecodeString(string(name))
if err != nil {
panic("unable to decode name to bytes: " + name)
}
return res
}
// String encodes PeerName as a string.
func (name PeerName) String() string {
return string(name)
}