github.com/aquanetwork/aquachain@v1.7.8/aqua/bloombits.go (about)

     1  // Copyright 2017 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package aqua
    18  
    19  import (
    20  	"time"
    21  
    22  	"gitlab.com/aquachain/aquachain/aquadb"
    23  	"gitlab.com/aquachain/aquachain/common"
    24  	"gitlab.com/aquachain/aquachain/common/bitutil"
    25  	"gitlab.com/aquachain/aquachain/core"
    26  	"gitlab.com/aquachain/aquachain/core/bloombits"
    27  	"gitlab.com/aquachain/aquachain/core/types"
    28  	"gitlab.com/aquachain/aquachain/params"
    29  )
    30  
    31  const (
    32  	// bloomServiceThreads is the number of goroutines used globally by an AquaChain
    33  	// instance to service bloombits lookups for all running filters.
    34  	bloomServiceThreads = 16
    35  
    36  	// bloomFilterThreads is the number of goroutines used locally per filter to
    37  	// multiplex requests onto the global servicing goroutines.
    38  	bloomFilterThreads = 3
    39  
    40  	// bloomRetrievalBatch is the maximum number of bloom bit retrievals to service
    41  	// in a single batch.
    42  	bloomRetrievalBatch = 16
    43  
    44  	// bloomRetrievalWait is the maximum time to wait for enough bloom bit requests
    45  	// to accumulate request an entire batch (avoiding hysteresis).
    46  	bloomRetrievalWait = time.Duration(0)
    47  )
    48  
    49  // startBloomHandlers starts a batch of goroutines to accept bloom bit database
    50  // retrievals from possibly a range of filters and serving the data to satisfy.
    51  func (aqua *AquaChain) startBloomHandlers() {
    52  	for i := 0; i < bloomServiceThreads; i++ {
    53  		go func() {
    54  			for {
    55  				select {
    56  				case <-aqua.shutdownChan:
    57  					return
    58  
    59  				case request := <-aqua.bloomRequests:
    60  					task := <-request
    61  					task.Bitsets = make([][]byte, len(task.Sections))
    62  					for i, section := range task.Sections {
    63  						head := core.GetCanonicalHash(aqua.chainDb, (section+1)*params.BloomBitsBlocks-1)
    64  						if compVector, err := core.GetBloomBits(aqua.chainDb, task.Bit, section, head); err == nil {
    65  							if blob, err := bitutil.DecompressBytes(compVector, int(params.BloomBitsBlocks)/8); err == nil {
    66  								task.Bitsets[i] = blob
    67  							} else {
    68  								task.Error = err
    69  							}
    70  						} else {
    71  							task.Error = err
    72  						}
    73  					}
    74  					request <- task
    75  				}
    76  			}
    77  		}()
    78  	}
    79  }
    80  
    81  const (
    82  	// bloomConfirms is the number of confirmation blocks before a bloom section is
    83  	// considered probably final and its rotated bits are calculated.
    84  	bloomConfirms = 256
    85  
    86  	// bloomThrottling is the time to wait between processing two consecutive index
    87  	// sections. It's useful during chain upgrades to prevent disk overload.
    88  	bloomThrottling = 100 * time.Millisecond
    89  )
    90  
    91  // BloomIndexer implements a core.ChainIndexer, building up a rotated bloom bits index
    92  // for the AquaChain header bloom filters, permitting blazing fast filtering.
    93  type BloomIndexer struct {
    94  	size uint64 // section size to generate bloombits for
    95  
    96  	db      aquadb.Database      // database instance to write index data and metadata into
    97  	gen     *bloombits.Generator // generator to rotate the bloom bits crating the bloom index
    98  	section uint64               // Section is the section number being processed currently
    99  	head    common.Hash          // Head is the hash of the last header processed
   100  }
   101  
   102  // NewBloomIndexer returns a chain indexer that generates bloom bits data for the
   103  // canonical chain for fast logs filtering.
   104  func NewBloomIndexer(cfg *params.ChainConfig, db aquadb.Database, size uint64) *core.ChainIndexer {
   105  	backend := &BloomIndexer{
   106  		db:   db,
   107  		size: size,
   108  	}
   109  	table := aquadb.NewTable(db, string(core.BloomBitsIndexPrefix))
   110  
   111  	return core.NewChainIndexer(cfg, db, table, backend, size, bloomConfirms, bloomThrottling, "bloombits")
   112  }
   113  
   114  // Reset implements core.ChainIndexerBackend, starting a new bloombits index
   115  // section.
   116  func (b *BloomIndexer) Reset(section uint64, lastSectionHead common.Hash) error {
   117  	gen, err := bloombits.NewGenerator(uint(b.size))
   118  	b.gen, b.section, b.head = gen, section, common.Hash{}
   119  	return err
   120  }
   121  
   122  // Process implements core.ChainIndexerBackend, adding a new header's bloom into
   123  // the index.
   124  func (b *BloomIndexer) Process(header *types.Header) {
   125  	b.gen.AddBloom(uint(header.Number.Uint64()-b.section*b.size), header.Bloom)
   126  	b.head = header.Hash()
   127  }
   128  
   129  // Commit implements core.ChainIndexerBackend, finalizing the bloom section and
   130  // writing it out into the database.
   131  func (b *BloomIndexer) Commit() error {
   132  	batch := b.db.NewBatch()
   133  
   134  	for i := 0; i < types.BloomBitLength; i++ {
   135  		bits, err := b.gen.Bitset(uint(i))
   136  		if err != nil {
   137  			return err
   138  		}
   139  		core.WriteBloomBits(batch, uint(i), b.section, b.head, bitutil.CompressBytes(bits))
   140  	}
   141  	return batch.Write()
   142  }