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