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