postprocess.go 17.3 KB
Newer Older
1
// Copyright 2017 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package light

import (
20
	"bytes"
21
	"context"
22 23
	"encoding/binary"
	"errors"
24
	"fmt"
25 26 27
	"math/big"
	"time"

28
	mapset "github.com/deckarep/golang-set"
29 30 31
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/bitutil"
	"github.com/ethereum/go-ethereum/core"
32
	"github.com/ethereum/go-ethereum/core/rawdb"
33 34 35 36 37 38 39 40
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/params"
	"github.com/ethereum/go-ethereum/rlp"
	"github.com/ethereum/go-ethereum/trie"
)

41 42 43 44
// IndexerConfig includes a set of configs for chain indexers.
type IndexerConfig struct {
	// The block frequency for creating CHTs.
	ChtSize uint64
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	// The number of confirmations needed to generate/accept a canonical hash help trie.
	ChtConfirms uint64

	// The block frequency for creating new bloom bits.
	BloomSize uint64

	// The number of confirmation needed before a bloom section is considered probably final and its rotated bits
	// are calculated.
	BloomConfirms uint64

	// The block frequency for creating BloomTrie.
	BloomTrieSize uint64

	// The number of confirmations needed to generate/accept a bloom trie.
	BloomTrieConfirms uint64
}

var (
	// DefaultServerIndexerConfig wraps a set of configs as a default indexer config for server side.
	DefaultServerIndexerConfig = &IndexerConfig{
66
		ChtSize:           params.CHTFrequency,
67 68 69 70 71 72 73 74
		ChtConfirms:       params.HelperTrieProcessConfirmations,
		BloomSize:         params.BloomBitsBlocks,
		BloomConfirms:     params.BloomConfirms,
		BloomTrieSize:     params.BloomTrieFrequency,
		BloomTrieConfirms: params.HelperTrieProcessConfirmations,
	}
	// DefaultClientIndexerConfig wraps a set of configs as a default indexer config for client side.
	DefaultClientIndexerConfig = &IndexerConfig{
75
		ChtSize:           params.CHTFrequency,
76 77 78 79 80 81 82 83
		ChtConfirms:       params.HelperTrieConfirmations,
		BloomSize:         params.BloomBitsBlocksClient,
		BloomConfirms:     params.HelperTrieConfirmations,
		BloomTrieSize:     params.BloomTrieFrequency,
		BloomTrieConfirms: params.HelperTrieConfirmations,
	}
	// TestServerIndexerConfig wraps a set of configs as a test indexer config for server side.
	TestServerIndexerConfig = &IndexerConfig{
84 85 86 87 88 89
		ChtSize:           128,
		ChtConfirms:       1,
		BloomSize:         16,
		BloomConfirms:     1,
		BloomTrieSize:     128,
		BloomTrieConfirms: 1,
90 91 92
	}
	// TestClientIndexerConfig wraps a set of configs as a test indexer config for client side.
	TestClientIndexerConfig = &IndexerConfig{
93 94 95 96 97 98
		ChtSize:           128,
		ChtConfirms:       8,
		BloomSize:         128,
		BloomConfirms:     8,
		BloomTrieSize:     128,
		BloomTrieConfirms: 8,
99
	}
100 101 102
)

var (
103 104 105
	errNoTrustedCht       = errors.New("no trusted canonical hash trie")
	errNoTrustedBloomTrie = errors.New("no trusted bloom trie")
	errNoHeader           = errors.New("header not found")
106
	chtPrefix             = []byte("chtRootV2-") // chtPrefix + chtNum (uint64 big endian) -> trie root hash
107 108 109 110 111 112 113 114 115
	ChtTablePrefix        = "cht-"
)

// ChtNode structures are stored in the Canonical Hash Trie in an RLP encoded format
type ChtNode struct {
	Hash common.Hash
	Td   *big.Int
}

116
// GetChtRoot reads the CHT root associated to the given section from the database
117 118 119 120 121 122 123
func GetChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
	var encNumber [8]byte
	binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
	data, _ := db.Get(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...))
	return common.BytesToHash(data)
}

124
// StoreChtRoot writes the CHT root associated to the given section into the database
125 126 127 128 129 130
func StoreChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
	var encNumber [8]byte
	binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
	db.Put(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
}

131
// ChtIndexerBackend implements core.ChainIndexerBackend.
132
type ChtIndexerBackend struct {
133
	disablePruning       bool
134 135
	diskdb, trieTable    ethdb.Database
	odr                  OdrBackend
136
	triedb               *trie.Database
137
	trieset              mapset.Set
138 139 140 141 142
	section, sectionSize uint64
	lastHash             common.Hash
	trie                 *trie.Trie
}

143
// NewChtIndexer creates a Cht chain indexer
144
func NewChtIndexer(db ethdb.Database, odr OdrBackend, size, confirms uint64, disablePruning bool) *core.ChainIndexer {
145
	trieTable := rawdb.NewTable(db, ChtTablePrefix)
146
	backend := &ChtIndexerBackend{
147 148 149
		diskdb:         db,
		odr:            odr,
		trieTable:      trieTable,
150
		triedb:         trie.NewDatabaseWithConfig(trieTable, &trie.Config{Cache: 1}), // Use a tiny cache only to keep memory down
151 152 153
		trieset:        mapset.NewSet(),
		sectionSize:    size,
		disablePruning: disablePruning,
154
	}
155
	return core.NewChainIndexer(db, rawdb.NewTable(db, "chtIndexV2-"), backend, size, confirms, time.Millisecond*100, "cht")
156 157
}

158 159 160 161
// fetchMissingNodes tries to retrieve the last entry of the latest trusted CHT from the
// ODR backend in order to be able to add new entries and calculate subsequent root hashes
func (c *ChtIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error {
	batch := c.trieTable.NewBatch()
162
	r := &ChtRequest{ChtRoot: root, ChtNum: section - 1, BlockNum: section*c.sectionSize - 1, Config: c.odr.IndexerConfig()}
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
	for {
		err := c.odr.Retrieve(ctx, r)
		switch err {
		case nil:
			r.Proof.Store(batch)
			return batch.Write()
		case ErrNoPeers:
			// if there are no peers to serve, retry later
			select {
			case <-ctx.Done():
				return ctx.Err()
			case <-time.After(time.Second * 10):
				// stay in the loop and try again
			}
		default:
			return err
		}
	}
}

183
// Reset implements core.ChainIndexerBackend
184
func (c *ChtIndexerBackend) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
185 186
	var root common.Hash
	if section > 0 {
187
		root = GetChtRoot(c.diskdb, section-1, lastSectionHead)
188 189
	}
	var err error
190
	c.trie, err = trie.New(common.Hash{}, root, c.triedb)
191 192 193 194

	if err != nil && c.odr != nil {
		err = c.fetchMissingNodes(ctx, section, root)
		if err == nil {
195
			c.trie, err = trie.New(common.Hash{}, root, c.triedb)
196 197
		}
	}
198 199 200 201 202
	c.section = section
	return err
}

// Process implements core.ChainIndexerBackend
203
func (c *ChtIndexerBackend) Process(ctx context.Context, header *types.Header) error {
204 205 206
	hash, num := header.Hash(), header.Number.Uint64()
	c.lastHash = hash

207
	td := rawdb.ReadTd(c.diskdb, hash, num)
208 209 210 211 212 213 214
	if td == nil {
		panic(nil)
	}
	var encNumber [8]byte
	binary.BigEndian.PutUint64(encNumber[:], num)
	data, _ := rlp.EncodeToBytes(ChtNode{hash, td})
	c.trie.Update(encNumber[:], data)
215
	return nil
216 217 218 219
}

// Commit implements core.ChainIndexerBackend
func (c *ChtIndexerBackend) Commit() error {
220 221 222 223 224 225 226 227 228 229 230 231
	root, nodes, err := c.trie.Commit(false)
	if err != nil {
		return err
	}
	// Commit trie changes into trie database in case it's not nil.
	if nodes != nil {
		if err := c.triedb.Update(trie.NewWithNodeSet(nodes)); err != nil {
			return err
		}
	}
	// Re-create trie with newly generated root and updated database.
	c.trie, err = trie.New(common.Hash{}, root, c.triedb)
232 233 234
	if err != nil {
		return err
	}
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
	// Pruning historical trie nodes if necessary.
	if !c.disablePruning {
		// Flush the triedb and track the latest trie nodes.
		c.trieset.Clear()
		c.triedb.Commit(root, false, func(hash common.Hash) { c.trieset.Add(hash) })

		it := c.trieTable.NewIterator(nil, nil)
		defer it.Release()

		var (
			deleted   int
			remaining int
			t         = time.Now()
		)
		for it.Next() {
			trimmed := bytes.TrimPrefix(it.Key(), []byte(ChtTablePrefix))
			if !c.trieset.Contains(common.BytesToHash(trimmed)) {
				c.trieTable.Delete(trimmed)
				deleted += 1
			} else {
				remaining += 1
			}
		}
		log.Debug("Prune historical CHT trie nodes", "deleted", deleted, "remaining", remaining, "elapsed", common.PrettyDuration(time.Since(t)))
	} else {
		c.triedb.Commit(root, false, nil)
	}
262
	log.Info("Storing CHT", "section", c.section, "head", fmt.Sprintf("%064x", c.lastHash), "root", fmt.Sprintf("%064x", root))
263
	StoreChtRoot(c.diskdb, c.section, c.lastHash, root)
264 265 266
	return nil
}

267 268
// Prune implements core.ChainIndexerBackend which deletes all chain data
// (except hash<->number mappings) older than the specified threshold.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
func (c *ChtIndexerBackend) Prune(threshold uint64) error {
	// Short circuit if the light pruning is disabled.
	if c.disablePruning {
		return nil
	}
	t := time.Now()
	// Always keep genesis header in database.
	start, end := uint64(1), (threshold+1)*c.sectionSize

	var batch = c.diskdb.NewBatch()
	for {
		numbers, hashes := rawdb.ReadAllCanonicalHashes(c.diskdb, start, end, 10240)
		if len(numbers) == 0 {
			break
		}
		for i := 0; i < len(numbers); i++ {
			// Keep hash<->number mapping in database otherwise the hash based
			// API(e.g. GetReceipt, GetLogs) will be broken.
			//
			// Storage size wise, the size of a mapping is ~41bytes. For one
			// section is about 1.3MB which is acceptable.
			//
			// In order to totally get rid of this index, we need an additional
			// flag to specify how many historical data light client can serve.
			rawdb.DeleteCanonicalHash(batch, numbers[i])
			rawdb.DeleteBlockWithoutNumber(batch, hashes[i], numbers[i])
		}
		if batch.ValueSize() > ethdb.IdealBatchSize {
			if err := batch.Write(); err != nil {
				return err
			}
			batch.Reset()
		}
		start = numbers[len(numbers)-1] + 1
	}
	if err := batch.Write(); err != nil {
		return err
	}
	log.Debug("Prune history headers", "threshold", threshold, "elapsed", common.PrettyDuration(time.Since(t)))
	return nil
}

311 312 313 314 315
var (
	bloomTriePrefix      = []byte("bltRoot-") // bloomTriePrefix + bloomTrieNum (uint64 big endian) -> trie root hash
	BloomTrieTablePrefix = "blt-"
)

316
// GetBloomTrieRoot reads the BloomTrie root associated to the given section from the database
317 318 319 320 321 322 323
func GetBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
	var encNumber [8]byte
	binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
	data, _ := db.Get(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...))
	return common.BytesToHash(data)
}

324
// StoreBloomTrieRoot writes the BloomTrie root associated to the given section into the database
325 326 327 328 329 330 331 332
func StoreBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
	var encNumber [8]byte
	binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
	db.Put(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
}

// BloomTrieIndexerBackend implements core.ChainIndexerBackend
type BloomTrieIndexerBackend struct {
333
	disablePruning    bool
334 335
	diskdb, trieTable ethdb.Database
	triedb            *trie.Database
336
	trieset           mapset.Set
337 338 339 340 341 342 343
	odr               OdrBackend
	section           uint64
	parentSize        uint64
	size              uint64
	bloomTrieRatio    uint64
	trie              *trie.Trie
	sectionHeads      []common.Hash
344 345 346
}

// NewBloomTrieIndexer creates a BloomTrie chain indexer
347
func NewBloomTrieIndexer(db ethdb.Database, odr OdrBackend, parentSize, size uint64, disablePruning bool) *core.ChainIndexer {
348
	trieTable := rawdb.NewTable(db, BloomTrieTablePrefix)
349
	backend := &BloomTrieIndexerBackend{
350 351 352
		diskdb:         db,
		odr:            odr,
		trieTable:      trieTable,
353
		triedb:         trie.NewDatabaseWithConfig(trieTable, &trie.Config{Cache: 1}), // Use a tiny cache only to keep memory down
354 355 356 357
		trieset:        mapset.NewSet(),
		parentSize:     parentSize,
		size:           size,
		disablePruning: disablePruning,
358
	}
359
	backend.bloomTrieRatio = size / parentSize
360
	backend.sectionHeads = make([]common.Hash, backend.bloomTrieRatio)
361
	return core.NewChainIndexer(db, rawdb.NewTable(db, "bltIndex-"), backend, size, 0, time.Millisecond*100, "bloomtrie")
362 363 364 365 366 367 368 369 370 371 372 373 374 375
}

// fetchMissingNodes tries to retrieve the last entries of the latest trusted bloom trie from the
// ODR backend in order to be able to add new entries and calculate subsequent root hashes
func (b *BloomTrieIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error {
	indexCh := make(chan uint, types.BloomBitLength)
	type res struct {
		nodes *NodeSet
		err   error
	}
	resCh := make(chan res, types.BloomBitLength)
	for i := 0; i < 20; i++ {
		go func() {
			for bitIndex := range indexCh {
376
				r := &BloomRequest{BloomTrieRoot: root, BloomTrieNum: section - 1, BitIdx: bitIndex, SectionIndexList: []uint64{section - 1}, Config: b.odr.IndexerConfig()}
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
				for {
					if err := b.odr.Retrieve(ctx, r); err == ErrNoPeers {
						// if there are no peers to serve, retry later
						select {
						case <-ctx.Done():
							resCh <- res{nil, ctx.Err()}
							return
						case <-time.After(time.Second * 10):
							// stay in the loop and try again
						}
					} else {
						resCh <- res{r.Proofs, err}
						break
					}
				}
			}
		}()
	}
	for i := uint(0); i < types.BloomBitLength; i++ {
		indexCh <- i
	}
	close(indexCh)
	batch := b.trieTable.NewBatch()
	for i := uint(0); i < types.BloomBitLength; i++ {
		res := <-resCh
		if res.err != nil {
			return res.err
		}
		res.nodes.Store(batch)
	}
	return batch.Write()
408 409 410
}

// Reset implements core.ChainIndexerBackend
411
func (b *BloomTrieIndexerBackend) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
412 413
	var root common.Hash
	if section > 0 {
414
		root = GetBloomTrieRoot(b.diskdb, section-1, lastSectionHead)
415 416
	}
	var err error
417
	b.trie, err = trie.New(common.Hash{}, root, b.triedb)
418 419 420
	if err != nil && b.odr != nil {
		err = b.fetchMissingNodes(ctx, section, root)
		if err == nil {
421
			b.trie, err = trie.New(common.Hash{}, root, b.triedb)
422 423
		}
	}
424 425 426 427 428
	b.section = section
	return err
}

// Process implements core.ChainIndexerBackend
429
func (b *BloomTrieIndexerBackend) Process(ctx context.Context, header *types.Header) error {
430 431 432
	num := header.Number.Uint64() - b.section*b.size
	if (num+1)%b.parentSize == 0 {
		b.sectionHeads[num/b.parentSize] = header.Hash()
433
	}
434
	return nil
435 436 437 438 439 440 441 442 443 444 445 446
}

// Commit implements core.ChainIndexerBackend
func (b *BloomTrieIndexerBackend) Commit() error {
	var compSize, decompSize uint64

	for i := uint(0); i < types.BloomBitLength; i++ {
		var encKey [10]byte
		binary.BigEndian.PutUint16(encKey[0:2], uint16(i))
		binary.BigEndian.PutUint64(encKey[2:10], b.section)
		var decomp []byte
		for j := uint64(0); j < b.bloomTrieRatio; j++ {
447
			data, err := rawdb.ReadBloomBits(b.diskdb, i, b.section*b.bloomTrieRatio+j, b.sectionHeads[j])
448 449 450
			if err != nil {
				return err
			}
451
			decompData, err2 := bitutil.DecompressBytes(data, int(b.parentSize/8))
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
			if err2 != nil {
				return err2
			}
			decomp = append(decomp, decompData...)
		}
		comp := bitutil.CompressBytes(decomp)

		decompSize += uint64(len(decomp))
		compSize += uint64(len(comp))
		if len(comp) > 0 {
			b.trie.Update(encKey[:], comp)
		} else {
			b.trie.Delete(encKey[:])
		}
	}
467 468 469 470 471 472 473 474 475 476 477 478
	root, nodes, err := b.trie.Commit(false)
	if err != nil {
		return err
	}
	// Commit trie changes into trie database in case it's not nil.
	if nodes != nil {
		if err := b.triedb.Update(trie.NewWithNodeSet(nodes)); err != nil {
			return err
		}
	}
	// Re-create trie with newly generated root and updated database.
	b.trie, err = trie.New(common.Hash{}, root, b.triedb)
479 480 481
	if err != nil {
		return err
	}
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
	// Pruning historical trie nodes if necessary.
	if !b.disablePruning {
		// Flush the triedb and track the latest trie nodes.
		b.trieset.Clear()
		b.triedb.Commit(root, false, func(hash common.Hash) { b.trieset.Add(hash) })

		it := b.trieTable.NewIterator(nil, nil)
		defer it.Release()

		var (
			deleted   int
			remaining int
			t         = time.Now()
		)
		for it.Next() {
			trimmed := bytes.TrimPrefix(it.Key(), []byte(BloomTrieTablePrefix))
			if !b.trieset.Contains(common.BytesToHash(trimmed)) {
				b.trieTable.Delete(trimmed)
				deleted += 1
			} else {
				remaining += 1
			}
		}
		log.Debug("Prune historical bloom trie nodes", "deleted", deleted, "remaining", remaining, "elapsed", common.PrettyDuration(time.Since(t)))
	} else {
		b.triedb.Commit(root, false, nil)
	}
509 510
	sectionHead := b.sectionHeads[b.bloomTrieRatio-1]
	StoreBloomTrieRoot(b.diskdb, b.section, sectionHead, root)
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
	log.Info("Storing bloom trie", "section", b.section, "head", fmt.Sprintf("%064x", sectionHead), "root", fmt.Sprintf("%064x", root), "compression", float64(compSize)/float64(decompSize))

	return nil
}

// Prune implements core.ChainIndexerBackend which deletes all
// bloombits which older than the specified threshold.
func (b *BloomTrieIndexerBackend) Prune(threshold uint64) error {
	// Short circuit if the light pruning is disabled.
	if b.disablePruning {
		return nil
	}
	start := time.Now()
	for i := uint(0); i < types.BloomBitLength; i++ {
		rawdb.DeleteBloombits(b.diskdb, i, 0, threshold*b.bloomTrieRatio+b.bloomTrieRatio)
	}
	log.Debug("Prune history bloombits", "threshold", threshold, "elapsed", common.PrettyDuration(time.Since(start)))
528 529
	return nil
}