github.com/ethereum/go-ethereum@v1.14.3/core/chain_indexer.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  	"encoding/binary"
    22  	"errors"
    23  	"fmt"
    24  	"sync"
    25  	"sync/atomic"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/core/rawdb"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/ethdb"
    32  	"github.com/ethereum/go-ethereum/event"
    33  	"github.com/ethereum/go-ethereum/log"
    34  )
    35  
    36  // ChainIndexerBackend defines the methods needed to process chain segments in
    37  // the background and write the segment results into the database. These can be
    38  // used to create filter blooms or CHTs.
    39  type ChainIndexerBackend interface {
    40  	// Reset initiates the processing of a new chain segment, potentially terminating
    41  	// any partially completed operations (in case of a reorg).
    42  	Reset(ctx context.Context, section uint64, prevHead common.Hash) error
    43  
    44  	// Process crunches through the next header in the chain segment. The caller
    45  	// will ensure a sequential order of headers.
    46  	Process(ctx context.Context, header *types.Header) error
    47  
    48  	// Commit finalizes the section metadata and stores it into the database.
    49  	Commit() error
    50  
    51  	// Prune deletes the chain index older than the given threshold.
    52  	Prune(threshold uint64) error
    53  }
    54  
    55  // ChainIndexerChain interface is used for connecting the indexer to a blockchain
    56  type ChainIndexerChain interface {
    57  	// CurrentHeader retrieves the latest locally known header.
    58  	CurrentHeader() *types.Header
    59  
    60  	// SubscribeChainHeadEvent subscribes to new head header notifications.
    61  	SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
    62  }
    63  
    64  // ChainIndexer does a post-processing job for equally sized sections of the
    65  // canonical chain (like BlooomBits and CHT structures). A ChainIndexer is
    66  // connected to the blockchain through the event system by starting a
    67  // ChainHeadEventLoop in a goroutine.
    68  //
    69  // Further child ChainIndexers can be added which use the output of the parent
    70  // section indexer. These child indexers receive new head notifications only
    71  // after an entire section has been finished or in case of rollbacks that might
    72  // affect already finished sections.
    73  type ChainIndexer struct {
    74  	chainDb  ethdb.Database      // Chain database to index the data from
    75  	indexDb  ethdb.Database      // Prefixed table-view of the db to write index metadata into
    76  	backend  ChainIndexerBackend // Background processor generating the index data content
    77  	children []*ChainIndexer     // Child indexers to cascade chain updates to
    78  
    79  	active    atomic.Bool     // Flag whether the event loop was started
    80  	update    chan struct{}   // Notification channel that headers should be processed
    81  	quit      chan chan error // Quit channel to tear down running goroutines
    82  	ctx       context.Context
    83  	ctxCancel func()
    84  
    85  	sectionSize uint64 // Number of blocks in a single chain segment to process
    86  	confirmsReq uint64 // Number of confirmations before processing a completed segment
    87  
    88  	storedSections uint64 // Number of sections successfully indexed into the database
    89  	knownSections  uint64 // Number of sections known to be complete (block wise)
    90  	cascadedHead   uint64 // Block number of the last completed section cascaded to subindexers
    91  
    92  	checkpointSections uint64      // Number of sections covered by the checkpoint
    93  	checkpointHead     common.Hash // Section head belonging to the checkpoint
    94  
    95  	throttling time.Duration // Disk throttling to prevent a heavy upgrade from hogging resources
    96  
    97  	log  log.Logger
    98  	lock sync.Mutex
    99  }
   100  
   101  // NewChainIndexer creates a new chain indexer to do background processing on
   102  // chain segments of a given size after certain number of confirmations passed.
   103  // The throttling parameter might be used to prevent database thrashing.
   104  func NewChainIndexer(chainDb ethdb.Database, indexDb ethdb.Database, backend ChainIndexerBackend, section, confirm uint64, throttling time.Duration, kind string) *ChainIndexer {
   105  	c := &ChainIndexer{
   106  		chainDb:     chainDb,
   107  		indexDb:     indexDb,
   108  		backend:     backend,
   109  		update:      make(chan struct{}, 1),
   110  		quit:        make(chan chan error),
   111  		sectionSize: section,
   112  		confirmsReq: confirm,
   113  		throttling:  throttling,
   114  		log:         log.New("type", kind),
   115  	}
   116  	// Initialize database dependent fields and start the updater
   117  	c.loadValidSections()
   118  	c.ctx, c.ctxCancel = context.WithCancel(context.Background())
   119  
   120  	go c.updateLoop()
   121  
   122  	return c
   123  }
   124  
   125  // AddCheckpoint adds a checkpoint. Sections are never processed and the chain
   126  // is not expected to be available before this point. The indexer assumes that
   127  // the backend has sufficient information available to process subsequent sections.
   128  //
   129  // Note: knownSections == 0 and storedSections == checkpointSections until
   130  // syncing reaches the checkpoint
   131  func (c *ChainIndexer) AddCheckpoint(section uint64, shead common.Hash) {
   132  	c.lock.Lock()
   133  	defer c.lock.Unlock()
   134  
   135  	// Short circuit if the given checkpoint is below than local's.
   136  	if c.checkpointSections >= section+1 || section < c.storedSections {
   137  		return
   138  	}
   139  	c.checkpointSections = section + 1
   140  	c.checkpointHead = shead
   141  
   142  	c.setSectionHead(section, shead)
   143  	c.setValidSections(section + 1)
   144  }
   145  
   146  // Start creates a goroutine to feed chain head events into the indexer for
   147  // cascading background processing. Children do not need to be started, they
   148  // are notified about new events by their parents.
   149  func (c *ChainIndexer) Start(chain ChainIndexerChain) {
   150  	events := make(chan ChainHeadEvent, 10)
   151  	sub := chain.SubscribeChainHeadEvent(events)
   152  
   153  	go c.eventLoop(chain.CurrentHeader(), events, sub)
   154  }
   155  
   156  // Close tears down all goroutines belonging to the indexer and returns any error
   157  // that might have occurred internally.
   158  func (c *ChainIndexer) Close() error {
   159  	var errs []error
   160  
   161  	c.ctxCancel()
   162  
   163  	// Tear down the primary update loop
   164  	errc := make(chan error)
   165  	c.quit <- errc
   166  	if err := <-errc; err != nil {
   167  		errs = append(errs, err)
   168  	}
   169  	// If needed, tear down the secondary event loop
   170  	if c.active.Load() {
   171  		c.quit <- errc
   172  		if err := <-errc; err != nil {
   173  			errs = append(errs, err)
   174  		}
   175  	}
   176  	// Close all children
   177  	for _, child := range c.children {
   178  		if err := child.Close(); err != nil {
   179  			errs = append(errs, err)
   180  		}
   181  	}
   182  	// Return any failures
   183  	switch {
   184  	case len(errs) == 0:
   185  		return nil
   186  
   187  	case len(errs) == 1:
   188  		return errs[0]
   189  
   190  	default:
   191  		return fmt.Errorf("%v", errs)
   192  	}
   193  }
   194  
   195  // eventLoop is a secondary - optional - event loop of the indexer which is only
   196  // started for the outermost indexer to push chain head events into a processing
   197  // queue.
   198  func (c *ChainIndexer) eventLoop(currentHeader *types.Header, events chan ChainHeadEvent, sub event.Subscription) {
   199  	// Mark the chain indexer as active, requiring an additional teardown
   200  	c.active.Store(true)
   201  
   202  	defer sub.Unsubscribe()
   203  
   204  	// Fire the initial new head event to start any outstanding processing
   205  	c.newHead(currentHeader.Number.Uint64(), false)
   206  
   207  	var (
   208  		prevHeader = currentHeader
   209  		prevHash   = currentHeader.Hash()
   210  	)
   211  	for {
   212  		select {
   213  		case errc := <-c.quit:
   214  			// Chain indexer terminating, report no failure and abort
   215  			errc <- nil
   216  			return
   217  
   218  		case ev, ok := <-events:
   219  			// Received a new event, ensure it's not nil (closing) and update
   220  			if !ok {
   221  				errc := <-c.quit
   222  				errc <- nil
   223  				return
   224  			}
   225  			header := ev.Block.Header()
   226  			if header.ParentHash != prevHash {
   227  				// Reorg to the common ancestor if needed (might not exist in light sync mode, skip reorg then)
   228  				// TODO(karalabe, zsfelfoldi): This seems a bit brittle, can we detect this case explicitly?
   229  
   230  				if rawdb.ReadCanonicalHash(c.chainDb, prevHeader.Number.Uint64()) != prevHash {
   231  					if h := rawdb.FindCommonAncestor(c.chainDb, prevHeader, header); h != nil {
   232  						c.newHead(h.Number.Uint64(), true)
   233  					}
   234  				}
   235  			}
   236  			c.newHead(header.Number.Uint64(), false)
   237  
   238  			prevHeader, prevHash = header, header.Hash()
   239  		}
   240  	}
   241  }
   242  
   243  // newHead notifies the indexer about new chain heads and/or reorgs.
   244  func (c *ChainIndexer) newHead(head uint64, reorg bool) {
   245  	c.lock.Lock()
   246  	defer c.lock.Unlock()
   247  
   248  	// If a reorg happened, invalidate all sections until that point
   249  	if reorg {
   250  		// Revert the known section number to the reorg point
   251  		known := (head + 1) / c.sectionSize
   252  		stored := known
   253  		if known < c.checkpointSections {
   254  			known = 0
   255  		}
   256  		if stored < c.checkpointSections {
   257  			stored = c.checkpointSections
   258  		}
   259  		if known < c.knownSections {
   260  			c.knownSections = known
   261  		}
   262  		// Revert the stored sections from the database to the reorg point
   263  		if stored < c.storedSections {
   264  			c.setValidSections(stored)
   265  		}
   266  		// Update the new head number to the finalized section end and notify children
   267  		head = known * c.sectionSize
   268  
   269  		if head < c.cascadedHead {
   270  			c.cascadedHead = head
   271  			for _, child := range c.children {
   272  				child.newHead(c.cascadedHead, true)
   273  			}
   274  		}
   275  		return
   276  	}
   277  	// No reorg, calculate the number of newly known sections and update if high enough
   278  	var sections uint64
   279  	if head >= c.confirmsReq {
   280  		sections = (head + 1 - c.confirmsReq) / c.sectionSize
   281  		if sections < c.checkpointSections {
   282  			sections = 0
   283  		}
   284  		if sections > c.knownSections {
   285  			if c.knownSections < c.checkpointSections {
   286  				// syncing reached the checkpoint, verify section head
   287  				syncedHead := rawdb.ReadCanonicalHash(c.chainDb, c.checkpointSections*c.sectionSize-1)
   288  				if syncedHead != c.checkpointHead {
   289  					c.log.Error("Synced chain does not match checkpoint", "number", c.checkpointSections*c.sectionSize-1, "expected", c.checkpointHead, "synced", syncedHead)
   290  					return
   291  				}
   292  			}
   293  			c.knownSections = sections
   294  
   295  			select {
   296  			case c.update <- struct{}{}:
   297  			default:
   298  			}
   299  		}
   300  	}
   301  }
   302  
   303  // updateLoop is the main event loop of the indexer which pushes chain segments
   304  // down into the processing backend.
   305  func (c *ChainIndexer) updateLoop() {
   306  	var (
   307  		updating bool
   308  		updated  time.Time
   309  	)
   310  
   311  	for {
   312  		select {
   313  		case errc := <-c.quit:
   314  			// Chain indexer terminating, report no failure and abort
   315  			errc <- nil
   316  			return
   317  
   318  		case <-c.update:
   319  			// Section headers completed (or rolled back), update the index
   320  			c.lock.Lock()
   321  			if c.knownSections > c.storedSections {
   322  				// Periodically print an upgrade log message to the user
   323  				if time.Since(updated) > 8*time.Second {
   324  					if c.knownSections > c.storedSections+1 {
   325  						updating = true
   326  						c.log.Info("Upgrading chain index", "percentage", c.storedSections*100/c.knownSections)
   327  					}
   328  					updated = time.Now()
   329  				}
   330  				// Cache the current section count and head to allow unlocking the mutex
   331  				c.verifyLastHead()
   332  				section := c.storedSections
   333  				var oldHead common.Hash
   334  				if section > 0 {
   335  					oldHead = c.SectionHead(section - 1)
   336  				}
   337  				// Process the newly defined section in the background
   338  				c.lock.Unlock()
   339  				newHead, err := c.processSection(section, oldHead)
   340  				if err != nil {
   341  					select {
   342  					case <-c.ctx.Done():
   343  						<-c.quit <- nil
   344  						return
   345  					default:
   346  					}
   347  					c.log.Error("Section processing failed", "error", err)
   348  				}
   349  				c.lock.Lock()
   350  
   351  				// If processing succeeded and no reorgs occurred, mark the section completed
   352  				if err == nil && (section == 0 || oldHead == c.SectionHead(section-1)) {
   353  					c.setSectionHead(section, newHead)
   354  					c.setValidSections(section + 1)
   355  					if c.storedSections == c.knownSections && updating {
   356  						updating = false
   357  						c.log.Info("Finished upgrading chain index")
   358  					}
   359  					c.cascadedHead = c.storedSections*c.sectionSize - 1
   360  					for _, child := range c.children {
   361  						c.log.Trace("Cascading chain index update", "head", c.cascadedHead)
   362  						child.newHead(c.cascadedHead, false)
   363  					}
   364  				} else {
   365  					// If processing failed, don't retry until further notification
   366  					c.log.Debug("Chain index processing failed", "section", section, "err", err)
   367  					c.verifyLastHead()
   368  					c.knownSections = c.storedSections
   369  				}
   370  			}
   371  			// If there are still further sections to process, reschedule
   372  			if c.knownSections > c.storedSections {
   373  				time.AfterFunc(c.throttling, func() {
   374  					select {
   375  					case c.update <- struct{}{}:
   376  					default:
   377  					}
   378  				})
   379  			}
   380  			c.lock.Unlock()
   381  		}
   382  	}
   383  }
   384  
   385  // processSection processes an entire section by calling backend functions while
   386  // ensuring the continuity of the passed headers. Since the chain mutex is not
   387  // held while processing, the continuity can be broken by a long reorg, in which
   388  // case the function returns with an error.
   389  func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (common.Hash, error) {
   390  	c.log.Trace("Processing new chain section", "section", section)
   391  
   392  	// Reset and partial processing
   393  	if err := c.backend.Reset(c.ctx, section, lastHead); err != nil {
   394  		c.setValidSections(0)
   395  		return common.Hash{}, err
   396  	}
   397  
   398  	for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ {
   399  		hash := rawdb.ReadCanonicalHash(c.chainDb, number)
   400  		if hash == (common.Hash{}) {
   401  			return common.Hash{}, fmt.Errorf("canonical block #%d unknown", number)
   402  		}
   403  		header := rawdb.ReadHeader(c.chainDb, hash, number)
   404  		if header == nil {
   405  			return common.Hash{}, fmt.Errorf("block #%d [%x..] not found", number, hash[:4])
   406  		} else if header.ParentHash != lastHead {
   407  			return common.Hash{}, errors.New("chain reorged during section processing")
   408  		}
   409  		if err := c.backend.Process(c.ctx, header); err != nil {
   410  			return common.Hash{}, err
   411  		}
   412  		lastHead = header.Hash()
   413  	}
   414  	if err := c.backend.Commit(); err != nil {
   415  		return common.Hash{}, err
   416  	}
   417  	return lastHead, nil
   418  }
   419  
   420  // verifyLastHead compares last stored section head with the corresponding block hash in the
   421  // actual canonical chain and rolls back reorged sections if necessary to ensure that stored
   422  // sections are all valid
   423  func (c *ChainIndexer) verifyLastHead() {
   424  	for c.storedSections > 0 && c.storedSections > c.checkpointSections {
   425  		if c.SectionHead(c.storedSections-1) == rawdb.ReadCanonicalHash(c.chainDb, c.storedSections*c.sectionSize-1) {
   426  			return
   427  		}
   428  		c.setValidSections(c.storedSections - 1)
   429  	}
   430  }
   431  
   432  // Sections returns the number of processed sections maintained by the indexer
   433  // and also the information about the last header indexed for potential canonical
   434  // verifications.
   435  func (c *ChainIndexer) Sections() (uint64, uint64, common.Hash) {
   436  	c.lock.Lock()
   437  	defer c.lock.Unlock()
   438  
   439  	c.verifyLastHead()
   440  	return c.storedSections, c.storedSections*c.sectionSize - 1, c.SectionHead(c.storedSections - 1)
   441  }
   442  
   443  // AddChildIndexer adds a child ChainIndexer that can use the output of this one
   444  func (c *ChainIndexer) AddChildIndexer(indexer *ChainIndexer) {
   445  	if indexer == c {
   446  		panic("can't add indexer as a child of itself")
   447  	}
   448  	c.lock.Lock()
   449  	defer c.lock.Unlock()
   450  
   451  	c.children = append(c.children, indexer)
   452  
   453  	// Cascade any pending updates to new children too
   454  	sections := c.storedSections
   455  	if c.knownSections < sections {
   456  		// if a section is "stored" but not "known" then it is a checkpoint without
   457  		// available chain data so we should not cascade it yet
   458  		sections = c.knownSections
   459  	}
   460  	if sections > 0 {
   461  		indexer.newHead(sections*c.sectionSize-1, false)
   462  	}
   463  }
   464  
   465  // Prune deletes all chain data older than given threshold.
   466  func (c *ChainIndexer) Prune(threshold uint64) error {
   467  	return c.backend.Prune(threshold)
   468  }
   469  
   470  // loadValidSections reads the number of valid sections from the index database
   471  // and caches is into the local state.
   472  func (c *ChainIndexer) loadValidSections() {
   473  	data, _ := c.indexDb.Get([]byte("count"))
   474  	if len(data) == 8 {
   475  		c.storedSections = binary.BigEndian.Uint64(data)
   476  	}
   477  }
   478  
   479  // setValidSections writes the number of valid sections to the index database
   480  func (c *ChainIndexer) setValidSections(sections uint64) {
   481  	// Set the current number of valid sections in the database
   482  	var data [8]byte
   483  	binary.BigEndian.PutUint64(data[:], sections)
   484  	c.indexDb.Put([]byte("count"), data[:])
   485  
   486  	// Remove any reorged sections, caching the valids in the mean time
   487  	for c.storedSections > sections {
   488  		c.storedSections--
   489  		c.removeSectionHead(c.storedSections)
   490  	}
   491  	c.storedSections = sections // needed if new > old
   492  }
   493  
   494  // SectionHead retrieves the last block hash of a processed section from the
   495  // index database.
   496  func (c *ChainIndexer) SectionHead(section uint64) common.Hash {
   497  	var data [8]byte
   498  	binary.BigEndian.PutUint64(data[:], section)
   499  
   500  	hash, _ := c.indexDb.Get(append([]byte("shead"), data[:]...))
   501  	if len(hash) == len(common.Hash{}) {
   502  		return common.BytesToHash(hash)
   503  	}
   504  	return common.Hash{}
   505  }
   506  
   507  // setSectionHead writes the last block hash of a processed section to the index
   508  // database.
   509  func (c *ChainIndexer) setSectionHead(section uint64, hash common.Hash) {
   510  	var data [8]byte
   511  	binary.BigEndian.PutUint64(data[:], section)
   512  
   513  	c.indexDb.Put(append([]byte("shead"), data[:]...), hash.Bytes())
   514  }
   515  
   516  // removeSectionHead removes the reference to a processed section from the index
   517  // database.
   518  func (c *ChainIndexer) removeSectionHead(section uint64) {
   519  	var data [8]byte
   520  	binary.BigEndian.PutUint64(data[:], section)
   521  
   522  	c.indexDb.Delete(append([]byte("shead"), data[:]...))
   523  }