github.1git.de/covalenthq/bsp-geth@v1.8.27/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, 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  	c.checkpointSections = section + 1
   132  	c.checkpointHead = shead
   133  
   134  	if section < c.storedSections {
   135  		return
   136  	}
   137  	c.setSectionHead(section, shead)
   138  	c.setValidSections(section + 1)
   139  }
   140  
   141  // Start creates a goroutine to feed chain head events into the indexer for
   142  // cascading background processing. Children do not need to be started, they
   143  // are notified about new events by their parents.
   144  func (c *ChainIndexer) Start(chain ChainIndexerChain) {
   145  	events := make(chan ChainHeadEvent, 10)
   146  	sub := chain.SubscribeChainHeadEvent(events)
   147  
   148  	go c.eventLoop(chain.CurrentHeader(), events, sub)
   149  }
   150  
   151  // Close tears down all goroutines belonging to the indexer and returns any error
   152  // that might have occurred internally.
   153  func (c *ChainIndexer) Close() error {
   154  	var errs []error
   155  
   156  	c.ctxCancel()
   157  
   158  	// Tear down the primary update loop
   159  	errc := make(chan error)
   160  	c.quit <- errc
   161  	if err := <-errc; err != nil {
   162  		errs = append(errs, err)
   163  	}
   164  	// If needed, tear down the secondary event loop
   165  	if atomic.LoadUint32(&c.active) != 0 {
   166  		c.quit <- errc
   167  		if err := <-errc; err != nil {
   168  			errs = append(errs, err)
   169  		}
   170  	}
   171  	// Close all children
   172  	for _, child := range c.children {
   173  		if err := child.Close(); err != nil {
   174  			errs = append(errs, err)
   175  		}
   176  	}
   177  	// Return any failures
   178  	switch {
   179  	case len(errs) == 0:
   180  		return nil
   181  
   182  	case len(errs) == 1:
   183  		return errs[0]
   184  
   185  	default:
   186  		return fmt.Errorf("%v", errs)
   187  	}
   188  }
   189  
   190  // eventLoop is a secondary - optional - event loop of the indexer which is only
   191  // started for the outermost indexer to push chain head events into a processing
   192  // queue.
   193  func (c *ChainIndexer) eventLoop(currentHeader *types.Header, events chan ChainHeadEvent, sub event.Subscription) {
   194  	// Mark the chain indexer as active, requiring an additional teardown
   195  	atomic.StoreUint32(&c.active, 1)
   196  
   197  	defer sub.Unsubscribe()
   198  
   199  	// Fire the initial new head event to start any outstanding processing
   200  	c.newHead(currentHeader.Number.Uint64(), false)
   201  
   202  	var (
   203  		prevHeader = currentHeader
   204  		prevHash   = currentHeader.Hash()
   205  	)
   206  	for {
   207  		select {
   208  		case errc := <-c.quit:
   209  			// Chain indexer terminating, report no failure and abort
   210  			errc <- nil
   211  			return
   212  
   213  		case ev, ok := <-events:
   214  			// Received a new event, ensure it's not nil (closing) and update
   215  			if !ok {
   216  				errc := <-c.quit
   217  				errc <- nil
   218  				return
   219  			}
   220  			header := ev.Block.Header()
   221  			if header.ParentHash != prevHash {
   222  				// Reorg to the common ancestor if needed (might not exist in light sync mode, skip reorg then)
   223  				// TODO(karalabe, zsfelfoldi): This seems a bit brittle, can we detect this case explicitly?
   224  
   225  				if rawdb.ReadCanonicalHash(c.chainDb, prevHeader.Number.Uint64()) != prevHash {
   226  					if h := rawdb.FindCommonAncestor(c.chainDb, prevHeader, header); h != nil {
   227  						c.newHead(h.Number.Uint64(), true)
   228  					}
   229  				}
   230  			}
   231  			c.newHead(header.Number.Uint64(), false)
   232  
   233  			prevHeader, prevHash = header, header.Hash()
   234  		}
   235  	}
   236  }
   237  
   238  // newHead notifies the indexer about new chain heads and/or reorgs.
   239  func (c *ChainIndexer) newHead(head uint64, reorg bool) {
   240  	c.lock.Lock()
   241  	defer c.lock.Unlock()
   242  
   243  	// If a reorg happened, invalidate all sections until that point
   244  	if reorg {
   245  		// Revert the known section number to the reorg point
   246  		known := head / c.sectionSize
   247  		stored := known
   248  		if known < c.checkpointSections {
   249  			known = 0
   250  		}
   251  		if stored < c.checkpointSections {
   252  			stored = c.checkpointSections
   253  		}
   254  		if known < c.knownSections {
   255  			c.knownSections = known
   256  		}
   257  		// Revert the stored sections from the database to the reorg point
   258  		if stored < c.storedSections {
   259  			c.setValidSections(stored)
   260  		}
   261  		// Update the new head number to the finalized section end and notify children
   262  		head = known * c.sectionSize
   263  
   264  		if head < c.cascadedHead {
   265  			c.cascadedHead = head
   266  			for _, child := range c.children {
   267  				child.newHead(c.cascadedHead, true)
   268  			}
   269  		}
   270  		return
   271  	}
   272  	// No reorg, calculate the number of newly known sections and update if high enough
   273  	var sections uint64
   274  	if head >= c.confirmsReq {
   275  		sections = (head + 1 - c.confirmsReq) / c.sectionSize
   276  		if sections < c.checkpointSections {
   277  			sections = 0
   278  		}
   279  		if sections > c.knownSections {
   280  			if c.knownSections < c.checkpointSections {
   281  				// syncing reached the checkpoint, verify section head
   282  				syncedHead := rawdb.ReadCanonicalHash(c.chainDb, c.checkpointSections*c.sectionSize-1)
   283  				if syncedHead != c.checkpointHead {
   284  					c.log.Error("Synced chain does not match checkpoint", "number", c.checkpointSections*c.sectionSize-1, "expected", c.checkpointHead, "synced", syncedHead)
   285  					return
   286  				}
   287  			}
   288  			c.knownSections = sections
   289  
   290  			select {
   291  			case c.update <- struct{}{}:
   292  			default:
   293  			}
   294  		}
   295  	}
   296  }
   297  
   298  // updateLoop is the main event loop of the indexer which pushes chain segments
   299  // down into the processing backend.
   300  func (c *ChainIndexer) updateLoop() {
   301  	var (
   302  		updating bool
   303  		updated  time.Time
   304  	)
   305  
   306  	for {
   307  		select {
   308  		case errc := <-c.quit:
   309  			// Chain indexer terminating, report no failure and abort
   310  			errc <- nil
   311  			return
   312  
   313  		case <-c.update:
   314  			// Section headers completed (or rolled back), update the index
   315  			c.lock.Lock()
   316  			if c.knownSections > c.storedSections {
   317  				// Periodically print an upgrade log message to the user
   318  				if time.Since(updated) > 8*time.Second {
   319  					if c.knownSections > c.storedSections+1 {
   320  						updating = true
   321  						c.log.Info("Upgrading chain index", "percentage", c.storedSections*100/c.knownSections)
   322  					}
   323  					updated = time.Now()
   324  				}
   325  				// Cache the current section count and head to allow unlocking the mutex
   326  				section := c.storedSections
   327  				var oldHead common.Hash
   328  				if section > 0 {
   329  					oldHead = c.SectionHead(section - 1)
   330  				}
   331  				// Process the newly defined section in the background
   332  				c.lock.Unlock()
   333  				newHead, err := c.processSection(section, oldHead)
   334  				if err != nil {
   335  					select {
   336  					case <-c.ctx.Done():
   337  						<-c.quit <- nil
   338  						return
   339  					default:
   340  					}
   341  					c.log.Error("Section processing failed", "error", err)
   342  				}
   343  				c.lock.Lock()
   344  
   345  				// If processing succeeded and no reorgs occcurred, mark the section completed
   346  				if err == nil && oldHead == c.SectionHead(section-1) {
   347  					c.setSectionHead(section, newHead)
   348  					c.setValidSections(section + 1)
   349  					if c.storedSections == c.knownSections && updating {
   350  						updating = false
   351  						c.log.Info("Finished upgrading chain index")
   352  					}
   353  					c.cascadedHead = c.storedSections*c.sectionSize - 1
   354  					for _, child := range c.children {
   355  						c.log.Trace("Cascading chain index update", "head", c.cascadedHead)
   356  						child.newHead(c.cascadedHead, false)
   357  					}
   358  				} else {
   359  					// If processing failed, don't retry until further notification
   360  					c.log.Debug("Chain index processing failed", "section", section, "err", err)
   361  					c.knownSections = c.storedSections
   362  				}
   363  			}
   364  			// If there are still further sections to process, reschedule
   365  			if c.knownSections > c.storedSections {
   366  				time.AfterFunc(c.throttling, func() {
   367  					select {
   368  					case c.update <- struct{}{}:
   369  					default:
   370  					}
   371  				})
   372  			}
   373  			c.lock.Unlock()
   374  		}
   375  	}
   376  }
   377  
   378  // processSection processes an entire section by calling backend functions while
   379  // ensuring the continuity of the passed headers. Since the chain mutex is not
   380  // held while processing, the continuity can be broken by a long reorg, in which
   381  // case the function returns with an error.
   382  func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (common.Hash, error) {
   383  	c.log.Trace("Processing new chain section", "section", section)
   384  
   385  	// Reset and partial processing
   386  
   387  	if err := c.backend.Reset(c.ctx, section, lastHead); err != nil {
   388  		c.setValidSections(0)
   389  		return common.Hash{}, err
   390  	}
   391  
   392  	for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ {
   393  		hash := rawdb.ReadCanonicalHash(c.chainDb, number)
   394  		if hash == (common.Hash{}) {
   395  			return common.Hash{}, fmt.Errorf("canonical block #%d unknown", number)
   396  		}
   397  		header := rawdb.ReadHeader(c.chainDb, hash, number)
   398  		if header == nil {
   399  			return common.Hash{}, fmt.Errorf("block #%d [%x…] not found", number, hash[:4])
   400  		} else if header.ParentHash != lastHead {
   401  			return common.Hash{}, fmt.Errorf("chain reorged during section processing")
   402  		}
   403  		if err := c.backend.Process(c.ctx, header); err != nil {
   404  			return common.Hash{}, err
   405  		}
   406  		lastHead = header.Hash()
   407  	}
   408  	if err := c.backend.Commit(); err != nil {
   409  		return common.Hash{}, err
   410  	}
   411  	return lastHead, nil
   412  }
   413  
   414  // Sections returns the number of processed sections maintained by the indexer
   415  // and also the information about the last header indexed for potential canonical
   416  // verifications.
   417  func (c *ChainIndexer) Sections() (uint64, uint64, common.Hash) {
   418  	c.lock.Lock()
   419  	defer c.lock.Unlock()
   420  
   421  	return c.storedSections, c.storedSections*c.sectionSize - 1, c.SectionHead(c.storedSections - 1)
   422  }
   423  
   424  // AddChildIndexer adds a child ChainIndexer that can use the output of this one
   425  func (c *ChainIndexer) AddChildIndexer(indexer *ChainIndexer) {
   426  	c.lock.Lock()
   427  	defer c.lock.Unlock()
   428  
   429  	c.children = append(c.children, indexer)
   430  
   431  	// Cascade any pending updates to new children too
   432  	sections := c.storedSections
   433  	if c.knownSections < sections {
   434  		// if a section is "stored" but not "known" then it is a checkpoint without
   435  		// available chain data so we should not cascade it yet
   436  		sections = c.knownSections
   437  	}
   438  	if sections > 0 {
   439  		indexer.newHead(sections*c.sectionSize-1, false)
   440  	}
   441  }
   442  
   443  // loadValidSections reads the number of valid sections from the index database
   444  // and caches is into the local state.
   445  func (c *ChainIndexer) loadValidSections() {
   446  	data, _ := c.indexDb.Get([]byte("count"))
   447  	if len(data) == 8 {
   448  		c.storedSections = binary.BigEndian.Uint64(data)
   449  	}
   450  }
   451  
   452  // setValidSections writes the number of valid sections to the index database
   453  func (c *ChainIndexer) setValidSections(sections uint64) {
   454  	// Set the current number of valid sections in the database
   455  	var data [8]byte
   456  	binary.BigEndian.PutUint64(data[:], sections)
   457  	c.indexDb.Put([]byte("count"), data[:])
   458  
   459  	// Remove any reorged sections, caching the valids in the mean time
   460  	for c.storedSections > sections {
   461  		c.storedSections--
   462  		c.removeSectionHead(c.storedSections)
   463  	}
   464  	c.storedSections = sections // needed if new > old
   465  }
   466  
   467  // SectionHead retrieves the last block hash of a processed section from the
   468  // index database.
   469  func (c *ChainIndexer) SectionHead(section uint64) common.Hash {
   470  	var data [8]byte
   471  	binary.BigEndian.PutUint64(data[:], section)
   472  
   473  	hash, _ := c.indexDb.Get(append([]byte("shead"), data[:]...))
   474  	if len(hash) == len(common.Hash{}) {
   475  		return common.BytesToHash(hash)
   476  	}
   477  	return common.Hash{}
   478  }
   479  
   480  // setSectionHead writes the last block hash of a processed section to the index
   481  // database.
   482  func (c *ChainIndexer) setSectionHead(section uint64, hash common.Hash) {
   483  	var data [8]byte
   484  	binary.BigEndian.PutUint64(data[:], section)
   485  
   486  	c.indexDb.Put(append([]byte("shead"), data[:]...), hash.Bytes())
   487  }
   488  
   489  // removeSectionHead removes the reference to a processed section from the index
   490  // database.
   491  func (c *ChainIndexer) removeSectionHead(section uint64) {
   492  	var data [8]byte
   493  	binary.BigEndian.PutUint64(data[:], section)
   494  
   495  	c.indexDb.Delete(append([]byte("shead"), data[:]...))
   496  }