database_util.go 22.4 KB
Newer Older
1
// Copyright 2015 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 6 7 8
// 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.
//
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 13 14
// GNU Lesser General Public License for more details.
//
// 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 18 19 20
package core

import (
	"bytes"
21
	"encoding/binary"
22
	"encoding/json"
23
	"errors"
24
	"fmt"
25 26 27 28
	"math/big"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
29
	"github.com/ethereum/go-ethereum/ethdb"
30
	"github.com/ethereum/go-ethereum/log"
31
	"github.com/ethereum/go-ethereum/metrics"
32
	"github.com/ethereum/go-ethereum/params"
33 34 35
	"github.com/ethereum/go-ethereum/rlp"
)

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// DatabaseReader wraps the Get method of a backing data store.
type DatabaseReader interface {
	Get(key []byte) (value []byte, err error)
}

// DatabaseWriter wraps the Put method of a backing data store.
type DatabaseWriter interface {
	Put(key, value []byte) error
}

// DatabaseDeleter wraps the Delete method of a backing data store.
type DatabaseDeleter interface {
	Delete(key []byte) error
}

51
var (
52 53
	headHeaderKey = []byte("LastHeader")
	headBlockKey  = []byte("LastBlock")
54
	headFastKey   = []byte("LastFast")
55

56 57 58 59 60 61 62 63 64
	// Data item prefixes (use single byte to avoid mixing data types, avoid `i`).
	headerPrefix        = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header
	tdSuffix            = []byte("t") // headerPrefix + num (uint64 big endian) + hash + tdSuffix -> td
	numSuffix           = []byte("n") // headerPrefix + num (uint64 big endian) + numSuffix -> hash
	blockHashPrefix     = []byte("H") // blockHashPrefix + hash -> num (uint64 big endian)
	bodyPrefix          = []byte("b") // bodyPrefix + num (uint64 big endian) + hash -> block body
	blockReceiptsPrefix = []byte("r") // blockReceiptsPrefix + num (uint64 big endian) + hash -> block receipts
	lookupPrefix        = []byte("l") // lookupPrefix + hash -> transaction/receipt lookup metadata
	bloomBitsPrefix     = []byte("B") // bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash -> bloom bits
65

66 67 68 69 70
	preimagePrefix = "secure-key-"              // preimagePrefix + hash -> preimage
	configPrefix   = []byte("ethereum-config-") // config prefix for the db

	// Chain index prefixes (use `i` + single byte to avoid mixing data types).
	BloomBitsIndexPrefix = []byte("iB") // BloomBitsIndexPrefix is the data table of a chain indexer to track its progress
71

72 73 74
	// used by old db, now only used for conversion
	oldReceiptsPrefix = []byte("receipts-")
	oldTxMetaSuffix   = []byte{0x01}
75

76
	ErrChainConfigNotFound = errors.New("ChainConfig not found") // general config not found error
77

78 79
	preimageCounter    = metrics.NewCounter("db/preimage/total")
	preimageHitCounter = metrics.NewCounter("db/preimage/hits")
80 81
)

82 83 84 85 86 87 88 89
// txLookupEntry is a positional metadata to help looking up the data content of
// a transaction or receipt given only its hash.
type txLookupEntry struct {
	BlockHash  common.Hash
	BlockIndex uint64
	Index      uint64
}

90 91 92 93 94 95 96
// encodeBlockNumber encodes a block number as big endian uint64
func encodeBlockNumber(number uint64) []byte {
	enc := make([]byte, 8)
	binary.BigEndian.PutUint64(enc, number)
	return enc
}

97
// GetCanonicalHash retrieves a hash assigned to a canonical block number.
98
func GetCanonicalHash(db DatabaseReader, number uint64) common.Hash {
99
	data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
100
	if len(data) == 0 {
101
		return common.Hash{}
102 103
	}
	return common.BytesToHash(data)
104 105
}

106 107 108 109 110 111
// missingNumber is returned by GetBlockNumber if no header with the
// given block hash has been stored in the database
const missingNumber = uint64(0xffffffffffffffff)

// GetBlockNumber returns the block number assigned to a block hash
// if the corresponding header is present in the database
112
func GetBlockNumber(db DatabaseReader, hash common.Hash) uint64 {
113 114
	data, _ := db.Get(append(blockHashPrefix, hash.Bytes()...))
	if len(data) != 8 {
115
		return missingNumber
116 117 118 119
	}
	return binary.BigEndian.Uint64(data)
}

120 121 122 123
// GetHeadHeaderHash retrieves the hash of the current canonical head block's
// header. The difference between this and GetHeadBlockHash is that whereas the
// last block hash is only updated upon a full block import, the last header
// hash is updated already at header import, allowing head tracking for the
124
// light synchronization mechanism.
125
func GetHeadHeaderHash(db DatabaseReader) common.Hash {
126
	data, _ := db.Get(headHeaderKey)
127 128 129 130 131 132
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
}

133
// GetHeadBlockHash retrieves the hash of the current canonical head block.
134
func GetHeadBlockHash(db DatabaseReader) common.Hash {
135
	data, _ := db.Get(headBlockKey)
136 137 138 139 140 141
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
}

142 143 144 145
// GetHeadFastBlockHash retrieves the hash of the current canonical head block during
// fast synchronization. The difference between this and GetHeadBlockHash is that
// whereas the last block hash is only updated upon a full block import, the last
// fast hash is updated when importing pre-processed blocks.
146
func GetHeadFastBlockHash(db DatabaseReader) common.Hash {
147 148 149 150 151 152 153
	data, _ := db.Get(headFastKey)
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
}

154 155
// GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
// if the header's not found.
156
func GetHeaderRLP(db DatabaseReader, hash common.Hash, number uint64) rlp.RawValue {
157
	data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
158 159 160
	return data
}

161 162
// GetHeader retrieves the block header corresponding to the hash, nil if none
// found.
163
func GetHeader(db DatabaseReader, hash common.Hash, number uint64) *types.Header {
164
	data := GetHeaderRLP(db, hash, number)
165 166 167
	if len(data) == 0 {
		return nil
	}
168 169
	header := new(types.Header)
	if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
170
		log.Error("Invalid block header RLP", "hash", hash, "err", err)
171 172
		return nil
	}
173
	return header
174 175
}

176
// GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
177
func GetBodyRLP(db DatabaseReader, hash common.Hash, number uint64) rlp.RawValue {
178
	data, _ := db.Get(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
179
	return data
180 181
}

182 183
// GetBody retrieves the block body (transactons, uncles) corresponding to the
// hash, nil if none found.
184
func GetBody(db DatabaseReader, hash common.Hash, number uint64) *types.Body {
185
	data := GetBodyRLP(db, hash, number)
186 187
	if len(data) == 0 {
		return nil
188
	}
189
	body := new(types.Body)
190
	if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
191
		log.Error("Invalid block body RLP", "hash", hash, "err", err)
192
		return nil
193
	}
194
	return body
195 196
}

197 198
// GetTd retrieves a block's total difficulty corresponding to the hash, nil if
// none found.
199
func GetTd(db DatabaseReader, hash common.Hash, number uint64) *big.Int {
200
	data, _ := db.Get(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash[:]...), tdSuffix...))
201
	if len(data) == 0 {
202
		return nil
203
	}
204 205
	td := new(big.Int)
	if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
206
		log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err)
207 208
		return nil
	}
209
	return td
210 211
}

212
// GetBlock retrieves an entire block corresponding to the hash, assembling it
213 214 215 216 217
// back from the stored header and body. If either the header or body could not
// be retrieved nil is returned.
//
// Note, due to concurrent download of header and block body the header and thus
// canonical hash can be stored in the database but the body data not (yet).
218
func GetBlock(db DatabaseReader, hash common.Hash, number uint64) *types.Block {
219
	// Retrieve the block header and body contents
220
	header := GetHeader(db, hash, number)
221 222 223
	if header == nil {
		return nil
	}
224
	body := GetBody(db, hash, number)
225
	if body == nil {
226 227
		return nil
	}
228 229
	// Reassemble the block and return
	return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
230 231
}

232 233
// GetBlockReceipts retrieves the receipts generated by the transactions included
// in a block given by its hash.
234
func GetBlockReceipts(db DatabaseReader, hash common.Hash, number uint64) types.Receipts {
235
	data, _ := db.Get(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash[:]...))
236
	if len(data) == 0 {
237
		return nil
238 239 240
	}
	storageReceipts := []*types.ReceiptForStorage{}
	if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
241
		log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
242 243 244 245 246 247 248 249 250
		return nil
	}
	receipts := make(types.Receipts, len(storageReceipts))
	for i, receipt := range storageReceipts {
		receipts[i] = (*types.Receipt)(receipt)
	}
	return receipts
}

251 252
// GetTxLookupEntry retrieves the positional metadata associated with a transaction
// hash to allow retrieving the transaction or receipt by hash.
253
func GetTxLookupEntry(db DatabaseReader, hash common.Hash) (common.Hash, uint64, uint64) {
254 255 256 257 258 259 260 261 262 263 264 265 266 267
	// Load the positional metadata from disk and bail if it fails
	data, _ := db.Get(append(lookupPrefix, hash.Bytes()...))
	if len(data) == 0 {
		return common.Hash{}, 0, 0
	}
	// Parse and return the contents of the lookup entry
	var entry txLookupEntry
	if err := rlp.DecodeBytes(data, &entry); err != nil {
		log.Error("Invalid lookup entry RLP", "hash", hash, "err", err)
		return common.Hash{}, 0, 0
	}
	return entry.BlockHash, entry.BlockIndex, entry.Index
}

268 269
// GetTransaction retrieves a specific transaction from the database, along with
// its added positional metadata.
270
func GetTransaction(db DatabaseReader, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
271 272 273 274 275 276 277 278 279 280 281 282
	// Retrieve the lookup metadata and resolve the transaction from the body
	blockHash, blockNumber, txIndex := GetTxLookupEntry(db, hash)

	if blockHash != (common.Hash{}) {
		body := GetBody(db, blockHash, blockNumber)
		if body == nil || len(body.Transactions) <= int(txIndex) {
			log.Error("Transaction referenced missing", "number", blockNumber, "hash", blockHash, "index", txIndex)
			return nil, common.Hash{}, 0, 0
		}
		return body.Transactions[txIndex], blockHash, blockNumber, txIndex
	}
	// Old transaction representation, load the transaction and it's metadata separately
283 284 285 286 287 288 289 290 291
	data, _ := db.Get(hash.Bytes())
	if len(data) == 0 {
		return nil, common.Hash{}, 0, 0
	}
	var tx types.Transaction
	if err := rlp.DecodeBytes(data, &tx); err != nil {
		return nil, common.Hash{}, 0, 0
	}
	// Retrieve the blockchain positional metadata
292
	data, _ = db.Get(append(hash.Bytes(), oldTxMetaSuffix...))
293 294 295
	if len(data) == 0 {
		return nil, common.Hash{}, 0, 0
	}
296 297
	var entry txLookupEntry
	if err := rlp.DecodeBytes(data, &entry); err != nil {
298 299
		return nil, common.Hash{}, 0, 0
	}
300
	return &tx, entry.BlockHash, entry.BlockIndex, entry.Index
301 302
}

303 304
// GetReceipt retrieves a specific transaction receipt from the database, along with
// its added positional metadata.
305
func GetReceipt(db DatabaseReader, hash common.Hash) (*types.Receipt, common.Hash, uint64, uint64) {
306 307 308 309 310 311 312 313 314 315 316 317 318
	// Retrieve the lookup metadata and resolve the receipt from the receipts
	blockHash, blockNumber, receiptIndex := GetTxLookupEntry(db, hash)

	if blockHash != (common.Hash{}) {
		receipts := GetBlockReceipts(db, blockHash, blockNumber)
		if len(receipts) <= int(receiptIndex) {
			log.Error("Receipt refereced missing", "number", blockNumber, "hash", blockHash, "index", receiptIndex)
			return nil, common.Hash{}, 0, 0
		}
		return receipts[receiptIndex], blockHash, blockNumber, receiptIndex
	}
	// Old receipt representation, load the receipt and set an unknown metadata
	data, _ := db.Get(append(oldReceiptsPrefix, hash[:]...))
319
	if len(data) == 0 {
320
		return nil, common.Hash{}, 0, 0
321 322 323 324
	}
	var receipt types.ReceiptForStorage
	err := rlp.DecodeBytes(data, &receipt)
	if err != nil {
325
		log.Error("Invalid receipt RLP", "hash", hash, "err", err)
326
	}
327
	return (*types.Receipt)(&receipt), common.Hash{}, 0, 0
328 329
}

330 331 332 333 334 335 336 337 338 339 340 341
// GetBloomBits retrieves the compressed bloom bit vector belonging to the given
// section and bit index from the.
func GetBloomBits(db DatabaseReader, bit uint, section uint64, head common.Hash) []byte {
	key := append(append(bloomBitsPrefix, make([]byte, 10)...), head.Bytes()...)

	binary.BigEndian.PutUint16(key[1:], uint16(bit))
	binary.BigEndian.PutUint64(key[3:], section)

	bits, _ := db.Get(key)
	return bits
}

342
// WriteCanonicalHash stores the canonical hash for the given block number.
343
func WriteCanonicalHash(db DatabaseWriter, hash common.Hash, number uint64) error {
344
	key := append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)
345
	if err := db.Put(key, hash.Bytes()); err != nil {
346
		log.Crit("Failed to store number to hash mapping", "err", err)
347
	}
348 349 350
	return nil
}

351
// WriteHeadHeaderHash stores the head header's hash.
352
func WriteHeadHeaderHash(db DatabaseWriter, hash common.Hash) error {
353
	if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
354
		log.Crit("Failed to store last header's hash", "err", err)
355
	}
356 357 358 359
	return nil
}

// WriteHeadBlockHash stores the head block's hash.
360
func WriteHeadBlockHash(db DatabaseWriter, hash common.Hash) error {
361
	if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
362
		log.Crit("Failed to store last block's hash", "err", err)
363 364 365
	}
	return nil
}
366

367
// WriteHeadFastBlockHash stores the fast head block's hash.
368
func WriteHeadFastBlockHash(db DatabaseWriter, hash common.Hash) error {
369
	if err := db.Put(headFastKey, hash.Bytes()); err != nil {
370
		log.Crit("Failed to store last fast block's hash", "err", err)
371 372 373 374
	}
	return nil
}

375
// WriteHeader serializes a block header into the database.
376
func WriteHeader(db DatabaseWriter, header *types.Header) error {
377
	data, err := rlp.EncodeToBytes(header)
378 379 380
	if err != nil {
		return err
	}
381 382 383 384 385
	hash := header.Hash().Bytes()
	num := header.Number.Uint64()
	encNum := encodeBlockNumber(num)
	key := append(blockHashPrefix, hash...)
	if err := db.Put(key, encNum); err != nil {
386
		log.Crit("Failed to store hash to number mapping", "err", err)
387 388
	}
	key = append(append(headerPrefix, encNum...), hash...)
389
	if err := db.Put(key, data); err != nil {
390
		log.Crit("Failed to store header", "err", err)
391 392 393
	}
	return nil
}
394

395
// WriteBody serializes the body of a block into the database.
396
func WriteBody(db DatabaseWriter, hash common.Hash, number uint64, body *types.Body) error {
397
	data, err := rlp.EncodeToBytes(body)
398 399 400
	if err != nil {
		return err
	}
401 402 403 404
	return WriteBodyRLP(db, hash, number, data)
}

// WriteBodyRLP writes a serialized body of a block into the database.
405
func WriteBodyRLP(db DatabaseWriter, hash common.Hash, number uint64, rlp rlp.RawValue) error {
406
	key := append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
407
	if err := db.Put(key, rlp); err != nil {
408
		log.Crit("Failed to store block body", "err", err)
409 410 411 412 413
	}
	return nil
}

// WriteTd serializes the total difficulty of a block into the database.
414
func WriteTd(db DatabaseWriter, hash common.Hash, number uint64, td *big.Int) error {
415
	data, err := rlp.EncodeToBytes(td)
416 417
	if err != nil {
		return err
418
	}
419
	key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...)
420
	if err := db.Put(key, data); err != nil {
421
		log.Crit("Failed to store block total difficulty", "err", err)
422 423 424
	}
	return nil
}
425

426
// WriteBlock serializes a block into the database, header and body separately.
427
func WriteBlock(db DatabaseWriter, block *types.Block) error {
428
	// Store the body first to retain database consistency
429
	if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
430 431 432 433 434 435
		return err
	}
	// Store the header too, signaling full block ownership
	if err := WriteHeader(db, block.Header()); err != nil {
		return err
	}
436 437
	return nil
}
438

439 440 441
// WriteBlockReceipts stores all the transaction receipts belonging to a block
// as a single receipt slice. This is used during chain reorganisations for
// rescheduling dropped transactions.
442
func WriteBlockReceipts(db DatabaseWriter, hash common.Hash, number uint64, receipts types.Receipts) error {
443 444 445 446 447 448 449 450 451 452
	// Convert the receipts into their storage form and serialize them
	storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
	for i, receipt := range receipts {
		storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
	}
	bytes, err := rlp.EncodeToBytes(storageReceipts)
	if err != nil {
		return err
	}
	// Store the flattened receipt slice
453 454
	key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
	if err := db.Put(key, bytes); err != nil {
455
		log.Crit("Failed to store block receipts", "err", err)
456 457 458 459
	}
	return nil
}

460 461 462
// WriteTxLookupEntries stores a positional metadata for every transaction from
// a block, enabling hash based transaction and receipt lookups.
func WriteTxLookupEntries(db ethdb.Database, block *types.Block) error {
463 464
	batch := db.NewBatch()

465
	// Iterate over each transaction and encode its metadata
466
	for i, tx := range block.Transactions() {
467
		entry := txLookupEntry{
468 469 470 471
			BlockHash:  block.Hash(),
			BlockIndex: block.NumberU64(),
			Index:      uint64(i),
		}
472
		data, err := rlp.EncodeToBytes(entry)
473 474 475
		if err != nil {
			return err
		}
476
		if err := batch.Put(append(lookupPrefix, tx.Hash().Bytes()...), data); err != nil {
477 478 479 480 481
			return err
		}
	}
	// Write the scheduled data into the database
	if err := batch.Write(); err != nil {
482
		log.Crit("Failed to store lookup entries", "err", err)
483 484 485 486
	}
	return nil
}

487 488 489 490 491 492 493 494 495 496 497 498 499
// WriteBloomBits writes the compressed bloom bits vector belonging to the given
// section and bit index.
func WriteBloomBits(db DatabaseWriter, bit uint, section uint64, head common.Hash, bits []byte) {
	key := append(append(bloomBitsPrefix, make([]byte, 10)...), head.Bytes()...)

	binary.BigEndian.PutUint16(key[1:], uint16(bit))
	binary.BigEndian.PutUint64(key[3:], section)

	if err := db.Put(key, bits); err != nil {
		log.Crit("Failed to store bloom bits", "err", err)
	}
}

500
// DeleteCanonicalHash removes the number to hash canonical mapping.
501
func DeleteCanonicalHash(db DatabaseDeleter, number uint64) {
502
	db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
503 504
}

505
// DeleteHeader removes all block header data associated with a hash.
506
func DeleteHeader(db DatabaseDeleter, hash common.Hash, number uint64) {
507 508
	db.Delete(append(blockHashPrefix, hash.Bytes()...))
	db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
509 510 511
}

// DeleteBody removes all block body data associated with a hash.
512
func DeleteBody(db DatabaseDeleter, hash common.Hash, number uint64) {
513
	db.Delete(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
514 515 516
}

// DeleteTd removes all block total difficulty data associated with a hash.
517
func DeleteTd(db DatabaseDeleter, hash common.Hash, number uint64) {
518
	db.Delete(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...))
519 520 521
}

// DeleteBlock removes all block data associated with a hash.
522
func DeleteBlock(db DatabaseDeleter, hash common.Hash, number uint64) {
523 524 525 526
	DeleteBlockReceipts(db, hash, number)
	DeleteHeader(db, hash, number)
	DeleteBody(db, hash, number)
	DeleteTd(db, hash, number)
527 528
}

529
// DeleteBlockReceipts removes all receipt data associated with a block hash.
530
func DeleteBlockReceipts(db DatabaseDeleter, hash common.Hash, number uint64) {
531
	db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
532 533
}

534
// DeleteTxLookupEntry removes all transaction data associated with a hash.
535
func DeleteTxLookupEntry(db DatabaseDeleter, hash common.Hash) {
536
	db.Delete(append(lookupPrefix, hash.Bytes()...))
537 538
}

539 540 541 542 543 544 545 546 547 548 549 550 551 552
// PreimageTable returns a Database instance with the key prefix for preimage entries.
func PreimageTable(db ethdb.Database) ethdb.Database {
	return ethdb.NewTable(db, preimagePrefix)
}

// WritePreimages writes the provided set of preimages to the database. `number` is the
// current block number, and is used for debug messages only.
func WritePreimages(db ethdb.Database, number uint64, preimages map[common.Hash][]byte) error {
	table := PreimageTable(db)
	batch := table.NewBatch()
	hitCount := 0
	for hash, preimage := range preimages {
		if _, err := table.Get(hash.Bytes()); err != nil {
			batch.Put(hash.Bytes(), preimage)
553
			hitCount++
554 555 556 557 558 559 560 561 562 563 564 565
		}
	}
	preimageCounter.Inc(int64(len(preimages)))
	preimageHitCounter.Inc(int64(hitCount))
	if hitCount > 0 {
		if err := batch.Write(); err != nil {
			return fmt.Errorf("preimage write fail for block %d: %v", number, err)
		}
	}
	return nil
}

566
// GetBlockChainVersion reads the version number from db.
567
func GetBlockChainVersion(db DatabaseReader) int {
568 569 570 571 572 573 574
	var vsn uint
	enc, _ := db.Get([]byte("BlockchainVersion"))
	rlp.DecodeBytes(enc, &vsn)
	return int(vsn)
}

// WriteBlockChainVersion writes vsn as the version number to db.
575
func WriteBlockChainVersion(db DatabaseWriter, vsn int) {
576 577 578
	enc, _ := rlp.EncodeToBytes(uint(vsn))
	db.Put([]byte("BlockchainVersion"), enc)
}
579 580

// WriteChainConfig writes the chain config settings to the database.
581
func WriteChainConfig(db DatabaseWriter, hash common.Hash, cfg *params.ChainConfig) error {
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
	// short circuit and ignore if nil config. GetChainConfig
	// will return a default.
	if cfg == nil {
		return nil
	}

	jsonChainConfig, err := json.Marshal(cfg)
	if err != nil {
		return err
	}

	return db.Put(append(configPrefix, hash[:]...), jsonChainConfig)
}

// GetChainConfig will fetch the network settings based on the given hash.
597
func GetChainConfig(db DatabaseReader, hash common.Hash) (*params.ChainConfig, error) {
598 599
	jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
	if len(jsonChainConfig) == 0 {
600
		return nil, ErrChainConfigNotFound
601 602
	}

603
	var config params.ChainConfig
604 605 606 607 608 609
	if err := json.Unmarshal(jsonChainConfig, &config); err != nil {
		return nil, err
	}

	return &config, nil
}
610 611

// FindCommonAncestor returns the last common ancestor of two block headers
612
func FindCommonAncestor(db DatabaseReader, a, b *types.Header) *types.Header {
613 614
	for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
		a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1)
615 616 617 618
		if a == nil {
			return nil
		}
	}
619 620
	for an := a.Number.Uint64(); an < b.Number.Uint64(); {
		b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1)
621 622 623 624 625
		if b == nil {
			return nil
		}
	}
	for a.Hash() != b.Hash() {
626
		a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1)
627 628 629
		if a == nil {
			return nil
		}
630
		b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1)
631 632 633 634 635 636
		if b == nil {
			return nil
		}
	}
	return a
}