aboutsummaryrefslogtreecommitdiffstats
path: root/p2p/protocol.go
blob: 5d05ced7d2cdeffc61ebb0761cd73244b64659d9 (plain) (blame)
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
package p2p

import (
    "bytes"
    "fmt"
    "net"
    "sort"
    "sync"
    "time"
)

type Protocol interface {
    Start()
    Stop()
    HandleIn(*Msg, chan *Msg)
    HandleOut(*Msg) bool
    Offset() MsgCode
    Name() string
}

const (
    P2PVersion      = 0
    pingTimeout     = 2
    pingGracePeriod = 2
)

const (
    HandshakeMsg = iota
    DiscMsg
    PingMsg
    PongMsg
    GetPeersMsg
    PeersMsg
    offset = 16
)

type ProtocolState uint8

const (
    nullState = iota
    handshakeReceived
)

type DiscReason byte

const (
    // Values are given explicitly instead of by iota because these values are
    // defined by the wire protocol spec; it is easier for humans to ensure
    // correctness when values are explicit.
    DiscRequested           = 0x00
    DiscNetworkError        = 0x01
    DiscProtocolError       = 0x02
    DiscUselessPeer         = 0x03
    DiscTooManyPeers        = 0x04
    DiscAlreadyConnected    = 0x05
    DiscIncompatibleVersion = 0x06
    DiscInvalidIdentity     = 0x07
    DiscQuitting            = 0x08
    DiscUnexpectedIdentity  = 0x09
    DiscSelf                = 0x0a
    DiscReadTimeout         = 0x0b
    DiscSubprotocolError    = 0x10
)

var discReasonToString = map[DiscReason]string{
    DiscRequested:           "Disconnect requested",
    DiscNetworkError:        "Network error",
    DiscProtocolError:       "Breach of protocol",
    DiscUselessPeer:         "Useless peer",
    DiscTooManyPeers:        "Too many peers",
    DiscAlreadyConnected:    "Already connected",
    DiscIncompatibleVersion: "Incompatible P2P protocol version",
    DiscInvalidIdentity:     "Invalid node identity",
    DiscQuitting:            "Client quitting",
    DiscUnexpectedIdentity:  "Unexpected identity",
    DiscSelf:                "Connected to self",
    DiscReadTimeout:         "Read timeout",
    DiscSubprotocolError:    "Subprotocol error",
}

func (d DiscReason) String() string {
    if len(discReasonToString) < int(d) {
        return "Unknown"
    }

    return discReasonToString[d]
}

type BaseProtocol struct {
    peer      *Peer
    state     ProtocolState
    stateLock sync.RWMutex
}

func NewBaseProtocol(peer *Peer) *BaseProtocol {
    self := &BaseProtocol{
        peer: peer,
    }

    return self
}

func (self *BaseProtocol) Start() {
    if self.peer != nil {
        self.peer.Write("", self.peer.Server().Handshake())
        go self.peer.Messenger().PingPong(
            pingTimeout*time.Second,
            pingGracePeriod*time.Second,
            self.Ping,
            self.Timeout,
        )
    }
}

func (self *BaseProtocol) Stop() {
}

func (self *BaseProtocol) Ping() {
    msg, _ := NewMsg(PingMsg)
    self.peer.Write("", msg)
}

func (self *BaseProtocol) Timeout() {
    self.peerError(PingTimeout, "")
}

func (self *BaseProtocol) Name() string {
    return ""
}

func (self *BaseProtocol) Offset() MsgCode {
    return offset
}

func (self *BaseProtocol) CheckState(state ProtocolState) bool {
    self.stateLock.RLock()
    self.stateLock.RUnlock()
    if self.state != state {
        return false
    } else {
        return true
    }
}

func (self *BaseProtocol) HandleIn(msg *Msg, response chan *Msg) {
    if msg.Code() == HandshakeMsg {
        self.handleHandshake(msg)
    } else {
        if !self.CheckState(handshakeReceived) {
            self.peerError(ProtocolBreach, "message code %v not allowed", msg.Code())
            close(response)
            return
        }
        switch msg.Code() {
        case DiscMsg:
            logger.Infof("Disconnect requested from peer %v, reason", DiscReason(msg.Data().Get(0).Uint()))
            self.peer.Server().PeerDisconnect() <- DisconnectRequest{
                addr:   self.peer.Address,
                reason: DiscRequested,
            }
        case PingMsg:
            out, _ := NewMsg(PongMsg)
            response <- out
        case PongMsg:
        case GetPeersMsg:
            // Peer asked for list of connected peers
            if out, err := self.peer.Server().PeersMessage(); err != nil {
                response <- out
            }
        case PeersMsg:
            self.handlePeers(msg)
        default:
            self.peerError(InvalidMsgCode, "unknown message code %v", msg.Code())
        }
    }
    close(response)
}

func (self *BaseProtocol) HandleOut(msg *Msg) (allowed bool) {
    // somewhat overly paranoid
    allowed = msg.Code() == HandshakeMsg || msg.Code() == DiscMsg || msg.Code() < self.Offset() && self.CheckState(handshakeReceived)
    return
}

func (self *BaseProtocol) peerError(errorCode ErrorCode, format string, v ...interface{}) {
    err := NewPeerError(errorCode, format, v...)
    logger.Warnln(err)
    fmt.Println(self.peer, err)
    if self.peer != nil {
        self.peer.PeerErrorChan() <- err
    }
}

func (self *BaseProtocol) handlePeers(msg *Msg) {
    it := msg.Data().NewIterator()
    for it.Next() {
        ip := net.IP(it.Value().Get(0).Bytes())
        port := it.Value().Get(1).Uint()
        address := &net.TCPAddr{IP: ip, Port: int(port)}
        go self.peer.Server().PeerConnect(address)
    }
}

func (self *BaseProtocol) handleHandshake(msg *Msg) {
    self.stateLock.Lock()
    defer self.stateLock.Unlock()
    if self.state != nullState {
        self.peerError(ProtocolBreach, "extra handshake")
        return
    }

    c := msg.Data()

    var (
        p2pVersion = c.Get(0).Uint()
        id         = c.Get(1).Str()
        caps       = c.Get(2)
        port       = c.Get(3).Uint()
        pubkey     = c.Get(4).Bytes()
    )
    fmt.Printf("handshake received %v, %v, %v, %v, %v ", p2pVersion, id, caps, port, pubkey)

    // Check correctness of p2p protocol version
    if p2pVersion != P2PVersion {
        self.peerError(P2PVersionMismatch, "Require protocol %d, received %d\n", P2PVersion, p2pVersion)
        return
    }

    // Handle the pub key (validation, uniqueness)
    if len(pubkey) == 0 {
        self.peerError(PubkeyMissing, "not supplied in handshake.")
        return
    }

    if len(pubkey) != 64 {
        self.peerError(PubkeyInvalid, "require 512 bit, got %v", len(pubkey)*8)
        return
    }

    // Self connect detection
    if bytes.Compare(self.peer.Server().ClientIdentity().Pubkey()[1:], pubkey) == 0 {
        self.peerError(PubkeyForbidden, "not allowed to connect to self")
        return
    }

    // register pubkey on server. this also sets the pubkey on the peer (need lock)
    if err := self.peer.Server().RegisterPubkey(self.peer, pubkey); err != nil {
        self.peerError(PubkeyForbidden, err.Error())
        return
    }

    // check port
    if self.peer.Inbound {
        uint16port := uint16(port)
        if self.peer.Port > 0 && self.peer.Port != uint16port {
            self.peerError(PortMismatch, "port mismatch: %v != %v", self.peer.Port, port)
            return
        } else {
            self.peer.Port = uint16port
        }
    }

    capsIt := caps.NewIterator()
    for capsIt.Next() {
        cap := capsIt.Value().Str()
        self.peer.Caps = append(self.peer.Caps, cap)
    }
    sort.Strings(self.peer.Caps)
    self.peer.Messenger().AddProtocols(self.peer.Caps)

    self.peer.Id = id

    self.state = handshakeReceived

    //p.ethereum.PushPeer(p)
    // p.ethereum.reactor.Post("peerList", p.ethereum.Peers())
    return
}