github.com/wanghao-bianjie/go-ethereum@v1.9.7/p2p/rlpx.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package p2p
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/aes"
    22  	"crypto/cipher"
    23  	"crypto/ecdsa"
    24  	"crypto/elliptic"
    25  	"crypto/hmac"
    26  	"crypto/rand"
    27  	"encoding/binary"
    28  	"errors"
    29  	"fmt"
    30  	"hash"
    31  	"io"
    32  	"io/ioutil"
    33  	mrand "math/rand"
    34  	"net"
    35  	"sync"
    36  	"time"
    37  
    38  	"github.com/ethereum/go-ethereum/common/bitutil"
    39  	"github.com/ethereum/go-ethereum/crypto"
    40  	"github.com/ethereum/go-ethereum/crypto/ecies"
    41  	"github.com/ethereum/go-ethereum/metrics"
    42  	"github.com/ethereum/go-ethereum/rlp"
    43  	"github.com/golang/snappy"
    44  	"golang.org/x/crypto/sha3"
    45  )
    46  
    47  const (
    48  	maxUint24 = ^uint32(0) >> 8
    49  
    50  	sskLen = 16                     // ecies.MaxSharedKeyLength(pubKey) / 2
    51  	sigLen = crypto.SignatureLength // elliptic S256
    52  	pubLen = 64                     // 512 bit pubkey in uncompressed representation without format byte
    53  	shaLen = 32                     // hash length (for nonce etc)
    54  
    55  	authMsgLen  = sigLen + shaLen + pubLen + shaLen + 1
    56  	authRespLen = pubLen + shaLen + 1
    57  
    58  	eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */
    59  
    60  	encAuthMsgLen  = authMsgLen + eciesOverhead  // size of encrypted pre-EIP-8 initiator handshake
    61  	encAuthRespLen = authRespLen + eciesOverhead // size of encrypted pre-EIP-8 handshake reply
    62  
    63  	// total timeout for encryption handshake and protocol
    64  	// handshake in both directions.
    65  	handshakeTimeout = 5 * time.Second
    66  
    67  	// This is the timeout for sending the disconnect reason.
    68  	// This is shorter than the usual timeout because we don't want
    69  	// to wait if the connection is known to be bad anyway.
    70  	discWriteTimeout = 1 * time.Second
    71  )
    72  
    73  // errPlainMessageTooLarge is returned if a decompressed message length exceeds
    74  // the allowed 24 bits (i.e. length >= 16MB).
    75  var errPlainMessageTooLarge = errors.New("message length >= 16MB")
    76  
    77  // rlpx is the transport protocol used by actual (non-test) connections.
    78  // It wraps the frame encoder with locks and read/write deadlines.
    79  type rlpx struct {
    80  	fd net.Conn
    81  
    82  	rmu, wmu sync.Mutex
    83  	rw       *rlpxFrameRW
    84  }
    85  
    86  func newRLPX(fd net.Conn) transport {
    87  	fd.SetDeadline(time.Now().Add(handshakeTimeout))
    88  	return &rlpx{fd: fd}
    89  }
    90  
    91  func (t *rlpx) ReadMsg() (Msg, error) {
    92  	t.rmu.Lock()
    93  	defer t.rmu.Unlock()
    94  	t.fd.SetReadDeadline(time.Now().Add(frameReadTimeout))
    95  	return t.rw.ReadMsg()
    96  }
    97  
    98  func (t *rlpx) WriteMsg(msg Msg) error {
    99  	t.wmu.Lock()
   100  	defer t.wmu.Unlock()
   101  	t.fd.SetWriteDeadline(time.Now().Add(frameWriteTimeout))
   102  	return t.rw.WriteMsg(msg)
   103  }
   104  
   105  func (t *rlpx) close(err error) {
   106  	t.wmu.Lock()
   107  	defer t.wmu.Unlock()
   108  	// Tell the remote end why we're disconnecting if possible.
   109  	if t.rw != nil {
   110  		if r, ok := err.(DiscReason); ok && r != DiscNetworkError {
   111  			// rlpx tries to send DiscReason to disconnected peer
   112  			// if the connection is net.Pipe (in-memory simulation)
   113  			// it hangs forever, since net.Pipe does not implement
   114  			// a write deadline. Because of this only try to send
   115  			// the disconnect reason message if there is no error.
   116  			if err := t.fd.SetWriteDeadline(time.Now().Add(discWriteTimeout)); err == nil {
   117  				SendItems(t.rw, discMsg, r)
   118  			}
   119  		}
   120  	}
   121  	t.fd.Close()
   122  }
   123  
   124  func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
   125  	// Writing our handshake happens concurrently, we prefer
   126  	// returning the handshake read error. If the remote side
   127  	// disconnects us early with a valid reason, we should return it
   128  	// as the error so it can be tracked elsewhere.
   129  	werr := make(chan error, 1)
   130  	go func() { werr <- Send(t.rw, handshakeMsg, our) }()
   131  	if their, err = readProtocolHandshake(t.rw); err != nil {
   132  		<-werr // make sure the write terminates too
   133  		return nil, err
   134  	}
   135  	if err := <-werr; err != nil {
   136  		return nil, fmt.Errorf("write error: %v", err)
   137  	}
   138  	// If the protocol version supports Snappy encoding, upgrade immediately
   139  	t.rw.snappy = their.Version >= snappyProtocolVersion
   140  
   141  	return their, nil
   142  }
   143  
   144  func readProtocolHandshake(rw MsgReader) (*protoHandshake, error) {
   145  	msg, err := rw.ReadMsg()
   146  	if err != nil {
   147  		return nil, err
   148  	}
   149  	if msg.Size > baseProtocolMaxMsgSize {
   150  		return nil, fmt.Errorf("message too big")
   151  	}
   152  	if msg.Code == discMsg {
   153  		// Disconnect before protocol handshake is valid according to the
   154  		// spec and we send it ourself if the post-handshake checks fail.
   155  		// We can't return the reason directly, though, because it is echoed
   156  		// back otherwise. Wrap it in a string instead.
   157  		var reason [1]DiscReason
   158  		rlp.Decode(msg.Payload, &reason)
   159  		return nil, reason[0]
   160  	}
   161  	if msg.Code != handshakeMsg {
   162  		return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
   163  	}
   164  	var hs protoHandshake
   165  	if err := msg.Decode(&hs); err != nil {
   166  		return nil, err
   167  	}
   168  	if len(hs.ID) != 64 || !bitutil.TestBytes(hs.ID) {
   169  		return nil, DiscInvalidIdentity
   170  	}
   171  	return &hs, nil
   172  }
   173  
   174  // doEncHandshake runs the protocol handshake using authenticated
   175  // messages. the protocol handshake is the first authenticated message
   176  // and also verifies whether the encryption handshake 'worked' and the
   177  // remote side actually provided the right public key.
   178  func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
   179  	var (
   180  		sec secrets
   181  		err error
   182  	)
   183  	if dial == nil {
   184  		sec, err = receiverEncHandshake(t.fd, prv)
   185  	} else {
   186  		sec, err = initiatorEncHandshake(t.fd, prv, dial)
   187  	}
   188  	if err != nil {
   189  		return nil, err
   190  	}
   191  	t.wmu.Lock()
   192  	t.rw = newRLPXFrameRW(t.fd, sec)
   193  	t.wmu.Unlock()
   194  	return sec.Remote.ExportECDSA(), nil
   195  }
   196  
   197  // encHandshake contains the state of the encryption handshake.
   198  type encHandshake struct {
   199  	initiator            bool
   200  	remote               *ecies.PublicKey  // remote-pubk
   201  	initNonce, respNonce []byte            // nonce
   202  	randomPrivKey        *ecies.PrivateKey // ecdhe-random
   203  	remoteRandomPub      *ecies.PublicKey  // ecdhe-random-pubk
   204  }
   205  
   206  // secrets represents the connection secrets
   207  // which are negotiated during the encryption handshake.
   208  type secrets struct {
   209  	Remote                *ecies.PublicKey
   210  	AES, MAC              []byte
   211  	EgressMAC, IngressMAC hash.Hash
   212  	Token                 []byte
   213  }
   214  
   215  // RLPx v4 handshake auth (defined in EIP-8).
   216  type authMsgV4 struct {
   217  	gotPlain bool // whether read packet had plain format.
   218  
   219  	Signature       [sigLen]byte
   220  	InitiatorPubkey [pubLen]byte
   221  	Nonce           [shaLen]byte
   222  	Version         uint
   223  
   224  	// Ignore additional fields (forward-compatibility)
   225  	Rest []rlp.RawValue `rlp:"tail"`
   226  }
   227  
   228  // RLPx v4 handshake response (defined in EIP-8).
   229  type authRespV4 struct {
   230  	RandomPubkey [pubLen]byte
   231  	Nonce        [shaLen]byte
   232  	Version      uint
   233  
   234  	// Ignore additional fields (forward-compatibility)
   235  	Rest []rlp.RawValue `rlp:"tail"`
   236  }
   237  
   238  // secrets is called after the handshake is completed.
   239  // It extracts the connection secrets from the handshake values.
   240  func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
   241  	ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
   242  	if err != nil {
   243  		return secrets{}, err
   244  	}
   245  
   246  	// derive base secrets from ephemeral key agreement
   247  	sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
   248  	aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
   249  	s := secrets{
   250  		Remote: h.remote,
   251  		AES:    aesSecret,
   252  		MAC:    crypto.Keccak256(ecdheSecret, aesSecret),
   253  	}
   254  
   255  	// setup sha3 instances for the MACs
   256  	mac1 := sha3.NewLegacyKeccak256()
   257  	mac1.Write(xor(s.MAC, h.respNonce))
   258  	mac1.Write(auth)
   259  	mac2 := sha3.NewLegacyKeccak256()
   260  	mac2.Write(xor(s.MAC, h.initNonce))
   261  	mac2.Write(authResp)
   262  	if h.initiator {
   263  		s.EgressMAC, s.IngressMAC = mac1, mac2
   264  	} else {
   265  		s.EgressMAC, s.IngressMAC = mac2, mac1
   266  	}
   267  
   268  	return s, nil
   269  }
   270  
   271  // staticSharedSecret returns the static shared secret, the result
   272  // of key agreement between the local and remote static node key.
   273  func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
   274  	return ecies.ImportECDSA(prv).GenerateShared(h.remote, sskLen, sskLen)
   275  }
   276  
   277  // initiatorEncHandshake negotiates a session token on conn.
   278  // it should be called on the dialing side of the connection.
   279  //
   280  // prv is the local client's private key.
   281  func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s secrets, err error) {
   282  	h := &encHandshake{initiator: true, remote: ecies.ImportECDSAPublic(remote)}
   283  	authMsg, err := h.makeAuthMsg(prv)
   284  	if err != nil {
   285  		return s, err
   286  	}
   287  	authPacket, err := sealEIP8(authMsg, h)
   288  	if err != nil {
   289  		return s, err
   290  	}
   291  	if _, err = conn.Write(authPacket); err != nil {
   292  		return s, err
   293  	}
   294  
   295  	authRespMsg := new(authRespV4)
   296  	authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
   297  	if err != nil {
   298  		return s, err
   299  	}
   300  	if err := h.handleAuthResp(authRespMsg); err != nil {
   301  		return s, err
   302  	}
   303  	return h.secrets(authPacket, authRespPacket)
   304  }
   305  
   306  // makeAuthMsg creates the initiator handshake message.
   307  func (h *encHandshake) makeAuthMsg(prv *ecdsa.PrivateKey) (*authMsgV4, error) {
   308  	// Generate random initiator nonce.
   309  	h.initNonce = make([]byte, shaLen)
   310  	_, err := rand.Read(h.initNonce)
   311  	if err != nil {
   312  		return nil, err
   313  	}
   314  	// Generate random keypair to for ECDH.
   315  	h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
   316  	if err != nil {
   317  		return nil, err
   318  	}
   319  
   320  	// Sign known message: static-shared-secret ^ nonce
   321  	token, err := h.staticSharedSecret(prv)
   322  	if err != nil {
   323  		return nil, err
   324  	}
   325  	signed := xor(token, h.initNonce)
   326  	signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
   327  	if err != nil {
   328  		return nil, err
   329  	}
   330  
   331  	msg := new(authMsgV4)
   332  	copy(msg.Signature[:], signature)
   333  	copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
   334  	copy(msg.Nonce[:], h.initNonce)
   335  	msg.Version = 4
   336  	return msg, nil
   337  }
   338  
   339  func (h *encHandshake) handleAuthResp(msg *authRespV4) (err error) {
   340  	h.respNonce = msg.Nonce[:]
   341  	h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:])
   342  	return err
   343  }
   344  
   345  // receiverEncHandshake negotiates a session token on conn.
   346  // it should be called on the listening side of the connection.
   347  //
   348  // prv is the local client's private key.
   349  func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s secrets, err error) {
   350  	authMsg := new(authMsgV4)
   351  	authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
   352  	if err != nil {
   353  		return s, err
   354  	}
   355  	h := new(encHandshake)
   356  	if err := h.handleAuthMsg(authMsg, prv); err != nil {
   357  		return s, err
   358  	}
   359  
   360  	authRespMsg, err := h.makeAuthResp()
   361  	if err != nil {
   362  		return s, err
   363  	}
   364  	var authRespPacket []byte
   365  	if authMsg.gotPlain {
   366  		authRespPacket, err = authRespMsg.sealPlain(h)
   367  	} else {
   368  		authRespPacket, err = sealEIP8(authRespMsg, h)
   369  	}
   370  	if err != nil {
   371  		return s, err
   372  	}
   373  	if _, err = conn.Write(authRespPacket); err != nil {
   374  		return s, err
   375  	}
   376  	return h.secrets(authPacket, authRespPacket)
   377  }
   378  
   379  func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
   380  	// Import the remote identity.
   381  	rpub, err := importPublicKey(msg.InitiatorPubkey[:])
   382  	if err != nil {
   383  		return err
   384  	}
   385  	h.initNonce = msg.Nonce[:]
   386  	h.remote = rpub
   387  
   388  	// Generate random keypair for ECDH.
   389  	// If a private key is already set, use it instead of generating one (for testing).
   390  	if h.randomPrivKey == nil {
   391  		h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
   392  		if err != nil {
   393  			return err
   394  		}
   395  	}
   396  
   397  	// Check the signature.
   398  	token, err := h.staticSharedSecret(prv)
   399  	if err != nil {
   400  		return err
   401  	}
   402  	signedMsg := xor(token, h.initNonce)
   403  	remoteRandomPub, err := crypto.Ecrecover(signedMsg, msg.Signature[:])
   404  	if err != nil {
   405  		return err
   406  	}
   407  	h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
   408  	return nil
   409  }
   410  
   411  func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
   412  	// Generate random nonce.
   413  	h.respNonce = make([]byte, shaLen)
   414  	if _, err = rand.Read(h.respNonce); err != nil {
   415  		return nil, err
   416  	}
   417  
   418  	msg = new(authRespV4)
   419  	copy(msg.Nonce[:], h.respNonce)
   420  	copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
   421  	msg.Version = 4
   422  	return msg, nil
   423  }
   424  
   425  func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) {
   426  	buf := make([]byte, authMsgLen)
   427  	n := copy(buf, msg.Signature[:])
   428  	n += copy(buf[n:], crypto.Keccak256(exportPubkey(&h.randomPrivKey.PublicKey)))
   429  	n += copy(buf[n:], msg.InitiatorPubkey[:])
   430  	n += copy(buf[n:], msg.Nonce[:])
   431  	buf[n] = 0 // token-flag
   432  	return ecies.Encrypt(rand.Reader, h.remote, buf, nil, nil)
   433  }
   434  
   435  func (msg *authMsgV4) decodePlain(input []byte) {
   436  	n := copy(msg.Signature[:], input)
   437  	n += shaLen // skip sha3(initiator-ephemeral-pubk)
   438  	n += copy(msg.InitiatorPubkey[:], input[n:])
   439  	copy(msg.Nonce[:], input[n:])
   440  	msg.Version = 4
   441  	msg.gotPlain = true
   442  }
   443  
   444  func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
   445  	buf := make([]byte, authRespLen)
   446  	n := copy(buf, msg.RandomPubkey[:])
   447  	copy(buf[n:], msg.Nonce[:])
   448  	return ecies.Encrypt(rand.Reader, hs.remote, buf, nil, nil)
   449  }
   450  
   451  func (msg *authRespV4) decodePlain(input []byte) {
   452  	n := copy(msg.RandomPubkey[:], input)
   453  	copy(msg.Nonce[:], input[n:])
   454  	msg.Version = 4
   455  }
   456  
   457  var padSpace = make([]byte, 300)
   458  
   459  func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
   460  	buf := new(bytes.Buffer)
   461  	if err := rlp.Encode(buf, msg); err != nil {
   462  		return nil, err
   463  	}
   464  	// pad with random amount of data. the amount needs to be at least 100 bytes to make
   465  	// the message distinguishable from pre-EIP-8 handshakes.
   466  	pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
   467  	buf.Write(pad)
   468  	prefix := make([]byte, 2)
   469  	binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
   470  
   471  	enc, err := ecies.Encrypt(rand.Reader, h.remote, buf.Bytes(), nil, prefix)
   472  	return append(prefix, enc...), err
   473  }
   474  
   475  type plainDecoder interface {
   476  	decodePlain([]byte)
   477  }
   478  
   479  func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
   480  	buf := make([]byte, plainSize)
   481  	if _, err := io.ReadFull(r, buf); err != nil {
   482  		return buf, err
   483  	}
   484  	// Attempt decoding pre-EIP-8 "plain" format.
   485  	key := ecies.ImportECDSA(prv)
   486  	if dec, err := key.Decrypt(buf, nil, nil); err == nil {
   487  		msg.decodePlain(dec)
   488  		return buf, nil
   489  	}
   490  	// Could be EIP-8 format, try that.
   491  	prefix := buf[:2]
   492  	size := binary.BigEndian.Uint16(prefix)
   493  	if size < uint16(plainSize) {
   494  		return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
   495  	}
   496  	buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
   497  	if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
   498  		return buf, err
   499  	}
   500  	dec, err := key.Decrypt(buf[2:], nil, prefix)
   501  	if err != nil {
   502  		return buf, err
   503  	}
   504  	// Can't use rlp.DecodeBytes here because it rejects
   505  	// trailing data (forward-compatibility).
   506  	s := rlp.NewStream(bytes.NewReader(dec), 0)
   507  	return buf, s.Decode(msg)
   508  }
   509  
   510  // importPublicKey unmarshals 512 bit public keys.
   511  func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
   512  	var pubKey65 []byte
   513  	switch len(pubKey) {
   514  	case 64:
   515  		// add 'uncompressed key' flag
   516  		pubKey65 = append([]byte{0x04}, pubKey...)
   517  	case 65:
   518  		pubKey65 = pubKey
   519  	default:
   520  		return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
   521  	}
   522  	// TODO: fewer pointless conversions
   523  	pub, err := crypto.UnmarshalPubkey(pubKey65)
   524  	if err != nil {
   525  		return nil, err
   526  	}
   527  	return ecies.ImportECDSAPublic(pub), nil
   528  }
   529  
   530  func exportPubkey(pub *ecies.PublicKey) []byte {
   531  	if pub == nil {
   532  		panic("nil pubkey")
   533  	}
   534  	return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
   535  }
   536  
   537  func xor(one, other []byte) (xor []byte) {
   538  	xor = make([]byte, len(one))
   539  	for i := 0; i < len(one); i++ {
   540  		xor[i] = one[i] ^ other[i]
   541  	}
   542  	return xor
   543  }
   544  
   545  var (
   546  	// this is used in place of actual frame header data.
   547  	// TODO: replace this when Msg contains the protocol type code.
   548  	zeroHeader = []byte{0xC2, 0x80, 0x80}
   549  	// sixteen zero bytes
   550  	zero16 = make([]byte, 16)
   551  )
   552  
   553  // rlpxFrameRW implements a simplified version of RLPx framing.
   554  // chunked messages are not supported and all headers are equal to
   555  // zeroHeader.
   556  //
   557  // rlpxFrameRW is not safe for concurrent use from multiple goroutines.
   558  type rlpxFrameRW struct {
   559  	conn io.ReadWriter
   560  	enc  cipher.Stream
   561  	dec  cipher.Stream
   562  
   563  	macCipher  cipher.Block
   564  	egressMAC  hash.Hash
   565  	ingressMAC hash.Hash
   566  
   567  	snappy bool
   568  }
   569  
   570  func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW {
   571  	macc, err := aes.NewCipher(s.MAC)
   572  	if err != nil {
   573  		panic("invalid MAC secret: " + err.Error())
   574  	}
   575  	encc, err := aes.NewCipher(s.AES)
   576  	if err != nil {
   577  		panic("invalid AES secret: " + err.Error())
   578  	}
   579  	// we use an all-zeroes IV for AES because the key used
   580  	// for encryption is ephemeral.
   581  	iv := make([]byte, encc.BlockSize())
   582  	return &rlpxFrameRW{
   583  		conn:       conn,
   584  		enc:        cipher.NewCTR(encc, iv),
   585  		dec:        cipher.NewCTR(encc, iv),
   586  		macCipher:  macc,
   587  		egressMAC:  s.EgressMAC,
   588  		ingressMAC: s.IngressMAC,
   589  	}
   590  }
   591  
   592  func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
   593  	ptype, _ := rlp.EncodeToBytes(msg.Code)
   594  
   595  	// if snappy is enabled, compress message now
   596  	if rw.snappy {
   597  		if msg.Size > maxUint24 {
   598  			return errPlainMessageTooLarge
   599  		}
   600  		payload, _ := ioutil.ReadAll(msg.Payload)
   601  		payload = snappy.Encode(nil, payload)
   602  
   603  		msg.Payload = bytes.NewReader(payload)
   604  		msg.Size = uint32(len(payload))
   605  	}
   606  	msg.meterSize = msg.Size
   607  	if metrics.Enabled && msg.meterCap.Name != "" { // don't meter non-subprotocol messages
   608  		metrics.GetOrRegisterMeter(fmt.Sprintf("%s/%s/%d/%#02x", MetricsOutboundTraffic, msg.meterCap.Name, msg.meterCap.Version, msg.meterCode), nil).Mark(int64(msg.meterSize))
   609  	}
   610  	// write header
   611  	headbuf := make([]byte, 32)
   612  	fsize := uint32(len(ptype)) + msg.Size
   613  	if fsize > maxUint24 {
   614  		return errors.New("message size overflows uint24")
   615  	}
   616  	putInt24(fsize, headbuf) // TODO: check overflow
   617  	copy(headbuf[3:], zeroHeader)
   618  	rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
   619  
   620  	// write header MAC
   621  	copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
   622  	if _, err := rw.conn.Write(headbuf); err != nil {
   623  		return err
   624  	}
   625  
   626  	// write encrypted frame, updating the egress MAC hash with
   627  	// the data written to conn.
   628  	tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
   629  	if _, err := tee.Write(ptype); err != nil {
   630  		return err
   631  	}
   632  	if _, err := io.Copy(tee, msg.Payload); err != nil {
   633  		return err
   634  	}
   635  	if padding := fsize % 16; padding > 0 {
   636  		if _, err := tee.Write(zero16[:16-padding]); err != nil {
   637  			return err
   638  		}
   639  	}
   640  
   641  	// write frame MAC. egress MAC hash is up to date because
   642  	// frame content was written to it as well.
   643  	fmacseed := rw.egressMAC.Sum(nil)
   644  	mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
   645  	_, err := rw.conn.Write(mac)
   646  	return err
   647  }
   648  
   649  func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
   650  	// read the header
   651  	headbuf := make([]byte, 32)
   652  	if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
   653  		return msg, err
   654  	}
   655  	// verify header mac
   656  	shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
   657  	if !hmac.Equal(shouldMAC, headbuf[16:]) {
   658  		return msg, errors.New("bad header MAC")
   659  	}
   660  	rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
   661  	fsize := readInt24(headbuf)
   662  	// ignore protocol type for now
   663  
   664  	// read the frame content
   665  	var rsize = fsize // frame size rounded up to 16 byte boundary
   666  	if padding := fsize % 16; padding > 0 {
   667  		rsize += 16 - padding
   668  	}
   669  	framebuf := make([]byte, rsize)
   670  	if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
   671  		return msg, err
   672  	}
   673  
   674  	// read and validate frame MAC. we can re-use headbuf for that.
   675  	rw.ingressMAC.Write(framebuf)
   676  	fmacseed := rw.ingressMAC.Sum(nil)
   677  	if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
   678  		return msg, err
   679  	}
   680  	shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
   681  	if !hmac.Equal(shouldMAC, headbuf[:16]) {
   682  		return msg, errors.New("bad frame MAC")
   683  	}
   684  
   685  	// decrypt frame content
   686  	rw.dec.XORKeyStream(framebuf, framebuf)
   687  
   688  	// decode message code
   689  	content := bytes.NewReader(framebuf[:fsize])
   690  	if err := rlp.Decode(content, &msg.Code); err != nil {
   691  		return msg, err
   692  	}
   693  	msg.Size = uint32(content.Len())
   694  	msg.meterSize = msg.Size
   695  	msg.Payload = content
   696  
   697  	// if snappy is enabled, verify and decompress message
   698  	if rw.snappy {
   699  		payload, err := ioutil.ReadAll(msg.Payload)
   700  		if err != nil {
   701  			return msg, err
   702  		}
   703  		size, err := snappy.DecodedLen(payload)
   704  		if err != nil {
   705  			return msg, err
   706  		}
   707  		if size > int(maxUint24) {
   708  			return msg, errPlainMessageTooLarge
   709  		}
   710  		payload, err = snappy.Decode(nil, payload)
   711  		if err != nil {
   712  			return msg, err
   713  		}
   714  		msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload)
   715  	}
   716  	return msg, nil
   717  }
   718  
   719  // updateMAC reseeds the given hash with encrypted seed.
   720  // it returns the first 16 bytes of the hash sum after seeding.
   721  func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
   722  	aesbuf := make([]byte, aes.BlockSize)
   723  	block.Encrypt(aesbuf, mac.Sum(nil))
   724  	for i := range aesbuf {
   725  		aesbuf[i] ^= seed[i]
   726  	}
   727  	mac.Write(aesbuf)
   728  	return mac.Sum(nil)[:16]
   729  }
   730  
   731  func readInt24(b []byte) uint32 {
   732  	return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
   733  }
   734  
   735  func putInt24(v uint32, b []byte) {
   736  	b[0] = byte(v >> 16)
   737  	b[1] = byte(v >> 8)
   738  	b[2] = byte(v)
   739  }