enr_test.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 IP key.
  49. func TestGetSetIP4(t *testing.T) {
  50. ip := IP{192, 168, 0, 3}
  51. var r Record
  52. r.Set(ip)
  53. var ip2 IP
  54. require.NoError(t, r.Load(&ip2))
  55. assert.Equal(t, ip, ip2)
  56. }
  57. // TestGetSetIP6 tests encoding/decoding and setting/getting of the IP key.
  58. func TestGetSetIP6(t *testing.T) {
  59. ip := IP{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 IP
  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 TestGetSetUDP(t *testing.T) {
  68. port := UDP(30309)
  69. var r Record
  70. r.Set(port)
  71. var port2 UDP
  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 := SignV4(&r, 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 := IP{127, 0, 0, 1}
  88. r.Set(ip4)
  89. // Check error for missing keys.
  90. var udp UDP
  91. err := r.Load(&udp)
  92. if !IsNotFound(err) {
  93. t.Error("IsNotFound should return true for missing key")
  94. }
  95. assert.Equal(t, &KeyError{Key: udp.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, SignV4(&r, 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 := IP{192, 168, 0, 3}
  171. r.Set(ip)
  172. ip2 := IP{192, 168, 0, 4}
  173. r.Set(ip2)
  174. var ip3 IP
  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(UDP(30303))
  182. r.Set(IP{127, 0, 0, 1})
  183. require.NoError(t, SignV4(&r, 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, SignV4(&r, privkey))
  199. expected := "a448f24c6d18e575453db13171562b71999873db5b286df957af199ec94617f7"
  200. assert.Equal(t, expected, hex.EncodeToString(r.NodeAddr()))
  201. }
  202. var pyRecord, _ = hex.DecodeString("f884b8407098ad865b00a582051940cb9cf36836572411a47278783077011599ed5cd16b76f2635f4e234738f30813a89eb9137e3e3df5266e3a1f11df72ecf1145ccb9c01826964827634826970847f00000189736563703235366b31a103ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31388375647082765f")
  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("a448f24c6d18e575453db13171562b71999873db5b286df957af199ec94617f7")
  212. wantSeq = uint64(1)
  213. wantIP = IP{127, 0, 0, 1}
  214. wantUDP = UDP(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(IP): &wantIP, new(UDP): &wantUDP}
  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(SizeLimit)))
  236. if err := SignV4(&r, 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, SignV4(&r, 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, SignV4(&r, 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. }