-
Notifications
You must be signed in to change notification settings - Fork 21
/
peer.go
106 lines (87 loc) · 2.34 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"net"
"time"
"github.com/btcsuite/btcd/wire"
)
type Peer struct {
client *Client
conn net.Conn
nonce uint64 // Nonce we're sending to the peer
pver uint32 // Negotiated ProtocolVersion
Address string
UserAgent string
ProtocolVersion int32
ConnectTimeout time.Duration // For the connect phase (can be overridden)
}
func NewPeer(client *Client, address string) *Peer {
p := Peer{
client: client,
pver: client.pver,
Address: address,
ConnectTimeout: time.Duration(20 * time.Second),
}
return &p
}
func (p *Peer) Connect() error {
if p.conn != nil {
return fmt.Errorf("Peer already connected, can't connect again.")
}
conn, err := net.DialTimeout("tcp", p.Address, p.ConnectTimeout)
if err != nil {
return err
}
p.conn = conn
return nil
}
func (p *Peer) Disconnect() {
p.conn.Close()
logger.Debugf("[%s] Closed.", p.Address)
}
func (p *Peer) Handshake() error {
if p.conn == nil {
return fmt.Errorf("Peer is not connected, can't handshake.")
}
logger.Debugf("[%s] Starting handshake.", p.Address)
nonce, err := wire.RandomUint64()
if err != nil {
return err
}
p.nonce = nonce
msgVersion, err := wire.NewMsgVersionFromConn(p.conn, p.nonce, 0)
msgVersion.UserAgent = p.client.userAgent
msgVersion.DisableRelayTx = true
if err := p.WriteMessage(msgVersion); err != nil {
return err
}
// Read the response version.
msg, _, err := p.ReadMessage()
if err != nil {
return err
}
vmsg, ok := msg.(*wire.MsgVersion)
if !ok {
return fmt.Errorf("Did not receive version message: %T", vmsg)
}
p.ProtocolVersion = vmsg.ProtocolVersion
p.UserAgent = vmsg.UserAgent
// Negotiate protocol version.
if uint32(vmsg.ProtocolVersion) < p.pver {
p.pver = uint32(vmsg.ProtocolVersion)
}
logger.Debugf("[%s] -> Version: %s", p.Address, vmsg.UserAgent)
// Normally we'd check if vmsg.Nonce == p.nonce but the crawler does not
// accept external connections so we skip it.
// Send verack.
if err := p.WriteMessage(wire.NewMsgVerAck()); err != nil {
return err
}
return nil
}
func (p *Peer) WriteMessage(msg wire.Message) error {
return wire.WriteMessage(p.conn, msg, p.pver, p.client.btcnet)
}
func (p *Peer) ReadMessage() (wire.Message, []byte, error) {
return wire.ReadMessage(p.conn, p.pver, p.client.btcnet)
}