github.com/codingfuture/orig-energi3@v0.8.4/p2p/discv5/node_test.go (about)

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