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
17package core
18
19import (
20	"encoding/json"
21	"math/big"
22	"runtime"
23	"testing"
24	"time"
25
26	"github.com/ethereum/go-ethereum/common"
27	"github.com/ethereum/go-ethereum/consensus"
28	"github.com/ethereum/go-ethereum/consensus/beacon"
29	"github.com/ethereum/go-ethereum/consensus/clique"
30	"github.com/ethereum/go-ethereum/consensus/ethash"
31	"github.com/ethereum/go-ethereum/core/rawdb"
32	"github.com/ethereum/go-ethereum/core/types"
33	"github.com/ethereum/go-ethereum/core/vm"
34	"github.com/ethereum/go-ethereum/crypto"
35	"github.com/ethereum/go-ethereum/params"
36)
37
38// Tests that simple header verification works, for both good and bad blocks.
39func TestHeaderVerification(t *testing.T) {
40	// Create a simple chain to verify
41	var (
42		testdb    = rawdb.NewMemoryDatabase()
43		gspec     = &Genesis{Config: params.TestChainConfig}
44		genesis   = gspec.MustCommit(testdb)
45		blocks, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), testdb, 8, nil)
46	)
47	headers := make([]*types.Header, len(blocks))
48	for i, block := range blocks {
49		headers[i] = block.Header()
50	}
51	// Run the header checker for blocks one-by-one, checking for both valid and invalid nonces
52	chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
53	defer chain.Stop()
54
55	for i := 0; i < len(blocks); i++ {
56		for j, valid := range []bool{true, false} {
57			var results <-chan error
58
59			if valid {
60				engine := ethash.NewFaker()
61				_, results = engine.VerifyHeaders(chain, []*types.Header{headers[i]}, []bool{true})
62			} else {
63				engine := ethash.NewFakeFailer(headers[i].Number.Uint64())
64				_, results = engine.VerifyHeaders(chain, []*types.Header{headers[i]}, []bool{true})
65			}
66			// Wait for the verification result
67			select {
68			case result := <-results:
69				if (result == nil) != valid {
70					t.Errorf("test %d.%d: validity mismatch: have %v, want %v", i, j, result, valid)
71				}
72			case <-time.After(time.Second):
73				t.Fatalf("test %d.%d: verification timeout", i, j)
74			}
75			// Make sure no more data is returned
76			select {
77			case result := <-results:
78				t.Fatalf("test %d.%d: unexpected result returned: %v", i, j, result)
79			case <-time.After(25 * time.Millisecond):
80			}
81		}
82		chain.InsertChain(blocks[i : i+1])
83	}
84}
85
86func TestHeaderVerificationForMergingClique(t *testing.T) { testHeaderVerificationForMerging(t, true) }
87func TestHeaderVerificationForMergingEthash(t *testing.T) { testHeaderVerificationForMerging(t, false) }
88
89// Tests the verification for eth1/2 merging, including pre-merge and post-merge
90func testHeaderVerificationForMerging(t *testing.T, isClique bool) {
91	var (
92		testdb      = rawdb.NewMemoryDatabase()
93		preBlocks   []*types.Block
94		postBlocks  []*types.Block
95		runEngine   consensus.Engine
96		chainConfig *params.ChainConfig
97		merger      = consensus.NewMerger(rawdb.NewMemoryDatabase())
98	)
99	if isClique {
100		var (
101			key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
102			addr   = crypto.PubkeyToAddress(key.PublicKey)
103			engine = clique.New(params.AllCliqueProtocolChanges.Clique, testdb)
104		)
105		genspec := &Genesis{
106			ExtraData: make([]byte, 32+common.AddressLength+crypto.SignatureLength),
107			Alloc: map[common.Address]GenesisAccount{
108				addr: {Balance: big.NewInt(1)},
109			},
110			BaseFee: big.NewInt(params.InitialBaseFee),
111		}
112		copy(genspec.ExtraData[32:], addr[:])
113		genesis := genspec.MustCommit(testdb)
114
115		genEngine := beacon.New(engine)
116		preBlocks, _ = GenerateChain(params.AllCliqueProtocolChanges, genesis, genEngine, testdb, 8, nil)
117		td := 0
118		for i, block := range preBlocks {
119			header := block.Header()
120			if i > 0 {
121				header.ParentHash = preBlocks[i-1].Hash()
122			}
123			header.Extra = make([]byte, 32+crypto.SignatureLength)
124			header.Difficulty = big.NewInt(2)
125
126			sig, _ := crypto.Sign(genEngine.SealHash(header).Bytes(), key)
127			copy(header.Extra[len(header.Extra)-crypto.SignatureLength:], sig)
128			preBlocks[i] = block.WithSeal(header)
129			// calculate td
130			td += int(block.Difficulty().Uint64())
131		}
132		config := *params.AllCliqueProtocolChanges
133		config.TerminalTotalDifficulty = big.NewInt(int64(td))
134		postBlocks, _ = GenerateChain(&config, preBlocks[len(preBlocks)-1], genEngine, testdb, 8, nil)
135		chainConfig = &config
136		runEngine = beacon.New(engine)
137	} else {
138		gspec := &Genesis{Config: params.TestChainConfig}
139		genesis := gspec.MustCommit(testdb)
140		genEngine := beacon.New(ethash.NewFaker())
141
142		preBlocks, _ = GenerateChain(params.TestChainConfig, genesis, genEngine, testdb, 8, nil)
143		td := 0
144		for _, block := range preBlocks {
145			// calculate td
146			td += int(block.Difficulty().Uint64())
147		}
148		config := *params.TestChainConfig
149		config.TerminalTotalDifficulty = big.NewInt(int64(td))
150		postBlocks, _ = GenerateChain(params.TestChainConfig, preBlocks[len(preBlocks)-1], genEngine, testdb, 8, nil)
151
152		chainConfig = &config
153		runEngine = beacon.New(ethash.NewFaker())
154	}
155
156	preHeaders := make([]*types.Header, len(preBlocks))
157	for i, block := range preBlocks {
158		preHeaders[i] = block.Header()
159
160		blob, _ := json.Marshal(block.Header())
161		t.Logf("Log header before the merging %d: %v", block.NumberU64(), string(blob))
162	}
163	postHeaders := make([]*types.Header, len(postBlocks))
164	for i, block := range postBlocks {
165		postHeaders[i] = block.Header()
166
167		blob, _ := json.Marshal(block.Header())
168		t.Logf("Log header after the merging %d: %v", block.NumberU64(), string(blob))
169	}
170	// Run the header checker for blocks one-by-one, checking for both valid and invalid nonces
171	chain, _ := NewBlockChain(testdb, nil, chainConfig, runEngine, vm.Config{}, nil, nil)
172	defer chain.Stop()
173
174	// Verify the blocks before the merging
175	for i := 0; i < len(preBlocks); i++ {
176		_, results := runEngine.VerifyHeaders(chain, []*types.Header{preHeaders[i]}, []bool{true})
177		// Wait for the verification result
178		select {
179		case result := <-results:
180			if result != nil {
181				t.Errorf("test %d: verification failed %v", i, result)
182			}
183		case <-time.After(time.Second):
184			t.Fatalf("test %d: verification timeout", i)
185		}
186		// Make sure no more data is returned
187		select {
188		case result := <-results:
189			t.Fatalf("test %d: unexpected result returned: %v", i, result)
190		case <-time.After(25 * time.Millisecond):
191		}
192		chain.InsertChain(preBlocks[i : i+1])
193	}
194
195	// Make the transition
196	merger.ReachTTD()
197	merger.FinalizePoS()
198
199	// Verify the blocks after the merging
200	for i := 0; i < len(postBlocks); i++ {
201		_, results := runEngine.VerifyHeaders(chain, []*types.Header{postHeaders[i]}, []bool{true})
202		// Wait for the verification result
203		select {
204		case result := <-results:
205			if result != nil {
206				t.Errorf("test %d: verification failed %v", i, result)
207			}
208		case <-time.After(time.Second):
209			t.Fatalf("test %d: verification timeout", i)
210		}
211		// Make sure no more data is returned
212		select {
213		case result := <-results:
214			t.Fatalf("test %d: unexpected result returned: %v", i, result)
215		case <-time.After(25 * time.Millisecond):
216		}
217		chain.InsertBlockWithoutSetHead(postBlocks[i])
218	}
219
220	// Verify the blocks with pre-merge blocks and post-merge blocks
221	var (
222		headers []*types.Header
223		seals   []bool
224	)
225	for _, block := range preBlocks {
226		headers = append(headers, block.Header())
227		seals = append(seals, true)
228	}
229	for _, block := range postBlocks {
230		headers = append(headers, block.Header())
231		seals = append(seals, true)
232	}
233	_, results := runEngine.VerifyHeaders(chain, headers, seals)
234	for i := 0; i < len(headers); i++ {
235		select {
236		case result := <-results:
237			if result != nil {
238				t.Errorf("test %d: verification failed %v", i, result)
239			}
240		case <-time.After(time.Second):
241			t.Fatalf("test %d: verification timeout", i)
242		}
243	}
244	// Make sure no more data is returned
245	select {
246	case result := <-results:
247		t.Fatalf("unexpected result returned: %v", result)
248	case <-time.After(25 * time.Millisecond):
249	}
250}
251
252// Tests that concurrent header verification works, for both good and bad blocks.
253func TestHeaderConcurrentVerification2(t *testing.T)  { testHeaderConcurrentVerification(t, 2) }
254func TestHeaderConcurrentVerification8(t *testing.T)  { testHeaderConcurrentVerification(t, 8) }
255func TestHeaderConcurrentVerification32(t *testing.T) { testHeaderConcurrentVerification(t, 32) }
256
257func testHeaderConcurrentVerification(t *testing.T, threads int) {
258	// Create a simple chain to verify
259	var (
260		testdb    = rawdb.NewMemoryDatabase()
261		gspec     = &Genesis{Config: params.TestChainConfig}
262		genesis   = gspec.MustCommit(testdb)
263		blocks, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), testdb, 8, nil)
264	)
265	headers := make([]*types.Header, len(blocks))
266	seals := make([]bool, len(blocks))
267
268	for i, block := range blocks {
269		headers[i] = block.Header()
270		seals[i] = true
271	}
272	// Set the number of threads to verify on
273	old := runtime.GOMAXPROCS(threads)
274	defer runtime.GOMAXPROCS(old)
275
276	// Run the header checker for the entire block chain at once both for a valid and
277	// also an invalid chain (enough if one arbitrary block is invalid).
278	for i, valid := range []bool{true, false} {
279		var results <-chan error
280
281		if valid {
282			chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
283			_, results = chain.engine.VerifyHeaders(chain, headers, seals)
284			chain.Stop()
285		} else {
286			chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFakeFailer(uint64(len(headers)-1)), vm.Config{}, nil, nil)
287			_, results = chain.engine.VerifyHeaders(chain, headers, seals)
288			chain.Stop()
289		}
290		// Wait for all the verification results
291		checks := make(map[int]error)
292		for j := 0; j < len(blocks); j++ {
293			select {
294			case result := <-results:
295				checks[j] = result
296
297			case <-time.After(time.Second):
298				t.Fatalf("test %d.%d: verification timeout", i, j)
299			}
300		}
301		// Check nonce check validity
302		for j := 0; j < len(blocks); j++ {
303			want := valid || (j < len(blocks)-2) // We chose the last-but-one nonce in the chain to fail
304			if (checks[j] == nil) != want {
305				t.Errorf("test %d.%d: validity mismatch: have %v, want %v", i, j, checks[j], want)
306			}
307			if !want {
308				// A few blocks after the first error may pass verification due to concurrent
309				// workers. We don't care about those in this test, just that the correct block
310				// errors out.
311				break
312			}
313		}
314		// Make sure no more data is returned
315		select {
316		case result := <-results:
317			t.Fatalf("test %d: unexpected result returned: %v", i, result)
318		case <-time.After(25 * time.Millisecond):
319		}
320	}
321}
322
323// Tests that aborting a header validation indeed prevents further checks from being
324// run, as well as checks that no left-over goroutines are leaked.
325func TestHeaderConcurrentAbortion2(t *testing.T)  { testHeaderConcurrentAbortion(t, 2) }
326func TestHeaderConcurrentAbortion8(t *testing.T)  { testHeaderConcurrentAbortion(t, 8) }
327func TestHeaderConcurrentAbortion32(t *testing.T) { testHeaderConcurrentAbortion(t, 32) }
328
329func testHeaderConcurrentAbortion(t *testing.T, threads int) {
330	// Create a simple chain to verify
331	var (
332		testdb    = rawdb.NewMemoryDatabase()
333		gspec     = &Genesis{Config: params.TestChainConfig}
334		genesis   = gspec.MustCommit(testdb)
335		blocks, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), testdb, 1024, nil)
336	)
337	headers := make([]*types.Header, len(blocks))
338	seals := make([]bool, len(blocks))
339
340	for i, block := range blocks {
341		headers[i] = block.Header()
342		seals[i] = true
343	}
344	// Set the number of threads to verify on
345	old := runtime.GOMAXPROCS(threads)
346	defer runtime.GOMAXPROCS(old)
347
348	// Start the verifications and immediately abort
349	chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFakeDelayer(time.Millisecond), vm.Config{}, nil, nil)
350	defer chain.Stop()
351
352	abort, results := chain.engine.VerifyHeaders(chain, headers, seals)
353	close(abort)
354
355	// Deplete the results channel
356	verified := 0
357	for depleted := false; !depleted; {
358		select {
359		case result := <-results:
360			if result != nil {
361				t.Errorf("header %d: validation failed: %v", verified, result)
362			}
363			verified++
364		case <-time.After(50 * time.Millisecond):
365			depleted = true
366		}
367	}
368	// Check that abortion was honored by not processing too many POWs
369	if verified > 2*threads {
370		t.Errorf("verification count too large: have %d, want below %d", verified, 2*threads)
371	}
372}
373
374func TestCalcGasLimit(t *testing.T) {
375	for i, tc := range []struct {
376		pGasLimit uint64
377		max       uint64
378		min       uint64
379	}{
380		{20000000, 20019530, 19980470},
381		{40000000, 40039061, 39960939},
382	} {
383		// Increase
384		if have, want := CalcGasLimit(tc.pGasLimit, 2*tc.pGasLimit), tc.max; have != want {
385			t.Errorf("test %d: have %d want <%d", i, have, want)
386		}
387		// Decrease
388		if have, want := CalcGasLimit(tc.pGasLimit, 0), tc.min; have != want {
389			t.Errorf("test %d: have %d want >%d", i, have, want)
390		}
391		// Small decrease
392		if have, want := CalcGasLimit(tc.pGasLimit, tc.pGasLimit-1), tc.pGasLimit-1; have != want {
393			t.Errorf("test %d: have %d want %d", i, have, want)
394		}
395		// Small increase
396		if have, want := CalcGasLimit(tc.pGasLimit, tc.pGasLimit+1), tc.pGasLimit+1; have != want {
397			t.Errorf("test %d: have %d want %d", i, have, want)
398		}
399		// No change
400		if have, want := CalcGasLimit(tc.pGasLimit, tc.pGasLimit), tc.pGasLimit; have != want {
401			t.Errorf("test %d: have %d want %d", i, have, want)
402		}
403	}
404}
405