github.com/MetalBlockchain/subnet-evm@v0.4.9/core/chain_indexer.go (about)

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