PageRenderTime 105ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/p2p/enr/enr_test.go

https://bitbucket.org/trung8x/go-ethereum
Go | 318 lines | 238 code | 46 blank | 34 comment | 29 complexity | 2acc99833441cba29a216c5f062e3553 MD5 | raw file
Possible License(s): Apache-2.0, MIT, 0BSD, MPL-2.0-no-copyleft-exception, JSON, GPL-3.0, BSD-3-Clause, LGPL-2.1, BSD-2-Clause
  1. // Copyright 2017 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 enr
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "math/rand"
  22. "testing"
  23. "time"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/rlp"
  26. "github.com/stretchr/testify/assert"
  27. "github.com/stretchr/testify/require"
  28. )
  29. var (
  30. privkey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  31. pubkey = &privkey.PublicKey
  32. )
  33. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  34. func randomString(strlen int) string {
  35. b := make([]byte, strlen)
  36. rnd.Read(b)
  37. return string(b)
  38. }
  39. // TestGetSetID tests encoding/decoding and setting/getting of the ID key.
  40. func TestGetSetID(t *testing.T) {
  41. id := ID("someid")
  42. var r Record
  43. r.Set(id)
  44. var id2 ID
  45. require.NoError(t, r.Load(&id2))
  46. assert.Equal(t, id, id2)
  47. }
  48. // TestGetSetIP4 tests encoding/decoding and setting/getting of the IP4 key.
  49. func TestGetSetIP4(t *testing.T) {
  50. ip := IP4{192, 168, 0, 3}
  51. var r Record
  52. r.Set(ip)
  53. var ip2 IP4
  54. require.NoError(t, r.Load(&ip2))
  55. assert.Equal(t, ip, ip2)
  56. }
  57. // TestGetSetIP6 tests encoding/decoding and setting/getting of the IP6 key.
  58. func TestGetSetIP6(t *testing.T) {
  59. ip := IP6{0x20, 0x01, 0x48, 0x60, 0, 0, 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0x00, 0x68}
  60. var r Record
  61. r.Set(ip)
  62. var ip2 IP6
  63. require.NoError(t, r.Load(&ip2))
  64. assert.Equal(t, ip, ip2)
  65. }
  66. // TestGetSetDiscPort tests encoding/decoding and setting/getting of the DiscPort key.
  67. func TestGetSetDiscPort(t *testing.T) {
  68. port := DiscPort(30309)
  69. var r Record
  70. r.Set(port)
  71. var port2 DiscPort
  72. require.NoError(t, r.Load(&port2))
  73. assert.Equal(t, port, port2)
  74. }
  75. // TestGetSetSecp256k1 tests encoding/decoding and setting/getting of the Secp256k1 key.
  76. func TestGetSetSecp256k1(t *testing.T) {
  77. var r Record
  78. if err := r.Sign(privkey); err != nil {
  79. t.Fatal(err)
  80. }
  81. var pk Secp256k1
  82. require.NoError(t, r.Load(&pk))
  83. assert.EqualValues(t, pubkey, &pk)
  84. }
  85. func TestLoadErrors(t *testing.T) {
  86. var r Record
  87. ip4 := IP4{127, 0, 0, 1}
  88. r.Set(ip4)
  89. // Check error for missing keys.
  90. var ip6 IP6
  91. err := r.Load(&ip6)
  92. if !IsNotFound(err) {
  93. t.Error("IsNotFound should return true for missing key")
  94. }
  95. assert.Equal(t, &KeyError{Key: ip6.ENRKey(), Err: errNotFound}, err)
  96. // Check error for invalid keys.
  97. var list []uint
  98. err = r.Load(WithEntry(ip4.ENRKey(), &list))
  99. kerr, ok := err.(*KeyError)
  100. if !ok {
  101. t.Fatalf("expected KeyError, got %T", err)
  102. }
  103. assert.Equal(t, kerr.Key, ip4.ENRKey())
  104. assert.Error(t, kerr.Err)
  105. if IsNotFound(err) {
  106. t.Error("IsNotFound should return false for decoding errors")
  107. }
  108. }
  109. // TestSortedGetAndSet tests that Set produced a sorted pairs slice.
  110. func TestSortedGetAndSet(t *testing.T) {
  111. type pair struct {
  112. k string
  113. v uint32
  114. }
  115. for _, tt := range []struct {
  116. input []pair
  117. want []pair
  118. }{
  119. {
  120. input: []pair{{"a", 1}, {"c", 2}, {"b", 3}},
  121. want: []pair{{"a", 1}, {"b", 3}, {"c", 2}},
  122. },
  123. {
  124. input: []pair{{"a", 1}, {"c", 2}, {"b", 3}, {"d", 4}, {"a", 5}, {"bb", 6}},
  125. want: []pair{{"a", 5}, {"b", 3}, {"bb", 6}, {"c", 2}, {"d", 4}},
  126. },
  127. {
  128. input: []pair{{"c", 2}, {"b", 3}, {"d", 4}, {"a", 5}, {"bb", 6}},
  129. want: []pair{{"a", 5}, {"b", 3}, {"bb", 6}, {"c", 2}, {"d", 4}},
  130. },
  131. } {
  132. var r Record
  133. for _, i := range tt.input {
  134. r.Set(WithEntry(i.k, &i.v))
  135. }
  136. for i, w := range tt.want {
  137. // set got's key from r.pair[i], so that we preserve order of pairs
  138. got := pair{k: r.pairs[i].k}
  139. assert.NoError(t, r.Load(WithEntry(w.k, &got.v)))
  140. assert.Equal(t, w, got)
  141. }
  142. }
  143. }
  144. // TestDirty tests record signature removal on setting of new key/value pair in record.
  145. func TestDirty(t *testing.T) {
  146. var r Record
  147. if r.Signed() {
  148. t.Error("Signed returned true for zero record")
  149. }
  150. if _, err := rlp.EncodeToBytes(r); err != errEncodeUnsigned {
  151. t.Errorf("expected errEncodeUnsigned, got %#v", err)
  152. }
  153. require.NoError(t, r.Sign(privkey))
  154. if !r.Signed() {
  155. t.Error("Signed return false for signed record")
  156. }
  157. _, err := rlp.EncodeToBytes(r)
  158. assert.NoError(t, err)
  159. r.SetSeq(3)
  160. if r.Signed() {
  161. t.Error("Signed returned true for modified record")
  162. }
  163. if _, err := rlp.EncodeToBytes(r); err != errEncodeUnsigned {
  164. t.Errorf("expected errEncodeUnsigned, got %#v", err)
  165. }
  166. }
  167. // TestGetSetOverwrite tests value overwrite when setting a new value with an existing key in record.
  168. func TestGetSetOverwrite(t *testing.T) {
  169. var r Record
  170. ip := IP4{192, 168, 0, 3}
  171. r.Set(ip)
  172. ip2 := IP4{192, 168, 0, 4}
  173. r.Set(ip2)
  174. var ip3 IP4
  175. require.NoError(t, r.Load(&ip3))
  176. assert.Equal(t, ip2, ip3)
  177. }
  178. // TestSignEncodeAndDecode tests signing, RLP encoding and RLP decoding of a record.
  179. func TestSignEncodeAndDecode(t *testing.T) {
  180. var r Record
  181. r.Set(DiscPort(30303))
  182. r.Set(IP4{127, 0, 0, 1})
  183. require.NoError(t, r.Sign(privkey))
  184. blob, err := rlp.EncodeToBytes(r)
  185. require.NoError(t, err)
  186. var r2 Record
  187. require.NoError(t, rlp.DecodeBytes(blob, &r2))
  188. assert.Equal(t, r, r2)
  189. blob2, err := rlp.EncodeToBytes(r2)
  190. require.NoError(t, err)
  191. assert.Equal(t, blob, blob2)
  192. }
  193. func TestNodeAddr(t *testing.T) {
  194. var r Record
  195. if addr := r.NodeAddr(); addr != nil {
  196. t.Errorf("wrong address on empty record: got %v, want %v", addr, nil)
  197. }
  198. require.NoError(t, r.Sign(privkey))
  199. expected := "caaa1485d83b18b32ed9ad666026151bf0cae8a0a88c857ae2d4c5be2daa6726"
  200. assert.Equal(t, expected, hex.EncodeToString(r.NodeAddr()))
  201. }
  202. var pyRecord, _ = hex.DecodeString("f896b840954dc36583c1f4b69ab59b1375f362f06ee99f3723cd77e64b6de6d211c27d7870642a79d4516997f94091325d2a7ca6215376971455fb221d34f35b277149a1018664697363763582765f82696490736563703235366b312d6b656363616b83697034847f00000189736563703235366b31a103ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd3138")
  203. // TestPythonInterop checks that we can decode and verify a record produced by the Python
  204. // implementation.
  205. func TestPythonInterop(t *testing.T) {
  206. var r Record
  207. if err := rlp.DecodeBytes(pyRecord, &r); err != nil {
  208. t.Fatalf("can't decode: %v", err)
  209. }
  210. var (
  211. wantAddr, _ = hex.DecodeString("caaa1485d83b18b32ed9ad666026151bf0cae8a0a88c857ae2d4c5be2daa6726")
  212. wantSeq = uint64(1)
  213. wantIP = IP4{127, 0, 0, 1}
  214. wantDiscport = DiscPort(30303)
  215. )
  216. if r.Seq() != wantSeq {
  217. t.Errorf("wrong seq: got %d, want %d", r.Seq(), wantSeq)
  218. }
  219. if addr := r.NodeAddr(); !bytes.Equal(addr, wantAddr) {
  220. t.Errorf("wrong addr: got %x, want %x", addr, wantAddr)
  221. }
  222. want := map[Entry]interface{}{new(IP4): &wantIP, new(DiscPort): &wantDiscport}
  223. for k, v := range want {
  224. desc := fmt.Sprintf("loading key %q", k.ENRKey())
  225. if assert.NoError(t, r.Load(k), desc) {
  226. assert.Equal(t, k, v, desc)
  227. }
  228. }
  229. }
  230. // TestRecordTooBig tests that records bigger than SizeLimit bytes cannot be signed.
  231. func TestRecordTooBig(t *testing.T) {
  232. var r Record
  233. key := randomString(10)
  234. // set a big value for random key, expect error
  235. r.Set(WithEntry(key, randomString(300)))
  236. if err := r.Sign(privkey); err != errTooBig {
  237. t.Fatalf("expected to get errTooBig, got %#v", err)
  238. }
  239. // set an acceptable value for random key, expect no error
  240. r.Set(WithEntry(key, randomString(100)))
  241. require.NoError(t, r.Sign(privkey))
  242. }
  243. // TestSignEncodeAndDecodeRandom tests encoding/decoding of records containing random key/value pairs.
  244. func TestSignEncodeAndDecodeRandom(t *testing.T) {
  245. var r Record
  246. // random key/value pairs for testing
  247. pairs := map[string]uint32{}
  248. for i := 0; i < 10; i++ {
  249. key := randomString(7)
  250. value := rnd.Uint32()
  251. pairs[key] = value
  252. r.Set(WithEntry(key, &value))
  253. }
  254. require.NoError(t, r.Sign(privkey))
  255. _, err := rlp.EncodeToBytes(r)
  256. require.NoError(t, err)
  257. for k, v := range pairs {
  258. desc := fmt.Sprintf("key %q", k)
  259. var got uint32
  260. buf := WithEntry(k, &got)
  261. require.NoError(t, r.Load(buf), desc)
  262. require.Equal(t, v, got, desc)
  263. }
  264. }
  265. func BenchmarkDecode(b *testing.B) {
  266. var r Record
  267. for i := 0; i < b.N; i++ {
  268. rlp.DecodeBytes(pyRecord, &r)
  269. }
  270. b.StopTimer()
  271. r.NodeAddr()
  272. }