gopkg.in/bitherhq/go-bither.v1@v1.7.1/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/crypto"
    39  	"github.com/ethereum/go-ethereum/crypto/ecies"
    40  	"github.com/ethereum/go-ethereum/crypto/secp256k1"
    41  	"github.com/ethereum/go-ethereum/crypto/sha3"
    42  	"github.com/ethereum/go-ethereum/p2p/discover"
    43  	"github.com/ethereum/go-ethereum/rlp"
    44  	"github.com/golang/snappy"
    45  )
    46  
    47  const (
    48  	maxUint24 = ^uint32(0) >> 8
    49  
    50  	sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
    51  	sigLen = 65 // 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  			t.fd.SetWriteDeadline(time.Now().Add(discWriteTimeout))
   112  			SendItems(t.rw, discMsg, r)
   113  		}
   114  	}
   115  	t.fd.Close()
   116  }
   117  
   118  // doEncHandshake runs the protocol handshake using authenticated
   119  // messages. the protocol handshake is the first authenticated message
   120  // and also verifies whether the encryption handshake 'worked' and the
   121  // remote side actually provided the right public key.
   122  func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
   123  	// Writing our handshake happens concurrently, we prefer
   124  	// returning the handshake read error. If the remote side
   125  	// disconnects us early with a valid reason, we should return it
   126  	// as the error so it can be tracked elsewhere.
   127  	werr := make(chan error, 1)
   128  	go func() { werr <- Send(t.rw, handshakeMsg, our) }()
   129  	if their, err = readProtocolHandshake(t.rw, our); err != nil {
   130  		<-werr // make sure the write terminates too
   131  		return nil, err
   132  	}
   133  	if err := <-werr; err != nil {
   134  		return nil, fmt.Errorf("write error: %v", err)
   135  	}
   136  	// If the protocol version supports Snappy encoding, upgrade immediately
   137  	t.rw.snappy = their.Version >= snappyProtocolVersion
   138  
   139  	return their, nil
   140  }
   141  
   142  func readProtocolHandshake(rw MsgReader, our *protoHandshake) (*protoHandshake, error) {
   143  	msg, err := rw.ReadMsg()
   144  	if err != nil {
   145  		return nil, err
   146  	}
   147  	if msg.Size > baseProtocolMaxMsgSize {
   148  		return nil, fmt.Errorf("message too big")
   149  	}
   150  	if msg.Code == discMsg {
   151  		// Disconnect before protocol handshake is valid according to the
   152  		// spec and we send it ourself if the posthanshake checks fail.
   153  		// We can't return the reason directly, though, because it is echoed
   154  		// back otherwise. Wrap it in a string instead.
   155  		var reason [1]DiscReason
   156  		rlp.Decode(msg.Payload, &reason)
   157  		return nil, reason[0]
   158  	}
   159  	if msg.Code != handshakeMsg {
   160  		return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
   161  	}
   162  	var hs protoHandshake
   163  	if err := msg.Decode(&hs); err != nil {
   164  		return nil, err
   165  	}
   166  	if (hs.ID == discover.NodeID{}) {
   167  		return nil, DiscInvalidIdentity
   168  	}
   169  	return &hs, nil
   170  }
   171  
   172  func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *discover.Node) (discover.NodeID, error) {
   173  	var (
   174  		sec secrets
   175  		err error
   176  	)
   177  	if dial == nil {
   178  		sec, err = receiverEncHandshake(t.fd, prv, nil)
   179  	} else {
   180  		sec, err = initiatorEncHandshake(t.fd, prv, dial.ID, nil)
   181  	}
   182  	if err != nil {
   183  		return discover.NodeID{}, err
   184  	}
   185  	t.wmu.Lock()
   186  	t.rw = newRLPXFrameRW(t.fd, sec)
   187  	t.wmu.Unlock()
   188  	return sec.RemoteID, nil
   189  }
   190  
   191  // encHandshake contains the state of the encryption handshake.
   192  type encHandshake struct {
   193  	initiator bool
   194  	remoteID  discover.NodeID
   195  
   196  	remotePub            *ecies.PublicKey  // remote-pubk
   197  	initNonce, respNonce []byte            // nonce
   198  	randomPrivKey        *ecies.PrivateKey // ecdhe-random
   199  	remoteRandomPub      *ecies.PublicKey  // ecdhe-random-pubk
   200  }
   201  
   202  // secrets represents the connection secrets
   203  // which are negotiated during the encryption handshake.
   204  type secrets struct {
   205  	RemoteID              discover.NodeID
   206  	AES, MAC              []byte
   207  	EgressMAC, IngressMAC hash.Hash
   208  	Token                 []byte
   209  }
   210  
   211  // RLPx v4 handshake auth (defined in EIP-8).
   212  type authMsgV4 struct {
   213  	gotPlain bool // whether read packet had plain format.
   214  
   215  	Signature       [sigLen]byte
   216  	InitiatorPubkey [pubLen]byte
   217  	Nonce           [shaLen]byte
   218  	Version         uint
   219  
   220  	// Ignore additional fields (forward-compatibility)
   221  	Rest []rlp.RawValue `rlp:"tail"`
   222  }
   223  
   224  // RLPx v4 handshake response (defined in EIP-8).
   225  type authRespV4 struct {
   226  	RandomPubkey [pubLen]byte
   227  	Nonce        [shaLen]byte
   228  	Version      uint
   229  
   230  	// Ignore additional fields (forward-compatibility)
   231  	Rest []rlp.RawValue `rlp:"tail"`
   232  }
   233  
   234  // secrets is called after the handshake is completed.
   235  // It extracts the connection secrets from the handshake values.
   236  func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
   237  	ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
   238  	if err != nil {
   239  		return secrets{}, err
   240  	}
   241  
   242  	// derive base secrets from ephemeral key agreement
   243  	sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
   244  	aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
   245  	s := secrets{
   246  		RemoteID: h.remoteID,
   247  		AES:      aesSecret,
   248  		MAC:      crypto.Keccak256(ecdheSecret, aesSecret),
   249  	}
   250  
   251  	// setup sha3 instances for the MACs
   252  	mac1 := sha3.NewKeccak256()
   253  	mac1.Write(xor(s.MAC, h.respNonce))
   254  	mac1.Write(auth)
   255  	mac2 := sha3.NewKeccak256()
   256  	mac2.Write(xor(s.MAC, h.initNonce))
   257  	mac2.Write(authResp)
   258  	if h.initiator {
   259  		s.EgressMAC, s.IngressMAC = mac1, mac2
   260  	} else {
   261  		s.EgressMAC, s.IngressMAC = mac2, mac1
   262  	}
   263  
   264  	return s, nil
   265  }
   266  
   267  // staticSharedSecret returns the static shared secret, the result
   268  // of key agreement between the local and remote static node key.
   269  func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
   270  	return ecies.ImportECDSA(prv).GenerateShared(h.remotePub, sskLen, sskLen)
   271  }
   272  
   273  // initiatorEncHandshake negotiates a session token on conn.
   274  // it should be called on the dialing side of the connection.
   275  //
   276  // prv is the local client's private key.
   277  func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.NodeID, token []byte) (s secrets, err error) {
   278  	h := &encHandshake{initiator: true, remoteID: remoteID}
   279  	authMsg, err := h.makeAuthMsg(prv, token)
   280  	if err != nil {
   281  		return s, err
   282  	}
   283  	authPacket, err := sealEIP8(authMsg, h)
   284  	if err != nil {
   285  		return s, err
   286  	}
   287  	if _, err = conn.Write(authPacket); err != nil {
   288  		return s, err
   289  	}
   290  
   291  	authRespMsg := new(authRespV4)
   292  	authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
   293  	if err != nil {
   294  		return s, err
   295  	}
   296  	if err := h.handleAuthResp(authRespMsg); err != nil {
   297  		return s, err
   298  	}
   299  	return h.secrets(authPacket, authRespPacket)
   300  }
   301  
   302  // makeAuthMsg creates the initiator handshake message.
   303  func (h *encHandshake) makeAuthMsg(prv *ecdsa.PrivateKey, token []byte) (*authMsgV4, error) {
   304  	rpub, err := h.remoteID.Pubkey()
   305  	if err != nil {
   306  		return nil, fmt.Errorf("bad remoteID: %v", err)
   307  	}
   308  	h.remotePub = ecies.ImportECDSAPublic(rpub)
   309  	// Generate random initiator nonce.
   310  	h.initNonce = make([]byte, shaLen)
   311  	if _, err := rand.Read(h.initNonce); 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  // token is the token from a previous session with this node.
   350  func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, token []byte) (s secrets, err error) {
   351  	authMsg := new(authMsgV4)
   352  	authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
   353  	if err != nil {
   354  		return s, err
   355  	}
   356  	h := new(encHandshake)
   357  	if err := h.handleAuthMsg(authMsg, prv); err != nil {
   358  		return s, err
   359  	}
   360  
   361  	authRespMsg, err := h.makeAuthResp()
   362  	if err != nil {
   363  		return s, err
   364  	}
   365  	var authRespPacket []byte
   366  	if authMsg.gotPlain {
   367  		authRespPacket, err = authRespMsg.sealPlain(h)
   368  	} else {
   369  		authRespPacket, err = sealEIP8(authRespMsg, h)
   370  	}
   371  	if err != nil {
   372  		return s, err
   373  	}
   374  	if _, err = conn.Write(authRespPacket); err != nil {
   375  		return s, err
   376  	}
   377  	return h.secrets(authPacket, authRespPacket)
   378  }
   379  
   380  func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
   381  	// Import the remote identity.
   382  	h.initNonce = msg.Nonce[:]
   383  	h.remoteID = msg.InitiatorPubkey
   384  	rpub, err := h.remoteID.Pubkey()
   385  	if err != nil {
   386  		return fmt.Errorf("bad remoteID: %#v", err)
   387  	}
   388  	h.remotePub = ecies.ImportECDSAPublic(rpub)
   389  
   390  	// Generate random keypair for ECDH.
   391  	// If a private key is already set, use it instead of generating one (for testing).
   392  	if h.randomPrivKey == nil {
   393  		h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
   394  		if err != nil {
   395  			return err
   396  		}
   397  	}
   398  
   399  	// Check the signature.
   400  	token, err := h.staticSharedSecret(prv)
   401  	if err != nil {
   402  		return err
   403  	}
   404  	signedMsg := xor(token, h.initNonce)
   405  	remoteRandomPub, err := secp256k1.RecoverPubkey(signedMsg, msg.Signature[:])
   406  	if err != nil {
   407  		return err
   408  	}
   409  	h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
   410  	return nil
   411  }
   412  
   413  func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
   414  	// Generate random nonce.
   415  	h.respNonce = make([]byte, shaLen)
   416  	if _, err = rand.Read(h.respNonce); err != nil {
   417  		return nil, err
   418  	}
   419  
   420  	msg = new(authRespV4)
   421  	copy(msg.Nonce[:], h.respNonce)
   422  	copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
   423  	msg.Version = 4
   424  	return msg, nil
   425  }
   426  
   427  func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) {
   428  	buf := make([]byte, authMsgLen)
   429  	n := copy(buf, msg.Signature[:])
   430  	n += copy(buf[n:], crypto.Keccak256(exportPubkey(&h.randomPrivKey.PublicKey)))
   431  	n += copy(buf[n:], msg.InitiatorPubkey[:])
   432  	n += copy(buf[n:], msg.Nonce[:])
   433  	buf[n] = 0 // token-flag
   434  	return ecies.Encrypt(rand.Reader, h.remotePub, buf, nil, nil)
   435  }
   436  
   437  func (msg *authMsgV4) decodePlain(input []byte) {
   438  	n := copy(msg.Signature[:], input)
   439  	n += shaLen // skip sha3(initiator-ephemeral-pubk)
   440  	n += copy(msg.InitiatorPubkey[:], input[n:])
   441  	copy(msg.Nonce[:], input[n:])
   442  	msg.Version = 4
   443  	msg.gotPlain = true
   444  }
   445  
   446  func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
   447  	buf := make([]byte, authRespLen)
   448  	n := copy(buf, msg.RandomPubkey[:])
   449  	copy(buf[n:], msg.Nonce[:])
   450  	return ecies.Encrypt(rand.Reader, hs.remotePub, buf, nil, nil)
   451  }
   452  
   453  func (msg *authRespV4) decodePlain(input []byte) {
   454  	n := copy(msg.RandomPubkey[:], input)
   455  	copy(msg.Nonce[:], input[n:])
   456  	msg.Version = 4
   457  }
   458  
   459  var padSpace = make([]byte, 300)
   460  
   461  func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
   462  	buf := new(bytes.Buffer)
   463  	if err := rlp.Encode(buf, msg); err != nil {
   464  		return nil, err
   465  	}
   466  	// pad with random amount of data. the amount needs to be at least 100 bytes to make
   467  	// the message distinguishable from pre-EIP-8 handshakes.
   468  	pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
   469  	buf.Write(pad)
   470  	prefix := make([]byte, 2)
   471  	binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
   472  
   473  	enc, err := ecies.Encrypt(rand.Reader, h.remotePub, buf.Bytes(), nil, prefix)
   474  	return append(prefix, enc...), err
   475  }
   476  
   477  type plainDecoder interface {
   478  	decodePlain([]byte)
   479  }
   480  
   481  func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
   482  	buf := make([]byte, plainSize)
   483  	if _, err := io.ReadFull(r, buf); err != nil {
   484  		return buf, err
   485  	}
   486  	// Attempt decoding pre-EIP-8 "plain" format.
   487  	key := ecies.ImportECDSA(prv)
   488  	if dec, err := key.Decrypt(rand.Reader, buf, nil, nil); err == nil {
   489  		msg.decodePlain(dec)
   490  		return buf, nil
   491  	}
   492  	// Could be EIP-8 format, try that.
   493  	prefix := buf[:2]
   494  	size := binary.BigEndian.Uint16(prefix)
   495  	if size < uint16(plainSize) {
   496  		return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
   497  	}
   498  	buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
   499  	if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
   500  		return buf, err
   501  	}
   502  	dec, err := key.Decrypt(rand.Reader, buf[2:], nil, prefix)
   503  	if err != nil {
   504  		return buf, err
   505  	}
   506  	// Can't use rlp.DecodeBytes here because it rejects
   507  	// trailing data (forward-compatibility).
   508  	s := rlp.NewStream(bytes.NewReader(dec), 0)
   509  	return buf, s.Decode(msg)
   510  }
   511  
   512  // importPublicKey unmarshals 512 bit public keys.
   513  func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
   514  	var pubKey65 []byte
   515  	switch len(pubKey) {
   516  	case 64:
   517  		// add 'uncompressed key' flag
   518  		pubKey65 = append([]byte{0x04}, pubKey...)
   519  	case 65:
   520  		pubKey65 = pubKey
   521  	default:
   522  		return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
   523  	}
   524  	// TODO: fewer pointless conversions
   525  	pub := crypto.ToECDSAPub(pubKey65)
   526  	if pub.X == nil {
   527  		return nil, fmt.Errorf("invalid public key")
   528  	}
   529  	return ecies.ImportECDSAPublic(pub), nil
   530  }
   531  
   532  func exportPubkey(pub *ecies.PublicKey) []byte {
   533  	if pub == nil {
   534  		panic("nil pubkey")
   535  	}
   536  	return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
   537  }
   538  
   539  func xor(one, other []byte) (xor []byte) {
   540  	xor = make([]byte, len(one))
   541  	for i := 0; i < len(one); i++ {
   542  		xor[i] = one[i] ^ other[i]
   543  	}
   544  	return xor
   545  }
   546  
   547  var (
   548  	// this is used in place of actual frame header data.
   549  	// TODO: replace this when Msg contains the protocol type code.
   550  	zeroHeader = []byte{0xC2, 0x80, 0x80}
   551  	// sixteen zero bytes
   552  	zero16 = make([]byte, 16)
   553  )
   554  
   555  // rlpxFrameRW implements a simplified version of RLPx framing.
   556  // chunked messages are not supported and all headers are equal to
   557  // zeroHeader.
   558  //
   559  // rlpxFrameRW is not safe for concurrent use from multiple goroutines.
   560  type rlpxFrameRW struct {
   561  	conn io.ReadWriter
   562  	enc  cipher.Stream
   563  	dec  cipher.Stream
   564  
   565  	macCipher  cipher.Block
   566  	egressMAC  hash.Hash
   567  	ingressMAC hash.Hash
   568  
   569  	snappy bool
   570  }
   571  
   572  func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW {
   573  	macc, err := aes.NewCipher(s.MAC)
   574  	if err != nil {
   575  		panic("invalid MAC secret: " + err.Error())
   576  	}
   577  	encc, err := aes.NewCipher(s.AES)
   578  	if err != nil {
   579  		panic("invalid AES secret: " + err.Error())
   580  	}
   581  	// we use an all-zeroes IV for AES because the key used
   582  	// for encryption is ephemeral.
   583  	iv := make([]byte, encc.BlockSize())
   584  	return &rlpxFrameRW{
   585  		conn:       conn,
   586  		enc:        cipher.NewCTR(encc, iv),
   587  		dec:        cipher.NewCTR(encc, iv),
   588  		macCipher:  macc,
   589  		egressMAC:  s.EgressMAC,
   590  		ingressMAC: s.IngressMAC,
   591  	}
   592  }
   593  
   594  func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
   595  	ptype, _ := rlp.EncodeToBytes(msg.Code)
   596  
   597  	// if snappy is enabled, compress message now
   598  	if rw.snappy {
   599  		if msg.Size > maxUint24 {
   600  			return errPlainMessageTooLarge
   601  		}
   602  		payload, _ := ioutil.ReadAll(msg.Payload)
   603  		payload = snappy.Encode(nil, payload)
   604  
   605  		msg.Payload = bytes.NewReader(payload)
   606  		msg.Size = uint32(len(payload))
   607  	}
   608  	// write header
   609  	headbuf := make([]byte, 32)
   610  	fsize := uint32(len(ptype)) + msg.Size
   611  	if fsize > maxUint24 {
   612  		return errors.New("message size overflows uint24")
   613  	}
   614  	putInt24(fsize, headbuf) // TODO: check overflow
   615  	copy(headbuf[3:], zeroHeader)
   616  	rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
   617  
   618  	// write header MAC
   619  	copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
   620  	if _, err := rw.conn.Write(headbuf); err != nil {
   621  		return err
   622  	}
   623  
   624  	// write encrypted frame, updating the egress MAC hash with
   625  	// the data written to conn.
   626  	tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
   627  	if _, err := tee.Write(ptype); err != nil {
   628  		return err
   629  	}
   630  	if _, err := io.Copy(tee, msg.Payload); err != nil {
   631  		return err
   632  	}
   633  	if padding := fsize % 16; padding > 0 {
   634  		if _, err := tee.Write(zero16[:16-padding]); err != nil {
   635  			return err
   636  		}
   637  	}
   638  
   639  	// write frame MAC. egress MAC hash is up to date because
   640  	// frame content was written to it as well.
   641  	fmacseed := rw.egressMAC.Sum(nil)
   642  	mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
   643  	_, err := rw.conn.Write(mac)
   644  	return err
   645  }
   646  
   647  func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
   648  	// read the header
   649  	headbuf := make([]byte, 32)
   650  	if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
   651  		return msg, err
   652  	}
   653  	// verify header mac
   654  	shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
   655  	if !hmac.Equal(shouldMAC, headbuf[16:]) {
   656  		return msg, errors.New("bad header MAC")
   657  	}
   658  	rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
   659  	fsize := readInt24(headbuf)
   660  	// ignore protocol type for now
   661  
   662  	// read the frame content
   663  	var rsize = fsize // frame size rounded up to 16 byte boundary
   664  	if padding := fsize % 16; padding > 0 {
   665  		rsize += 16 - padding
   666  	}
   667  	framebuf := make([]byte, rsize)
   668  	if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
   669  		return msg, err
   670  	}
   671  
   672  	// read and validate frame MAC. we can re-use headbuf for that.
   673  	rw.ingressMAC.Write(framebuf)
   674  	fmacseed := rw.ingressMAC.Sum(nil)
   675  	if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
   676  		return msg, err
   677  	}
   678  	shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
   679  	if !hmac.Equal(shouldMAC, headbuf[:16]) {
   680  		return msg, errors.New("bad frame MAC")
   681  	}
   682  
   683  	// decrypt frame content
   684  	rw.dec.XORKeyStream(framebuf, framebuf)
   685  
   686  	// decode message code
   687  	content := bytes.NewReader(framebuf[:fsize])
   688  	if err := rlp.Decode(content, &msg.Code); err != nil {
   689  		return msg, err
   690  	}
   691  	msg.Size = uint32(content.Len())
   692  	msg.Payload = content
   693  
   694  	// if snappy is enabled, verify and decompress message
   695  	if rw.snappy {
   696  		payload, err := ioutil.ReadAll(msg.Payload)
   697  		if err != nil {
   698  			return msg, err
   699  		}
   700  		size, err := snappy.DecodedLen(payload)
   701  		if err != nil {
   702  			return msg, err
   703  		}
   704  		if size > int(maxUint24) {
   705  			return msg, errPlainMessageTooLarge
   706  		}
   707  		payload, err = snappy.Decode(nil, payload)
   708  		if err != nil {
   709  			return msg, err
   710  		}
   711  		msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload)
   712  	}
   713  	return msg, nil
   714  }
   715  
   716  // updateMAC reseeds the given hash with encrypted seed.
   717  // it returns the first 16 bytes of the hash sum after seeding.
   718  func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
   719  	aesbuf := make([]byte, aes.BlockSize)
   720  	block.Encrypt(aesbuf, mac.Sum(nil))
   721  	for i := range aesbuf {
   722  		aesbuf[i] ^= seed[i]
   723  	}
   724  	mac.Write(aesbuf)
   725  	return mac.Sum(nil)[:16]
   726  }
   727  
   728  func readInt24(b []byte) uint32 {
   729  	return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
   730  }
   731  
   732  func putInt24(v uint32, b []byte) {
   733  	b[0] = byte(v >> 16)
   734  	b[1] = byte(v >> 8)
   735  	b[2] = byte(v)
   736  }