-
Notifications
You must be signed in to change notification settings - Fork 2
/
peer.go
73 lines (59 loc) · 1.6 KB
/
peer.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
package p2p
import (
"bytes"
"encoding/base64"
"errors"
)
const (
// PeerIDSize is the size of a PeerID in bytes
PeerIDSize = 32
// Base64Alphabet is used when encoding IDs as base64 strings.
// It is a URL and filepath safe encoding, which maintains ordering.
Base64Alphabet = "-0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "_" + "abcdefghijklmnopqrstuvwxyz"
)
// PeerID is a identifier cryptographically related to a public key
type PeerID [32]byte
// Fingerprinter is the type of functions which create PeerIDs from PublicKeys
type Fingerprinter[PublicKey any] func(PublicKey) PeerID
func (pid PeerID) String() string {
return pid.Base64String()
}
func (pid PeerID) Base64String() string {
data, _ := pid.MarshalText()
return string(data)
}
var enc = base64.NewEncoding(Base64Alphabet).WithPadding(base64.NoPadding)
func (pid PeerID) MarshalText() ([]byte, error) {
data := make([]byte, enc.EncodedLen(len(pid)))
enc.Encode(data, pid[:])
return data, nil
}
func (pid *PeerID) UnmarshalText(data []byte) error {
if len(data) != enc.EncodedLen(len(pid)) {
return errors.New("data is wrong length")
}
enc.Decode(pid[:], data)
return nil
}
func (p PeerID) Compare(q PeerID) int {
return bytes.Compare(p[:], q[:])
}
func (p PeerID) Lt(q PeerID) bool {
return p.Compare(q) < 0
}
func (p PeerID) IsZero() bool {
return p == (PeerID{})
}
type HasPeerID interface {
Addr
GetPeerID() PeerID
}
func ExtractPeerID(x Addr) PeerID {
if hasPeerID, ok := x.(HasPeerID); ok {
return hasPeerID.GetPeerID()
}
if unwrap, ok := x.(UnwrapAddr); ok {
return ExtractPeerID(unwrap.Unwrap())
}
return PeerID{}
}