-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.go
51 lines (41 loc) · 1 KB
/
node.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
package brahms
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"net"
"strconv"
)
// NID is a node id
type NID [32]byte
func (id NID) String() string { return hex.EncodeToString(id[:2]) }
// Bytes returns the id as a byte slice
func (id NID) Bytes() []byte {
return id[:]
}
// IsNil returns whether the is its zero value
func (id NID) IsNil() bool {
return id == NID{}
}
// N describes a node by its ip info
func N(ip string, port uint16) (n *Node) {
return &Node{IP: net.ParseIP(ip), Port: port}
}
// Node describes how to reach another peer in the network
type Node struct {
IP net.IP
Port uint16
}
// Hash a node description into an ip
func (n *Node) Hash() (id NID) {
pb := make([]byte, 2)
binary.BigEndian.PutUint16(pb, n.Port)
return NID(sha256.Sum256(append(n.IP, pb...)))
}
func (n *Node) String() string {
return n.IP.String() + ":" + strconv.Itoa(int(n.Port))
}
// IsZero returns whether the node is a zero value
func (n Node) IsZero() bool {
return (n.IP == nil && n.Port == 0)
}