github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/p2pserver/net/netserver/rlpx.go (about)

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