forked from aergoio/aergo
/
handshake.go
226 lines (197 loc) · 6.52 KB
/
handshake.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
/**
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package p2p
import (
"bufio"
"encoding/binary"
"fmt"
"io"
"time"
"github.com/aergoio/aergo-lib/log"
"github.com/aergoio/aergo/p2p/p2pcommon"
"github.com/aergoio/aergo/types"
"github.com/libp2p/go-libp2p-peer"
)
// HSHandlerFactory is creator of HSHandler
type HSHandlerFactory interface {
CreateHSHandler(outbound bool, pm p2pcommon.PeerManager, actor p2pcommon.ActorService, log *log.Logger, pid peer.ID) HSHandler
}
// HSHandler will do handshake with remote peer
type HSHandler interface {
// Handle peer handshake till ttl, and return msgrw for this connection, and status of remote peer.
Handle(r io.Reader, w io.Writer, ttl time.Duration) (p2pcommon.MsgReadWriter, *types.Status, error)
}
type InboundHSHandler struct {
*PeerHandshaker
}
func (ih *InboundHSHandler) Handle(r io.Reader, w io.Writer, ttl time.Duration) (p2pcommon.MsgReadWriter, *types.Status, error) {
return ih.handshakeInboundPeerTimeout(r, w, ttl)
}
type OutboundHSHandler struct {
*PeerHandshaker
}
func (oh *OutboundHSHandler) Handle(r io.Reader, w io.Writer, ttl time.Duration) (p2pcommon.MsgReadWriter, *types.Status, error) {
return oh.handshakeOutboundPeerTimeout(r, w, ttl)
}
// PeerHandshaker works to handshake to just connected peer, it detect chain networks
// and protocol versions, and then select InnerHandshaker for that protocol version.
type PeerHandshaker struct {
pm p2pcommon.PeerManager
actorServ p2pcommon.ActorService
logger *log.Logger
peerID peer.ID
// check if is it adhoc
localChainID *types.ChainID
remoteStatus *types.Status
}
// InnerHandshaker do handshake work and msgreadwriter for a protocol version
type innerHandshaker interface {
doForOutbound() (*types.Status, error)
doForInbound() (*types.Status, error)
GetMsgRW() p2pcommon.MsgReadWriter
}
type hsResult struct {
rw p2pcommon.MsgReadWriter
statusMsg *types.Status
err error
}
func newHandshaker(pm p2pcommon.PeerManager, actor p2pcommon.ActorService, log *log.Logger, chainID *types.ChainID, peerID peer.ID) *PeerHandshaker {
return &PeerHandshaker{pm: pm, actorServ: actor, logger: log, localChainID: chainID, peerID: peerID}
}
func (h *PeerHandshaker) handshakeOutboundPeerTimeout(r io.Reader, w io.Writer, ttl time.Duration) (p2pcommon.MsgReadWriter, *types.Status, error) {
ret, err := runFuncTimeout(func(doneChan chan<- interface{}) {
rw, statusMsg, err := h.handshakeOutboundPeer(r, w)
doneChan <- &hsResult{rw: rw, statusMsg: statusMsg, err: err}
}, ttl)
if err != nil {
return nil, nil, err
}
return ret.(*hsResult).rw, ret.(*hsResult).statusMsg, ret.(*hsResult).err
}
func (h *PeerHandshaker) handshakeInboundPeerTimeout(r io.Reader, w io.Writer, ttl time.Duration) (p2pcommon.MsgReadWriter, *types.Status, error) {
ret, err := runFuncTimeout(func(doneChan chan<- interface{}) {
rw, statusMsg, err := h.handshakeInboundPeer(r, w)
doneChan <- &hsResult{rw: rw, statusMsg: statusMsg, err: err}
}, ttl)
if err != nil {
return nil, nil, err
}
return ret.(*hsResult).rw, ret.(*hsResult).statusMsg, ret.(*hsResult).err
}
type targetFunc func(chan<- interface{})
func runFuncTimeout(m targetFunc, ttl time.Duration) (interface{}, error) {
done := make(chan interface{})
go m(done)
select {
case hsResult := <-done:
return hsResult, nil
case <-time.NewTimer(ttl).C:
return nil, TimeoutError
}
}
func (h *PeerHandshaker) handshakeOutboundPeer(r io.Reader, w io.Writer) (p2pcommon.MsgReadWriter, *types.Status, error) {
bufReader, bufWriter := bufio.NewReader(r), bufio.NewWriter(w)
// send initial hsmessage
hsHeader := HSHeader{Magic: p2pcommon.MAGICTest, Version: p2pcommon.P2PVersion030}
sent, err := bufWriter.Write(hsHeader.Marshal())
if err != nil {
return nil, nil, err
}
if sent != len(hsHeader.Marshal()) {
return nil, nil, fmt.Errorf("transport error")
}
// continue to handshake with innerHandshaker
innerHS, err := h.selectProtocolVersion(hsHeader, bufReader, bufWriter)
if err != nil {
return nil, nil, err
}
status, err := innerHS.doForOutbound()
h.remoteStatus = status
return innerHS.GetMsgRW(), status, err
}
func (h *PeerHandshaker) handshakeInboundPeer(r io.Reader, w io.Writer) (p2pcommon.MsgReadWriter, *types.Status, error) {
var hsHeader HSHeader
bufReader, bufWriter := bufio.NewReader(r), bufio.NewWriter(w)
// wait initial hsmessage
headBuf := make([]byte, 8)
read, err := h.readToLen(bufReader, headBuf, 8)
if err != nil {
return nil, nil, err
}
if read != 8 {
return nil, nil, fmt.Errorf("transport error")
}
hsHeader.Unmarshal(headBuf)
// continue to handshake with innerHandshaker
innerHS, err := h.selectProtocolVersion(hsHeader, bufReader, bufWriter)
if err != nil {
return nil, nil, err
}
status, err := innerHS.doForInbound()
// send hsresponse
h.remoteStatus = status
return innerHS.GetMsgRW(), status, err
}
func (h *PeerHandshaker) readToLen(rd io.Reader, bf []byte, max int) (int, error) {
remain := max
offset := 0
for remain > 0 {
read, err := rd.Read(bf[offset:])
if err != nil {
return offset, err
}
remain -= read
offset += read
}
return offset, nil
}
func createStatusMsg(pm p2pcommon.PeerManager, actorServ p2pcommon.ActorService, chainID *types.ChainID) (*types.Status, error) {
// find my best block
bestBlock, err := actorServ.GetChainAccessor().GetBestBlock()
if err != nil {
return nil, err
}
selfAddr := pm.SelfMeta().ToPeerAddress()
chainIDbytes, err := chainID.Bytes()
if err != nil {
return nil, err
}
// create message data
statusMsg := &types.Status{
Sender: &selfAddr,
ChainID: chainIDbytes,
BestBlockHash: bestBlock.BlockHash(),
BestHeight: bestBlock.GetHeader().GetBlockNo(),
NoExpose: pm.SelfMeta().Hidden,
}
return statusMsg, nil
}
func (h *PeerHandshaker) selectProtocolVersion(head HSHeader, r *bufio.Reader, w *bufio.Writer) (innerHandshaker, error) {
switch head.Version {
case p2pcommon.P2PVersion030:
v030 := newV030StateHS(h.pm, h.actorServ, h.logger, h.localChainID, h.peerID, r, w)
return v030, nil
default:
return nil, fmt.Errorf("not supported version")
}
}
func (h *PeerHandshaker) checkProtocolVersion(versionStr string) error {
// TODO modify interface and put check code here
return nil
}
type HSHeader struct {
Magic uint32
Version uint32
}
func (h HSHeader) Marshal() []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint32(b, h.Magic)
binary.BigEndian.PutUint32(b[4:], h.Version)
return b
}
func (h *HSHeader) Unmarshal(b []byte) {
h.Magic = binary.BigEndian.Uint32(b)
h.Version = binary.BigEndian.Uint32(b[4:])
}