github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/light/postprocess.go (about)

     1  // Copyright 2016 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package light
    18  
    19  import (
    20  	"encoding/binary"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"time"
    25  
    26  	"github.com/SmartMeshFoundation/Spectrum/common"
    27  	"github.com/SmartMeshFoundation/Spectrum/common/bitutil"
    28  	"github.com/SmartMeshFoundation/Spectrum/core"
    29  	"github.com/SmartMeshFoundation/Spectrum/core/types"
    30  	"github.com/SmartMeshFoundation/Spectrum/ethdb"
    31  	"github.com/SmartMeshFoundation/Spectrum/log"
    32  	"github.com/SmartMeshFoundation/Spectrum/params"
    33  	"github.com/SmartMeshFoundation/Spectrum/rlp"
    34  	"github.com/SmartMeshFoundation/Spectrum/trie"
    35  )
    36  
    37  const (
    38  	ChtFrequency                   = 32768
    39  	ChtV1Frequency                 = 4096 // as long as we want to retain LES/1 compatibility, servers generate CHTs with the old, higher frequency
    40  	HelperTrieConfirmations        = 2048 // number of confirmations before a server is expected to have the given HelperTrie available
    41  	HelperTrieProcessConfirmations = 256  // number of confirmations before a HelperTrie is generated
    42  )
    43  
    44  // trustedCheckpoint represents a set of post-processed trie roots (CHT and BloomTrie) associated with
    45  // the appropriate section index and head hash. It is used to start light syncing from this checkpoint
    46  // and avoid downloading the entire header chain while still being able to securely access old headers/logs.
    47  type trustedCheckpoint struct {
    48  	name                                string
    49  	sectionIdx                          uint64
    50  	sectionHead, chtRoot, bloomTrieRoot common.Hash
    51  }
    52  
    53  var (
    54  	mainnetCheckpoint = trustedCheckpoint{
    55  		name:          "ETH mainnet",
    56  		sectionIdx:    129,
    57  		sectionHead:   common.HexToHash("64100587c8ec9a76870056d07cb0f58622552d16de6253a59cac4b580c899501"),
    58  		chtRoot:       common.HexToHash("bb4fb4076cbe6923c8a8ce8f158452bbe19564959313466989fda095a60884ca"),
    59  		bloomTrieRoot: common.HexToHash("0db524b2c4a2a9520a42fd842b02d2e8fb58ff37c75cf57bd0eb82daeace6716"),
    60  	}
    61  
    62  	ropstenCheckpoint = trustedCheckpoint{
    63  		name:          "Ropsten testnet",
    64  		sectionIdx:    50,
    65  		sectionHead:   common.HexToHash("00bd65923a1aa67f85e6b4ae67835784dd54be165c37f056691723c55bf016bd"),
    66  		chtRoot:       common.HexToHash("6f56dc61936752cc1f8c84b4addabdbe6a1c19693de3f21cb818362df2117f03"),
    67  		bloomTrieRoot: common.HexToHash("aca7d7c504d22737242effc3fdc604a762a0af9ced898036b5986c3a15220208"),
    68  	}
    69  )
    70  
    71  // trustedCheckpoints associates each known checkpoint with the genesis hash of the chain it belongs to
    72  var trustedCheckpoints = map[common.Hash]trustedCheckpoint{
    73  	params.MainnetGenesisHash: mainnetCheckpoint,
    74  	params.TestnetGenesisHash: ropstenCheckpoint,
    75  }
    76  
    77  var (
    78  	ErrNoTrustedCht       = errors.New("No trusted canonical hash trie")
    79  	ErrNoTrustedBloomTrie = errors.New("No trusted bloom trie")
    80  	ErrNoHeader           = errors.New("Header not found")
    81  	chtPrefix             = []byte("chtRoot-") // chtPrefix + chtNum (uint64 big endian) -> trie root hash
    82  	ChtTablePrefix        = "cht-"
    83  )
    84  
    85  // ChtNode structures are stored in the Canonical Hash Trie in an RLP encoded format
    86  type ChtNode struct {
    87  	Hash common.Hash
    88  	Td   *big.Int
    89  }
    90  
    91  // GetChtRoot reads the CHT root assoctiated to the given section from the database
    92  // Note that sectionIdx is specified according to LES/1 CHT section size
    93  func GetChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
    94  	var encNumber [8]byte
    95  	binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
    96  	data, _ := db.Get(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...))
    97  	return common.BytesToHash(data)
    98  }
    99  
   100  // GetChtV2Root reads the CHT root assoctiated to the given section from the database
   101  // Note that sectionIdx is specified according to LES/2 CHT section size
   102  func GetChtV2Root(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
   103  	return GetChtRoot(db, (sectionIdx+1)*(ChtFrequency/ChtV1Frequency)-1, sectionHead)
   104  }
   105  
   106  // StoreChtRoot writes the CHT root assoctiated to the given section into the database
   107  // Note that sectionIdx is specified according to LES/1 CHT section size
   108  func StoreChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
   109  	var encNumber [8]byte
   110  	binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
   111  	db.Put(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
   112  }
   113  
   114  // ChtIndexerBackend implements core.ChainIndexerBackend
   115  type ChtIndexerBackend struct {
   116  	db, cdb              ethdb.Database
   117  	section, sectionSize uint64
   118  	lastHash             common.Hash
   119  	trie                 *trie.Trie
   120  }
   121  
   122  // NewBloomTrieIndexer creates a BloomTrie chain indexer
   123  func NewChtIndexer(db ethdb.Database, clientMode bool) *core.ChainIndexer {
   124  	cdb := ethdb.NewTable(db, ChtTablePrefix)
   125  	idb := ethdb.NewTable(db, "chtIndex-")
   126  	var sectionSize, confirmReq uint64
   127  	if clientMode {
   128  		sectionSize = ChtFrequency
   129  		confirmReq = HelperTrieConfirmations
   130  	} else {
   131  		sectionSize = ChtV1Frequency
   132  		confirmReq = HelperTrieProcessConfirmations
   133  	}
   134  	return core.NewChainIndexer(db, idb, &ChtIndexerBackend{db: db, cdb: cdb, sectionSize: sectionSize}, sectionSize, confirmReq, time.Millisecond*100, "cht")
   135  }
   136  
   137  // Reset implements core.ChainIndexerBackend
   138  func (c *ChtIndexerBackend) Reset(section uint64, lastSectionHead common.Hash) error {
   139  	var root common.Hash
   140  	if section > 0 {
   141  		root = GetChtRoot(c.db, section-1, lastSectionHead)
   142  	}
   143  	var err error
   144  	c.trie, err = trie.New(root, c.cdb)
   145  	c.section = section
   146  	return err
   147  }
   148  
   149  // Process implements core.ChainIndexerBackend
   150  func (c *ChtIndexerBackend) Process(header *types.Header) {
   151  	hash, num := header.Hash(), header.Number.Uint64()
   152  	c.lastHash = hash
   153  
   154  	td := core.GetTd(c.db, hash, num)
   155  	if td == nil {
   156  		panic(nil)
   157  	}
   158  	var encNumber [8]byte
   159  	binary.BigEndian.PutUint64(encNumber[:], num)
   160  	data, _ := rlp.EncodeToBytes(ChtNode{hash, td})
   161  	c.trie.Update(encNumber[:], data)
   162  }
   163  
   164  // Commit implements core.ChainIndexerBackend
   165  func (c *ChtIndexerBackend) Commit() error {
   166  	batch := c.cdb.NewBatch()
   167  	root, err := c.trie.CommitTo(batch)
   168  	if err != nil {
   169  		return err
   170  	} else {
   171  		batch.Write()
   172  		if ((c.section+1)*c.sectionSize)%ChtFrequency == 0 {
   173  			log.Info("Storing CHT", "idx", c.section*c.sectionSize/ChtFrequency, "sectionHead", fmt.Sprintf("%064x", c.lastHash), "root", fmt.Sprintf("%064x", root))
   174  		}
   175  		StoreChtRoot(c.db, c.section, c.lastHash, root)
   176  	}
   177  	return nil
   178  }
   179  
   180  const (
   181  	BloomTrieFrequency        = 32768
   182  	ethBloomBitsSection       = 4096
   183  	ethBloomBitsConfirmations = 256
   184  )
   185  
   186  var (
   187  	bloomTriePrefix      = []byte("bltRoot-") // bloomTriePrefix + bloomTrieNum (uint64 big endian) -> trie root hash
   188  	BloomTrieTablePrefix = "blt-"
   189  )
   190  
   191  // GetBloomTrieRoot reads the BloomTrie root assoctiated to the given section from the database
   192  func GetBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
   193  	var encNumber [8]byte
   194  	binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
   195  	data, _ := db.Get(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...))
   196  	return common.BytesToHash(data)
   197  }
   198  
   199  // StoreBloomTrieRoot writes the BloomTrie root assoctiated to the given section into the database
   200  func StoreBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
   201  	var encNumber [8]byte
   202  	binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
   203  	db.Put(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
   204  }
   205  
   206  // BloomTrieIndexerBackend implements core.ChainIndexerBackend
   207  type BloomTrieIndexerBackend struct {
   208  	db, cdb                                    ethdb.Database
   209  	section, parentSectionSize, bloomTrieRatio uint64
   210  	trie                                       *trie.Trie
   211  	sectionHeads                               []common.Hash
   212  }
   213  
   214  // NewBloomTrieIndexer creates a BloomTrie chain indexer
   215  func NewBloomTrieIndexer(db ethdb.Database, clientMode bool) *core.ChainIndexer {
   216  	cdb := ethdb.NewTable(db, BloomTrieTablePrefix)
   217  	idb := ethdb.NewTable(db, "bltIndex-")
   218  	backend := &BloomTrieIndexerBackend{db: db, cdb: cdb}
   219  	var confirmReq uint64
   220  	if clientMode {
   221  		backend.parentSectionSize = BloomTrieFrequency
   222  		confirmReq = HelperTrieConfirmations
   223  	} else {
   224  		backend.parentSectionSize = ethBloomBitsSection
   225  		confirmReq = HelperTrieProcessConfirmations
   226  	}
   227  	backend.bloomTrieRatio = BloomTrieFrequency / backend.parentSectionSize
   228  	backend.sectionHeads = make([]common.Hash, backend.bloomTrieRatio)
   229  	return core.NewChainIndexer(db, idb, backend, BloomTrieFrequency, confirmReq-ethBloomBitsConfirmations, time.Millisecond*100, "bloomtrie")
   230  }
   231  
   232  // Reset implements core.ChainIndexerBackend
   233  func (b *BloomTrieIndexerBackend) Reset(section uint64, lastSectionHead common.Hash) error {
   234  	var root common.Hash
   235  	if section > 0 {
   236  		root = GetBloomTrieRoot(b.db, section-1, lastSectionHead)
   237  	}
   238  	var err error
   239  	b.trie, err = trie.New(root, b.cdb)
   240  	b.section = section
   241  	return err
   242  }
   243  
   244  // Process implements core.ChainIndexerBackend
   245  func (b *BloomTrieIndexerBackend) Process(header *types.Header) {
   246  	num := header.Number.Uint64() - b.section*BloomTrieFrequency
   247  	if (num+1)%b.parentSectionSize == 0 {
   248  		b.sectionHeads[num/b.parentSectionSize] = header.Hash()
   249  	}
   250  }
   251  
   252  // Commit implements core.ChainIndexerBackend
   253  func (b *BloomTrieIndexerBackend) Commit() error {
   254  	var compSize, decompSize uint64
   255  
   256  	for i := uint(0); i < types.BloomBitLength; i++ {
   257  		var encKey [10]byte
   258  		binary.BigEndian.PutUint16(encKey[0:2], uint16(i))
   259  		binary.BigEndian.PutUint64(encKey[2:10], b.section)
   260  		var decomp []byte
   261  		for j := uint64(0); j < b.bloomTrieRatio; j++ {
   262  			data, err := core.GetBloomBits(b.db, i, b.section*b.bloomTrieRatio+j, b.sectionHeads[j])
   263  			if err != nil {
   264  				return err
   265  			}
   266  			decompData, err2 := bitutil.DecompressBytes(data, int(b.parentSectionSize/8))
   267  			if err2 != nil {
   268  				return err2
   269  			}
   270  			decomp = append(decomp, decompData...)
   271  		}
   272  		comp := bitutil.CompressBytes(decomp)
   273  
   274  		decompSize += uint64(len(decomp))
   275  		compSize += uint64(len(comp))
   276  		if len(comp) > 0 {
   277  			b.trie.Update(encKey[:], comp)
   278  		} else {
   279  			b.trie.Delete(encKey[:])
   280  		}
   281  	}
   282  
   283  	batch := b.cdb.NewBatch()
   284  	root, err := b.trie.CommitTo(batch)
   285  	if err != nil {
   286  		return err
   287  	} else {
   288  		batch.Write()
   289  		sectionHead := b.sectionHeads[b.bloomTrieRatio-1]
   290  		log.Info("Storing BloomTrie", "section", b.section, "sectionHead", fmt.Sprintf("%064x", sectionHead), "root", fmt.Sprintf("%064x", root), "compression ratio", float64(compSize)/float64(decompSize))
   291  		StoreBloomTrieRoot(b.db, b.section, sectionHead, root)
   292  	}
   293  
   294  	return nil
   295  }