/
handshakev2.go
240 lines (219 loc) · 7.09 KB
/
handshakev2.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package p2p
import (
"context"
"encoding/binary"
"fmt"
"io"
"time"
"github.com/aergoio/aergo-lib/log"
"github.com/aergoio/aergo/v2/p2p/p2pcommon"
"github.com/aergoio/aergo/v2/p2p/p2putil"
"github.com/aergoio/aergo/v2/types"
)
// baseWireHandshaker works to handshake to just connected peer, it detect chain networks
// and protocol versions, and then select InnerHandshaker for that protocol version.
type baseWireHandshaker struct {
pm p2pcommon.PeerManager
actor p2pcommon.ActorService
verM p2pcommon.VersionedManager
logger *log.Logger
peerID types.PeerID
// check if is it ad hoc
localChainID *types.ChainID
remoteStatus *types.Status
result p2pcommon.HandshakeResult
remoteMeta p2pcommon.PeerMeta
remoteCert []*p2pcommon.AgentCertificateV1
}
type InboundWireHandshaker struct {
baseWireHandshaker
}
func NewInboundHSHandler(pm p2pcommon.PeerManager, actor p2pcommon.ActorService, verManager p2pcommon.VersionedManager, log *log.Logger, chainID *types.ChainID, peerID types.PeerID) p2pcommon.HSHandler {
return &InboundWireHandshaker{baseWireHandshaker{pm: pm, actor: actor, verM: verManager, logger: log, localChainID: chainID, peerID: peerID}}
}
func (h *InboundWireHandshaker) Handle(s io.ReadWriteCloser, ttl time.Duration) (*p2pcommon.HandshakeResult, error) {
ctx, cancel := context.WithTimeout(context.Background(), ttl)
defer cancel()
return h.handleInboundPeer(ctx, s)
}
func (h *InboundWireHandshaker) handleInboundPeer(ctx context.Context, rwc io.ReadWriteCloser) (*p2pcommon.HandshakeResult, error) {
// wait initial hs message
hsReq, err := h.readWireHSRequest(rwc)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// go on
}
if err != nil {
return h.writeErrAndReturn(err, p2pcommon.HSCodeWrongHSReq, rwc)
}
// check magic
if hsReq.Magic != p2pcommon.MAGICMain {
return h.writeErrAndReturn(fmt.Errorf("wrong magic %v", hsReq.Magic), p2pcommon.HSCodeWrongHSReq, rwc)
}
// continue to handshake with VersionedHandshaker
bestVer := h.verM.FindBestP2PVersion(hsReq.Versions)
if bestVer == p2pcommon.P2PVersionUnknown {
return h.writeErrAndReturn(fmt.Errorf("no matched p2p version for %v", hsReq.Versions), p2pcommon.HSCodeNoMatchedVersion, rwc)
} else {
h.logger.Debug().Stringer(p2putil.LogPeerID, types.LogPeerShort(h.peerID)).Str("version", bestVer.String()).Msg("Responding best p2p version")
resp := p2pcommon.HSHeadResp{Magic: hsReq.Magic, RespCode: bestVer.Uint32()}
err = h.writeWireHSResponse(resp, rwc)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// go on
}
if err != nil {
return nil, err
}
}
innerHS, err := h.verM.GetVersionedHandshaker(bestVer, h.peerID, rwc)
if err != nil {
return nil, err
}
return innerHS.DoForInbound(ctx)
}
type OutboundWireHandshaker struct {
baseWireHandshaker
}
func NewOutboundHSHandler(pm p2pcommon.PeerManager, actor p2pcommon.ActorService, verManager p2pcommon.VersionedManager, log *log.Logger, chainID *types.ChainID, peerID types.PeerID) p2pcommon.HSHandler {
return &OutboundWireHandshaker{baseWireHandshaker{pm: pm, actor: actor, verM: verManager, logger: log, localChainID: chainID, peerID: peerID}}
}
func (h *OutboundWireHandshaker) Handle(s io.ReadWriteCloser, ttl time.Duration) (*p2pcommon.HandshakeResult, error) {
ctx, cancel := context.WithTimeout(context.Background(), ttl)
defer cancel()
return h.handleOutboundPeer(ctx, s)
}
func (h *OutboundWireHandshaker) handleOutboundPeer(ctx context.Context, rwc io.ReadWriteCloser) (*p2pcommon.HandshakeResult, error) {
// send initial hs message
versions := p2pcommon.AttemptingOutboundVersions
hsHeader := p2pcommon.HSHeadReq{Magic: p2pcommon.MAGICMain, Versions: versions}
err := h.writeWireHSRequest(hsHeader, rwc)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// go on
}
if err != nil {
return nil, err
}
// read response
respHeader, err := h.readWireHSResp(rwc)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// go on
}
if err != nil {
return nil, err
}
// check response
if respHeader.Magic != hsHeader.Magic {
return nil, fmt.Errorf("remote peer failed: %v", respHeader.RespCode)
}
bestVersion := p2pcommon.P2PVersion(respHeader.RespCode)
h.logger.Debug().Stringer(p2putil.LogPeerID, types.LogPeerShort(h.peerID)).Str("version", bestVersion.String()).Msg("Responded best p2p version")
// continue to handshake with VersionedHandshaker
innerHS, err := h.verM.GetVersionedHandshaker(bestVersion, h.peerID, rwc)
if err != nil {
return nil, err
}
return innerHS.DoForOutbound(ctx)
}
func (h *baseWireHandshaker) writeWireHSRequest(hsHeader p2pcommon.HSHeadReq, wr io.Writer) (err error) {
bytes := hsHeader.Marshal()
sent, err := wr.Write(bytes)
if err != nil {
return
}
if sent != len(bytes) {
return fmt.Errorf("wrong sent size")
}
return
}
func (h *baseWireHandshaker) readWireHSRequest(rd io.Reader) (header p2pcommon.HSHeadReq, err error) {
buf := make([]byte, p2pcommon.HSMagicLength)
readn, err := p2putil.ReadToLen(rd, buf[:p2pcommon.HSMagicLength])
if err != nil {
return
}
if readn != p2pcommon.HSMagicLength {
err = fmt.Errorf("transport error")
return
}
header.Magic = binary.BigEndian.Uint32(buf)
readn, err = p2putil.ReadToLen(rd, buf[:p2pcommon.HSVerCntLength])
if err != nil {
return
}
if readn != p2pcommon.HSVerCntLength {
err = fmt.Errorf("transport error")
return
}
verCount := int(binary.BigEndian.Uint32(buf))
if verCount <= 0 || verCount > p2pcommon.HSMaxVersionCnt {
err = fmt.Errorf("invalid version count: %d", verCount)
return
}
versions := make([]p2pcommon.P2PVersion, verCount)
for i := 0; i < verCount; i++ {
readn, err = p2putil.ReadToLen(rd, buf[:p2pcommon.HSVersionLength])
if err != nil {
return
}
if readn != p2pcommon.HSVersionLength {
err = fmt.Errorf("transport error")
return
}
versions[i] = p2pcommon.P2PVersion(binary.BigEndian.Uint32(buf))
}
header.Versions = versions
return
}
func (h *baseWireHandshaker) writeWireHSResponse(hsHeader p2pcommon.HSHeadResp, wr io.Writer) (err error) {
bytes := hsHeader.Marshal()
sent, err := wr.Write(bytes)
if err != nil {
return
}
if sent != len(bytes) {
return fmt.Errorf("wrong sent size")
}
return
}
func (h *baseWireHandshaker) writeErrAndReturn(err error, errCode uint32, wr io.Writer) (*p2pcommon.HandshakeResult, error) {
errResp := p2pcommon.HSHeadResp{Magic: p2pcommon.HSError, RespCode: errCode}
_ = h.writeWireHSResponse(errResp, wr)
return nil, err
}
func (h *baseWireHandshaker) readWireHSResp(rd io.Reader) (header p2pcommon.HSHeadResp, err error) {
bytebuf := make([]byte, p2pcommon.HSMagicLength)
readn, err := p2putil.ReadToLen(rd, bytebuf[:p2pcommon.HSMagicLength])
if err != nil {
return
}
if readn != p2pcommon.HSMagicLength {
err = fmt.Errorf("transport error")
return
}
header.Magic = binary.BigEndian.Uint32(bytebuf)
readn, err = p2putil.ReadToLen(rd, bytebuf[:p2pcommon.HSVersionLength])
if err != nil {
return
}
if readn != p2pcommon.HSVersionLength {
err = fmt.Errorf("transport error")
return
}
header.RespCode = binary.BigEndian.Uint32(bytebuf)
return
}