github.com/theQRL/go-zond@v0.2.1/core/chain_indexer_test.go (about)

     1  // Copyright 2017 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  	"context"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"math/rand"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/theQRL/go-zond/common"
    29  	"github.com/theQRL/go-zond/core/rawdb"
    30  	"github.com/theQRL/go-zond/core/types"
    31  )
    32  
    33  func TestChainIndexerSingle(t *testing.T) {
    34  	for i := 0; i < 10; i++ {
    35  		testChainIndexer(t, 1)
    36  	}
    37  }
    38  
    39  // Runs multiple tests with randomized parameters and different number of
    40  // chain backends.
    41  func TestChainIndexerWithChildren(t *testing.T) {
    42  	for i := 2; i < 8; i++ {
    43  		testChainIndexer(t, i)
    44  	}
    45  }
    46  
    47  // NOTE(rgeraldes24): forks are not possible
    48  // testChainIndexer runs a test with either a single chain indexer or a chain of
    49  // multiple backends. The section size and required confirmation count parameters
    50  // are randomized.
    51  func testChainIndexer(t *testing.T, count int) {
    52  	db := rawdb.NewMemoryDatabase()
    53  	defer db.Close()
    54  
    55  	// Create a chain of indexers and ensure they all report empty
    56  	backends := make([]*testChainIndexBackend, count)
    57  	for i := 0; i < count; i++ {
    58  		var (
    59  			sectionSize = uint64(rand.Intn(100) + 1)
    60  			confirmsReq = uint64(rand.Intn(10))
    61  		)
    62  		backends[i] = &testChainIndexBackend{t: t, processCh: make(chan uint64)}
    63  		backends[i].indexer = NewChainIndexer(db, rawdb.NewTable(db, string([]byte{byte(i)})), backends[i], sectionSize, confirmsReq, 0, fmt.Sprintf("indexer-%d", i))
    64  
    65  		if sections, _, _ := backends[i].indexer.Sections(); sections != 0 {
    66  			t.Fatalf("Canonical section count mismatch: have %v, want %v", sections, 0)
    67  		}
    68  		if i > 0 {
    69  			backends[i-1].indexer.AddChildIndexer(backends[i].indexer)
    70  		}
    71  	}
    72  	defer backends[0].indexer.Close() // parent indexer shuts down children
    73  	// notify pings the root indexer about a new head or reorg, then expect
    74  	// processed blocks if a section is processable
    75  	notify := func(headNum, failNum uint64, reorg bool) {
    76  		backends[0].indexer.newHead(headNum, reorg)
    77  		if reorg {
    78  			for _, backend := range backends {
    79  				headNum = backend.reorg(headNum)
    80  				backend.assertSections()
    81  			}
    82  			return
    83  		}
    84  		var cascade bool
    85  		for _, backend := range backends {
    86  			headNum, cascade = backend.assertBlocks(headNum, failNum)
    87  			if !cascade {
    88  				break
    89  			}
    90  			backend.assertSections()
    91  		}
    92  	}
    93  	// inject inserts a new random canonical header into the database directly
    94  	inject := func(number uint64) {
    95  		header := &types.Header{
    96  			Number:          big.NewInt(int64(number)),
    97  			Extra:           big.NewInt(rand.Int63()).Bytes(),
    98  			BaseFee:         big.NewInt(0),
    99  			WithdrawalsHash: &types.EmptyWithdrawalsHash,
   100  		}
   101  		if number > 0 {
   102  			header.ParentHash = rawdb.ReadCanonicalHash(db, number-1)
   103  		}
   104  		rawdb.WriteHeader(db, header)
   105  		rawdb.WriteCanonicalHash(db, header.Hash(), number)
   106  	}
   107  
   108  	// Start indexer with an already existing chain
   109  	for i := uint64(0); i <= 100; i++ {
   110  		inject(i)
   111  	}
   112  	notify(100, 100, false)
   113  
   114  	// Add new blocks one by one
   115  	for i := uint64(101); i <= 1000; i++ {
   116  		inject(i)
   117  		notify(i, i, false)
   118  	}
   119  	// Do a reorg
   120  	notify(500, 500, true)
   121  
   122  	// Create new fork
   123  	// for i := uint64(501); i <= 1000; i++ {
   124  	// 	inject(i)
   125  	// 	notify(i, i, false)
   126  	// }
   127  	for i := uint64(1001); i <= 1500; i++ {
   128  		inject(i)
   129  	}
   130  
   131  	// Failed processing scenario where less blocks are available than notified
   132  	notify(2000, 1500, false)
   133  
   134  	// Notify about a reorg (which could have caused the missing blocks if happened during processing)
   135  	notify(1500, 1500, true)
   136  
   137  	// Create new fork
   138  	// for i := uint64(1501); i <= 2000; i++ {
   139  	// 	inject(i)
   140  	// 	notify(i, i, false)
   141  	//
   142  }
   143  
   144  // testChainIndexBackend implements ChainIndexerBackend
   145  type testChainIndexBackend struct {
   146  	t                          *testing.T
   147  	indexer                    *ChainIndexer
   148  	section, headerCnt, stored uint64
   149  	processCh                  chan uint64
   150  }
   151  
   152  // assertSections verifies if a chain indexer has the correct number of section.
   153  func (b *testChainIndexBackend) assertSections() {
   154  	// Keep trying for 3 seconds if it does not match
   155  	var sections uint64
   156  	for i := 0; i < 300; i++ {
   157  		sections, _, _ = b.indexer.Sections()
   158  		if sections == b.stored {
   159  			return
   160  		}
   161  		time.Sleep(10 * time.Millisecond)
   162  	}
   163  	b.t.Fatalf("Canonical section count mismatch: have %v, want %v", sections, b.stored)
   164  }
   165  
   166  // assertBlocks expects processing calls after new blocks have arrived. If the
   167  // failNum < headNum then we are simulating a scenario where a reorg has happened
   168  // after the processing has started and the processing of a section fails.
   169  func (b *testChainIndexBackend) assertBlocks(headNum, failNum uint64) (uint64, bool) {
   170  	var sections uint64
   171  	if headNum >= b.indexer.confirmsReq {
   172  		sections = (headNum + 1 - b.indexer.confirmsReq) / b.indexer.sectionSize
   173  		if sections > b.stored {
   174  			// expect processed blocks
   175  			for expectd := b.stored * b.indexer.sectionSize; expectd < sections*b.indexer.sectionSize; expectd++ {
   176  				if expectd > failNum {
   177  					// rolled back after processing started, no more process calls expected
   178  					// wait until updating is done to make sure that processing actually fails
   179  					var updating bool
   180  					for i := 0; i < 300; i++ {
   181  						b.indexer.lock.Lock()
   182  						updating = b.indexer.knownSections > b.indexer.storedSections
   183  						b.indexer.lock.Unlock()
   184  						if !updating {
   185  							break
   186  						}
   187  						time.Sleep(10 * time.Millisecond)
   188  					}
   189  					if updating {
   190  						b.t.Fatalf("update did not finish")
   191  					}
   192  					sections = expectd / b.indexer.sectionSize
   193  					break
   194  				}
   195  				select {
   196  				case <-time.After(10 * time.Second):
   197  					b.t.Fatalf("Expected processed block #%d, got nothing", expectd)
   198  				case processed := <-b.processCh:
   199  					if processed != expectd {
   200  						b.t.Errorf("Expected processed block #%d, got #%d", expectd, processed)
   201  					}
   202  				}
   203  			}
   204  			b.stored = sections
   205  		}
   206  	}
   207  	if b.stored == 0 {
   208  		return 0, false
   209  	}
   210  	return b.stored*b.indexer.sectionSize - 1, true
   211  }
   212  
   213  func (b *testChainIndexBackend) reorg(headNum uint64) uint64 {
   214  	firstChanged := (headNum + 1) / b.indexer.sectionSize
   215  	if firstChanged < b.stored {
   216  		b.stored = firstChanged
   217  	}
   218  	return b.stored * b.indexer.sectionSize
   219  }
   220  
   221  func (b *testChainIndexBackend) Reset(ctx context.Context, section uint64, prevHead common.Hash) error {
   222  	b.section = section
   223  	b.headerCnt = 0
   224  	return nil
   225  }
   226  
   227  func (b *testChainIndexBackend) Process(ctx context.Context, header *types.Header) error {
   228  	b.headerCnt++
   229  	if b.headerCnt > b.indexer.sectionSize {
   230  		b.t.Error("Processing too many headers")
   231  	}
   232  	//t.processCh <- header.Number.Uint64()
   233  	select {
   234  	case <-time.After(10 * time.Second):
   235  		b.t.Error("Unexpected call to Process")
   236  		// Can't use Fatal since this is not the test's goroutine.
   237  		// Returning error stops the chainIndexer's updateLoop
   238  		return errors.New("unexpected call to Process")
   239  	case b.processCh <- header.Number.Uint64():
   240  	}
   241  	return nil
   242  }
   243  
   244  func (b *testChainIndexBackend) Commit() error {
   245  	if b.headerCnt != b.indexer.sectionSize {
   246  		b.t.Error("Not enough headers processed")
   247  	}
   248  	return nil
   249  }
   250  
   251  func (b *testChainIndexBackend) Prune(threshold uint64) error {
   252  	return nil
   253  }