rlpx.go 19 KB

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