github.com/cryptogateway/go-paymex@v0.0.0-20210204174735-96277fb1e602/p2p/rlpx/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 rlpx implements the RLPx transport protocol.
    18  package rlpx
    19  
    20  import (
    21  	"bytes"
    22  	"crypto/aes"
    23  	"crypto/cipher"
    24  	"crypto/ecdsa"
    25  	"crypto/elliptic"
    26  	"crypto/hmac"
    27  	"crypto/rand"
    28  	"encoding/binary"
    29  	"errors"
    30  	"fmt"
    31  	"hash"
    32  	"io"
    33  	mrand "math/rand"
    34  	"net"
    35  	"time"
    36  
    37  	"github.com/cryptogateway/go-paymex/crypto"
    38  	"github.com/cryptogateway/go-paymex/crypto/ecies"
    39  	"github.com/cryptogateway/go-paymex/rlp"
    40  	"github.com/golang/snappy"
    41  	"golang.org/x/crypto/sha3"
    42  )
    43  
    44  // Conn is an RLPx network connection. It wraps a low-level network connection. The
    45  // underlying connection should not be used for other activity when it is wrapped by Conn.
    46  //
    47  // Before sending messages, a handshake must be performed by calling the Handshake method.
    48  // This type is not generally safe for concurrent use, but reading and writing of messages
    49  // may happen concurrently after the handshake.
    50  type Conn struct {
    51  	dialDest  *ecdsa.PublicKey
    52  	conn      net.Conn
    53  	handshake *handshakeState
    54  	snappy    bool
    55  }
    56  
    57  type handshakeState struct {
    58  	enc cipher.Stream
    59  	dec cipher.Stream
    60  
    61  	macCipher  cipher.Block
    62  	egressMAC  hash.Hash
    63  	ingressMAC hash.Hash
    64  }
    65  
    66  // NewConn wraps the given network connection. If dialDest is non-nil, the connection
    67  // behaves as the initiator during the handshake.
    68  func NewConn(conn net.Conn, dialDest *ecdsa.PublicKey) *Conn {
    69  	return &Conn{
    70  		dialDest: dialDest,
    71  		conn:     conn,
    72  	}
    73  }
    74  
    75  // SetSnappy enables or disables snappy compression of messages. This is usually called
    76  // after the devp2p Hello message exchange when the negotiated version indicates that
    77  // compression is available on both ends of the connection.
    78  func (c *Conn) SetSnappy(snappy bool) {
    79  	c.snappy = snappy
    80  }
    81  
    82  // SetReadDeadline sets the deadline for all future read operations.
    83  func (c *Conn) SetReadDeadline(time time.Time) error {
    84  	return c.conn.SetReadDeadline(time)
    85  }
    86  
    87  // SetWriteDeadline sets the deadline for all future write operations.
    88  func (c *Conn) SetWriteDeadline(time time.Time) error {
    89  	return c.conn.SetWriteDeadline(time)
    90  }
    91  
    92  // SetDeadline sets the deadline for all future read and write operations.
    93  func (c *Conn) SetDeadline(time time.Time) error {
    94  	return c.conn.SetDeadline(time)
    95  }
    96  
    97  // Read reads a message from the connection.
    98  func (c *Conn) Read() (code uint64, data []byte, wireSize int, err error) {
    99  	if c.handshake == nil {
   100  		panic("can't ReadMsg before handshake")
   101  	}
   102  
   103  	frame, err := c.handshake.readFrame(c.conn)
   104  	if err != nil {
   105  		return 0, nil, 0, err
   106  	}
   107  	code, data, err = rlp.SplitUint64(frame)
   108  	if err != nil {
   109  		return 0, nil, 0, fmt.Errorf("invalid message code: %v", err)
   110  	}
   111  	wireSize = len(data)
   112  
   113  	// If snappy is enabled, verify and decompress message.
   114  	if c.snappy {
   115  		var actualSize int
   116  		actualSize, err = snappy.DecodedLen(data)
   117  		if err != nil {
   118  			return code, nil, 0, err
   119  		}
   120  		if actualSize > maxUint24 {
   121  			return code, nil, 0, errPlainMessageTooLarge
   122  		}
   123  		data, err = snappy.Decode(nil, data)
   124  	}
   125  	return code, data, wireSize, err
   126  }
   127  
   128  func (h *handshakeState) readFrame(conn io.Reader) ([]byte, error) {
   129  	// read the header
   130  	headbuf := make([]byte, 32)
   131  	if _, err := io.ReadFull(conn, headbuf); err != nil {
   132  		return nil, err
   133  	}
   134  
   135  	// verify header mac
   136  	shouldMAC := updateMAC(h.ingressMAC, h.macCipher, headbuf[:16])
   137  	if !hmac.Equal(shouldMAC, headbuf[16:]) {
   138  		return nil, errors.New("bad header MAC")
   139  	}
   140  	h.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
   141  	fsize := readInt24(headbuf)
   142  	// ignore protocol type for now
   143  
   144  	// read the frame content
   145  	var rsize = fsize // frame size rounded up to 16 byte boundary
   146  	if padding := fsize % 16; padding > 0 {
   147  		rsize += 16 - padding
   148  	}
   149  	framebuf := make([]byte, rsize)
   150  	if _, err := io.ReadFull(conn, framebuf); err != nil {
   151  		return nil, err
   152  	}
   153  
   154  	// read and validate frame MAC. we can re-use headbuf for that.
   155  	h.ingressMAC.Write(framebuf)
   156  	fmacseed := h.ingressMAC.Sum(nil)
   157  	if _, err := io.ReadFull(conn, headbuf[:16]); err != nil {
   158  		return nil, err
   159  	}
   160  	shouldMAC = updateMAC(h.ingressMAC, h.macCipher, fmacseed)
   161  	if !hmac.Equal(shouldMAC, headbuf[:16]) {
   162  		return nil, errors.New("bad frame MAC")
   163  	}
   164  
   165  	// decrypt frame content
   166  	h.dec.XORKeyStream(framebuf, framebuf)
   167  	return framebuf[:fsize], nil
   168  }
   169  
   170  // Write writes a message to the connection.
   171  //
   172  // Write returns the written size of the message data. This may be less than or equal to
   173  // len(data) depending on whether snappy compression is enabled.
   174  func (c *Conn) Write(code uint64, data []byte) (uint32, error) {
   175  	if c.handshake == nil {
   176  		panic("can't WriteMsg before handshake")
   177  	}
   178  	if len(data) > maxUint24 {
   179  		return 0, errPlainMessageTooLarge
   180  	}
   181  	if c.snappy {
   182  		data = snappy.Encode(nil, data)
   183  	}
   184  
   185  	wireSize := uint32(len(data))
   186  	err := c.handshake.writeFrame(c.conn, code, data)
   187  	return wireSize, err
   188  }
   189  
   190  func (h *handshakeState) writeFrame(conn io.Writer, code uint64, data []byte) error {
   191  	ptype, _ := rlp.EncodeToBytes(code)
   192  
   193  	// write header
   194  	headbuf := make([]byte, 32)
   195  	fsize := len(ptype) + len(data)
   196  	if fsize > maxUint24 {
   197  		return errPlainMessageTooLarge
   198  	}
   199  	putInt24(uint32(fsize), headbuf)
   200  	copy(headbuf[3:], zeroHeader)
   201  	h.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
   202  
   203  	// write header MAC
   204  	copy(headbuf[16:], updateMAC(h.egressMAC, h.macCipher, headbuf[:16]))
   205  	if _, err := conn.Write(headbuf); err != nil {
   206  		return err
   207  	}
   208  
   209  	// write encrypted frame, updating the egress MAC hash with
   210  	// the data written to conn.
   211  	tee := cipher.StreamWriter{S: h.enc, W: io.MultiWriter(conn, h.egressMAC)}
   212  	if _, err := tee.Write(ptype); err != nil {
   213  		return err
   214  	}
   215  	if _, err := tee.Write(data); err != nil {
   216  		return err
   217  	}
   218  	if padding := fsize % 16; padding > 0 {
   219  		if _, err := tee.Write(zero16[:16-padding]); err != nil {
   220  			return err
   221  		}
   222  	}
   223  
   224  	// write frame MAC. egress MAC hash is up to date because
   225  	// frame content was written to it as well.
   226  	fmacseed := h.egressMAC.Sum(nil)
   227  	mac := updateMAC(h.egressMAC, h.macCipher, fmacseed)
   228  	_, err := conn.Write(mac)
   229  	return err
   230  }
   231  
   232  func readInt24(b []byte) uint32 {
   233  	return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
   234  }
   235  
   236  func putInt24(v uint32, b []byte) {
   237  	b[0] = byte(v >> 16)
   238  	b[1] = byte(v >> 8)
   239  	b[2] = byte(v)
   240  }
   241  
   242  // updateMAC reseeds the given hash with encrypted seed.
   243  // it returns the first 16 bytes of the hash sum after seeding.
   244  func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
   245  	aesbuf := make([]byte, aes.BlockSize)
   246  	block.Encrypt(aesbuf, mac.Sum(nil))
   247  	for i := range aesbuf {
   248  		aesbuf[i] ^= seed[i]
   249  	}
   250  	mac.Write(aesbuf)
   251  	return mac.Sum(nil)[:16]
   252  }
   253  
   254  // Handshake performs the handshake. This must be called before any data is written
   255  // or read from the connection.
   256  func (c *Conn) Handshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
   257  	var (
   258  		sec Secrets
   259  		err error
   260  	)
   261  	if c.dialDest != nil {
   262  		sec, err = initiatorEncHandshake(c.conn, prv, c.dialDest)
   263  	} else {
   264  		sec, err = receiverEncHandshake(c.conn, prv)
   265  	}
   266  	if err != nil {
   267  		return nil, err
   268  	}
   269  	c.InitWithSecrets(sec)
   270  	return sec.remote, err
   271  }
   272  
   273  // InitWithSecrets injects connection secrets as if a handshake had
   274  // been performed. This cannot be called after the handshake.
   275  func (c *Conn) InitWithSecrets(sec Secrets) {
   276  	if c.handshake != nil {
   277  		panic("can't handshake twice")
   278  	}
   279  	macc, err := aes.NewCipher(sec.MAC)
   280  	if err != nil {
   281  		panic("invalid MAC secret: " + err.Error())
   282  	}
   283  	encc, err := aes.NewCipher(sec.AES)
   284  	if err != nil {
   285  		panic("invalid AES secret: " + err.Error())
   286  	}
   287  	// we use an all-zeroes IV for AES because the key used
   288  	// for encryption is ephemeral.
   289  	iv := make([]byte, encc.BlockSize())
   290  	c.handshake = &handshakeState{
   291  		enc:        cipher.NewCTR(encc, iv),
   292  		dec:        cipher.NewCTR(encc, iv),
   293  		macCipher:  macc,
   294  		egressMAC:  sec.EgressMAC,
   295  		ingressMAC: sec.IngressMAC,
   296  	}
   297  }
   298  
   299  // Close closes the underlying network connection.
   300  func (c *Conn) Close() error {
   301  	return c.conn.Close()
   302  }
   303  
   304  // Constants for the handshake.
   305  const (
   306  	maxUint24 = int(^uint32(0) >> 8)
   307  
   308  	sskLen = 16                     // ecies.MaxSharedKeyLength(pubKey) / 2
   309  	sigLen = crypto.SignatureLength // elliptic S256
   310  	pubLen = 64                     // 512 bit pubkey in uncompressed representation without format byte
   311  	shaLen = 32                     // hash length (for nonce etc)
   312  
   313  	authMsgLen  = sigLen + shaLen + pubLen + shaLen + 1
   314  	authRespLen = pubLen + shaLen + 1
   315  
   316  	eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */
   317  
   318  	encAuthMsgLen  = authMsgLen + eciesOverhead  // size of encrypted pre-EIP-8 initiator handshake
   319  	encAuthRespLen = authRespLen + eciesOverhead // size of encrypted pre-EIP-8 handshake reply
   320  )
   321  
   322  var (
   323  	// this is used in place of actual frame header data.
   324  	// TODO: replace this when Msg contains the protocol type code.
   325  	zeroHeader = []byte{0xC2, 0x80, 0x80}
   326  	// sixteen zero bytes
   327  	zero16 = make([]byte, 16)
   328  
   329  	// errPlainMessageTooLarge is returned if a decompressed message length exceeds
   330  	// the allowed 24 bits (i.e. length >= 16MB).
   331  	errPlainMessageTooLarge = errors.New("message length >= 16MB")
   332  )
   333  
   334  // Secrets represents the connection secrets which are negotiated during the handshake.
   335  type Secrets struct {
   336  	AES, MAC              []byte
   337  	EgressMAC, IngressMAC hash.Hash
   338  	remote                *ecdsa.PublicKey
   339  }
   340  
   341  // encHandshake contains the state of the encryption handshake.
   342  type encHandshake struct {
   343  	initiator            bool
   344  	remote               *ecies.PublicKey  // remote-pubk
   345  	initNonce, respNonce []byte            // nonce
   346  	randomPrivKey        *ecies.PrivateKey // ecdhe-random
   347  	remoteRandomPub      *ecies.PublicKey  // ecdhe-random-pubk
   348  }
   349  
   350  // RLPx v4 handshake auth (defined in EIP-8).
   351  type authMsgV4 struct {
   352  	gotPlain bool // whether read packet had plain format.
   353  
   354  	Signature       [sigLen]byte
   355  	InitiatorPubkey [pubLen]byte
   356  	Nonce           [shaLen]byte
   357  	Version         uint
   358  
   359  	// Ignore additional fields (forward-compatibility)
   360  	Rest []rlp.RawValue `rlp:"tail"`
   361  }
   362  
   363  // RLPx v4 handshake response (defined in EIP-8).
   364  type authRespV4 struct {
   365  	RandomPubkey [pubLen]byte
   366  	Nonce        [shaLen]byte
   367  	Version      uint
   368  
   369  	// Ignore additional fields (forward-compatibility)
   370  	Rest []rlp.RawValue `rlp:"tail"`
   371  }
   372  
   373  // receiverEncHandshake negotiates a session token on conn.
   374  // it should be called on the listening side of the connection.
   375  //
   376  // prv is the local client's private key.
   377  func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s Secrets, err error) {
   378  	authMsg := new(authMsgV4)
   379  	authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
   380  	if err != nil {
   381  		return s, err
   382  	}
   383  	h := new(encHandshake)
   384  	if err := h.handleAuthMsg(authMsg, prv); err != nil {
   385  		return s, err
   386  	}
   387  
   388  	authRespMsg, err := h.makeAuthResp()
   389  	if err != nil {
   390  		return s, err
   391  	}
   392  	var authRespPacket []byte
   393  	if authMsg.gotPlain {
   394  		authRespPacket, err = authRespMsg.sealPlain(h)
   395  	} else {
   396  		authRespPacket, err = sealEIP8(authRespMsg, h)
   397  	}
   398  	if err != nil {
   399  		return s, err
   400  	}
   401  	if _, err = conn.Write(authRespPacket); err != nil {
   402  		return s, err
   403  	}
   404  	return h.secrets(authPacket, authRespPacket)
   405  }
   406  
   407  func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
   408  	// Import the remote identity.
   409  	rpub, err := importPublicKey(msg.InitiatorPubkey[:])
   410  	if err != nil {
   411  		return err
   412  	}
   413  	h.initNonce = msg.Nonce[:]
   414  	h.remote = rpub
   415  
   416  	// Generate random keypair for ECDH.
   417  	// If a private key is already set, use it instead of generating one (for testing).
   418  	if h.randomPrivKey == nil {
   419  		h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
   420  		if err != nil {
   421  			return err
   422  		}
   423  	}
   424  
   425  	// Check the signature.
   426  	token, err := h.staticSharedSecret(prv)
   427  	if err != nil {
   428  		return err
   429  	}
   430  	signedMsg := xor(token, h.initNonce)
   431  	remoteRandomPub, err := crypto.Ecrecover(signedMsg, msg.Signature[:])
   432  	if err != nil {
   433  		return err
   434  	}
   435  	h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
   436  	return nil
   437  }
   438  
   439  // secrets is called after the handshake is completed.
   440  // It extracts the connection secrets from the handshake values.
   441  func (h *encHandshake) secrets(auth, authResp []byte) (Secrets, error) {
   442  	ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
   443  	if err != nil {
   444  		return Secrets{}, err
   445  	}
   446  
   447  	// derive base secrets from ephemeral key agreement
   448  	sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
   449  	aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
   450  	s := Secrets{
   451  		remote: h.remote.ExportECDSA(),
   452  		AES:    aesSecret,
   453  		MAC:    crypto.Keccak256(ecdheSecret, aesSecret),
   454  	}
   455  
   456  	// setup sha3 instances for the MACs
   457  	mac1 := sha3.NewLegacyKeccak256()
   458  	mac1.Write(xor(s.MAC, h.respNonce))
   459  	mac1.Write(auth)
   460  	mac2 := sha3.NewLegacyKeccak256()
   461  	mac2.Write(xor(s.MAC, h.initNonce))
   462  	mac2.Write(authResp)
   463  	if h.initiator {
   464  		s.EgressMAC, s.IngressMAC = mac1, mac2
   465  	} else {
   466  		s.EgressMAC, s.IngressMAC = mac2, mac1
   467  	}
   468  
   469  	return s, nil
   470  }
   471  
   472  // staticSharedSecret returns the static shared secret, the result
   473  // of key agreement between the local and remote static node key.
   474  func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
   475  	return ecies.ImportECDSA(prv).GenerateShared(h.remote, sskLen, sskLen)
   476  }
   477  
   478  // initiatorEncHandshake negotiates a session token on conn.
   479  // it should be called on the dialing side of the connection.
   480  //
   481  // prv is the local client's private key.
   482  func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s Secrets, err error) {
   483  	h := &encHandshake{initiator: true, remote: ecies.ImportECDSAPublic(remote)}
   484  	authMsg, err := h.makeAuthMsg(prv)
   485  	if err != nil {
   486  		return s, err
   487  	}
   488  	authPacket, err := sealEIP8(authMsg, h)
   489  	if err != nil {
   490  		return s, err
   491  	}
   492  
   493  	if _, err = conn.Write(authPacket); err != nil {
   494  		return s, err
   495  	}
   496  
   497  	authRespMsg := new(authRespV4)
   498  	authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
   499  	if err != nil {
   500  		return s, err
   501  	}
   502  	if err := h.handleAuthResp(authRespMsg); err != nil {
   503  		return s, err
   504  	}
   505  	return h.secrets(authPacket, authRespPacket)
   506  }
   507  
   508  // makeAuthMsg creates the initiator handshake message.
   509  func (h *encHandshake) makeAuthMsg(prv *ecdsa.PrivateKey) (*authMsgV4, error) {
   510  	// Generate random initiator nonce.
   511  	h.initNonce = make([]byte, shaLen)
   512  	_, err := rand.Read(h.initNonce)
   513  	if err != nil {
   514  		return nil, err
   515  	}
   516  	// Generate random keypair to for ECDH.
   517  	h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
   518  	if err != nil {
   519  		return nil, err
   520  	}
   521  
   522  	// Sign known message: static-shared-secret ^ nonce
   523  	token, err := h.staticSharedSecret(prv)
   524  	if err != nil {
   525  		return nil, err
   526  	}
   527  	signed := xor(token, h.initNonce)
   528  	signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
   529  	if err != nil {
   530  		return nil, err
   531  	}
   532  
   533  	msg := new(authMsgV4)
   534  	copy(msg.Signature[:], signature)
   535  	copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
   536  	copy(msg.Nonce[:], h.initNonce)
   537  	msg.Version = 4
   538  	return msg, nil
   539  }
   540  
   541  func (h *encHandshake) handleAuthResp(msg *authRespV4) (err error) {
   542  	h.respNonce = msg.Nonce[:]
   543  	h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:])
   544  	return err
   545  }
   546  
   547  func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
   548  	// Generate random nonce.
   549  	h.respNonce = make([]byte, shaLen)
   550  	if _, err = rand.Read(h.respNonce); err != nil {
   551  		return nil, err
   552  	}
   553  
   554  	msg = new(authRespV4)
   555  	copy(msg.Nonce[:], h.respNonce)
   556  	copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
   557  	msg.Version = 4
   558  	return msg, nil
   559  }
   560  
   561  func (msg *authMsgV4) decodePlain(input []byte) {
   562  	n := copy(msg.Signature[:], input)
   563  	n += shaLen // skip sha3(initiator-ephemeral-pubk)
   564  	n += copy(msg.InitiatorPubkey[:], input[n:])
   565  	copy(msg.Nonce[:], input[n:])
   566  	msg.Version = 4
   567  	msg.gotPlain = true
   568  }
   569  
   570  func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
   571  	buf := make([]byte, authRespLen)
   572  	n := copy(buf, msg.RandomPubkey[:])
   573  	copy(buf[n:], msg.Nonce[:])
   574  	return ecies.Encrypt(rand.Reader, hs.remote, buf, nil, nil)
   575  }
   576  
   577  func (msg *authRespV4) decodePlain(input []byte) {
   578  	n := copy(msg.RandomPubkey[:], input)
   579  	copy(msg.Nonce[:], input[n:])
   580  	msg.Version = 4
   581  }
   582  
   583  var padSpace = make([]byte, 300)
   584  
   585  func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
   586  	buf := new(bytes.Buffer)
   587  	if err := rlp.Encode(buf, msg); err != nil {
   588  		return nil, err
   589  	}
   590  	// pad with random amount of data. the amount needs to be at least 100 bytes to make
   591  	// the message distinguishable from pre-EIP-8 handshakes.
   592  	pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
   593  	buf.Write(pad)
   594  	prefix := make([]byte, 2)
   595  	binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
   596  
   597  	enc, err := ecies.Encrypt(rand.Reader, h.remote, buf.Bytes(), nil, prefix)
   598  	return append(prefix, enc...), err
   599  }
   600  
   601  type plainDecoder interface {
   602  	decodePlain([]byte)
   603  }
   604  
   605  func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
   606  	buf := make([]byte, plainSize)
   607  	if _, err := io.ReadFull(r, buf); err != nil {
   608  		return buf, err
   609  	}
   610  	// Attempt decoding pre-EIP-8 "plain" format.
   611  	key := ecies.ImportECDSA(prv)
   612  	if dec, err := key.Decrypt(buf, nil, nil); err == nil {
   613  		msg.decodePlain(dec)
   614  		return buf, nil
   615  	}
   616  	// Could be EIP-8 format, try that.
   617  	prefix := buf[:2]
   618  	size := binary.BigEndian.Uint16(prefix)
   619  	if size < uint16(plainSize) {
   620  		return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
   621  	}
   622  	buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
   623  	if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
   624  		return buf, err
   625  	}
   626  	dec, err := key.Decrypt(buf[2:], nil, prefix)
   627  	if err != nil {
   628  		return buf, err
   629  	}
   630  	// Can't use rlp.DecodeBytes here because it rejects
   631  	// trailing data (forward-compatibility).
   632  	s := rlp.NewStream(bytes.NewReader(dec), 0)
   633  	return buf, s.Decode(msg)
   634  }
   635  
   636  // importPublicKey unmarshals 512 bit public keys.
   637  func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
   638  	var pubKey65 []byte
   639  	switch len(pubKey) {
   640  	case 64:
   641  		// add 'uncompressed key' flag
   642  		pubKey65 = append([]byte{0x04}, pubKey...)
   643  	case 65:
   644  		pubKey65 = pubKey
   645  	default:
   646  		return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
   647  	}
   648  	// TODO: fewer pointless conversions
   649  	pub, err := crypto.UnmarshalPubkey(pubKey65)
   650  	if err != nil {
   651  		return nil, err
   652  	}
   653  	return ecies.ImportECDSAPublic(pub), nil
   654  }
   655  
   656  func exportPubkey(pub *ecies.PublicKey) []byte {
   657  	if pub == nil {
   658  		panic("nil pubkey")
   659  	}
   660  	return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
   661  }
   662  
   663  func xor(one, other []byte) (xor []byte) {
   664  	xor = make([]byte, len(one))
   665  	for i := 0; i < len(one); i++ {
   666  		xor[i] = one[i] ^ other[i]
   667  	}
   668  	return xor
   669  }