-
Notifications
You must be signed in to change notification settings - Fork 1
/
handshake.go
58 lines (49 loc) · 1.32 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
package p2p
import (
"fmt"
"strconv"
)
// Handshake is the protocol independent data that is required to authenticate a peer.
type Handshake struct {
Network NetworkID
Version uint16
Type ParcelType
NodeID uint32
ListenPort string
Loopback uint64
Alternatives []Endpoint
}
// Valid checks the Handshake's data against a configuration.
// Loopback is checked outside of this function.
func (h *Handshake) Valid(conf *Configuration) error {
if h.Version < conf.ProtocolVersionMinimum {
return fmt.Errorf("version %d is below the minimum", h.Version)
}
if h.Network != conf.Network {
return fmt.Errorf("wrong network id %s", h.Network)
}
port, err := strconv.Atoi(h.ListenPort)
if err != nil {
return fmt.Errorf("unable to parse port %s: %v", h.ListenPort, err)
}
if port < 1 || port > 65535 {
return fmt.Errorf("given port out of range: %d", port)
}
for _, ep := range h.Alternatives {
if !ep.Valid() {
return fmt.Errorf("invalid list of alternatives provided")
}
}
return nil
}
// create a new handshake
func newHandshake(conf *Configuration, loopback uint64) *Handshake {
hs := new(Handshake)
hs.Type = TypeHandshake
hs.Network = conf.Network
hs.Version = conf.ProtocolVersion
hs.NodeID = conf.NodeID
hs.ListenPort = conf.ListenPort
hs.Loopback = loopback
return hs
}