forked from aergoio/aergo
/
v200handshake.go
341 lines (295 loc) · 10.6 KB
/
v200handshake.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package v200
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/aergoio/aergo/internal/enc"
"github.com/aergoio/aergo/internal/network"
"github.com/aergoio/aergo/p2p/p2pkey"
v030 "github.com/aergoio/aergo/p2p/v030"
"io"
"time"
"github.com/aergoio/aergo-lib/log"
"github.com/aergoio/aergo/p2p/p2pcommon"
"github.com/aergoio/aergo/p2p/p2putil"
"github.com/aergoio/aergo/types"
)
var (
ErrInvalidAgentStatus = errors.New("invalid agent status")
ErrInvalidCertIssue = errors.New("invalid issue request")
)
// V200Handshaker exchange status data over protocol version 1.0.0
type V200Handshaker struct {
is p2pcommon.InternalService
cm p2pcommon.CertificateManager
vm p2pcommon.VersionedManager
selfMeta p2pcommon.PeerMeta
logger *log.Logger
peerID types.PeerID
msgRW p2pcommon.MsgReadWriter
localGenesisHash []byte
remoteMeta p2pcommon.PeerMeta
remoteCerts []*p2pcommon.AgentCertificateV1
remoteHash types.BlockID
remoteNo types.BlockNo
}
var _ p2pcommon.VersionedHandshaker = (*V200Handshaker)(nil)
func (h *V200Handshaker) GetMsgRW() p2pcommon.MsgReadWriter {
return h.msgRW
}
func NewV200VersionedHS(is p2pcommon.InternalService, log *log.Logger, vm p2pcommon.VersionedManager, cm p2pcommon.CertificateManager, peerID types.PeerID, rwc io.ReadWriteCloser, genesis []byte) *V200Handshaker {
h := &V200Handshaker{selfMeta: is.SelfMeta(), is: is, logger: log, peerID: peerID, localGenesisHash: genesis, vm: vm, cm: cm}
// msg format is not changed
h.msgRW = v030.NewV030MsgPipe(rwc)
return h
}
// handshakeOutboundPeer start handshake with outbound peer
func (h *V200Handshaker) DoForOutbound(ctx context.Context) (*p2pcommon.HandshakeResult, error) {
// TODO need to check auth at first...
h.logger.Debug().Str(p2putil.LogPeerID, p2putil.ShortForm(h.peerID)).Msg("Starting versioned handshake for outbound peer connection")
// find my best block
bestBlock, err := h.is.GetChainAccessor().GetBestBlock()
if err != nil {
return nil, err
}
localID := h.vm.GetChainID(bestBlock.Header.BlockNo)
status, err := h.createLocalStatus(localID, bestBlock)
if err != nil {
h.logger.Warn().Err(err).Msg("Failed to create status message.")
h.sendGoAway("internal error")
return nil, err
}
err = h.sendLocalStatus(ctx, status)
if err != nil {
return nil, err
}
remotePeerStatus, err := h.receiveRemoteStatus(ctx)
if err != nil {
return nil, err
}
if err = h.checkRemoteStatus(remotePeerStatus); err != nil {
return nil, err
} else {
hsResult := &p2pcommon.HandshakeResult{Meta: h.remoteMeta, BestBlockHash: h.remoteHash, BestBlockNo: h.remoteNo, MsgRW: h.msgRW, Certificates: h.remoteCerts, Hidden: remotePeerStatus.NoExpose}
return hsResult, nil
}
}
func (h *V200Handshaker) sendLocalStatus(ctx context.Context, hostStatus *types.Status) error {
var err error
container := createMessage(p2pcommon.StatusRequest, p2pcommon.NewMsgID(), hostStatus)
if container == nil {
h.logger.Warn().Str(p2putil.LogPeerID, p2putil.ShortForm(h.peerID)).Msg("failed to create p2p message")
h.sendGoAway("internal error")
// h.logger.Warn().Str(LogPeerID, ShortForm(peerID)).Err(err).Msg("failed to create p2p message")
return fmt.Errorf("failed to craete container message")
}
if err = h.msgRW.WriteMsg(container); err != nil {
h.logger.Info().Str(p2putil.LogPeerID, p2putil.ShortForm(h.peerID)).Err(err).Msg("failed to write local status ")
return err
}
select {
case <-ctx.Done():
return ctx.Err()
default:
// go on
}
return nil
}
func (h *V200Handshaker) receiveRemoteStatus(ctx context.Context) (*types.Status, error) {
// and wait to response status
data, err := h.msgRW.ReadMsg()
if err != nil {
h.sendGoAway("malformed message")
// h.logger.Info().Err(err).Msg("fail to decode")
return nil, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// go on
}
if data.Subprotocol() != p2pcommon.StatusRequest {
if data.Subprotocol() == p2pcommon.GoAway {
return h.handleGoAway(h.peerID, data)
} else {
h.logger.Info().Str(p2putil.LogPeerID, p2putil.ShortForm(h.peerID)).Str("expected", p2pcommon.StatusRequest.String()).Str("actual", data.Subprotocol().String()).Msg("unexpected message type")
h.sendGoAway("unexpected message type")
return nil, fmt.Errorf("unexpected message type")
}
}
remotePeerStatus := &types.Status{}
err = p2putil.UnmarshalMessageBody(data.Payload(), remotePeerStatus)
if err != nil {
h.sendGoAway("malformed status message")
return nil, err
}
return remotePeerStatus, nil
}
func (h *V200Handshaker) checkRemoteStatus(remotePeerStatus *types.Status) error {
// check if chainID is same or not
remoteChainID := types.NewChainID()
err := remoteChainID.Read(remotePeerStatus.ChainID)
if err != nil {
h.sendGoAway("wrong status")
return err
}
localID := h.vm.GetChainID(remotePeerStatus.BestHeight)
if !localID.Equals(remoteChainID) {
h.sendGoAway("different chainID")
return fmt.Errorf("different chainID : %s", remoteChainID.ToJSON())
}
h.remoteHash, err = types.ParseToBlockID(remotePeerStatus.BestBlockHash)
if err != nil {
h.sendGoAway("wrong block hash")
return err
}
h.remoteNo = remotePeerStatus.BestHeight
peerAddress := remotePeerStatus.Sender
if peerAddress == nil || network.CheckAddressType(peerAddress.Address) == network.AddressTypeError {
h.sendGoAway("invalid peer address")
return fmt.Errorf("invalid peer address : %s", peerAddress)
}
rMeta := p2pcommon.NewMetaFromStatus(remotePeerStatus)
if rMeta.ID != h.peerID {
h.logger.Debug().Str("received_peer_id", rMeta.ID.Pretty()).Str(p2putil.LogPeerID, p2putil.ShortForm(h.peerID)).Msg("Inconsistent peerID")
h.sendGoAway("Inconsistent peerID")
return fmt.Errorf("inconsistent peerID")
}
// do additional check for genesises are identical
genHash := h.localGenesisHash
if !bytes.Equal(genHash, remotePeerStatus.Genesis) {
h.sendGoAway("different genesis block")
return fmt.Errorf("different genesis block local: %v , remote %v", enc.ToString(genHash), enc.ToString(remotePeerStatus.Genesis))
}
h.remoteMeta = rMeta
if err = h.checkByRole(remotePeerStatus); err != nil {
h.sendGoAway("invalid certificate works")
return fmt.Errorf("invalid certificate info: %v", err.Error())
}
return nil
}
// DoForInbound is handle handshake from inbound peer
func (h *V200Handshaker) DoForInbound(ctx context.Context) (*p2pcommon.HandshakeResult, error) {
// TODO need to check auth at first...
h.logger.Debug().Str(p2putil.LogPeerID, p2putil.ShortForm(h.peerID)).Msg("Starting versioned handshake for inbound peer connection")
// inbound: receive, check and send
remotePeerStatus, err := h.receiveRemoteStatus(ctx)
if err != nil {
return nil, err
}
if err = h.checkRemoteStatus(remotePeerStatus); err != nil {
return nil, err
}
bestBlock, err := h.is.GetChainAccessor().GetBestBlock()
if err != nil {
return nil, err
}
localID := h.vm.GetChainID(bestBlock.Header.BlockNo)
// send my status message as response
localStatus, err := h.createLocalStatus(localID, bestBlock)
if err != nil {
h.logger.Warn().Err(err).Msg("Failed to create localStatus message.")
h.sendGoAway("internal error")
return nil, err
}
err = h.sendLocalStatus(ctx, localStatus)
if err != nil {
return nil, err
}
hsResult := &p2pcommon.HandshakeResult{Meta: h.remoteMeta, BestBlockHash: h.remoteHash, BestBlockNo: h.remoteNo, MsgRW: h.msgRW, Certificates: h.remoteCerts, Hidden: remotePeerStatus.NoExpose}
return hsResult, nil
}
func (h *V200Handshaker) handleGoAway(peerID types.PeerID, data p2pcommon.Message) (*types.Status, error) {
goAway := &types.GoAwayNotice{}
if err := p2putil.UnmarshalMessageBody(data.Payload(), goAway); err != nil {
h.logger.Warn().Str(p2putil.LogPeerID, p2putil.ShortForm(peerID)).Err(err).Msg("Remote peer sent goAway but failed to decode internal message")
return nil, err
}
return nil, fmt.Errorf("remote peer refuse handshake: %s", goAway.GetMessage())
}
func (h *V200Handshaker) sendGoAway(msg string) {
goMsg := createMessage(p2pcommon.GoAway, p2pcommon.NewMsgID(), &types.GoAwayNotice{Message: msg})
if goMsg != nil {
h.msgRW.WriteMsg(goMsg)
}
}
func (h *V200Handshaker) checkByRole(status *types.Status) error {
if h.remoteMeta.Role == types.PeerRole_Agent {
err := h.checkAgent(status)
if err != nil {
return err
}
}
return nil
}
func (h *V200Handshaker) checkAgent(status *types.Status) error {
// Agent must have at least one block producer
if len(h.remoteMeta.ProducerIDs) == 0 {
return ErrInvalidAgentStatus
}
producers := make(map[types.PeerID]bool)
for _, id := range h.remoteMeta.ProducerIDs {
producers[id] = true
}
certs := make([]*p2pcommon.AgentCertificateV1, len(status.Certificates))
for i, pCert := range status.Certificates {
cert, err := p2putil.CheckAndGetV1(pCert)
if err != nil {
h.logger.Info().Err(err).Str(p2putil.LogPeerID, p2putil.ShortForm(h.remoteMeta.ID)).Msg("invalid agent certificate")
return ErrInvalidAgentStatus
}
// check certificate
if !types.IsSamePeerID(cert.AgentID, h.remoteMeta.ID) {
h.logger.Info().Err(err).Str(p2putil.LogPeerID, p2putil.ShortForm(h.remoteMeta.ID)).Msg("certificate is not for this agent")
return ErrInvalidAgentStatus
}
if _, exist := producers[cert.BPID]; !exist {
h.logger.Info().Err(err).Str(p2putil.LogPeerID, p2putil.ShortForm(h.remoteMeta.ID)).Str("bpID", p2putil.ShortForm(cert.BPID)).Msg("peer id of certificate not matched")
return ErrInvalidAgentStatus
}
certs[i] = cert
}
h.remoteCerts = certs
return nil
}
func (h *V200Handshaker) createLocalStatus(chainID *types.ChainID, bestBlock *types.Block) (*types.Status, error) {
selfAddr := h.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: h.selfMeta.Hidden,
Version: p2pkey.NodeVersion(),
Genesis: h.localGenesisHash,
}
if h.selfMeta.Role == types.PeerRole_Agent {
cs := h.cm.GetCertificates()
pcs, err := p2putil.ConvertCertsToProto(cs)
if err != nil {
h.logger.Error().Err(err).Msg("failed to convert certificates")
return nil, errors.New("internal error")
}
statusMsg.Certificates = pcs
}
return statusMsg, nil
}
func createMessage(protocolID p2pcommon.SubProtocol, msgID p2pcommon.MsgID, msgBody p2pcommon.MessageBody) p2pcommon.Message {
bytes, err := p2putil.MarshalMessageBody(msgBody)
if err != nil {
return nil
}
msg := p2pcommon.NewMessageValue(protocolID, msgID, p2pcommon.EmptyID, time.Now().UnixNano(), bytes)
return msg
}