github.com/klaytn/klaytn@v1.12.1/networks/p2p/rlpx/rlpx.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from p2p/rlpx/rlpx.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  // Package rlpx implements the RLPx transport protocol.
    22  package rlpx
    23  
    24  import (
    25  	"bufio"
    26  	"bytes"
    27  	"crypto/aes"
    28  	"crypto/cipher"
    29  	"crypto/ecdsa"
    30  	"crypto/elliptic"
    31  	"crypto/hmac"
    32  	"crypto/rand"
    33  	"encoding/binary"
    34  	"errors"
    35  	"fmt"
    36  	"hash"
    37  	"io"
    38  	mrand "math/rand"
    39  	"net"
    40  	"time"
    41  
    42  	"github.com/golang/snappy"
    43  	"github.com/klaytn/klaytn/common"
    44  	"github.com/klaytn/klaytn/crypto"
    45  	"github.com/klaytn/klaytn/crypto/ecies"
    46  	"github.com/klaytn/klaytn/crypto/secp256k1"
    47  	"github.com/klaytn/klaytn/crypto/sha3"
    48  	"github.com/klaytn/klaytn/networks/p2p/discover"
    49  	"github.com/klaytn/klaytn/rlp"
    50  )
    51  
    52  // Conn is an RLPx network connection. It wraps a low-level network connection. The
    53  // underlying connection should not be used for other activity when it is wrapped by Conn.
    54  //
    55  // Before sending messages, a handshake must be performed by calling the Handshake method.
    56  // This type is not generally safe for concurrent use, but reading and writing of messages
    57  // may happen concurrently after the handshake.
    58  type Conn struct {
    59  	dialDest *ecdsa.PublicKey
    60  	conn     net.Conn
    61  	session  *sessionState
    62  
    63  	// These are the buffers for snappy compression.
    64  	// Compression is enabled if they are non-nil.
    65  	snappyReadBuffer  []byte
    66  	snappyWriteBuffer []byte
    67  }
    68  
    69  // sessionState contains the session keys.
    70  type sessionState struct {
    71  	enc cipher.Stream
    72  	dec cipher.Stream
    73  
    74  	egressMAC  hashMAC
    75  	ingressMAC hashMAC
    76  	rbuf       readBuffer
    77  	wbuf       writeBuffer
    78  }
    79  
    80  // hashMAC holds the state of the RLPx v4 MAC contraption.
    81  type hashMAC struct {
    82  	cipher     cipher.Block
    83  	hash       hash.Hash
    84  	aesBuffer  [16]byte
    85  	hashBuffer [32]byte
    86  	seedBuffer [32]byte
    87  }
    88  
    89  func newHashMAC(cipher cipher.Block, h hash.Hash) hashMAC {
    90  	m := hashMAC{cipher: cipher, hash: h}
    91  	if cipher.BlockSize() != len(m.aesBuffer) {
    92  		panic(fmt.Errorf("invalid MAC cipher block size %d", cipher.BlockSize()))
    93  	}
    94  	if h.Size() != len(m.hashBuffer) {
    95  		panic(fmt.Errorf("invalid MAC digest size %d", h.Size()))
    96  	}
    97  	return m
    98  }
    99  
   100  // NewConn wraps the given network connection. If dialDest is non-nil, the connection
   101  // behaves as the initiator during the handshake.
   102  func NewConn(conn net.Conn, dialDest *ecdsa.PublicKey) *Conn {
   103  	return &Conn{
   104  		dialDest: dialDest,
   105  		conn:     conn,
   106  	}
   107  }
   108  
   109  // SetSnappy enables or disables snappy compression of messages. This is usually called
   110  // after the devp2p Hello message exchange when the negotiated version indicates that
   111  // compression is available on both ends of the connection.
   112  func (c *Conn) SetSnappy(snappy bool) {
   113  	if snappy {
   114  		c.snappyReadBuffer = []byte{}
   115  		c.snappyWriteBuffer = []byte{}
   116  	} else {
   117  		c.snappyReadBuffer = nil
   118  		c.snappyWriteBuffer = nil
   119  	}
   120  }
   121  
   122  // SetReadDeadline sets the deadline for all future read operations.
   123  func (c *Conn) SetReadDeadline(time time.Time) error {
   124  	return c.conn.SetReadDeadline(time)
   125  }
   126  
   127  // SetWriteDeadline sets the deadline for all future write operations.
   128  func (c *Conn) SetWriteDeadline(time time.Time) error {
   129  	return c.conn.SetWriteDeadline(time)
   130  }
   131  
   132  // SetDeadline sets the deadline for all future read and write operations.
   133  func (c *Conn) SetDeadline(time time.Time) error {
   134  	return c.conn.SetDeadline(time)
   135  }
   136  
   137  // Read reads a message from the connection.
   138  // The returned data buffer is valid until the next call to Read.
   139  func (c *Conn) Read() (code uint64, data []byte, err error) {
   140  	if c.session == nil {
   141  		panic("can't ReadMsg before handshake")
   142  	}
   143  
   144  	frame, err := c.session.readFrame(c.conn)
   145  	if err != nil {
   146  		return 0, nil, err
   147  	}
   148  	code, data, err = rlp.SplitUint64(frame)
   149  	if err != nil {
   150  		return 0, nil, fmt.Errorf("invalid message code: %v", err)
   151  	}
   152  
   153  	// If snappy is enabled, verify and decompress message.
   154  	if c.snappyReadBuffer != nil {
   155  		var actualSize int
   156  		actualSize, err = snappy.DecodedLen(data)
   157  		if err != nil {
   158  			return code, nil, err
   159  		}
   160  		if actualSize > maxUint24 {
   161  			return code, nil, errPlainMessageTooLarge
   162  		}
   163  		c.snappyReadBuffer = growslice(c.snappyReadBuffer, actualSize)
   164  		data, err = snappy.Decode(c.snappyReadBuffer, data)
   165  	}
   166  	return code, data, err
   167  }
   168  
   169  func (h *sessionState) readFrame(conn io.Reader) ([]byte, error) {
   170  	h.rbuf.reset()
   171  
   172  	// Read the frame header.
   173  	header, err := h.rbuf.read(conn, 32)
   174  	if err != nil {
   175  		return nil, err
   176  	}
   177  
   178  	// Verify header MAC.
   179  	wantHeaderMAC := h.ingressMAC.computeHeader(header[:16])
   180  	if !hmac.Equal(wantHeaderMAC, header[16:]) {
   181  		return nil, errors.New("bad header MAC")
   182  	}
   183  
   184  	// Decrypt the frame header to get the frame size.
   185  	h.dec.XORKeyStream(header[:16], header[:16])
   186  	fsize := readUint24(header[:16])
   187  	// Frame size rounded up to 16 byte boundary for padding.
   188  	rsize := fsize
   189  	if padding := fsize % 16; padding > 0 {
   190  		rsize += 16 - padding
   191  	}
   192  	// Read the frame content.
   193  	frame, err := h.rbuf.read(conn, int(rsize))
   194  	if err != nil {
   195  		return nil, err
   196  	}
   197  
   198  	// Validate frame MAC.
   199  	frameMAC, err := h.rbuf.read(conn, 16)
   200  	if err != nil {
   201  		return nil, err
   202  	}
   203  	wantFrameMAC := h.ingressMAC.computeFrame(frame)
   204  	if !hmac.Equal(wantFrameMAC, frameMAC) {
   205  		return nil, errors.New("bad frame MAC")
   206  	}
   207  
   208  	// Decrypt the frame data.
   209  	h.dec.XORKeyStream(frame, frame)
   210  	return frame[:fsize], nil
   211  }
   212  
   213  // Write writes a message to the connection.
   214  //
   215  // Write returns the written size of the message data. This may be less than or equal to
   216  // len(data) depending on whether snappy compression is enabled.
   217  func (c *Conn) Write(code uint64, data []byte) error {
   218  	if c.session == nil {
   219  		panic("can't WriteMsg before handshake")
   220  	}
   221  	if len(data) > maxUint24 {
   222  		return errPlainMessageTooLarge
   223  	}
   224  	if c.snappyWriteBuffer != nil {
   225  		// Ensure the buffer has sufficient size.
   226  		// Package snappy will allocate its own buffer if the provided
   227  		// one is smaller than MaxEncodedLen.
   228  		c.snappyWriteBuffer = growslice(c.snappyWriteBuffer, snappy.MaxEncodedLen(len(data)))
   229  		data = snappy.Encode(c.snappyWriteBuffer, data)
   230  	}
   231  
   232  	return c.session.writeFrame(c.conn, code, data)
   233  }
   234  
   235  func (h *sessionState) writeFrame(conn io.Writer, code uint64, data []byte) error {
   236  	h.wbuf.reset()
   237  
   238  	// Write header.
   239  	fsize := rlp.IntSize(code) + len(data)
   240  	if fsize > maxUint24 {
   241  		return errPlainMessageTooLarge
   242  	}
   243  	header := h.wbuf.appendZero(16)
   244  	putUint24(uint32(fsize), header)
   245  	copy(header[3:], zeroHeader)
   246  	h.enc.XORKeyStream(header, header)
   247  
   248  	// Write header MAC.
   249  	h.wbuf.Write(h.egressMAC.computeHeader(header))
   250  
   251  	// Encode and encrypt the frame data.
   252  	offset := len(h.wbuf.data)
   253  	h.wbuf.data = rlp.AppendUint64(h.wbuf.data, code)
   254  	h.wbuf.Write(data)
   255  	if padding := fsize % 16; padding > 0 {
   256  		h.wbuf.appendZero(16 - padding)
   257  	}
   258  
   259  	framedata := h.wbuf.data[offset:]
   260  	h.enc.XORKeyStream(framedata, framedata)
   261  
   262  	// Write frame MAC.
   263  	h.wbuf.Write(h.egressMAC.computeFrame(framedata))
   264  
   265  	_, err := conn.Write(h.wbuf.data)
   266  	return err
   267  }
   268  
   269  // computeHeader computes the MAC of a frame header.
   270  func (m *hashMAC) computeHeader(header []byte) []byte {
   271  	sum1 := m.hash.Sum(m.hashBuffer[:0])
   272  	return m.compute(sum1, header)
   273  }
   274  
   275  // computeFrame computes the MAC of framedata.
   276  func (m *hashMAC) computeFrame(framedata []byte) []byte {
   277  	m.hash.Write(framedata)
   278  	seed := m.hash.Sum(m.seedBuffer[:0])
   279  	return m.compute(seed, seed[:16])
   280  }
   281  
   282  // compute computes the MAC of a 16-byte 'seed'.
   283  //
   284  // To do this, it encrypts the current value of the hash state, then XORs the ciphertext
   285  // with seed. The obtained value is written back into the hash state and hash output is
   286  // taken again. The first 16 bytes of the resulting sum are the MAC value.
   287  //
   288  // This MAC construction is a horrible, legacy thing.
   289  func (m *hashMAC) compute(sum1, seed []byte) []byte {
   290  	if len(seed) != len(m.aesBuffer) {
   291  		panic("invalid MAC seed")
   292  	}
   293  
   294  	m.cipher.Encrypt(m.aesBuffer[:], sum1)
   295  	for i := range m.aesBuffer {
   296  		m.aesBuffer[i] ^= seed[i]
   297  	}
   298  	m.hash.Write(m.aesBuffer[:])
   299  	sum2 := m.hash.Sum(m.hashBuffer[:0])
   300  	return sum2[:16]
   301  }
   302  
   303  func (c *Conn) ConnTypeHandshake(myConnType common.ConnType) (common.ConnType, error) {
   304  	// myConnType validation
   305  	werr := make(chan error, 1)
   306  	if !myConnType.Valid() {
   307  		return common.ConnTypeUndefined, errors.New("Connection Type is not valid")
   308  	}
   309  
   310  	// send myConnType
   311  	go func() {
   312  		_, err := c.conn.Write([]byte{byte(myConnType)})
   313  		werr <- err
   314  	}()
   315  
   316  	// receive connType
   317  	byteVal, receiveErr := bufio.NewReader(c.conn).ReadByte()
   318  
   319  	// ensure sending is done
   320  	sendErr := <-werr
   321  
   322  	if receiveErr != nil {
   323  		return common.ConnTypeUndefined, receiveErr
   324  	}
   325  	if sendErr != nil {
   326  		return common.ConnTypeUndefined, sendErr
   327  	}
   328  
   329  	// received connType validation
   330  	conntype := common.ConnType(int(byteVal))
   331  	if !conntype.Valid() {
   332  		return common.ConnTypeUndefined, fmt.Errorf("invalid connection type: %v", conntype)
   333  	}
   334  	return conntype, nil
   335  }
   336  
   337  // Handshake performs the handshake. This must be called before any data is written
   338  // or read from the connection.
   339  func (c *Conn) Handshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
   340  	var (
   341  		sec Secrets
   342  		err error
   343  		h   handshakeState
   344  	)
   345  	if c.dialDest != nil {
   346  		sec, err = h.runInitiator(c.conn, prv, c.dialDest)
   347  	} else {
   348  		sec, err = h.runRecipient(c.conn, prv)
   349  	}
   350  	if err != nil {
   351  		return nil, err
   352  	}
   353  
   354  	c.InitWithSecrets(sec)
   355  	c.session.rbuf = h.rbuf
   356  	c.session.wbuf = h.wbuf
   357  	return sec.remote, err
   358  }
   359  
   360  // InitWithSecrets injects connection secrets as if a handshake had
   361  // been performed. This cannot be called after the handshake.
   362  func (c *Conn) InitWithSecrets(sec Secrets) {
   363  	if c.session != nil {
   364  		panic("can't handshake twice")
   365  	}
   366  	macc, err := aes.NewCipher(sec.MAC)
   367  	if err != nil {
   368  		panic("invalid MAC secret: " + err.Error())
   369  	}
   370  	encc, err := aes.NewCipher(sec.AES)
   371  	if err != nil {
   372  		panic("invalid AES secret: " + err.Error())
   373  	}
   374  	// we use an all-zeroes IV for AES because the key used
   375  	// for encryption is ephemeral.
   376  	iv := make([]byte, encc.BlockSize())
   377  	c.session = &sessionState{
   378  		enc:        cipher.NewCTR(encc, iv),
   379  		dec:        cipher.NewCTR(encc, iv),
   380  		egressMAC:  newHashMAC(macc, sec.EgressMAC),
   381  		ingressMAC: newHashMAC(macc, sec.IngressMAC),
   382  	}
   383  }
   384  
   385  // Close closes the underlying network connection.
   386  func (c *Conn) Close() error {
   387  	return c.conn.Close()
   388  }
   389  
   390  const (
   391  	sskLen = 16                     // ecies.MaxSharedKeyLength(pubKey) / 2
   392  	sigLen = crypto.SignatureLength // elliptic S256
   393  	pubLen = 64                     // 512 bit pubkey in uncompressed representation without format byte
   394  	shaLen = 32                     // hash length (for nonce etc)
   395  
   396  	eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */
   397  )
   398  
   399  var (
   400  	// this is used in place of actual frame header data.
   401  	// TODO: replace this when Msg contains the protocol type code.
   402  	zeroHeader = []byte{0xC2, 0x80, 0x80}
   403  
   404  	// errPlainMessageTooLarge is returned if a decompressed message length exceeds
   405  	// the allowed 24 bits (i.e. length >= 16MB).
   406  	errPlainMessageTooLarge = errors.New("message length >= 16MB")
   407  )
   408  
   409  // Secrets represents the connection secrets which are negotiated during the handshake.
   410  type Secrets struct {
   411  	AES, MAC              []byte
   412  	EgressMAC, IngressMAC hash.Hash
   413  	remote                *ecdsa.PublicKey
   414  }
   415  
   416  // encHandshake contains the state of the encryption handshake.
   417  type handshakeState struct {
   418  	initiator            bool
   419  	remote               *ecies.PublicKey  // remote-pubk
   420  	initNonce, respNonce []byte            // nonce
   421  	randomPrivKey        *ecies.PrivateKey // ecdhe-random
   422  	remoteRandomPub      *ecies.PublicKey  // ecdhe-random-pubk
   423  
   424  	rbuf readBuffer
   425  	wbuf writeBuffer
   426  }
   427  
   428  // RLPx v4 handshake auth (defined in EIP-8).
   429  type authMsgV4 struct {
   430  	Signature       [sigLen]byte
   431  	InitiatorPubkey [pubLen]byte
   432  	Nonce           [shaLen]byte
   433  	Version         uint
   434  
   435  	// Ignore additional fields (forward-compatibility)
   436  	Rest []rlp.RawValue `rlp:"tail"`
   437  }
   438  
   439  // RLPx v4 handshake response (defined in EIP-8).
   440  type authRespV4 struct {
   441  	RandomPubkey [pubLen]byte
   442  	Nonce        [shaLen]byte
   443  	Version      uint
   444  
   445  	// Ignore additional fields (forward-compatibility)
   446  	Rest []rlp.RawValue `rlp:"tail"`
   447  }
   448  
   449  // runRecipient negotiates a session token on conn.
   450  // it should be called on the listening side of the connection.
   451  //
   452  // prv is the local client's private key.
   453  func (h *handshakeState) runRecipient(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s Secrets, err error) {
   454  	authMsg := new(authMsgV4)
   455  	authPacket, err := h.readMsg(authMsg, prv, conn)
   456  	if err != nil {
   457  		return s, err
   458  	}
   459  	if err := h.handleAuthMsg(authMsg, prv); err != nil {
   460  		return s, err
   461  	}
   462  
   463  	authRespMsg, err := h.makeAuthResp()
   464  	if err != nil {
   465  		return s, err
   466  	}
   467  	authRespPacket, err := h.sealEIP8(authRespMsg)
   468  	if err != nil {
   469  		return s, err
   470  	}
   471  	if _, err = conn.Write(authRespPacket); err != nil {
   472  		return s, err
   473  	}
   474  
   475  	return h.secrets(authPacket, authRespPacket)
   476  }
   477  
   478  func (h *handshakeState) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
   479  	// Import the remote identity.
   480  	rpub, err := discover.NodeID(msg.InitiatorPubkey).Pubkey()
   481  	if err != nil {
   482  		return fmt.Errorf("bad remoteID: %#v", err)
   483  	}
   484  	h.initNonce = msg.Nonce[:]
   485  	h.remote = ecies.ImportECDSAPublic(rpub)
   486  
   487  	// Generate random keypair for ECDH.
   488  	// If a private key is already set, use it instead of generating one (for testing).
   489  	if h.randomPrivKey == nil {
   490  		h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
   491  		if err != nil {
   492  			return err
   493  		}
   494  	}
   495  
   496  	// Check the signature.
   497  	token, err := h.staticSharedSecret(prv)
   498  	if err != nil {
   499  		return err
   500  	}
   501  	signedMsg := xor(token, h.initNonce)
   502  	remoteRandomPub, err := secp256k1.RecoverPubkey(signedMsg, msg.Signature[:])
   503  	if err != nil {
   504  		return err
   505  	}
   506  	h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
   507  	return nil
   508  }
   509  
   510  // secrets are called after the handshake is completed.
   511  // It extracts the connection secrets from the handshake values.
   512  func (h *handshakeState) secrets(auth, authResp []byte) (Secrets, error) {
   513  	ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
   514  	if err != nil {
   515  		return Secrets{}, err
   516  	}
   517  
   518  	// derive base secrets from ephemeral key agreement
   519  	sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
   520  	aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
   521  	s := Secrets{
   522  		remote: h.remote.ExportECDSA(),
   523  		AES:    aesSecret,
   524  		MAC:    crypto.Keccak256(ecdheSecret, aesSecret),
   525  	}
   526  
   527  	// setup sha3 instances for the MACs
   528  	mac1 := sha3.NewKeccak256()
   529  	mac1.Write(xor(s.MAC, h.respNonce))
   530  	mac1.Write(auth)
   531  	mac2 := sha3.NewKeccak256()
   532  	mac2.Write(xor(s.MAC, h.initNonce))
   533  	mac2.Write(authResp)
   534  	if h.initiator {
   535  		s.EgressMAC, s.IngressMAC = mac1, mac2
   536  	} else {
   537  		s.EgressMAC, s.IngressMAC = mac2, mac1
   538  	}
   539  
   540  	return s, nil
   541  }
   542  
   543  // staticSharedSecret returns the static shared secret, the result
   544  // of key agreement between the local and remote static node key.
   545  func (h *handshakeState) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
   546  	return ecies.ImportECDSA(prv).GenerateShared(h.remote, sskLen, sskLen)
   547  }
   548  
   549  // runInitiator negotiates a session token on conn.
   550  // it should be called on the dialing side of the connection.
   551  //
   552  // prv is the local client's private key.
   553  func (h *handshakeState) runInitiator(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s Secrets, err error) {
   554  	h.initiator = true
   555  	h.remote = ecies.ImportECDSAPublic(remote)
   556  	authMsg, err := h.makeAuthMsg(prv)
   557  	if err != nil {
   558  		return s, err
   559  	}
   560  	authPacket, err := h.sealEIP8(authMsg)
   561  	if err != nil {
   562  		return s, err
   563  	}
   564  
   565  	if _, err = conn.Write(authPacket); err != nil {
   566  		return s, err
   567  	}
   568  
   569  	authRespMsg := new(authRespV4)
   570  	authRespPacket, err := h.readMsg(authRespMsg, prv, conn)
   571  	if err != nil {
   572  		return s, err
   573  	}
   574  	if err := h.handleAuthResp(authRespMsg); err != nil {
   575  		return s, err
   576  	}
   577  
   578  	return h.secrets(authPacket, authRespPacket)
   579  }
   580  
   581  // makeAuthMsg creates the initiator handshake message.
   582  func (h *handshakeState) makeAuthMsg(prv *ecdsa.PrivateKey) (*authMsgV4, error) {
   583  	// Generate random initiator nonce.
   584  	h.initNonce = make([]byte, shaLen)
   585  	_, err := rand.Read(h.initNonce)
   586  	if err != nil {
   587  		return nil, err
   588  	}
   589  	// Generate random keypair to for ECDH.
   590  	h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
   591  	if err != nil {
   592  		return nil, err
   593  	}
   594  
   595  	// Sign known message: static-shared-secret ^ nonce
   596  	token, err := h.staticSharedSecret(prv)
   597  	if err != nil {
   598  		return nil, err
   599  	}
   600  	signed := xor(token, h.initNonce)
   601  	signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
   602  	if err != nil {
   603  		return nil, err
   604  	}
   605  
   606  	msg := new(authMsgV4)
   607  	copy(msg.Signature[:], signature)
   608  	copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
   609  	copy(msg.Nonce[:], h.initNonce)
   610  	msg.Version = 4
   611  	return msg, nil
   612  }
   613  
   614  func (h *handshakeState) handleAuthResp(msg *authRespV4) (err error) {
   615  	h.respNonce = msg.Nonce[:]
   616  	h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:])
   617  	return err
   618  }
   619  
   620  func (h *handshakeState) makeAuthResp() (msg *authRespV4, err error) {
   621  	// Generate random nonce.
   622  	h.respNonce = make([]byte, shaLen)
   623  	if _, err = rand.Read(h.respNonce); err != nil {
   624  		return nil, err
   625  	}
   626  
   627  	msg = new(authRespV4)
   628  	copy(msg.Nonce[:], h.respNonce)
   629  	copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
   630  	msg.Version = 4
   631  	return msg, nil
   632  }
   633  
   634  // readMsg reads an encrypted handshake message, decoding it into msg.
   635  func (h *handshakeState) readMsg(msg interface{}, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
   636  	h.rbuf.reset()
   637  	h.rbuf.grow(512)
   638  
   639  	// Read the size prefix.
   640  	prefix, err := h.rbuf.read(r, 2)
   641  	if err != nil {
   642  		return nil, err
   643  	}
   644  	size := binary.BigEndian.Uint16(prefix)
   645  
   646  	// Read the handshake packet.
   647  	packet, err := h.rbuf.read(r, int(size))
   648  	if err != nil {
   649  		return nil, err
   650  	}
   651  	dec, err := ecies.ImportECDSA(prv).Decrypt(packet, nil, prefix)
   652  	if err != nil {
   653  		return nil, err
   654  	}
   655  	// Can't use rlp.DecodeBytes here because it rejects
   656  	// trailing data (forward-compatibility).
   657  	s := rlp.NewStream(bytes.NewReader(dec), 0)
   658  	err = s.Decode(msg)
   659  	return h.rbuf.data[:len(prefix)+len(packet)], err
   660  }
   661  
   662  // sealEIP8 encrypts a handshake message.
   663  func (h *handshakeState) sealEIP8(msg interface{}) ([]byte, error) {
   664  	h.wbuf.reset()
   665  
   666  	// Write the message plaintext.
   667  	if err := rlp.Encode(&h.wbuf, msg); err != nil {
   668  		return nil, err
   669  	}
   670  	// Pad with random amount of data. the amount needs to be at least 100 bytes to make
   671  	// the message distinguishable from pre-EIP-8 handshakes.
   672  	h.wbuf.appendZero(mrand.Intn(100) + 100)
   673  
   674  	prefix := make([]byte, 2)
   675  	binary.BigEndian.PutUint16(prefix, uint16(len(h.wbuf.data)+eciesOverhead))
   676  
   677  	enc, err := ecies.Encrypt(rand.Reader, h.remote, h.wbuf.data, nil, prefix)
   678  	return append(prefix, enc...), err
   679  }
   680  
   681  // importPublicKey unmarshals 512 bit public keys.
   682  func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
   683  	var pubKey65 []byte
   684  	switch len(pubKey) {
   685  	case 64:
   686  		// add 'uncompressed key' flag
   687  		pubKey65 = append([]byte{0x04}, pubKey...)
   688  	case 65:
   689  		pubKey65 = pubKey
   690  	default:
   691  		return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
   692  	}
   693  	// TODO: fewer pointless conversions
   694  	pub, err := crypto.UnmarshalPubkey(pubKey65)
   695  	if err != nil {
   696  		return nil, err
   697  	}
   698  	return ecies.ImportECDSAPublic(pub), nil
   699  }
   700  
   701  func exportPubkey(pub *ecies.PublicKey) []byte {
   702  	if pub == nil {
   703  		panic("nil pubkey")
   704  	}
   705  	return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
   706  }
   707  
   708  func xor(one, other []byte) (xor []byte) {
   709  	xor = make([]byte, len(one))
   710  	for i := 0; i < len(one); i++ {
   711  		xor[i] = one[i] ^ other[i]
   712  	}
   713  	return xor
   714  }