-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.go
86 lines (69 loc) · 1.75 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
74
75
76
77
78
79
80
81
82
83
84
85
86
// Package peer maintains the peer related information such as the set
// of know peers and their status.
package peer
import (
"sync"
)
// Peer represents information about a Node in the network.
type Peer struct {
Host string
}
// New contructs a new info value.
func New(host string) Peer {
return Peer{
Host: host,
}
}
// Match validates if the specified host matches this node.
func (p Peer) Match(host string) bool {
return p.Host == host
}
// =============================================================================
// PeerStatus represents information about the status
// of any given peer.
type PeerStatus struct {
LatestBlockHash string `json:"latest_block_hash"`
LatestBlockNumber uint64 `json:"latest_block_number"`
KnownPeers []Peer `json:"known_peers"`
}
// =============================================================================
// PeerSet represents the data representation to maintain a set of known peers.
type PeerSet struct {
mu sync.RWMutex
set map[Peer]struct{}
}
// NewPeerSet constructs a new info set to manage node peer information.
func NewPeerSet() *PeerSet {
return &PeerSet{
set: make(map[Peer]struct{}),
}
}
// Add adds a new node to the set.
func (ps *PeerSet) Add(peer Peer) bool {
ps.mu.Lock()
defer ps.mu.Unlock()
_, exists := ps.set[peer]
if !exists {
ps.set[peer] = struct{}{}
return true
}
return false
}
// Remove removes a node from the set.
func (ps *PeerSet) Remove(peer Peer) {
ps.mu.Lock()
defer ps.mu.Unlock()
delete(ps.set, peer)
}
// Copy returns a list of the known peers.
func (ps *PeerSet) Copy(host string) []Peer {
ps.mu.RLock()
defer ps.mu.RUnlock()
var peers []Peer
for peer := range ps.set {
if !peer.Match(host) {
peers = append(peers, peer)
}
}
return peers
}