github.com/bcskill/bcschain/v3@v3.4.9-beta2/p2p/discv5/node_test.go (about)

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