github.com/alanchchen/go-ethereum@v1.6.6-0.20170601190819-6171d01b1195/core/block_validator_test.go (about)

     1  // Copyright 2015 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 core
    18  
    19  import (
    20  	"runtime"
    21  	"testing"
    22  	"time"
    23  
    24  	"github.com/ethereum/go-ethereum/consensus/ethash"
    25  	"github.com/ethereum/go-ethereum/core/types"
    26  	"github.com/ethereum/go-ethereum/core/vm"
    27  	"github.com/ethereum/go-ethereum/ethdb"
    28  	"github.com/ethereum/go-ethereum/event"
    29  	"github.com/ethereum/go-ethereum/params"
    30  )
    31  
    32  // Tests that simple header verification works, for both good and bad blocks.
    33  func TestHeaderVerification(t *testing.T) {
    34  	// Create a simple chain to verify
    35  	var (
    36  		testdb, _ = ethdb.NewMemDatabase()
    37  		gspec     = &Genesis{Config: params.TestChainConfig}
    38  		genesis   = gspec.MustCommit(testdb)
    39  		blocks, _ = GenerateChain(params.TestChainConfig, genesis, testdb, 8, nil)
    40  	)
    41  	headers := make([]*types.Header, len(blocks))
    42  	for i, block := range blocks {
    43  		headers[i] = block.Header()
    44  	}
    45  	// Run the header checker for blocks one-by-one, checking for both valid and invalid nonces
    46  	chain, _ := NewBlockChain(testdb, params.TestChainConfig, ethash.NewFaker(), new(event.TypeMux), vm.Config{})
    47  
    48  	for i := 0; i < len(blocks); i++ {
    49  		for j, valid := range []bool{true, false} {
    50  			var results <-chan error
    51  
    52  			if valid {
    53  				engine := ethash.NewFaker()
    54  				_, results = engine.VerifyHeaders(chain, []*types.Header{headers[i]}, []bool{true})
    55  			} else {
    56  				engine := ethash.NewFakeFailer(headers[i].Number.Uint64())
    57  				_, results = engine.VerifyHeaders(chain, []*types.Header{headers[i]}, []bool{true})
    58  			}
    59  			// Wait for the verification result
    60  			select {
    61  			case result := <-results:
    62  				if (result == nil) != valid {
    63  					t.Errorf("test %d.%d: validity mismatch: have %v, want %v", i, j, result, valid)
    64  				}
    65  			case <-time.After(time.Second):
    66  				t.Fatalf("test %d.%d: verification timeout", i, j)
    67  			}
    68  			// Make sure no more data is returned
    69  			select {
    70  			case result := <-results:
    71  				t.Fatalf("test %d.%d: unexpected result returned: %v", i, j, result)
    72  			case <-time.After(25 * time.Millisecond):
    73  			}
    74  		}
    75  		chain.InsertChain(blocks[i : i+1])
    76  	}
    77  }
    78  
    79  // Tests that concurrent header verification works, for both good and bad blocks.
    80  func TestHeaderConcurrentVerification2(t *testing.T)  { testHeaderConcurrentVerification(t, 2) }
    81  func TestHeaderConcurrentVerification8(t *testing.T)  { testHeaderConcurrentVerification(t, 8) }
    82  func TestHeaderConcurrentVerification32(t *testing.T) { testHeaderConcurrentVerification(t, 32) }
    83  
    84  func testHeaderConcurrentVerification(t *testing.T, threads int) {
    85  	// Create a simple chain to verify
    86  	var (
    87  		testdb, _ = ethdb.NewMemDatabase()
    88  		gspec     = &Genesis{Config: params.TestChainConfig}
    89  		genesis   = gspec.MustCommit(testdb)
    90  		blocks, _ = GenerateChain(params.TestChainConfig, genesis, testdb, 8, nil)
    91  	)
    92  	headers := make([]*types.Header, len(blocks))
    93  	seals := make([]bool, len(blocks))
    94  
    95  	for i, block := range blocks {
    96  		headers[i] = block.Header()
    97  		seals[i] = true
    98  	}
    99  	// Set the number of threads to verify on
   100  	old := runtime.GOMAXPROCS(threads)
   101  	defer runtime.GOMAXPROCS(old)
   102  
   103  	// Run the header checker for the entire block chain at once both for a valid and
   104  	// also an invalid chain (enough if one arbitrary block is invalid).
   105  	for i, valid := range []bool{true, false} {
   106  		var results <-chan error
   107  
   108  		if valid {
   109  			chain, _ := NewBlockChain(testdb, params.TestChainConfig, ethash.NewFaker(), new(event.TypeMux), vm.Config{})
   110  			_, results = chain.engine.VerifyHeaders(chain, headers, seals)
   111  		} else {
   112  			chain, _ := NewBlockChain(testdb, params.TestChainConfig, ethash.NewFakeFailer(uint64(len(headers)-1)), new(event.TypeMux), vm.Config{})
   113  			_, results = chain.engine.VerifyHeaders(chain, headers, seals)
   114  		}
   115  		// Wait for all the verification results
   116  		checks := make(map[int]error)
   117  		for j := 0; j < len(blocks); j++ {
   118  			select {
   119  			case result := <-results:
   120  				checks[j] = result
   121  
   122  			case <-time.After(time.Second):
   123  				t.Fatalf("test %d.%d: verification timeout", i, j)
   124  			}
   125  		}
   126  		// Check nonce check validity
   127  		for j := 0; j < len(blocks); j++ {
   128  			want := valid || (j < len(blocks)-2) // We chose the last-but-one nonce in the chain to fail
   129  			if (checks[j] == nil) != want {
   130  				t.Errorf("test %d.%d: validity mismatch: have %v, want %v", i, j, checks[j], want)
   131  			}
   132  			if !want {
   133  				// A few blocks after the first error may pass verification due to concurrent
   134  				// workers. We don't care about those in this test, just that the correct block
   135  				// errors out.
   136  				break
   137  			}
   138  		}
   139  		// Make sure no more data is returned
   140  		select {
   141  		case result := <-results:
   142  			t.Fatalf("test %d: unexpected result returned: %v", i, result)
   143  		case <-time.After(25 * time.Millisecond):
   144  		}
   145  	}
   146  }
   147  
   148  // Tests that aborting a header validation indeed prevents further checks from being
   149  // run, as well as checks that no left-over goroutines are leaked.
   150  func TestHeaderConcurrentAbortion2(t *testing.T)  { testHeaderConcurrentAbortion(t, 2) }
   151  func TestHeaderConcurrentAbortion8(t *testing.T)  { testHeaderConcurrentAbortion(t, 8) }
   152  func TestHeaderConcurrentAbortion32(t *testing.T) { testHeaderConcurrentAbortion(t, 32) }
   153  
   154  func testHeaderConcurrentAbortion(t *testing.T, threads int) {
   155  	// Create a simple chain to verify
   156  	var (
   157  		testdb, _ = ethdb.NewMemDatabase()
   158  		gspec     = &Genesis{Config: params.TestChainConfig}
   159  		genesis   = gspec.MustCommit(testdb)
   160  		blocks, _ = GenerateChain(params.TestChainConfig, genesis, testdb, 1024, nil)
   161  	)
   162  	headers := make([]*types.Header, len(blocks))
   163  	seals := make([]bool, len(blocks))
   164  
   165  	for i, block := range blocks {
   166  		headers[i] = block.Header()
   167  		seals[i] = true
   168  	}
   169  	// Set the number of threads to verify on
   170  	old := runtime.GOMAXPROCS(threads)
   171  	defer runtime.GOMAXPROCS(old)
   172  
   173  	// Start the verifications and immediately abort
   174  	chain, _ := NewBlockChain(testdb, params.TestChainConfig, ethash.NewFakeDelayer(time.Millisecond), new(event.TypeMux), vm.Config{})
   175  	abort, results := chain.engine.VerifyHeaders(chain, headers, seals)
   176  	close(abort)
   177  
   178  	// Deplete the results channel
   179  	verified := 0
   180  	for depleted := false; !depleted; {
   181  		select {
   182  		case result := <-results:
   183  			if result != nil {
   184  				t.Errorf("header %d: validation failed: %v", verified, result)
   185  			}
   186  			verified++
   187  		case <-time.After(50 * time.Millisecond):
   188  			depleted = true
   189  		}
   190  	}
   191  	// Check that abortion was honored by not processing too many POWs
   192  	if verified > 2*threads {
   193  		t.Errorf("verification count too large: have %d, want below %d", verified, 2*threads)
   194  	}
   195  }