github.com/aitimate-0/go-ethereum@v1.9.7/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  	"math/rand"
    23  	"reflect"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/davecgh/go-spew/spew"
    28  	"github.com/ethereum/go-ethereum/common/mclock"
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/ethereum/go-ethereum/internal/testlog"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/p2p/enode"
    33  	"github.com/ethereum/go-ethereum/p2p/enr"
    34  )
    35  
    36  const (
    37  	signingKeySeed = 0x111111
    38  	nodesSeed1     = 0x2945237
    39  	nodesSeed2     = 0x4567299
    40  )
    41  
    42  func TestClientSyncTree(t *testing.T) {
    43  	r := mapResolver{
    44  		"n":                            "enrtree-root:v1 e=JWXYDBPXYWG6FX3GMDIBFA6CJ4 l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=1 sig=o908WmNp7LibOfPsr4btQwatZJ5URBr2ZAuxvK4UWHlsB9sUOTJQaGAlLPVAhM__XJesCHxLISo94z5Z2a463gA",
    45  		"C7HRFPF3BLGF3YR4DY5KX3SMBE.n": "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org",
    46  		"JWXYDBPXYWG6FX3GMDIBFA6CJ4.n": "enrtree-branch:2XS2367YHAXJFGLZHVAWLQD4ZY,H4FHT4B454P6UXFD7JCYQ5PWDY,MHTDO6TMUBRIA2XWG5LUDACK24",
    47  		"2XS2367YHAXJFGLZHVAWLQD4ZY.n": "enr:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3snqmgTiE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJxbAFvA",
    48  		"H4FHT4B454P6UXFD7JCYQ5PWDY.n": "enr:-HW4QAggRauloj2SDLtIHN1XBkvhFZ1vtf1raYQp9TBW2RD5EEawDzbtSmlXUfnaHcvwOizhVYLtr7e6vw7NAf6mTuoCgmlkgnY0iXNlY3AyNTZrMaECjrXI8TLNXU0f8cthpAMxEshUyQlK-AM0PW2wfrnacNI",
    49  		"MHTDO6TMUBRIA2XWG5LUDACK24.n": "enr:-HW4QLAYqmrwllBEnzWWs7I5Ev2IAs7x_dZlbYdRdMUx5EyKHDXp7AV5CkuPGUPdvbv1_Ms1CPfhcGCvSElSosZmyoqAgmlkgnY0iXNlY3AyNTZrMaECriawHKWdDRk2xeZkrOXBQ0dfMFLHY4eENZwdufn1S1o",
    50  	}
    51  	var (
    52  		wantNodes = testNodes(0x29452, 3)
    53  		wantLinks = []string{"enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org"}
    54  		wantSeq   = uint(1)
    55  	)
    56  
    57  	c, _ := NewClient(Config{Resolver: r, Logger: testlog.Logger(t, log.LvlTrace)})
    58  	stree, err := c.SyncTree("enrtree://AKPYQIUQIL7PSIACI32J7FGZW56E5FKHEFCCOFHILBIMW3M6LWXS2@n")
    59  	if err != nil {
    60  		t.Fatal("sync error:", err)
    61  	}
    62  	if !reflect.DeepEqual(sortByID(stree.Nodes()), sortByID(wantNodes)) {
    63  		t.Errorf("wrong nodes in synced tree:\nhave %v\nwant %v", spew.Sdump(stree.Nodes()), spew.Sdump(wantNodes))
    64  	}
    65  	if !reflect.DeepEqual(stree.Links(), wantLinks) {
    66  		t.Errorf("wrong links in synced tree: %v", stree.Links())
    67  	}
    68  	if stree.Seq() != wantSeq {
    69  		t.Errorf("synced tree has wrong seq: %d", stree.Seq())
    70  	}
    71  	if len(c.trees) > 0 {
    72  		t.Errorf("tree from SyncTree added to client")
    73  	}
    74  }
    75  
    76  // In this test, syncing the tree fails because it contains an invalid ENR entry.
    77  func TestClientSyncTreeBadNode(t *testing.T) {
    78  	// var b strings.Builder
    79  	// b.WriteString(enrPrefix)
    80  	// b.WriteString("-----")
    81  	// badHash := subdomain(&b)
    82  	// tree, _ := MakeTree(3, nil, []string{"enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org"})
    83  	// tree.entries[badHash] = &b
    84  	// tree.root.eroot = badHash
    85  	// url, _ := tree.Sign(testKey(signingKeySeed), "n")
    86  	// fmt.Println(url)
    87  	// fmt.Printf("%#v\n", tree.ToTXT("n"))
    88  
    89  	r := mapResolver{
    90  		"n":                            "enrtree-root:v1 e=INDMVBZEEQ4ESVYAKGIYU74EAA l=C7HRFPF3BLGF3YR4DY5KX3SMBE seq=3 sig=Vl3AmunLur0JZ3sIyJPSH6A3Vvdp4F40jWQeCmkIhmcgwE4VC5U9wpK8C_uL_CMY29fd6FAhspRvq2z_VysTLAA",
    91  		"C7HRFPF3BLGF3YR4DY5KX3SMBE.n": "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org",
    92  		"INDMVBZEEQ4ESVYAKGIYU74EAA.n": "enr:-----",
    93  	}
    94  	c, _ := NewClient(Config{Resolver: r, Logger: testlog.Logger(t, log.LvlTrace)})
    95  	_, err := c.SyncTree("enrtree://AKPYQIUQIL7PSIACI32J7FGZW56E5FKHEFCCOFHILBIMW3M6LWXS2@n")
    96  	wantErr := nameError{name: "INDMVBZEEQ4ESVYAKGIYU74EAA.n", err: entryError{typ: "enr", err: errInvalidENR}}
    97  	if err != wantErr {
    98  		t.Fatalf("expected sync error %q, got %q", wantErr, err)
    99  	}
   100  }
   101  
   102  // This test checks that RandomNode hits all entries.
   103  func TestClientRandomNode(t *testing.T) {
   104  	nodes := testNodes(nodesSeed1, 30)
   105  	tree, url := makeTestTree("n", nodes, nil)
   106  	r := mapResolver(tree.ToTXT("n"))
   107  	c, _ := NewClient(Config{Resolver: r, Logger: testlog.Logger(t, log.LvlTrace)})
   108  	if err := c.AddTree(url); err != nil {
   109  		t.Fatal(err)
   110  	}
   111  
   112  	checkRandomNode(t, c, nodes)
   113  }
   114  
   115  // This test checks that RandomNode traverses linked trees as well as explicitly added trees.
   116  func TestClientRandomNodeLinks(t *testing.T) {
   117  	nodes := testNodes(nodesSeed1, 40)
   118  	tree1, url1 := makeTestTree("t1", nodes[:10], nil)
   119  	tree2, url2 := makeTestTree("t2", nodes[10:], []string{url1})
   120  	cfg := Config{
   121  		Resolver: newMapResolver(tree1.ToTXT("t1"), tree2.ToTXT("t2")),
   122  		Logger:   testlog.Logger(t, log.LvlTrace),
   123  	}
   124  	c, _ := NewClient(cfg)
   125  	if err := c.AddTree(url2); err != nil {
   126  		t.Fatal(err)
   127  	}
   128  
   129  	checkRandomNode(t, c, nodes)
   130  }
   131  
   132  // This test verifies that RandomNode re-checks the root of the tree to catch
   133  // updates to nodes.
   134  func TestClientRandomNodeUpdates(t *testing.T) {
   135  	var (
   136  		clock    = new(mclock.Simulated)
   137  		nodes    = testNodes(nodesSeed1, 30)
   138  		resolver = newMapResolver()
   139  		cfg      = Config{
   140  			Resolver:        resolver,
   141  			Logger:          testlog.Logger(t, log.LvlTrace),
   142  			RecheckInterval: 20 * time.Minute,
   143  		}
   144  		c, _ = NewClient(cfg)
   145  	)
   146  	c.clock = clock
   147  	tree1, url := makeTestTree("n", nodes[:25], nil)
   148  
   149  	// Sync the original tree.
   150  	resolver.add(tree1.ToTXT("n"))
   151  	c.AddTree(url)
   152  	checkRandomNode(t, c, nodes[:25])
   153  
   154  	// Update some nodes and ensure RandomNode returns the new nodes as well.
   155  	keys := testKeys(nodesSeed1, len(nodes))
   156  	for i, n := range nodes[:len(nodes)/2] {
   157  		r := n.Record()
   158  		r.Set(enr.IP{127, 0, 0, 1})
   159  		r.SetSeq(55)
   160  		enode.SignV4(r, keys[i])
   161  		n2, _ := enode.New(enode.ValidSchemes, r)
   162  		nodes[i] = n2
   163  	}
   164  	tree2, _ := makeTestTree("n", nodes, nil)
   165  	clock.Run(cfg.RecheckInterval + 1*time.Second)
   166  	resolver.clear()
   167  	resolver.add(tree2.ToTXT("n"))
   168  	checkRandomNode(t, c, nodes)
   169  }
   170  
   171  // This test verifies that RandomNode re-checks the root of the tree to catch
   172  // updates to links.
   173  func TestClientRandomNodeLinkUpdates(t *testing.T) {
   174  	var (
   175  		clock    = new(mclock.Simulated)
   176  		nodes    = testNodes(nodesSeed1, 30)
   177  		resolver = newMapResolver()
   178  		cfg      = Config{
   179  			Resolver:        resolver,
   180  			Logger:          testlog.Logger(t, log.LvlTrace),
   181  			RecheckInterval: 20 * time.Minute,
   182  		}
   183  		c, _ = NewClient(cfg)
   184  	)
   185  	c.clock = clock
   186  	tree3, url3 := makeTestTree("t3", nodes[20:30], nil)
   187  	tree2, url2 := makeTestTree("t2", nodes[10:20], nil)
   188  	tree1, url1 := makeTestTree("t1", nodes[0:10], []string{url2})
   189  	resolver.add(tree1.ToTXT("t1"))
   190  	resolver.add(tree2.ToTXT("t2"))
   191  	resolver.add(tree3.ToTXT("t3"))
   192  
   193  	// Sync tree1 using RandomNode.
   194  	c.AddTree(url1)
   195  	checkRandomNode(t, c, nodes[:20])
   196  
   197  	// Add link to tree3, remove link to tree2.
   198  	tree1, _ = makeTestTree("t1", nodes[:10], []string{url3})
   199  	resolver.add(tree1.ToTXT("t1"))
   200  	clock.Run(cfg.RecheckInterval + 1*time.Second)
   201  	t.Log("tree1 updated")
   202  
   203  	var wantNodes []*enode.Node
   204  	wantNodes = append(wantNodes, tree1.Nodes()...)
   205  	wantNodes = append(wantNodes, tree3.Nodes()...)
   206  	checkRandomNode(t, c, wantNodes)
   207  
   208  	// Check that linked trees are GCed when they're no longer referenced.
   209  	if len(c.trees) != 2 {
   210  		t.Errorf("client knows %d trees, want 2", len(c.trees))
   211  	}
   212  }
   213  
   214  func checkRandomNode(t *testing.T, c *Client, wantNodes []*enode.Node) {
   215  	t.Helper()
   216  
   217  	var (
   218  		want     = make(map[enode.ID]*enode.Node)
   219  		maxCalls = len(wantNodes) * 2
   220  		calls    = 0
   221  		ctx      = context.Background()
   222  	)
   223  	for _, n := range wantNodes {
   224  		want[n.ID()] = n
   225  	}
   226  	for ; len(want) > 0 && calls < maxCalls; calls++ {
   227  		n := c.RandomNode(ctx)
   228  		if n == nil {
   229  			t.Fatalf("RandomNode returned nil (call %d)", calls)
   230  		}
   231  		delete(want, n.ID())
   232  	}
   233  	t.Logf("checkRandomNode called RandomNode %d times to find %d nodes", calls, len(wantNodes))
   234  	for _, n := range want {
   235  		t.Errorf("RandomNode didn't discover node %v", n.ID())
   236  	}
   237  }
   238  
   239  func makeTestTree(domain string, nodes []*enode.Node, links []string) (*Tree, string) {
   240  	tree, err := MakeTree(1, nodes, links)
   241  	if err != nil {
   242  		panic(err)
   243  	}
   244  	url, err := tree.Sign(testKey(signingKeySeed), domain)
   245  	if err != nil {
   246  		panic(err)
   247  	}
   248  	return tree, url
   249  }
   250  
   251  // testKeys creates deterministic private keys for testing.
   252  func testKeys(seed int64, n int) []*ecdsa.PrivateKey {
   253  	rand := rand.New(rand.NewSource(seed))
   254  	keys := make([]*ecdsa.PrivateKey, n)
   255  	for i := 0; i < n; i++ {
   256  		key, err := ecdsa.GenerateKey(crypto.S256(), rand)
   257  		if err != nil {
   258  			panic("can't generate key: " + err.Error())
   259  		}
   260  		keys[i] = key
   261  	}
   262  	return keys
   263  }
   264  
   265  func testKey(seed int64) *ecdsa.PrivateKey {
   266  	return testKeys(seed, 1)[0]
   267  }
   268  
   269  func testNodes(seed int64, n int) []*enode.Node {
   270  	keys := testKeys(seed, n)
   271  	nodes := make([]*enode.Node, n)
   272  	for i, key := range keys {
   273  		record := new(enr.Record)
   274  		record.SetSeq(uint64(i))
   275  		enode.SignV4(record, key)
   276  		n, err := enode.New(enode.ValidSchemes, record)
   277  		if err != nil {
   278  			panic(err)
   279  		}
   280  		nodes[i] = n
   281  	}
   282  	return nodes
   283  }
   284  
   285  func testNode(seed int64) *enode.Node {
   286  	return testNodes(seed, 1)[0]
   287  }
   288  
   289  type mapResolver map[string]string
   290  
   291  func newMapResolver(maps ...map[string]string) mapResolver {
   292  	mr := make(mapResolver)
   293  	for _, m := range maps {
   294  		mr.add(m)
   295  	}
   296  	return mr
   297  }
   298  
   299  func (mr mapResolver) clear() {
   300  	for k := range mr {
   301  		delete(mr, k)
   302  	}
   303  }
   304  
   305  func (mr mapResolver) add(m map[string]string) {
   306  	for k, v := range m {
   307  		mr[k] = v
   308  	}
   309  }
   310  
   311  func (mr mapResolver) LookupTXT(ctx context.Context, name string) ([]string, error) {
   312  	if record, ok := mr[name]; ok {
   313  		return []string{record}, nil
   314  	}
   315  	return nil, nil
   316  }