rlpx_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // Copyright 2020 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
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "encoding/hex"
  21. "fmt"
  22. "io"
  23. "math/rand"
  24. "net"
  25. "reflect"
  26. "strings"
  27. "testing"
  28. "github.com/davecgh/go-spew/spew"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/crypto/ecies"
  31. "github.com/ethereum/go-ethereum/p2p/simulations/pipes"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "github.com/stretchr/testify/assert"
  34. )
  35. type message struct {
  36. code uint64
  37. data []byte
  38. err error
  39. }
  40. func TestHandshake(t *testing.T) {
  41. p1, p2 := createPeers(t)
  42. p1.Close()
  43. p2.Close()
  44. }
  45. // This test checks that messages can be sent and received through WriteMsg/ReadMsg.
  46. func TestReadWriteMsg(t *testing.T) {
  47. peer1, peer2 := createPeers(t)
  48. defer peer1.Close()
  49. defer peer2.Close()
  50. testCode := uint64(23)
  51. testData := []byte("test")
  52. checkMsgReadWrite(t, peer1, peer2, testCode, testData)
  53. t.Log("enabling snappy")
  54. peer1.SetSnappy(true)
  55. peer2.SetSnappy(true)
  56. checkMsgReadWrite(t, peer1, peer2, testCode, testData)
  57. }
  58. func checkMsgReadWrite(t *testing.T, p1, p2 *Conn, msgCode uint64, msgData []byte) {
  59. // Set up the reader.
  60. ch := make(chan message, 1)
  61. go func() {
  62. var msg message
  63. msg.code, msg.data, _, msg.err = p1.Read()
  64. ch <- msg
  65. }()
  66. // Write the message.
  67. _, err := p2.Write(msgCode, msgData)
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. // Check it was received correctly.
  72. msg := <-ch
  73. assert.Equal(t, msgCode, msg.code, "wrong message code returned from ReadMsg")
  74. assert.Equal(t, msgData, msg.data, "wrong message data returned from ReadMsg")
  75. }
  76. func createPeers(t *testing.T) (peer1, peer2 *Conn) {
  77. conn1, conn2 := net.Pipe()
  78. key1, key2 := newkey(), newkey()
  79. peer1 = NewConn(conn1, &key2.PublicKey) // dialer
  80. peer2 = NewConn(conn2, nil) // listener
  81. doHandshake(t, peer1, peer2, key1, key2)
  82. return peer1, peer2
  83. }
  84. func doHandshake(t *testing.T, peer1, peer2 *Conn, key1, key2 *ecdsa.PrivateKey) {
  85. keyChan := make(chan *ecdsa.PublicKey, 1)
  86. go func() {
  87. pubKey, err := peer2.Handshake(key2)
  88. if err != nil {
  89. t.Errorf("peer2 could not do handshake: %v", err)
  90. }
  91. keyChan <- pubKey
  92. }()
  93. pubKey2, err := peer1.Handshake(key1)
  94. if err != nil {
  95. t.Errorf("peer1 could not do handshake: %v", err)
  96. }
  97. pubKey1 := <-keyChan
  98. // Confirm the handshake was successful.
  99. if !reflect.DeepEqual(pubKey1, &key1.PublicKey) || !reflect.DeepEqual(pubKey2, &key2.PublicKey) {
  100. t.Fatal("unsuccessful handshake")
  101. }
  102. }
  103. // This test checks the frame data of written messages.
  104. func TestFrameReadWrite(t *testing.T) {
  105. conn := NewConn(nil, nil)
  106. hash := fakeHash([]byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})
  107. conn.InitWithSecrets(Secrets{
  108. AES: crypto.Keccak256(),
  109. MAC: crypto.Keccak256(),
  110. IngressMAC: hash,
  111. EgressMAC: hash,
  112. })
  113. h := conn.session
  114. golden := unhex(`
  115. 00828ddae471818bb0bfa6b551d1cb42
  116. 01010101010101010101010101010101
  117. ba628a4ba590cb43f7848f41c4382885
  118. 01010101010101010101010101010101
  119. `)
  120. msgCode := uint64(8)
  121. msg := []uint{1, 2, 3, 4}
  122. msgEnc, _ := rlp.EncodeToBytes(msg)
  123. // Check writeFrame. The frame that's written should be equal to the test vector.
  124. buf := new(bytes.Buffer)
  125. if err := h.writeFrame(buf, msgCode, msgEnc); err != nil {
  126. t.Fatalf("WriteMsg error: %v", err)
  127. }
  128. if !bytes.Equal(buf.Bytes(), golden) {
  129. t.Fatalf("output mismatch:\n got: %x\n want: %x", buf.Bytes(), golden)
  130. }
  131. // Check readFrame on the test vector.
  132. content, err := h.readFrame(bytes.NewReader(golden))
  133. if err != nil {
  134. t.Fatalf("ReadMsg error: %v", err)
  135. }
  136. wantContent := unhex("08C401020304")
  137. if !bytes.Equal(content, wantContent) {
  138. t.Errorf("frame content mismatch:\ngot %x\nwant %x", content, wantContent)
  139. }
  140. }
  141. type fakeHash []byte
  142. func (fakeHash) Write(p []byte) (int, error) { return len(p), nil }
  143. func (fakeHash) Reset() {}
  144. func (fakeHash) BlockSize() int { return 0 }
  145. func (h fakeHash) Size() int { return len(h) }
  146. func (h fakeHash) Sum(b []byte) []byte { return append(b, h...) }
  147. type handshakeAuthTest struct {
  148. input string
  149. wantVersion uint
  150. wantRest []rlp.RawValue
  151. }
  152. var eip8HandshakeAuthTests = []handshakeAuthTest{
  153. // (Auth₂) EIP-8 encoding
  154. {
  155. input: `
  156. 01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b
  157. 0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84
  158. 9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c
  159. da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc
  160. 147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6
  161. d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee
  162. 70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09
  163. c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3
  164. 6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e
  165. 2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c
  166. 3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c
  167. `,
  168. wantVersion: 4,
  169. wantRest: []rlp.RawValue{},
  170. },
  171. // (Auth₃) RLPx v4 EIP-8 encoding with version 56, additional list elements
  172. {
  173. input: `
  174. 01b8044c6c312173685d1edd268aa95e1d495474c6959bcdd10067ba4c9013df9e40ff45f5bfd6f7
  175. 2471f93a91b493f8e00abc4b80f682973de715d77ba3a005a242eb859f9a211d93a347fa64b597bf
  176. 280a6b88e26299cf263b01b8dfdb712278464fd1c25840b995e84d367d743f66c0e54a586725b7bb
  177. f12acca27170ae3283c1073adda4b6d79f27656993aefccf16e0d0409fe07db2dc398a1b7e8ee93b
  178. cd181485fd332f381d6a050fba4c7641a5112ac1b0b61168d20f01b479e19adf7fdbfa0905f63352
  179. bfc7e23cf3357657455119d879c78d3cf8c8c06375f3f7d4861aa02a122467e069acaf513025ff19
  180. 6641f6d2810ce493f51bee9c966b15c5043505350392b57645385a18c78f14669cc4d960446c1757
  181. 1b7c5d725021babbcd786957f3d17089c084907bda22c2b2675b4378b114c601d858802a55345a15
  182. 116bc61da4193996187ed70d16730e9ae6b3bb8787ebcaea1871d850997ddc08b4f4ea668fbf3740
  183. 7ac044b55be0908ecb94d4ed172ece66fd31bfdadf2b97a8bc690163ee11f5b575a4b44e36e2bfb2
  184. f0fce91676fd64c7773bac6a003f481fddd0bae0a1f31aa27504e2a533af4cef3b623f4791b2cca6
  185. d490
  186. `,
  187. wantVersion: 56,
  188. wantRest: []rlp.RawValue{{0x01}, {0x02}, {0xC2, 0x04, 0x05}},
  189. },
  190. }
  191. type handshakeAckTest struct {
  192. input string
  193. wantVersion uint
  194. wantRest []rlp.RawValue
  195. }
  196. var eip8HandshakeRespTests = []handshakeAckTest{
  197. // (Ack₂) EIP-8 encoding
  198. {
  199. input: `
  200. 01ea0451958701280a56482929d3b0757da8f7fbe5286784beead59d95089c217c9b917788989470
  201. b0e330cc6e4fb383c0340ed85fab836ec9fb8a49672712aeabbdfd1e837c1ff4cace34311cd7f4de
  202. 05d59279e3524ab26ef753a0095637ac88f2b499b9914b5f64e143eae548a1066e14cd2f4bd7f814
  203. c4652f11b254f8a2d0191e2f5546fae6055694aed14d906df79ad3b407d94692694e259191cde171
  204. ad542fc588fa2b7333313d82a9f887332f1dfc36cea03f831cb9a23fea05b33deb999e85489e645f
  205. 6aab1872475d488d7bd6c7c120caf28dbfc5d6833888155ed69d34dbdc39c1f299be1057810f34fb
  206. e754d021bfca14dc989753d61c413d261934e1a9c67ee060a25eefb54e81a4d14baff922180c395d
  207. 3f998d70f46f6b58306f969627ae364497e73fc27f6d17ae45a413d322cb8814276be6ddd13b885b
  208. 201b943213656cde498fa0e9ddc8e0b8f8a53824fbd82254f3e2c17e8eaea009c38b4aa0a3f306e8
  209. 797db43c25d68e86f262e564086f59a2fc60511c42abfb3057c247a8a8fe4fb3ccbadde17514b7ac
  210. 8000cdb6a912778426260c47f38919a91f25f4b5ffb455d6aaaf150f7e5529c100ce62d6d92826a7
  211. 1778d809bdf60232ae21ce8a437eca8223f45ac37f6487452ce626f549b3b5fdee26afd2072e4bc7
  212. 5833c2464c805246155289f4
  213. `,
  214. wantVersion: 4,
  215. wantRest: []rlp.RawValue{},
  216. },
  217. // (Ack₃) EIP-8 encoding with version 57, additional list elements
  218. {
  219. input: `
  220. 01f004076e58aae772bb101ab1a8e64e01ee96e64857ce82b1113817c6cdd52c09d26f7b90981cd7
  221. ae835aeac72e1573b8a0225dd56d157a010846d888dac7464baf53f2ad4e3d584531fa203658fab0
  222. 3a06c9fd5e35737e417bc28c1cbf5e5dfc666de7090f69c3b29754725f84f75382891c561040ea1d
  223. dc0d8f381ed1b9d0d4ad2a0ec021421d847820d6fa0ba66eaf58175f1b235e851c7e2124069fbc20
  224. 2888ddb3ac4d56bcbd1b9b7eab59e78f2e2d400905050f4a92dec1c4bdf797b3fc9b2f8e84a482f3
  225. d800386186712dae00d5c386ec9387a5e9c9a1aca5a573ca91082c7d68421f388e79127a5177d4f8
  226. 590237364fd348c9611fa39f78dcdceee3f390f07991b7b47e1daa3ebcb6ccc9607811cb17ce51f1
  227. c8c2c5098dbdd28fca547b3f58c01a424ac05f869f49c6a34672ea2cbbc558428aa1fe48bbfd6115
  228. 8b1b735a65d99f21e70dbc020bfdface9f724a0d1fb5895db971cc81aa7608baa0920abb0a565c9c
  229. 436e2fd13323428296c86385f2384e408a31e104670df0791d93e743a3a5194ee6b076fb6323ca59
  230. 3011b7348c16cf58f66b9633906ba54a2ee803187344b394f75dd2e663a57b956cb830dd7a908d4f
  231. 39a2336a61ef9fda549180d4ccde21514d117b6c6fd07a9102b5efe710a32af4eeacae2cb3b1dec0
  232. 35b9593b48b9d3ca4c13d245d5f04169b0b1
  233. `,
  234. wantVersion: 57,
  235. wantRest: []rlp.RawValue{{0x06}, {0xC2, 0x07, 0x08}, {0x81, 0xFA}},
  236. },
  237. }
  238. var (
  239. keyA, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  240. keyB, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  241. )
  242. func TestHandshakeForwardCompatibility(t *testing.T) {
  243. var (
  244. pubA = crypto.FromECDSAPub(&keyA.PublicKey)[1:]
  245. pubB = crypto.FromECDSAPub(&keyB.PublicKey)[1:]
  246. ephA, _ = crypto.HexToECDSA("869d6ecf5211f1cc60418a13b9d870b22959d0c16f02bec714c960dd2298a32d")
  247. ephB, _ = crypto.HexToECDSA("e238eb8e04fee6511ab04c6dd3c89ce097b11f25d584863ac2b6d5b35b1847e4")
  248. ephPubA = crypto.FromECDSAPub(&ephA.PublicKey)[1:]
  249. ephPubB = crypto.FromECDSAPub(&ephB.PublicKey)[1:]
  250. nonceA = unhex("7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6")
  251. nonceB = unhex("559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd")
  252. _, _, _, _ = pubA, pubB, ephPubA, ephPubB
  253. authSignature = unhex("299ca6acfd35e3d72d8ba3d1e2b60b5561d5af5218eb5bc182045769eb4226910a301acae3b369fffc4a4899d6b02531e89fd4fe36a2cf0d93607ba470b50f7800")
  254. _ = authSignature
  255. )
  256. makeAuth := func(test handshakeAuthTest) *authMsgV4 {
  257. msg := &authMsgV4{Version: test.wantVersion, Rest: test.wantRest}
  258. copy(msg.Signature[:], authSignature)
  259. copy(msg.InitiatorPubkey[:], pubA)
  260. copy(msg.Nonce[:], nonceA)
  261. return msg
  262. }
  263. makeAck := func(test handshakeAckTest) *authRespV4 {
  264. msg := &authRespV4{Version: test.wantVersion, Rest: test.wantRest}
  265. copy(msg.RandomPubkey[:], ephPubB)
  266. copy(msg.Nonce[:], nonceB)
  267. return msg
  268. }
  269. // check auth msg parsing
  270. for _, test := range eip8HandshakeAuthTests {
  271. var h handshakeState
  272. r := bytes.NewReader(unhex(test.input))
  273. msg := new(authMsgV4)
  274. ciphertext, err := h.readMsg(msg, keyB, r)
  275. if err != nil {
  276. t.Errorf("error for input %x:\n %v", unhex(test.input), err)
  277. continue
  278. }
  279. if !bytes.Equal(ciphertext, unhex(test.input)) {
  280. t.Errorf("wrong ciphertext for input %x:\n %x", unhex(test.input), ciphertext)
  281. }
  282. want := makeAuth(test)
  283. if !reflect.DeepEqual(msg, want) {
  284. t.Errorf("wrong msg for input %x:\ngot %s\nwant %s", unhex(test.input), spew.Sdump(msg), spew.Sdump(want))
  285. }
  286. }
  287. // check auth resp parsing
  288. for _, test := range eip8HandshakeRespTests {
  289. var h handshakeState
  290. input := unhex(test.input)
  291. r := bytes.NewReader(input)
  292. msg := new(authRespV4)
  293. ciphertext, err := h.readMsg(msg, keyA, r)
  294. if err != nil {
  295. t.Errorf("error for input %x:\n %v", input, err)
  296. continue
  297. }
  298. if !bytes.Equal(ciphertext, input) {
  299. t.Errorf("wrong ciphertext for input %x:\n %x", input, err)
  300. }
  301. want := makeAck(test)
  302. if !reflect.DeepEqual(msg, want) {
  303. t.Errorf("wrong msg for input %x:\ngot %s\nwant %s", input, spew.Sdump(msg), spew.Sdump(want))
  304. }
  305. }
  306. // check derivation for (Auth₂, Ack₂) on recipient side
  307. var (
  308. hs = &handshakeState{
  309. initiator: false,
  310. respNonce: nonceB,
  311. randomPrivKey: ecies.ImportECDSA(ephB),
  312. }
  313. authCiphertext = unhex(eip8HandshakeAuthTests[0].input)
  314. authRespCiphertext = unhex(eip8HandshakeRespTests[0].input)
  315. authMsg = makeAuth(eip8HandshakeAuthTests[0])
  316. wantAES = unhex("80e8632c05fed6fc2a13b0f8d31a3cf645366239170ea067065aba8e28bac487")
  317. wantMAC = unhex("2ea74ec5dae199227dff1af715362700e989d889d7a493cb0639691efb8e5f98")
  318. wantFooIngressHash = unhex("0c7ec6340062cc46f5e9f1e3cf86f8c8c403c5a0964f5df0ebd34a75ddc86db5")
  319. )
  320. if err := hs.handleAuthMsg(authMsg, keyB); err != nil {
  321. t.Fatalf("handleAuthMsg: %v", err)
  322. }
  323. derived, err := hs.secrets(authCiphertext, authRespCiphertext)
  324. if err != nil {
  325. t.Fatalf("secrets: %v", err)
  326. }
  327. if !bytes.Equal(derived.AES, wantAES) {
  328. t.Errorf("aes-secret mismatch:\ngot %x\nwant %x", derived.AES, wantAES)
  329. }
  330. if !bytes.Equal(derived.MAC, wantMAC) {
  331. t.Errorf("mac-secret mismatch:\ngot %x\nwant %x", derived.MAC, wantMAC)
  332. }
  333. io.WriteString(derived.IngressMAC, "foo")
  334. fooIngressHash := derived.IngressMAC.Sum(nil)
  335. if !bytes.Equal(fooIngressHash, wantFooIngressHash) {
  336. t.Errorf("ingress-mac('foo') mismatch:\ngot %x\nwant %x", fooIngressHash, wantFooIngressHash)
  337. }
  338. }
  339. func BenchmarkHandshakeRead(b *testing.B) {
  340. var input = unhex(eip8HandshakeAuthTests[0].input)
  341. for i := 0; i < b.N; i++ {
  342. var (
  343. h handshakeState
  344. r = bytes.NewReader(input)
  345. msg = new(authMsgV4)
  346. )
  347. if _, err := h.readMsg(msg, keyB, r); err != nil {
  348. b.Fatal(err)
  349. }
  350. }
  351. }
  352. func BenchmarkThroughput(b *testing.B) {
  353. pipe1, pipe2, err := pipes.TCPPipe()
  354. if err != nil {
  355. b.Fatal(err)
  356. }
  357. var (
  358. conn1, conn2 = NewConn(pipe1, nil), NewConn(pipe2, &keyA.PublicKey)
  359. handshakeDone = make(chan error, 1)
  360. msgdata = make([]byte, 1024)
  361. rand = rand.New(rand.NewSource(1337))
  362. )
  363. rand.Read(msgdata)
  364. // Server side.
  365. go func() {
  366. defer conn1.Close()
  367. // Perform handshake.
  368. _, err := conn1.Handshake(keyA)
  369. handshakeDone <- err
  370. if err != nil {
  371. return
  372. }
  373. conn1.SetSnappy(true)
  374. // Keep sending messages until connection closed.
  375. for {
  376. if _, err := conn1.Write(0, msgdata); err != nil {
  377. return
  378. }
  379. }
  380. }()
  381. // Set up client side.
  382. defer conn2.Close()
  383. if _, err := conn2.Handshake(keyB); err != nil {
  384. b.Fatal("client handshake error:", err)
  385. }
  386. conn2.SetSnappy(true)
  387. if err := <-handshakeDone; err != nil {
  388. b.Fatal("server hanshake error:", err)
  389. }
  390. // Read N messages.
  391. b.SetBytes(int64(len(msgdata)))
  392. b.ReportAllocs()
  393. for i := 0; i < b.N; i++ {
  394. _, _, _, err := conn2.Read()
  395. if err != nil {
  396. b.Fatal("read error:", err)
  397. }
  398. }
  399. }
  400. func unhex(str string) []byte {
  401. r := strings.NewReplacer("\t", "", " ", "", "\n", "")
  402. b, err := hex.DecodeString(r.Replace(str))
  403. if err != nil {
  404. panic(fmt.Sprintf("invalid hex string: %q", str))
  405. }
  406. return b
  407. }
  408. func newkey() *ecdsa.PrivateKey {
  409. key, err := crypto.GenerateKey()
  410. if err != nil {
  411. panic("couldn't generate key: " + err.Error())
  412. }
  413. return key
  414. }