github.com/core-coin/go-core/v2@v2.1.9/les/fetcher_test.go (about)

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