github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/les/fetcher_test.go (about)

     1  // Copyright 2020 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 les
    18  
    19  import (
    20  	"math/big"
    21  	"testing"
    22  	"time"
    23  
    24  	"github.com/kisexp/xdchain/consensus/ethash"
    25  	"github.com/kisexp/xdchain/core"
    26  	"github.com/kisexp/xdchain/core/rawdb"
    27  	"github.com/kisexp/xdchain/core/types"
    28  	"github.com/kisexp/xdchain/p2p/enode"
    29  )
    30  
    31  // verifyImportEvent verifies that one single event arrive on an import channel.
    32  func verifyImportEvent(t *testing.T, imported chan interface{}, arrive bool) {
    33  	if arrive {
    34  		select {
    35  		case <-imported:
    36  		case <-time.After(time.Second):
    37  			t.Fatalf("import timeout")
    38  		}
    39  	} else {
    40  		select {
    41  		case <-imported:
    42  			t.Fatalf("import invoked")
    43  		case <-time.After(20 * time.Millisecond):
    44  		}
    45  	}
    46  }
    47  
    48  // verifyImportDone verifies that no more events are arriving on an import channel.
    49  func verifyImportDone(t *testing.T, imported chan interface{}) {
    50  	select {
    51  	case <-imported:
    52  		t.Fatalf("extra block imported")
    53  	case <-time.After(50 * time.Millisecond):
    54  	}
    55  }
    56  
    57  // verifyChainHeight verifies the chain height is as expected.
    58  func verifyChainHeight(t *testing.T, fetcher *lightFetcher, height uint64) {
    59  	local := fetcher.chain.CurrentHeader().Number.Uint64()
    60  	if local != height {
    61  		t.Fatalf("chain height mismatch, got %d, want %d", local, height)
    62  	}
    63  }
    64  
    65  func TestSequentialAnnouncementsLes2(t *testing.T) { testSequentialAnnouncements(t, 2) }
    66  func TestSequentialAnnouncementsLes3(t *testing.T) { testSequentialAnnouncements(t, 3) }
    67  
    68  func testSequentialAnnouncements(t *testing.T, protocol int) {
    69  	s, c, teardown := newClientServerEnv(t, 4, protocol, nil, nil, 0, false, false, true)
    70  	defer teardown()
    71  
    72  	// Create connected peer pair.
    73  	c.handler.fetcher.noAnnounce = true // Ignore the first announce from peer which can trigger a resync.
    74  	p1, _, err := newTestPeerPair("peer", protocol, s.handler, c.handler)
    75  	if err != nil {
    76  		t.Fatalf("Failed to create peer pair %v", err)
    77  	}
    78  	c.handler.fetcher.noAnnounce = false
    79  
    80  	importCh := make(chan interface{})
    81  	c.handler.fetcher.newHeadHook = func(header *types.Header) {
    82  		importCh <- header
    83  	}
    84  	for i := uint64(1); i <= s.backend.Blockchain().CurrentHeader().Number.Uint64(); i++ {
    85  		header := s.backend.Blockchain().GetHeaderByNumber(i)
    86  		hash, number := header.Hash(), header.Number.Uint64()
    87  		td := rawdb.ReadTd(s.db, hash, number)
    88  
    89  		announce := announceData{hash, number, td, 0, nil}
    90  		if p1.cpeer.announceType == announceTypeSigned {
    91  			announce.sign(s.handler.server.privateKey)
    92  		}
    93  		p1.cpeer.sendAnnounce(announce)
    94  		verifyImportEvent(t, importCh, true)
    95  	}
    96  	verifyImportDone(t, importCh)
    97  	verifyChainHeight(t, c.handler.fetcher, 4)
    98  }
    99  
   100  func TestGappedAnnouncementsLes2(t *testing.T) { testGappedAnnouncements(t, 2) }
   101  func TestGappedAnnouncementsLes3(t *testing.T) { testGappedAnnouncements(t, 3) }
   102  
   103  func testGappedAnnouncements(t *testing.T, protocol int) {
   104  	s, c, teardown := newClientServerEnv(t, 4, protocol, nil, nil, 0, false, false, true)
   105  	defer teardown()
   106  
   107  	// Create connected peer pair.
   108  	c.handler.fetcher.noAnnounce = true // Ignore the first announce from peer which can trigger a resync.
   109  	peer, _, err := newTestPeerPair("peer", protocol, s.handler, c.handler)
   110  	if err != nil {
   111  		t.Fatalf("Failed to create peer pair %v", err)
   112  	}
   113  	c.handler.fetcher.noAnnounce = false
   114  
   115  	done := make(chan *types.Header, 1)
   116  	c.handler.fetcher.newHeadHook = func(header *types.Header) { done <- header }
   117  
   118  	// Prepare announcement by latest header.
   119  	latest := s.backend.Blockchain().CurrentHeader()
   120  	hash, number := latest.Hash(), latest.Number.Uint64()
   121  	td := rawdb.ReadTd(s.db, hash, number)
   122  
   123  	// Sign the announcement if necessary.
   124  	announce := announceData{hash, number, td, 0, nil}
   125  	if peer.cpeer.announceType == announceTypeSigned {
   126  		announce.sign(s.handler.server.privateKey)
   127  	}
   128  	peer.cpeer.sendAnnounce(announce)
   129  
   130  	<-done // Wait syncing
   131  	verifyChainHeight(t, c.handler.fetcher, 4)
   132  
   133  	// Send a reorged announcement
   134  	var newAnno = make(chan struct{}, 1)
   135  	c.handler.fetcher.noAnnounce = true
   136  	c.handler.fetcher.newAnnounce = func(*serverPeer, *announceData) {
   137  		newAnno <- struct{}{}
   138  	}
   139  	blocks, _ := core.GenerateChain(rawdb.ReadChainConfig(s.db, s.backend.Blockchain().Genesis().Hash()), s.backend.Blockchain().GetBlockByNumber(3),
   140  		ethash.NewFaker(), s.db, 2, func(i int, gen *core.BlockGen) {
   141  			gen.OffsetTime(-9) // higher block difficulty
   142  		})
   143  	s.backend.Blockchain().InsertChain(blocks)
   144  	<-newAnno
   145  	c.handler.fetcher.noAnnounce = false
   146  	c.handler.fetcher.newAnnounce = nil
   147  
   148  	latest = blocks[len(blocks)-1].Header()
   149  	hash, number = latest.Hash(), latest.Number.Uint64()
   150  	td = rawdb.ReadTd(s.db, hash, number)
   151  
   152  	announce = announceData{hash, number, td, 1, nil}
   153  	if peer.cpeer.announceType == announceTypeSigned {
   154  		announce.sign(s.handler.server.privateKey)
   155  	}
   156  	peer.cpeer.sendAnnounce(announce)
   157  
   158  	<-done // Wait syncing
   159  	verifyChainHeight(t, c.handler.fetcher, 5)
   160  }
   161  
   162  func TestTrustedAnnouncementsLes2(t *testing.T) { testTrustedAnnouncement(t, 2) }
   163  func TestTrustedAnnouncementsLes3(t *testing.T) { testTrustedAnnouncement(t, 3) }
   164  
   165  func testTrustedAnnouncement(t *testing.T, protocol int) {
   166  	var (
   167  		servers   []*testServer
   168  		teardowns []func()
   169  		nodes     []*enode.Node
   170  		ids       []string
   171  		cpeers    []*clientPeer
   172  		speers    []*serverPeer
   173  	)
   174  	for i := 0; i < 10; i++ {
   175  		s, n, teardown := newTestServerPeer(t, 10, protocol)
   176  
   177  		servers = append(servers, s)
   178  		nodes = append(nodes, n)
   179  		teardowns = append(teardowns, teardown)
   180  
   181  		// A half of them are trusted servers.
   182  		if i < 5 {
   183  			ids = append(ids, n.String())
   184  		}
   185  	}
   186  	_, c, teardown := newClientServerEnv(t, 0, protocol, nil, ids, 60, false, false, true)
   187  	defer teardown()
   188  	defer func() {
   189  		for i := 0; i < len(teardowns); i++ {
   190  			teardowns[i]()
   191  		}
   192  	}()
   193  
   194  	c.handler.fetcher.noAnnounce = true // Ignore the first announce from peer which can trigger a resync.
   195  
   196  	// Connect all server instances.
   197  	for i := 0; i < len(servers); i++ {
   198  		sp, cp, err := connect(servers[i].handler, nodes[i].ID(), c.handler, protocol)
   199  		if err != nil {
   200  			t.Fatalf("connect server and client failed, err %s", err)
   201  		}
   202  		cpeers = append(cpeers, cp)
   203  		speers = append(speers, sp)
   204  	}
   205  	c.handler.fetcher.noAnnounce = false
   206  
   207  	newHead := make(chan *types.Header, 1)
   208  	c.handler.fetcher.newHeadHook = func(header *types.Header) { newHead <- header }
   209  
   210  	check := func(height []uint64, expected uint64, callback func()) {
   211  		for i := 0; i < len(height); i++ {
   212  			for j := 0; j < len(servers); j++ {
   213  				h := servers[j].backend.Blockchain().GetHeaderByNumber(height[i])
   214  				hash, number := h.Hash(), h.Number.Uint64()
   215  				td := rawdb.ReadTd(servers[j].db, hash, number)
   216  
   217  				// Sign the announcement if necessary.
   218  				announce := announceData{hash, number, td, 0, nil}
   219  				p := cpeers[j]
   220  				if p.announceType == announceTypeSigned {
   221  					announce.sign(servers[j].handler.server.privateKey)
   222  				}
   223  				p.sendAnnounce(announce)
   224  			}
   225  		}
   226  		if callback != nil {
   227  			callback()
   228  		}
   229  		verifyChainHeight(t, c.handler.fetcher, expected)
   230  	}
   231  	check([]uint64{1}, 1, func() { <-newHead })   // Sequential announcements
   232  	check([]uint64{4}, 4, func() { <-newHead })   // ULC-style light syncing, rollback untrusted headers
   233  	check([]uint64{10}, 10, func() { <-newHead }) // Sync the whole chain.
   234  }
   235  
   236  func TestInvalidAnnounces(t *testing.T) {
   237  	s, c, teardown := newClientServerEnv(t, 4, lpv3, nil, nil, 0, false, false, true)
   238  	defer teardown()
   239  
   240  	// Create connected peer pair.
   241  	c.handler.fetcher.noAnnounce = true // Ignore the first announce from peer which can trigger a resync.
   242  	peer, _, err := newTestPeerPair("peer", lpv3, s.handler, c.handler)
   243  	if err != nil {
   244  		t.Fatalf("Failed to create peer pair %v", err)
   245  	}
   246  	c.handler.fetcher.noAnnounce = false
   247  
   248  	done := make(chan *types.Header, 1)
   249  	c.handler.fetcher.newHeadHook = func(header *types.Header) { done <- header }
   250  
   251  	// Prepare announcement by latest header.
   252  	headerOne := s.backend.Blockchain().GetHeaderByNumber(1)
   253  	hash, number := headerOne.Hash(), headerOne.Number.Uint64()
   254  	td := big.NewInt(200) // bad td
   255  
   256  	// Sign the announcement if necessary.
   257  	announce := announceData{hash, number, td, 0, nil}
   258  	if peer.cpeer.announceType == announceTypeSigned {
   259  		announce.sign(s.handler.server.privateKey)
   260  	}
   261  	peer.cpeer.sendAnnounce(announce)
   262  	<-done // Wait syncing
   263  
   264  	// Ensure the bad peer is evicited
   265  	if c.handler.backend.peers.len() != 0 {
   266  		t.Fatalf("Failed to evict invalid peer")
   267  	}
   268  }