-
Notifications
You must be signed in to change notification settings - Fork 4
/
peer.go
83 lines (66 loc) · 1.72 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
package peer
import (
"io"
"net"
"sync"
"github.com/vulpemventures/neutrino-elements/pkg/protocol"
)
// PeerID is peer IP address.
type PeerID string
// Peer describes a network's node.
type Peer interface {
// ID returns peer ID. Must be unique in the network.
ID() PeerID
// Connection returns peer connection, using to send and receive Elements messages.
Connection() io.ReadWriteCloser
// Addr returns the Network Address of the peer
Addr() *protocol.Addr
// PeersTip returns current tip block height
PeersTip() uint32
// SetPeersTip sets the block height tip of the peer
SetPeersTip(startBlockHeight uint32)
}
type elementsPeer struct {
networkAddress *protocol.Addr
tcpConnection net.Conn
startBlockHeight uint32
//used to synchronize access to the peers startBlockHeight
m *sync.RWMutex
}
func NewElementsPeer(peerAddr string) (Peer, error) {
conn, err := net.Dial("tcp", peerAddr)
if err != nil {
return nil, err
}
netAddress, err := protocol.ParseNodeAddr(peerAddr)
if err != nil {
return nil, err
}
return &elementsPeer{
networkAddress: netAddress,
tcpConnection: conn,
m: new(sync.RWMutex),
}, nil
}
func (e *elementsPeer) ID() PeerID {
return PeerID(e.tcpConnection.LocalAddr().String())
}
func (e *elementsPeer) Connection() io.ReadWriteCloser {
return e.tcpConnection
}
func (e *elementsPeer) Addr() *protocol.Addr {
return e.networkAddress
}
func (e *elementsPeer) PeersTip() uint32 {
e.m.RLock()
defer e.m.RUnlock()
return e.startBlockHeight
}
func (e *elementsPeer) SetPeersTip(startBlockHeight uint32) {
e.m.Lock()
defer e.m.Unlock()
e.startBlockHeight = startBlockHeight
}
func (e *elementsPeer) String() string {
return e.tcpConnection.RemoteAddr().String()
}