github.com/jimmyx0x/go-ethereum@v1.10.28/p2p/discover/v4_lookup_test.go (about)

     1  // Copyright 2019 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 discover
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"fmt"
    22  	"net"
    23  	"sort"
    24  	"testing"
    25  
    26  	"github.com/ethereum/go-ethereum/crypto"
    27  	"github.com/ethereum/go-ethereum/p2p/discover/v4wire"
    28  	"github.com/ethereum/go-ethereum/p2p/enode"
    29  	"github.com/ethereum/go-ethereum/p2p/enr"
    30  )
    31  
    32  func TestUDPv4_Lookup(t *testing.T) {
    33  	t.Parallel()
    34  	test := newUDPTest(t)
    35  
    36  	// Lookup on empty table returns no nodes.
    37  	targetKey, _ := decodePubkey(crypto.S256(), lookupTestnet.target[:])
    38  	if results := test.udp.LookupPubkey(targetKey); len(results) > 0 {
    39  		t.Fatalf("lookup on empty table returned %d results: %#v", len(results), results)
    40  	}
    41  
    42  	// Seed table with initial node.
    43  	fillTable(test.table, []*node{wrapNode(lookupTestnet.node(256, 0))})
    44  
    45  	// Start the lookup.
    46  	resultC := make(chan []*enode.Node, 1)
    47  	go func() {
    48  		resultC <- test.udp.LookupPubkey(targetKey)
    49  		test.close()
    50  	}()
    51  
    52  	// Answer lookup packets.
    53  	serveTestnet(test, lookupTestnet)
    54  
    55  	// Verify result nodes.
    56  	results := <-resultC
    57  	t.Logf("results:")
    58  	for _, e := range results {
    59  		t.Logf("  ld=%d, %x", enode.LogDist(lookupTestnet.target.id(), e.ID()), e.ID().Bytes())
    60  	}
    61  	if len(results) != bucketSize {
    62  		t.Errorf("wrong number of results: got %d, want %d", len(results), bucketSize)
    63  	}
    64  	checkLookupResults(t, lookupTestnet, results)
    65  }
    66  
    67  func TestUDPv4_LookupIterator(t *testing.T) {
    68  	t.Parallel()
    69  	test := newUDPTest(t)
    70  	defer test.close()
    71  
    72  	// Seed table with initial nodes.
    73  	bootnodes := make([]*node, len(lookupTestnet.dists[256]))
    74  	for i := range lookupTestnet.dists[256] {
    75  		bootnodes[i] = wrapNode(lookupTestnet.node(256, i))
    76  	}
    77  	fillTable(test.table, bootnodes)
    78  	go serveTestnet(test, lookupTestnet)
    79  
    80  	// Create the iterator and collect the nodes it yields.
    81  	iter := test.udp.RandomNodes()
    82  	seen := make(map[enode.ID]*enode.Node)
    83  	for limit := lookupTestnet.len(); iter.Next() && len(seen) < limit; {
    84  		seen[iter.Node().ID()] = iter.Node()
    85  	}
    86  	iter.Close()
    87  
    88  	// Check that all nodes in lookupTestnet were seen by the iterator.
    89  	results := make([]*enode.Node, 0, len(seen))
    90  	for _, n := range seen {
    91  		results = append(results, n)
    92  	}
    93  	sortByID(results)
    94  	want := lookupTestnet.nodes()
    95  	if err := checkNodesEqual(results, want); err != nil {
    96  		t.Fatal(err)
    97  	}
    98  }
    99  
   100  // TestUDPv4_LookupIteratorClose checks that lookupIterator ends when its Close
   101  // method is called.
   102  func TestUDPv4_LookupIteratorClose(t *testing.T) {
   103  	t.Parallel()
   104  	test := newUDPTest(t)
   105  	defer test.close()
   106  
   107  	// Seed table with initial nodes.
   108  	bootnodes := make([]*node, len(lookupTestnet.dists[256]))
   109  	for i := range lookupTestnet.dists[256] {
   110  		bootnodes[i] = wrapNode(lookupTestnet.node(256, i))
   111  	}
   112  	fillTable(test.table, bootnodes)
   113  	go serveTestnet(test, lookupTestnet)
   114  
   115  	it := test.udp.RandomNodes()
   116  	if ok := it.Next(); !ok || it.Node() == nil {
   117  		t.Fatalf("iterator didn't return any node")
   118  	}
   119  
   120  	it.Close()
   121  
   122  	ncalls := 0
   123  	for ; ncalls < 100 && it.Next(); ncalls++ {
   124  		if it.Node() == nil {
   125  			t.Error("iterator returned Node() == nil node after Next() == true")
   126  		}
   127  	}
   128  	t.Logf("iterator returned %d nodes after close", ncalls)
   129  	if it.Next() {
   130  		t.Errorf("Next() == true after close and %d more calls", ncalls)
   131  	}
   132  	if n := it.Node(); n != nil {
   133  		t.Errorf("iterator returned non-nil node after close and %d more calls", ncalls)
   134  	}
   135  }
   136  
   137  func serveTestnet(test *udpTest, testnet *preminedTestnet) {
   138  	for done := false; !done; {
   139  		done = test.waitPacketOut(func(p v4wire.Packet, to *net.UDPAddr, hash []byte) {
   140  			n, key := testnet.nodeByAddr(to)
   141  			switch p.(type) {
   142  			case *v4wire.Ping:
   143  				test.packetInFrom(nil, key, to, &v4wire.Pong{Expiration: futureExp, ReplyTok: hash})
   144  			case *v4wire.Findnode:
   145  				dist := enode.LogDist(n.ID(), testnet.target.id())
   146  				nodes := testnet.nodesAtDistance(dist - 1)
   147  				test.packetInFrom(nil, key, to, &v4wire.Neighbors{Expiration: futureExp, Nodes: nodes})
   148  			}
   149  		})
   150  	}
   151  }
   152  
   153  // checkLookupResults verifies that the results of a lookup are the closest nodes to
   154  // the testnet's target.
   155  func checkLookupResults(t *testing.T, tn *preminedTestnet, results []*enode.Node) {
   156  	t.Helper()
   157  	t.Logf("results:")
   158  	for _, e := range results {
   159  		t.Logf("  ld=%d, %x", enode.LogDist(tn.target.id(), e.ID()), e.ID().Bytes())
   160  	}
   161  	if hasDuplicates(wrapNodes(results)) {
   162  		t.Errorf("result set contains duplicate entries")
   163  	}
   164  	if !sortedByDistanceTo(tn.target.id(), wrapNodes(results)) {
   165  		t.Errorf("result set not sorted by distance to target")
   166  	}
   167  	wantNodes := tn.closest(len(results))
   168  	if err := checkNodesEqual(results, wantNodes); err != nil {
   169  		t.Error(err)
   170  	}
   171  }
   172  
   173  // This is the test network for the Lookup test.
   174  // The nodes were obtained by running lookupTestnet.mine with a random NodeID as target.
   175  var lookupTestnet = &preminedTestnet{
   176  	target: hexEncPubkey("5d485bdcbe9bc89314a10ae9231e429d33853e3a8fa2af39f5f827370a2e4185e344ace5d16237491dad41f278f1d3785210d29ace76cd627b9147ee340b1125"),
   177  	dists: [257][]*ecdsa.PrivateKey{
   178  		251: {
   179  			hexEncPrivkey("29738ba0c1a4397d6a65f292eee07f02df8e58d41594ba2be3cf84ce0fc58169"),
   180  			hexEncPrivkey("511b1686e4e58a917f7f848e9bf5539d206a68f5ad6b54b552c2399fe7d174ae"),
   181  			hexEncPrivkey("d09e5eaeec0fd596236faed210e55ef45112409a5aa7f3276d26646080dcfaeb"),
   182  			hexEncPrivkey("c1e20dbbf0d530e50573bd0a260b32ec15eb9190032b4633d44834afc8afe578"),
   183  			hexEncPrivkey("ed5f38f5702d92d306143e5d9154fb21819777da39af325ea359f453d179e80b"),
   184  		},
   185  		252: {
   186  			hexEncPrivkey("1c9b1cafbec00848d2c174b858219914b42a7d5c9359b1ca03fd650e8239ae94"),
   187  			hexEncPrivkey("e0e1e8db4a6f13c1ffdd3e96b72fa7012293ced187c9dcdcb9ba2af37a46fa10"),
   188  			hexEncPrivkey("3d53823e0a0295cb09f3e11d16c1b44d07dd37cec6f739b8df3a590189fe9fb9"),
   189  		},
   190  		253: {
   191  			hexEncPrivkey("2d0511ae9bf590166597eeab86b6f27b1ab761761eaea8965487b162f8703847"),
   192  			hexEncPrivkey("6cfbd7b8503073fc3dbdb746a7c672571648d3bd15197ccf7f7fef3d904f53a2"),
   193  			hexEncPrivkey("a30599b12827b69120633f15b98a7f6bc9fc2e9a0fd6ae2ebb767c0e64d743ab"),
   194  			hexEncPrivkey("14a98db9b46a831d67eff29f3b85b1b485bb12ae9796aea98d91be3dc78d8a91"),
   195  			hexEncPrivkey("2369ff1fc1ff8ca7d20b17e2673adc3365c3674377f21c5d9dafaff21fe12e24"),
   196  			hexEncPrivkey("9ae91101d6b5048607f41ec0f690ef5d09507928aded2410aabd9237aa2727d7"),
   197  			hexEncPrivkey("05e3c59090a3fd1ae697c09c574a36fcf9bedd0afa8fe3946f21117319ca4973"),
   198  			hexEncPrivkey("06f31c5ea632658f718a91a1b1b9ae4b7549d7b3bc61cbc2be5f4a439039f3ad"),
   199  		},
   200  		254: {
   201  			hexEncPrivkey("dec742079ec00ff4ec1284d7905bc3de2366f67a0769431fd16f80fd68c58a7c"),
   202  			hexEncPrivkey("ff02c8861fa12fbd129d2a95ea663492ef9c1e51de19dcfbbfe1c59894a28d2b"),
   203  			hexEncPrivkey("4dded9e4eefcbce4262be4fd9e8a773670ab0b5f448f286ec97dfc8cf681444a"),
   204  			hexEncPrivkey("750d931e2a8baa2c9268cb46b7cd851f4198018bed22f4dceb09dd334a2395f6"),
   205  			hexEncPrivkey("ce1435a956a98ffec484cd11489c4f165cf1606819ab6b521cee440f0c677e9e"),
   206  			hexEncPrivkey("996e7f8d1638be92d7328b4770f47e5420fc4bafecb4324fd33b1f5d9f403a75"),
   207  			hexEncPrivkey("ebdc44e77a6cc0eb622e58cf3bb903c3da4c91ca75b447b0168505d8fc308b9c"),
   208  			hexEncPrivkey("46bd1eddcf6431bea66fc19ebc45df191c1c7d6ed552dcdc7392885009c322f0"),
   209  		},
   210  		255: {
   211  			hexEncPrivkey("da8645f90826e57228d9ea72aff84500060ad111a5d62e4af831ed8e4b5acfb8"),
   212  			hexEncPrivkey("3c944c5d9af51d4c1d43f5d0f3a1a7ef65d5e82744d669b58b5fed242941a566"),
   213  			hexEncPrivkey("5ebcde76f1d579eebf6e43b0ffe9157e65ffaa391175d5b9aa988f47df3e33da"),
   214  			hexEncPrivkey("97f78253a7d1d796e4eaabce721febcc4550dd68fb11cc818378ba807a2cb7de"),
   215  			hexEncPrivkey("a38cd7dc9b4079d1c0406afd0fdb1165c285f2c44f946eca96fc67772c988c7d"),
   216  			hexEncPrivkey("d64cbb3ffdf712c372b7a22a176308ef8f91861398d5dbaf326fd89c6eaeef1c"),
   217  			hexEncPrivkey("d269609743ef29d6446e3355ec647e38d919c82a4eb5837e442efd7f4218944f"),
   218  			hexEncPrivkey("d8f7bcc4a530efde1d143717007179e0d9ace405ddaaf151c4d863753b7fd64c"),
   219  		},
   220  		256: {
   221  			hexEncPrivkey("8c5b422155d33ea8e9d46f71d1ad3e7b24cb40051413ffa1a81cff613d243ba9"),
   222  			hexEncPrivkey("937b1af801def4e8f5a3a8bd225a8bcff1db764e41d3e177f2e9376e8dd87233"),
   223  			hexEncPrivkey("120260dce739b6f71f171da6f65bc361b5fad51db74cf02d3e973347819a6518"),
   224  			hexEncPrivkey("1fa56cf25d4b46c2bf94e82355aa631717b63190785ac6bae545a88aadc304a9"),
   225  			hexEncPrivkey("3c38c503c0376f9b4adcbe935d5f4b890391741c764f61b03cd4d0d42deae002"),
   226  			hexEncPrivkey("3a54af3e9fa162bc8623cdf3e5d9b70bf30ade1d54cc3abea8659aba6cff471f"),
   227  			hexEncPrivkey("6799a02ea1999aefdcbcc4d3ff9544478be7365a328d0d0f37c26bd95ade0cda"),
   228  			hexEncPrivkey("e24a7bc9051058f918646b0f6e3d16884b2a55a15553b89bab910d55ebc36116"),
   229  		},
   230  	},
   231  }
   232  
   233  type preminedTestnet struct {
   234  	target encPubkey
   235  	dists  [hashBits + 1][]*ecdsa.PrivateKey
   236  }
   237  
   238  func (tn *preminedTestnet) len() int {
   239  	n := 0
   240  	for _, keys := range tn.dists {
   241  		n += len(keys)
   242  	}
   243  	return n
   244  }
   245  
   246  func (tn *preminedTestnet) nodes() []*enode.Node {
   247  	result := make([]*enode.Node, 0, tn.len())
   248  	for dist, keys := range tn.dists {
   249  		for index := range keys {
   250  			result = append(result, tn.node(dist, index))
   251  		}
   252  	}
   253  	sortByID(result)
   254  	return result
   255  }
   256  
   257  func (tn *preminedTestnet) node(dist, index int) *enode.Node {
   258  	key := tn.dists[dist][index]
   259  	rec := new(enr.Record)
   260  	rec.Set(enr.IP{127, byte(dist >> 8), byte(dist), byte(index)})
   261  	rec.Set(enr.UDP(5000))
   262  	enode.SignV4(rec, key)
   263  	n, _ := enode.New(enode.ValidSchemes, rec)
   264  	return n
   265  }
   266  
   267  func (tn *preminedTestnet) nodeByAddr(addr *net.UDPAddr) (*enode.Node, *ecdsa.PrivateKey) {
   268  	dist := int(addr.IP[1])<<8 + int(addr.IP[2])
   269  	index := int(addr.IP[3])
   270  	key := tn.dists[dist][index]
   271  	return tn.node(dist, index), key
   272  }
   273  
   274  func (tn *preminedTestnet) nodesAtDistance(dist int) []v4wire.Node {
   275  	result := make([]v4wire.Node, len(tn.dists[dist]))
   276  	for i := range result {
   277  		result[i] = nodeToRPC(wrapNode(tn.node(dist, i)))
   278  	}
   279  	return result
   280  }
   281  
   282  func (tn *preminedTestnet) neighborsAtDistances(base *enode.Node, distances []uint, elems int) []*enode.Node {
   283  	var result []*enode.Node
   284  	for d := range lookupTestnet.dists {
   285  		for i := range lookupTestnet.dists[d] {
   286  			n := lookupTestnet.node(d, i)
   287  			d := enode.LogDist(base.ID(), n.ID())
   288  			if containsUint(uint(d), distances) {
   289  				result = append(result, n)
   290  				if len(result) >= elems {
   291  					return result
   292  				}
   293  			}
   294  		}
   295  	}
   296  	return result
   297  }
   298  
   299  func (tn *preminedTestnet) closest(n int) (nodes []*enode.Node) {
   300  	for d := range tn.dists {
   301  		for i := range tn.dists[d] {
   302  			nodes = append(nodes, tn.node(d, i))
   303  		}
   304  	}
   305  	sort.Slice(nodes, func(i, j int) bool {
   306  		return enode.DistCmp(tn.target.id(), nodes[i].ID(), nodes[j].ID()) < 0
   307  	})
   308  	return nodes[:n]
   309  }
   310  
   311  var _ = (*preminedTestnet).mine // avoid linter warning about mine being dead code.
   312  
   313  // mine generates a testnet struct literal with nodes at
   314  // various distances to the network's target.
   315  func (tn *preminedTestnet) mine() {
   316  	// Clear existing slices first (useful when re-mining).
   317  	for i := range tn.dists {
   318  		tn.dists[i] = nil
   319  	}
   320  
   321  	targetSha := tn.target.id()
   322  	found, need := 0, 40
   323  	for found < need {
   324  		k := newkey()
   325  		ld := enode.LogDist(targetSha, encodePubkey(&k.PublicKey).id())
   326  		if len(tn.dists[ld]) < 8 {
   327  			tn.dists[ld] = append(tn.dists[ld], k)
   328  			found++
   329  			fmt.Printf("found ID with ld %d (%d/%d)\n", ld, found, need)
   330  		}
   331  	}
   332  	fmt.Printf("&preminedTestnet{\n")
   333  	fmt.Printf("	target: hexEncPubkey(\"%x\"),\n", tn.target[:])
   334  	fmt.Printf("	dists: [%d][]*ecdsa.PrivateKey{\n", len(tn.dists))
   335  	for ld, ns := range tn.dists {
   336  		if len(ns) == 0 {
   337  			continue
   338  		}
   339  		fmt.Printf("		%d: {\n", ld)
   340  		for _, key := range ns {
   341  			fmt.Printf("			hexEncPrivkey(\"%x\"),\n", crypto.FromECDSA(key))
   342  		}
   343  		fmt.Printf("		},\n")
   344  	}
   345  	fmt.Printf("	},\n")
   346  	fmt.Printf("}\n")
   347  }