node_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 discv5
  17. import (
  18. "fmt"
  19. "math/big"
  20. "math/rand"
  21. "net"
  22. "reflect"
  23. "strings"
  24. "testing"
  25. "testing/quick"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. )
  30. func ExampleNewNode() {
  31. id := MustHexID("1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439")
  32. // Complete nodes contain UDP and TCP endpoints:
  33. n1 := NewNode(id, net.ParseIP("2001:db8:3c4d:15::abcd:ef12"), 52150, 30303)
  34. fmt.Println("n1:", n1)
  35. fmt.Println("n1.Incomplete() ->", n1.Incomplete())
  36. // An incomplete node can be created by passing zero values
  37. // for all parameters except id.
  38. n2 := NewNode(id, nil, 0, 0)
  39. fmt.Println("n2:", n2)
  40. fmt.Println("n2.Incomplete() ->", n2.Incomplete())
  41. // Output:
  42. // n1: enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439@[2001:db8:3c4d:15::abcd:ef12]:30303?discport=52150
  43. // n1.Incomplete() -> false
  44. // n2: enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439
  45. // n2.Incomplete() -> true
  46. }
  47. var parseNodeTests = []struct {
  48. rawurl string
  49. wantError string
  50. wantResult *Node
  51. }{
  52. {
  53. rawurl: "http://foobar",
  54. wantError: `invalid URL scheme, want "enode"`,
  55. },
  56. {
  57. rawurl: "enode://01010101@123.124.125.126:3",
  58. wantError: `invalid node ID (wrong length, want 128 hex chars)`,
  59. },
  60. // Complete nodes with IP address.
  61. {
  62. rawurl: "enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439@hostname:3",
  63. wantError: `invalid IP address`,
  64. },
  65. {
  66. rawurl: "enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439@127.0.0.1:foo",
  67. wantError: `invalid port`,
  68. },
  69. {
  70. rawurl: "enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439@127.0.0.1:3?discport=foo",
  71. wantError: `invalid discport in query`,
  72. },
  73. {
  74. rawurl: "enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439@127.0.0.1:52150",
  75. wantResult: NewNode(
  76. MustHexID("0x1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439"),
  77. net.IP{0x7f, 0x0, 0x0, 0x1},
  78. 52150,
  79. 52150,
  80. ),
  81. },
  82. {
  83. rawurl: "enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439@[::]:52150",
  84. wantResult: NewNode(
  85. MustHexID("0x1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439"),
  86. net.ParseIP("::"),
  87. 52150,
  88. 52150,
  89. ),
  90. },
  91. {
  92. rawurl: "enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439@[2001:db8:3c4d:15::abcd:ef12]:52150",
  93. wantResult: NewNode(
  94. MustHexID("0x1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439"),
  95. net.ParseIP("2001:db8:3c4d:15::abcd:ef12"),
  96. 52150,
  97. 52150,
  98. ),
  99. },
  100. {
  101. rawurl: "enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439@127.0.0.1:52150?discport=22334",
  102. wantResult: NewNode(
  103. MustHexID("0x1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439"),
  104. net.IP{0x7f, 0x0, 0x0, 0x1},
  105. 22334,
  106. 52150,
  107. ),
  108. },
  109. // Incomplete nodes with no address.
  110. {
  111. rawurl: "1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439",
  112. wantResult: NewNode(
  113. MustHexID("0x1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439"),
  114. nil, 0, 0,
  115. ),
  116. },
  117. {
  118. rawurl: "enode://1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439",
  119. wantResult: NewNode(
  120. MustHexID("0x1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439"),
  121. nil, 0, 0,
  122. ),
  123. },
  124. // Invalid URLs
  125. {
  126. rawurl: "01010101",
  127. wantError: `invalid node ID (wrong length, want 128 hex chars)`,
  128. },
  129. {
  130. rawurl: "enode://01010101",
  131. wantError: `invalid node ID (wrong length, want 128 hex chars)`,
  132. },
  133. {
  134. // This test checks that errors from url.Parse are handled.
  135. rawurl: "://foo",
  136. wantError: `parse ://foo: missing protocol scheme`,
  137. },
  138. }
  139. func TestParseNode(t *testing.T) {
  140. for _, test := range parseNodeTests {
  141. n, err := ParseNode(test.rawurl)
  142. if test.wantError != "" {
  143. if err == nil {
  144. t.Errorf("test %q:\n got nil error, expected %#q", test.rawurl, test.wantError)
  145. continue
  146. } else if err.Error() != test.wantError {
  147. t.Errorf("test %q:\n got error %#q, expected %#q", test.rawurl, err.Error(), test.wantError)
  148. continue
  149. }
  150. } else {
  151. if err != nil {
  152. t.Errorf("test %q:\n unexpected error: %v", test.rawurl, err)
  153. continue
  154. }
  155. if !reflect.DeepEqual(n, test.wantResult) {
  156. t.Errorf("test %q:\n result mismatch:\ngot: %#v, want: %#v", test.rawurl, n, test.wantResult)
  157. }
  158. }
  159. }
  160. }
  161. func TestNodeString(t *testing.T) {
  162. for i, test := range parseNodeTests {
  163. if test.wantError == "" && strings.HasPrefix(test.rawurl, "enode://") {
  164. str := test.wantResult.String()
  165. if str != test.rawurl {
  166. t.Errorf("test %d: Node.String() mismatch:\ngot: %s\nwant: %s", i, str, test.rawurl)
  167. }
  168. }
  169. }
  170. }
  171. func TestHexID(t *testing.T) {
  172. ref := NodeID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 106, 217, 182, 31, 165, 174, 1, 67, 7, 235, 220, 150, 66, 83, 173, 205, 159, 44, 10, 57, 42, 161, 26, 188}
  173. id1 := MustHexID("0x000000000000000000000000000000000000000000000000000000000000000000000000000000806ad9b61fa5ae014307ebdc964253adcd9f2c0a392aa11abc")
  174. id2 := MustHexID("000000000000000000000000000000000000000000000000000000000000000000000000000000806ad9b61fa5ae014307ebdc964253adcd9f2c0a392aa11abc")
  175. if id1 != ref {
  176. t.Errorf("wrong id1\ngot %v\nwant %v", id1[:], ref[:])
  177. }
  178. if id2 != ref {
  179. t.Errorf("wrong id2\ngot %v\nwant %v", id2[:], ref[:])
  180. }
  181. }
  182. func TestNodeID_recover(t *testing.T) {
  183. prv := newkey()
  184. hash := make([]byte, 32)
  185. sig, err := crypto.Sign(hash, prv)
  186. if err != nil {
  187. t.Fatalf("signing error: %v", err)
  188. }
  189. pub := PubkeyID(&prv.PublicKey)
  190. recpub, err := recoverNodeID(hash, sig)
  191. if err != nil {
  192. t.Fatalf("recovery error: %v", err)
  193. }
  194. if pub != recpub {
  195. t.Errorf("recovered wrong pubkey:\ngot: %v\nwant: %v", recpub, pub)
  196. }
  197. ecdsa, err := pub.Pubkey()
  198. if err != nil {
  199. t.Errorf("Pubkey error: %v", err)
  200. }
  201. if !reflect.DeepEqual(ecdsa, &prv.PublicKey) {
  202. t.Errorf("Pubkey mismatch:\n got: %#v\n want: %#v", ecdsa, &prv.PublicKey)
  203. }
  204. }
  205. func TestNodeID_pubkeyBad(t *testing.T) {
  206. ecdsa, err := NodeID{}.Pubkey()
  207. if err == nil {
  208. t.Error("expected error for zero ID")
  209. }
  210. if ecdsa != nil {
  211. t.Error("expected nil result")
  212. }
  213. }
  214. func TestNodeID_distcmp(t *testing.T) {
  215. distcmpBig := func(target, a, b common.Hash) int {
  216. tbig := new(big.Int).SetBytes(target[:])
  217. abig := new(big.Int).SetBytes(a[:])
  218. bbig := new(big.Int).SetBytes(b[:])
  219. return new(big.Int).Xor(tbig, abig).Cmp(new(big.Int).Xor(tbig, bbig))
  220. }
  221. if err := quick.CheckEqual(distcmp, distcmpBig, quickcfg()); err != nil {
  222. t.Error(err)
  223. }
  224. }
  225. // the random tests is likely to miss the case where they're equal.
  226. func TestNodeID_distcmpEqual(t *testing.T) {
  227. base := common.Hash{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
  228. x := common.Hash{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
  229. if distcmp(base, x, x) != 0 {
  230. t.Errorf("distcmp(base, x, x) != 0")
  231. }
  232. }
  233. func TestNodeID_logdist(t *testing.T) {
  234. logdistBig := func(a, b common.Hash) int {
  235. abig, bbig := new(big.Int).SetBytes(a[:]), new(big.Int).SetBytes(b[:])
  236. return new(big.Int).Xor(abig, bbig).BitLen()
  237. }
  238. if err := quick.CheckEqual(logdist, logdistBig, quickcfg()); err != nil {
  239. t.Error(err)
  240. }
  241. }
  242. // the random tests is likely to miss the case where they're equal.
  243. func TestNodeID_logdistEqual(t *testing.T) {
  244. x := common.Hash{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
  245. if logdist(x, x) != 0 {
  246. t.Errorf("logdist(x, x) != 0")
  247. }
  248. }
  249. func TestNodeID_hashAtDistance(t *testing.T) {
  250. // we don't use quick.Check here because its output isn't
  251. // very helpful when the test fails.
  252. cfg := quickcfg()
  253. for i := 0; i < cfg.MaxCount; i++ {
  254. a := gen(common.Hash{}, cfg.Rand).(common.Hash)
  255. dist := cfg.Rand.Intn(len(common.Hash{}) * 8)
  256. result := hashAtDistance(a, dist)
  257. actualdist := logdist(result, a)
  258. if dist != actualdist {
  259. t.Log("a: ", a)
  260. t.Log("result:", result)
  261. t.Fatalf("#%d: distance of result is %d, want %d", i, actualdist, dist)
  262. }
  263. }
  264. }
  265. func quickcfg() *quick.Config {
  266. return &quick.Config{
  267. MaxCount: 5000,
  268. Rand: rand.New(rand.NewSource(time.Now().Unix())),
  269. }
  270. }
  271. // TODO: The Generate method can be dropped when we require Go >= 1.5
  272. // because testing/quick learned to generate arrays in 1.5.
  273. func (NodeID) Generate(rand *rand.Rand, size int) reflect.Value {
  274. var id NodeID
  275. m := rand.Intn(len(id))
  276. for i := len(id) - 1; i > m; i-- {
  277. id[i] = byte(rand.Uint32())
  278. }
  279. return reflect.ValueOf(id)
  280. }