forked from FactomProject/factomd
/
handshake.go
66 lines (55 loc) · 1.66 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
package p2p
import (
"fmt"
"hash/crc32"
"strconv"
)
// Handshake is an alias of V9MSG for backward compatibility
type Handshake V9Msg
// Valid checks if the other node is compatible
func (h *Handshake) Valid(conf *Configuration) error {
if h.Header.Version < conf.ProtocolVersionMinimum {
return fmt.Errorf("version %d is below the minimum", h.Header.Version)
}
if h.Header.Network != conf.Network {
return fmt.Errorf("wrong network id %x", h.Header.Network)
}
if len(h.Payload) == 0 {
return fmt.Errorf("zero-length payload")
}
if h.Header.Length != uint32(len(h.Payload)) {
return fmt.Errorf("length in header does not match payload")
}
csum := crc32.Checksum(h.Payload, crcTable)
if csum != h.Header.Crc32 {
return fmt.Errorf("invalid checksum")
}
port, err := strconv.Atoi(h.Header.PeerPort)
if err != nil {
return fmt.Errorf("unable to parse port %s: %v", h.Header.PeerPort, err)
}
if port < 1 || port > 65535 {
return fmt.Errorf("given port out of range: %d", port)
}
return nil
}
func newHandshake(conf *Configuration, payload []byte) *Handshake {
hs := new(Handshake)
hs.Header = V9Header{
Network: conf.Network,
Version: conf.ProtocolVersion,
Type: TypeHandshake,
NodeID: uint64(conf.NodeID),
PeerPort: conf.ListenPort,
AppHash: "NetworkMessage",
AppType: "Network",
}
hs.SetPayload(payload)
return hs
}
// SetPayload adds a payload to the handshake and updates the header with metadata
func (h *Handshake) SetPayload(payload []byte) {
h.Payload = payload
h.Header.Crc32 = crc32.Checksum(h.Payload, crcTable)
h.Header.Length = uint32(len(h.Payload))
}