github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/p2p/dnsdisc/client_test.go (about)

     1  // Copyright 2018 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 dnsdisc
    18  
    19  import (
    20  	"context"
    21  	"crypto/ecdsa"
    22  	"errors"
    23  	"math/rand"
    24  	"reflect"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/davecgh/go-spew/spew"
    29  	"github.com/kisexp/xdchain/common/mclock"
    30  	"github.com/kisexp/xdchain/crypto"
    31  	"github.com/kisexp/xdchain/internal/testlog"
    32  	"github.com/kisexp/xdchain/log"
    33  	"github.com/kisexp/xdchain/p2p/enode"
    34  	"github.com/kisexp/xdchain/p2p/enr"
    35  )
    36  
    37  const (
    38  	signingKeySeed = 0x111111
    39  	nodesSeed1     = 0x2945237
    40  	nodesSeed2     = 0x4567299
    41  )
    42  
    43  func TestClientSyncTree(t *testing.T) {
    44  	r := mapResolver{
    45  		"n":                            "enrtree-root:v1 e=JWXYDBPXYWG6FX3GMDIBFA6CJ4 l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=1 sig=o908WmNp7LibOfPsr4btQwatZJ5URBr2ZAuxvK4UWHlsB9sUOTJQaGAlLPVAhM__XJesCHxLISo94z5Z2a463gA",
    46  		"C7HRFPF3BLGF3YR4DY5KX3SMBE.n": "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org",
    47  		"JWXYDBPXYWG6FX3GMDIBFA6CJ4.n": "enrtree-branch:2XS2367YHAXJFGLZHVAWLQD4ZY,H4FHT4B454P6UXFD7JCYQ5PWDY,MHTDO6TMUBRIA2XWG5LUDACK24",
    48  		"2XS2367YHAXJFGLZHVAWLQD4ZY.n": "enr:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3snqmgTiE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJxbAFvA",
    49  		"H4FHT4B454P6UXFD7JCYQ5PWDY.n": "enr:-HW4QAggRauloj2SDLtIHN1XBkvhFZ1vtf1raYQp9TBW2RD5EEawDzbtSmlXUfnaHcvwOizhVYLtr7e6vw7NAf6mTuoCgmlkgnY0iXNlY3AyNTZrMaECjrXI8TLNXU0f8cthpAMxEshUyQlK-AM0PW2wfrnacNI",
    50  		"MHTDO6TMUBRIA2XWG5LUDACK24.n": "enr:-HW4QLAYqmrwllBEnzWWs7I5Ev2IAs7x_dZlbYdRdMUx5EyKHDXp7AV5CkuPGUPdvbv1_Ms1CPfhcGCvSElSosZmyoqAgmlkgnY0iXNlY3AyNTZrMaECriawHKWdDRk2xeZkrOXBQ0dfMFLHY4eENZwdufn1S1o",
    51  	}
    52  	var (
    53  		wantNodes = testNodes(0x29452, 3)
    54  		wantLinks = []string{"enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org"}
    55  		wantSeq   = uint(1)
    56  	)
    57  
    58  	c := NewClient(Config{Resolver: r, Logger: testlog.Logger(t, log.LvlTrace)})
    59  	stree, err := c.SyncTree("enrtree://AKPYQIUQIL7PSIACI32J7FGZW56E5FKHEFCCOFHILBIMW3M6LWXS2@n")
    60  	if err != nil {
    61  		t.Fatal("sync error:", err)
    62  	}
    63  	if !reflect.DeepEqual(sortByID(stree.Nodes()), sortByID(wantNodes)) {
    64  		t.Errorf("wrong nodes in synced tree:\nhave %v\nwant %v", spew.Sdump(stree.Nodes()), spew.Sdump(wantNodes))
    65  	}
    66  	if !reflect.DeepEqual(stree.Links(), wantLinks) {
    67  		t.Errorf("wrong links in synced tree: %v", stree.Links())
    68  	}
    69  	if stree.Seq() != wantSeq {
    70  		t.Errorf("synced tree has wrong seq: %d", stree.Seq())
    71  	}
    72  }
    73  
    74  // In this test, syncing the tree fails because it contains an invalid ENR entry.
    75  func TestClientSyncTreeBadNode(t *testing.T) {
    76  	// var b strings.Builder
    77  	// b.WriteString(enrPrefix)
    78  	// b.WriteString("-----")
    79  	// badHash := subdomain(&b)
    80  	// tree, _ := MakeTree(3, nil, []string{"enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org"})
    81  	// tree.entries[badHash] = &b
    82  	// tree.root.eroot = badHash
    83  	// url, _ := tree.Sign(testKey(signingKeySeed), "n")
    84  	// fmt.Println(url)
    85  	// fmt.Printf("%#v\n", tree.ToTXT("n"))
    86  
    87  	r := mapResolver{
    88  		"n":                            "enrtree-root:v1 e=INDMVBZEEQ4ESVYAKGIYU74EAA l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=3 sig=Vl3AmunLur0JZ3sIyJPSH6A3Vvdp4F40jWQeCmkIhmcgwE4VC5U9wpK8C_uL_CMY29fd6FAhspRvq2z_VysTLAA",
    89  		"C7HRFPF3BLGF3YR4DY5KX3SMBE.n": "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org",
    90  		"INDMVBZEEQ4ESVYAKGIYU74EAA.n": "enr:-----",
    91  	}
    92  	c := NewClient(Config{Resolver: r, Logger: testlog.Logger(t, log.LvlTrace)})
    93  	_, err := c.SyncTree("enrtree://AKPYQIUQIL7PSIACI32J7FGZW56E5FKHEFCCOFHILBIMW3M6LWXS2@n")
    94  	wantErr := nameError{name: "INDMVBZEEQ4ESVYAKGIYU74EAA.n", err: entryError{typ: "enr", err: errInvalidENR}}
    95  	if err != wantErr {
    96  		t.Fatalf("expected sync error %q, got %q", wantErr, err)
    97  	}
    98  }
    99  
   100  // This test checks that randomIterator finds all entries.
   101  func TestIterator(t *testing.T) {
   102  	nodes := testNodes(nodesSeed1, 30)
   103  	tree, url := makeTestTree("n", nodes, nil)
   104  	r := mapResolver(tree.ToTXT("n"))
   105  	c := NewClient(Config{
   106  		Resolver:  r,
   107  		Logger:    testlog.Logger(t, log.LvlTrace),
   108  		RateLimit: 500,
   109  	})
   110  	it, err := c.NewIterator(url)
   111  	if err != nil {
   112  		t.Fatal(err)
   113  	}
   114  
   115  	checkIterator(t, it, nodes)
   116  }
   117  
   118  // This test checks if closing randomIterator races.
   119  func TestIteratorClose(t *testing.T) {
   120  	nodes := testNodes(nodesSeed1, 500)
   121  	tree1, url1 := makeTestTree("t1", nodes, nil)
   122  	c := NewClient(Config{Resolver: newMapResolver(tree1.ToTXT("t1"))})
   123  	it, err := c.NewIterator(url1)
   124  	if err != nil {
   125  		t.Fatal(err)
   126  	}
   127  
   128  	done := make(chan struct{})
   129  	go func() {
   130  		for it.Next() {
   131  			_ = it.Node()
   132  		}
   133  		close(done)
   134  	}()
   135  
   136  	time.Sleep(50 * time.Millisecond)
   137  	it.Close()
   138  	<-done
   139  }
   140  
   141  // This test checks that randomIterator traverses linked trees as well as explicitly added trees.
   142  func TestIteratorLinks(t *testing.T) {
   143  	nodes := testNodes(nodesSeed1, 40)
   144  	tree1, url1 := makeTestTree("t1", nodes[:10], nil)
   145  	tree2, url2 := makeTestTree("t2", nodes[10:], []string{url1})
   146  	c := NewClient(Config{
   147  		Resolver:  newMapResolver(tree1.ToTXT("t1"), tree2.ToTXT("t2")),
   148  		Logger:    testlog.Logger(t, log.LvlTrace),
   149  		RateLimit: 500,
   150  	})
   151  	it, err := c.NewIterator(url2)
   152  	if err != nil {
   153  		t.Fatal(err)
   154  	}
   155  
   156  	checkIterator(t, it, nodes)
   157  }
   158  
   159  // This test verifies that randomIterator re-checks the root of the tree to catch
   160  // updates to nodes.
   161  func TestIteratorNodeUpdates(t *testing.T) {
   162  	var (
   163  		clock    = new(mclock.Simulated)
   164  		nodes    = testNodes(nodesSeed1, 30)
   165  		resolver = newMapResolver()
   166  		c        = NewClient(Config{
   167  			Resolver:        resolver,
   168  			Logger:          testlog.Logger(t, log.LvlTrace),
   169  			RecheckInterval: 20 * time.Minute,
   170  			RateLimit:       500,
   171  		})
   172  	)
   173  	c.clock = clock
   174  	tree1, url := makeTestTree("n", nodes[:25], nil)
   175  	it, err := c.NewIterator(url)
   176  	if err != nil {
   177  		t.Fatal(err)
   178  	}
   179  
   180  	// Sync the original tree.
   181  	resolver.add(tree1.ToTXT("n"))
   182  	checkIterator(t, it, nodes[:25])
   183  
   184  	// Ensure RandomNode returns the new nodes after the tree is updated.
   185  	updateSomeNodes(nodesSeed1, nodes)
   186  	tree2, _ := makeTestTree("n", nodes, nil)
   187  	resolver.clear()
   188  	resolver.add(tree2.ToTXT("n"))
   189  	t.Log("tree updated")
   190  
   191  	clock.Run(c.cfg.RecheckInterval + 1*time.Second)
   192  	checkIterator(t, it, nodes)
   193  }
   194  
   195  // This test checks that the tree root is rechecked when a couple of leaf
   196  // requests have failed. The test is just like TestIteratorNodeUpdates, but
   197  // without advancing the clock by recheckInterval after the tree update.
   198  func TestIteratorRootRecheckOnFail(t *testing.T) {
   199  	var (
   200  		clock    = new(mclock.Simulated)
   201  		nodes    = testNodes(nodesSeed1, 30)
   202  		resolver = newMapResolver()
   203  		c        = NewClient(Config{
   204  			Resolver:        resolver,
   205  			Logger:          testlog.Logger(t, log.LvlTrace),
   206  			RecheckInterval: 20 * time.Minute,
   207  			RateLimit:       500,
   208  			// Disabling the cache is required for this test because the client doesn't
   209  			// notice leaf failures if all records are cached.
   210  			CacheLimit: 1,
   211  		})
   212  	)
   213  	c.clock = clock
   214  	tree1, url := makeTestTree("n", nodes[:25], nil)
   215  	it, err := c.NewIterator(url)
   216  	if err != nil {
   217  		t.Fatal(err)
   218  	}
   219  
   220  	// Sync the original tree.
   221  	resolver.add(tree1.ToTXT("n"))
   222  	checkIterator(t, it, nodes[:25])
   223  
   224  	// Ensure RandomNode returns the new nodes after the tree is updated.
   225  	updateSomeNodes(nodesSeed1, nodes)
   226  	tree2, _ := makeTestTree("n", nodes, nil)
   227  	resolver.clear()
   228  	resolver.add(tree2.ToTXT("n"))
   229  	t.Log("tree updated")
   230  
   231  	checkIterator(t, it, nodes)
   232  }
   233  
   234  // updateSomeNodes applies ENR updates to some of the given nodes.
   235  func updateSomeNodes(keySeed int64, nodes []*enode.Node) {
   236  	keys := testKeys(nodesSeed1, len(nodes))
   237  	for i, n := range nodes[:len(nodes)/2] {
   238  		r := n.Record()
   239  		r.Set(enr.IP{127, 0, 0, 1})
   240  		r.SetSeq(55)
   241  		enode.SignV4(r, keys[i])
   242  		n2, _ := enode.New(enode.ValidSchemes, r)
   243  		nodes[i] = n2
   244  	}
   245  }
   246  
   247  // This test verifies that randomIterator re-checks the root of the tree to catch
   248  // updates to links.
   249  func TestIteratorLinkUpdates(t *testing.T) {
   250  	var (
   251  		clock    = new(mclock.Simulated)
   252  		nodes    = testNodes(nodesSeed1, 30)
   253  		resolver = newMapResolver()
   254  		c        = NewClient(Config{
   255  			Resolver:        resolver,
   256  			Logger:          testlog.Logger(t, log.LvlTrace),
   257  			RecheckInterval: 20 * time.Minute,
   258  			RateLimit:       500,
   259  		})
   260  	)
   261  	c.clock = clock
   262  	tree3, url3 := makeTestTree("t3", nodes[20:30], nil)
   263  	tree2, url2 := makeTestTree("t2", nodes[10:20], nil)
   264  	tree1, url1 := makeTestTree("t1", nodes[0:10], []string{url2})
   265  	resolver.add(tree1.ToTXT("t1"))
   266  	resolver.add(tree2.ToTXT("t2"))
   267  	resolver.add(tree3.ToTXT("t3"))
   268  
   269  	it, err := c.NewIterator(url1)
   270  	if err != nil {
   271  		t.Fatal(err)
   272  	}
   273  
   274  	// Sync tree1 using RandomNode.
   275  	checkIterator(t, it, nodes[:20])
   276  
   277  	// Add link to tree3, remove link to tree2.
   278  	tree1, _ = makeTestTree("t1", nodes[:10], []string{url3})
   279  	resolver.add(tree1.ToTXT("t1"))
   280  	t.Log("tree1 updated")
   281  
   282  	clock.Run(c.cfg.RecheckInterval + 1*time.Second)
   283  
   284  	var wantNodes []*enode.Node
   285  	wantNodes = append(wantNodes, tree1.Nodes()...)
   286  	wantNodes = append(wantNodes, tree3.Nodes()...)
   287  	checkIterator(t, it, wantNodes)
   288  
   289  	// Check that linked trees are GCed when they're no longer referenced.
   290  	knownTrees := it.(*randomIterator).trees
   291  	if len(knownTrees) != 2 {
   292  		t.Errorf("client knows %d trees, want 2", len(knownTrees))
   293  	}
   294  }
   295  
   296  func checkIterator(t *testing.T, it enode.Iterator, wantNodes []*enode.Node) {
   297  	t.Helper()
   298  
   299  	var (
   300  		want     = make(map[enode.ID]*enode.Node)
   301  		maxCalls = len(wantNodes) * 3
   302  		calls    = 0
   303  	)
   304  	for _, n := range wantNodes {
   305  		want[n.ID()] = n
   306  	}
   307  	for ; len(want) > 0 && calls < maxCalls; calls++ {
   308  		if !it.Next() {
   309  			t.Fatalf("Next returned false (call %d)", calls)
   310  		}
   311  		n := it.Node()
   312  		delete(want, n.ID())
   313  	}
   314  	t.Logf("checkIterator called Next %d times to find %d nodes", calls, len(wantNodes))
   315  	for _, n := range want {
   316  		t.Errorf("iterator didn't discover node %v", n.ID())
   317  	}
   318  }
   319  
   320  func makeTestTree(domain string, nodes []*enode.Node, links []string) (*Tree, string) {
   321  	tree, err := MakeTree(1, nodes, links)
   322  	if err != nil {
   323  		panic(err)
   324  	}
   325  	url, err := tree.Sign(testKey(signingKeySeed), domain)
   326  	if err != nil {
   327  		panic(err)
   328  	}
   329  	return tree, url
   330  }
   331  
   332  // testKeys creates deterministic private keys for testing.
   333  func testKeys(seed int64, n int) []*ecdsa.PrivateKey {
   334  	rand := rand.New(rand.NewSource(seed))
   335  	keys := make([]*ecdsa.PrivateKey, n)
   336  	for i := 0; i < n; i++ {
   337  		key, err := ecdsa.GenerateKey(crypto.S256(), rand)
   338  		if err != nil {
   339  			panic("can't generate key: " + err.Error())
   340  		}
   341  		keys[i] = key
   342  	}
   343  	return keys
   344  }
   345  
   346  func testKey(seed int64) *ecdsa.PrivateKey {
   347  	return testKeys(seed, 1)[0]
   348  }
   349  
   350  func testNodes(seed int64, n int) []*enode.Node {
   351  	keys := testKeys(seed, n)
   352  	nodes := make([]*enode.Node, n)
   353  	for i, key := range keys {
   354  		record := new(enr.Record)
   355  		record.SetSeq(uint64(i))
   356  		enode.SignV4(record, key)
   357  		n, err := enode.New(enode.ValidSchemes, record)
   358  		if err != nil {
   359  			panic(err)
   360  		}
   361  		nodes[i] = n
   362  	}
   363  	return nodes
   364  }
   365  
   366  func testNode(seed int64) *enode.Node {
   367  	return testNodes(seed, 1)[0]
   368  }
   369  
   370  type mapResolver map[string]string
   371  
   372  func newMapResolver(maps ...map[string]string) mapResolver {
   373  	mr := make(mapResolver)
   374  	for _, m := range maps {
   375  		mr.add(m)
   376  	}
   377  	return mr
   378  }
   379  
   380  func (mr mapResolver) clear() {
   381  	for k := range mr {
   382  		delete(mr, k)
   383  	}
   384  }
   385  
   386  func (mr mapResolver) add(m map[string]string) {
   387  	for k, v := range m {
   388  		mr[k] = v
   389  	}
   390  }
   391  
   392  func (mr mapResolver) LookupTXT(ctx context.Context, name string) ([]string, error) {
   393  	if record, ok := mr[name]; ok {
   394  		return []string{record}, nil
   395  	}
   396  	return nil, errors.New("not found")
   397  }