github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/core/blockchain_insert.go (about)

     1  // Copyright 2018 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  	"time"
    21  
    22  	"github.com/tirogen/go-ethereum/common"
    23  	"github.com/tirogen/go-ethereum/common/mclock"
    24  	"github.com/tirogen/go-ethereum/core/types"
    25  	"github.com/tirogen/go-ethereum/log"
    26  )
    27  
    28  // insertStats tracks and reports on block insertion.
    29  type insertStats struct {
    30  	queued, processed, ignored int
    31  	usedGas                    uint64
    32  	lastIndex                  int
    33  	startTime                  mclock.AbsTime
    34  }
    35  
    36  // statsReportLimit is the time limit during import and export after which we
    37  // always print out progress. This avoids the user wondering what's going on.
    38  const statsReportLimit = 8 * time.Second
    39  
    40  // report prints statistics if some number of blocks have been processed
    41  // or more than a few seconds have passed since the last message.
    42  func (st *insertStats) report(chain []*types.Block, index int, dirty common.StorageSize, setHead bool) {
    43  	// Fetch the timings for the batch
    44  	var (
    45  		now     = mclock.Now()
    46  		elapsed = now.Sub(st.startTime)
    47  	)
    48  	// If we're at the last block of the batch or report period reached, log
    49  	if index == len(chain)-1 || elapsed >= statsReportLimit {
    50  		// Count the number of transactions in this segment
    51  		var txs int
    52  		for _, block := range chain[st.lastIndex : index+1] {
    53  			txs += len(block.Transactions())
    54  		}
    55  		end := chain[index]
    56  
    57  		// Assemble the log context and send it to the logger
    58  		context := []interface{}{
    59  			"number", end.Number(), "hash", end.Hash(),
    60  			"blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000,
    61  			"elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed),
    62  		}
    63  		if timestamp := time.Unix(int64(end.Time()), 0); time.Since(timestamp) > time.Minute {
    64  			context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
    65  		}
    66  		context = append(context, []interface{}{"dirty", dirty}...)
    67  
    68  		if st.queued > 0 {
    69  			context = append(context, []interface{}{"queued", st.queued}...)
    70  		}
    71  		if st.ignored > 0 {
    72  			context = append(context, []interface{}{"ignored", st.ignored}...)
    73  		}
    74  		if setHead {
    75  			log.Info("Imported new chain segment", context...)
    76  		} else {
    77  			log.Info("Imported new potential chain segment", context...)
    78  		}
    79  		// Bump the stats reported to the next section
    80  		*st = insertStats{startTime: now, lastIndex: index + 1}
    81  	}
    82  }
    83  
    84  // insertIterator is a helper to assist during chain import.
    85  type insertIterator struct {
    86  	chain types.Blocks // Chain of blocks being iterated over
    87  
    88  	results <-chan error // Verification result sink from the consensus engine
    89  	errors  []error      // Header verification errors for the blocks
    90  
    91  	index     int       // Current offset of the iterator
    92  	validator Validator // Validator to run if verification succeeds
    93  }
    94  
    95  // newInsertIterator creates a new iterator based on the given blocks, which are
    96  // assumed to be a contiguous chain.
    97  func newInsertIterator(chain types.Blocks, results <-chan error, validator Validator) *insertIterator {
    98  	return &insertIterator{
    99  		chain:     chain,
   100  		results:   results,
   101  		errors:    make([]error, 0, len(chain)),
   102  		index:     -1,
   103  		validator: validator,
   104  	}
   105  }
   106  
   107  // next returns the next block in the iterator, along with any potential validation
   108  // error for that block. When the end is reached, it will return (nil, nil).
   109  func (it *insertIterator) next() (*types.Block, error) {
   110  	// If we reached the end of the chain, abort
   111  	if it.index+1 >= len(it.chain) {
   112  		it.index = len(it.chain)
   113  		return nil, nil
   114  	}
   115  	// Advance the iterator and wait for verification result if not yet done
   116  	it.index++
   117  	if len(it.errors) <= it.index {
   118  		it.errors = append(it.errors, <-it.results)
   119  	}
   120  	if it.errors[it.index] != nil {
   121  		return it.chain[it.index], it.errors[it.index]
   122  	}
   123  	// Block header valid, run body validation and return
   124  	return it.chain[it.index], it.validator.ValidateBody(it.chain[it.index])
   125  }
   126  
   127  // peek returns the next block in the iterator, along with any potential validation
   128  // error for that block, but does **not** advance the iterator.
   129  //
   130  // Both header and body validation errors (nil too) is cached into the iterator
   131  // to avoid duplicating work on the following next() call.
   132  func (it *insertIterator) peek() (*types.Block, error) {
   133  	// If we reached the end of the chain, abort
   134  	if it.index+1 >= len(it.chain) {
   135  		return nil, nil
   136  	}
   137  	// Wait for verification result if not yet done
   138  	if len(it.errors) <= it.index+1 {
   139  		it.errors = append(it.errors, <-it.results)
   140  	}
   141  	if it.errors[it.index+1] != nil {
   142  		return it.chain[it.index+1], it.errors[it.index+1]
   143  	}
   144  	// Block header valid, ignore body validation since we don't have a parent anyway
   145  	return it.chain[it.index+1], nil
   146  }
   147  
   148  // previous returns the previous header that was being processed, or nil.
   149  func (it *insertIterator) previous() *types.Header {
   150  	if it.index < 1 {
   151  		return nil
   152  	}
   153  	return it.chain[it.index-1].Header()
   154  }
   155  
   156  // current returns the current header that is being processed, or nil.
   157  func (it *insertIterator) current() *types.Header {
   158  	if it.index == -1 || it.index >= len(it.chain) {
   159  		return nil
   160  	}
   161  	return it.chain[it.index].Header()
   162  }
   163  
   164  // first returns the first block in the it.
   165  func (it *insertIterator) first() *types.Block {
   166  	return it.chain[0]
   167  }
   168  
   169  // remaining returns the number of remaining blocks.
   170  func (it *insertIterator) remaining() int {
   171  	return len(it.chain) - it.index
   172  }
   173  
   174  // processed returns the number of processed blocks.
   175  func (it *insertIterator) processed() int {
   176  	return it.index + 1
   177  }