plugeth/p2p/protocol.go

267 lines
6.3 KiB
Go
Raw Normal View History

2014-10-23 15:57:54 +00:00
package p2p
import (
"bytes"
"time"
)
// Protocol represents a P2P subprotocol implementation.
type Protocol struct {
// Name should contain the official protocol name,
// often a three-letter word.
Name string
2014-11-04 12:21:44 +00:00
// Version should contain the version number of the protocol.
Version uint
2014-11-04 12:21:44 +00:00
// Length should contain the number of message codes used
// by the protocol.
Length uint64
2014-11-04 12:21:44 +00:00
// Run is called in a new groutine when the protocol has been
// negotiated with a peer. It should read and write messages from
// rw. The Payload for each message must be fully consumed.
//
// The peer connection is closed when Start returns. It should return
// any protocol-level error (such as an I/O error) that is
// encountered.
Run func(peer *Peer, rw MsgReadWriter) error
2014-11-04 12:21:44 +00:00
}
func (p Protocol) cap() Cap {
return Cap{p.Name, p.Version}
2014-10-23 15:57:54 +00:00
}
const (
baseProtocolVersion = 2
baseProtocolLength = uint64(16)
baseProtocolMaxMsgSize = 10 * 1024 * 1024
2014-10-23 15:57:54 +00:00
)
const (
// devp2p message codes
handshakeMsg = 0x00
discMsg = 0x01
pingMsg = 0x02
pongMsg = 0x03
getPeersMsg = 0x04
peersMsg = 0x05
2014-10-23 15:57:54 +00:00
)
// handshake is the structure of a handshake list.
type handshake struct {
Version uint64
ID string
Caps []Cap
ListenPort uint64
NodeID []byte
}
2014-10-23 15:57:54 +00:00
func (h *handshake) String() string {
return h.ID
}
func (h *handshake) Pubkey() []byte {
return h.NodeID
}
2014-10-23 15:57:54 +00:00
// Cap is the structure of a peer capability.
type Cap struct {
Name string
Version uint
2014-10-23 15:57:54 +00:00
}
func (cap Cap) RlpData() interface{} {
return []interface{}{cap.Name, cap.Version}
2014-10-23 15:57:54 +00:00
}
type capsByName []Cap
func (cs capsByName) Len() int { return len(cs) }
func (cs capsByName) Less(i, j int) bool { return cs[i].Name < cs[j].Name }
func (cs capsByName) Swap(i, j int) { cs[i], cs[j] = cs[j], cs[i] }
type baseProtocol struct {
rw MsgReadWriter
peer *Peer
2014-10-23 15:57:54 +00:00
}
func runBaseProtocol(peer *Peer, rw MsgReadWriter) error {
bp := &baseProtocol{rw, peer}
2015-01-05 16:10:42 +00:00
errc := make(chan error, 1)
go func() { errc <- rw.WriteMsg(bp.handshakeMsg()) }()
if err := bp.readHandshake(); err != nil {
return err
}
// handle write error
if err := <-errc; err != nil {
2014-11-04 12:21:44 +00:00
return err
}
// run main loop
2014-11-04 12:21:44 +00:00
go func() {
2014-11-25 11:25:31 +00:00
for {
if err := bp.handle(rw); err != nil {
2015-01-05 16:10:42 +00:00
errc <- err
2014-11-25 11:25:31 +00:00
break
}
}
2014-11-04 12:21:44 +00:00
}()
2015-01-05 16:10:42 +00:00
return bp.loop(errc)
2014-10-23 15:57:54 +00:00
}
var pingTimeout = 2 * time.Second
func (bp *baseProtocol) loop(quit <-chan error) error {
ping := time.NewTimer(pingTimeout)
activity := bp.peer.activity.Subscribe(time.Time{})
lastActive := time.Time{}
defer ping.Stop()
defer activity.Unsubscribe()
2014-11-04 12:21:44 +00:00
getPeersTick := time.NewTicker(10 * time.Second)
defer getPeersTick.Stop()
err := bp.rw.EncodeMsg(getPeersMsg)
for err == nil {
2014-11-04 12:21:44 +00:00
select {
case err = <-quit:
2014-11-04 12:21:44 +00:00
return err
case <-getPeersTick.C:
err = bp.rw.EncodeMsg(getPeersMsg)
case event := <-activity.Chan():
ping.Reset(pingTimeout)
lastActive = event.(time.Time)
case t := <-ping.C:
if lastActive.Add(pingTimeout * 2).Before(t) {
err = newPeerError(errPingTimeout, "")
} else if lastActive.Add(pingTimeout).Before(t) {
err = bp.rw.EncodeMsg(pingMsg)
2014-11-04 12:21:44 +00:00
}
}
}
return err
2014-10-23 15:57:54 +00:00
}
2014-11-25 11:25:31 +00:00
func (bp *baseProtocol) handle(rw MsgReadWriter) error {
msg, err := rw.ReadMsg()
if err != nil {
return err
}
if msg.Size > baseProtocolMaxMsgSize {
return newPeerError(errMisc, "message too big")
}
// make sure that the payload has been fully consumed
defer msg.Discard()
switch msg.Code {
2014-11-04 12:21:44 +00:00
case handshakeMsg:
return newPeerError(errProtocolBreach, "extra handshake received")
2014-10-23 15:57:54 +00:00
2014-11-04 12:21:44 +00:00
case discMsg:
var reason [1]DiscReason
2014-11-25 11:25:31 +00:00
if err := msg.Decode(&reason); err != nil {
return err
}
return discRequestedError(reason[0])
2014-10-23 15:57:54 +00:00
2014-11-04 12:21:44 +00:00
case pingMsg:
return bp.rw.EncodeMsg(pongMsg)
2014-10-23 15:57:54 +00:00
2014-11-04 12:21:44 +00:00
case pongMsg:
2014-10-23 15:57:54 +00:00
2014-11-04 12:21:44 +00:00
case getPeersMsg:
2015-01-05 16:10:42 +00:00
peers := bp.peer.PeerList()
// this is dangerous. the spec says that we should _delay_
// sending the response if no new information is available.
// this means that would need to send a response later when
// new peers become available.
//
// TODO: add event mechanism to notify baseProtocol for new peers
if len(peers) > 0 {
2015-01-05 16:10:42 +00:00
return bp.rw.EncodeMsg(peersMsg, peers...)
2014-10-23 15:57:54 +00:00
}
2014-11-04 12:21:44 +00:00
case peersMsg:
2014-11-25 11:25:31 +00:00
var peers []*peerAddr
if err := msg.Decode(&peers); err != nil {
return err
}
for _, addr := range peers {
bp.peer.Debugf("received peer suggestion: %v", addr)
bp.peer.newPeerAddr <- addr
}
2014-10-23 15:57:54 +00:00
2014-11-04 12:21:44 +00:00
default:
2014-11-25 11:25:31 +00:00
return newPeerError(errInvalidMsgCode, "unknown message code %v", msg.Code)
2014-10-23 15:57:54 +00:00
}
2014-11-04 12:21:44 +00:00
return nil
2014-10-23 15:57:54 +00:00
}
2015-01-05 16:10:42 +00:00
func (bp *baseProtocol) readHandshake() error {
2014-11-25 11:25:31 +00:00
// read and handle remote handshake
2015-01-05 16:10:42 +00:00
msg, err := bp.rw.ReadMsg()
2014-11-25 11:25:31 +00:00
if err != nil {
return err
}
if msg.Code != handshakeMsg {
return newPeerError(errProtocolBreach, "first message must be handshake, got %x", msg.Code)
}
if msg.Size > baseProtocolMaxMsgSize {
return newPeerError(errMisc, "message too big")
2014-10-23 15:57:54 +00:00
}
2014-11-25 11:25:31 +00:00
var hs handshake
if err := msg.Decode(&hs); err != nil {
return err
2014-10-23 15:57:54 +00:00
}
2014-11-25 11:25:31 +00:00
// validate handshake info
if hs.Version != baseProtocolVersion {
return newPeerError(errP2PVersionMismatch, "Require protocol %d, received %d\n",
baseProtocolVersion, hs.Version)
2014-10-23 15:57:54 +00:00
}
if len(hs.NodeID) == 0 {
return newPeerError(errPubkeyMissing, "")
}
if len(hs.NodeID) != 64 {
return newPeerError(errPubkeyInvalid, "require 512 bit, got %v", len(hs.NodeID)*8)
}
if da := bp.peer.dialAddr; da != nil {
// verify that the peer we wanted to connect to
// actually holds the target public key.
if da.Pubkey != nil && !bytes.Equal(da.Pubkey, hs.NodeID) {
return newPeerError(errPubkeyForbidden, "dial address pubkey mismatch")
}
}
pa := newPeerAddr(bp.peer.conn.RemoteAddr(), hs.NodeID)
if err := bp.peer.pubkeyHook(pa); err != nil {
return newPeerError(errPubkeyForbidden, "%v", err)
}
2014-11-25 11:25:31 +00:00
// TODO: remove Caps with empty name
var addr *peerAddr
if hs.ListenPort != 0 {
addr = newPeerAddr(bp.peer.conn.RemoteAddr(), hs.NodeID)
addr.Port = hs.ListenPort
2014-10-23 15:57:54 +00:00
}
bp.peer.setHandshakeInfo(&hs, addr, hs.Caps)
bp.peer.startSubprotocols(hs.Caps)
return nil
}
2014-10-23 15:57:54 +00:00
func (bp *baseProtocol) handshakeMsg() Msg {
var (
port uint64
caps []interface{}
)
if bp.peer.ourListenAddr != nil {
port = bp.peer.ourListenAddr.Port
2014-10-23 15:57:54 +00:00
}
for _, proto := range bp.peer.protocols {
caps = append(caps, proto.cap())
}
return NewMsg(handshakeMsg,
baseProtocolVersion,
bp.peer.ourID.String(),
caps,
port,
bp.peer.ourID.Pubkey()[1:],
)
}