database_util.go 22.2 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
	"math/big"
26
	"sync"
27 28 29

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

37
var (
38 39
	headHeaderKey = []byte("LastHeader")
	headBlockKey  = []byte("LastBlock")
40
	headFastKey   = []byte("LastFast")
41

42 43 44 45 46 47
	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
48
	lookupPrefix        = []byte("l")   // lookupPrefix + hash -> transaction/receipt lookup metadata
49
	preimagePrefix      = "secure-key-" // preimagePrefix + hash -> preimage
50

51 52
	mipmapPre    = []byte("mipmap-log-bloom-")
	MIPMapLevels = []uint64{1000000, 500000, 100000, 50000, 1000}
53

54
	configPrefix = []byte("ethereum-config-") // config prefix for the db
55

56 57 58
	// used by old db, now only used for conversion
	oldReceiptsPrefix = []byte("receipts-")
	oldTxMetaSuffix   = []byte{0x01}
59

60
	ErrChainConfigNotFound = errors.New("ChainConfig not found") // general config not found error
61 62

	mipmapBloomMu sync.Mutex // protect against race condition when updating mipmap blooms
63 64 65

	preimageCounter    = metrics.NewCounter("db/preimage/total")
	preimageHitCounter = metrics.NewCounter("db/preimage/hits")
66 67
)

68 69 70 71 72 73 74 75
// 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
}

76 77 78 79 80 81 82
// 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
}

83
// GetCanonicalHash retrieves a hash assigned to a canonical block number.
84
func GetCanonicalHash(db ethdb.Database, number uint64) common.Hash {
85
	data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
86
	if len(data) == 0 {
87
		return common.Hash{}
88 89
	}
	return common.BytesToHash(data)
90 91
}

92 93 94 95 96 97 98 99 100
// 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
func GetBlockNumber(db ethdb.Database, hash common.Hash) uint64 {
	data, _ := db.Get(append(blockHashPrefix, hash.Bytes()...))
	if len(data) != 8 {
101
		return missingNumber
102 103 104 105
	}
	return binary.BigEndian.Uint64(data)
}

106 107 108 109
// 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
110
// light synchronization mechanism.
111
func GetHeadHeaderHash(db ethdb.Database) common.Hash {
112
	data, _ := db.Get(headHeaderKey)
113 114 115 116 117 118
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
}

119
// GetHeadBlockHash retrieves the hash of the current canonical head block.
120
func GetHeadBlockHash(db ethdb.Database) common.Hash {
121
	data, _ := db.Get(headBlockKey)
122 123 124 125 126 127
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
}

128 129 130 131 132 133 134 135 136 137 138 139
// 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.
func GetHeadFastBlockHash(db ethdb.Database) common.Hash {
	data, _ := db.Get(headFastKey)
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
}

140 141
// GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
// if the header's not found.
142 143
func GetHeaderRLP(db ethdb.Database, hash common.Hash, number uint64) rlp.RawValue {
	data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
144 145 146
	return data
}

147 148
// GetHeader retrieves the block header corresponding to the hash, nil if none
// found.
149 150
func GetHeader(db ethdb.Database, hash common.Hash, number uint64) *types.Header {
	data := GetHeaderRLP(db, hash, number)
151 152 153
	if len(data) == 0 {
		return nil
	}
154 155
	header := new(types.Header)
	if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
156
		log.Error("Invalid block header RLP", "hash", hash, "err", err)
157 158
		return nil
	}
159
	return header
160 161
}

162
// GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
163 164
func GetBodyRLP(db ethdb.Database, hash common.Hash, number uint64) rlp.RawValue {
	data, _ := db.Get(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
165
	return data
166 167
}

168 169
// GetBody retrieves the block body (transactons, uncles) corresponding to the
// hash, nil if none found.
170 171
func GetBody(db ethdb.Database, hash common.Hash, number uint64) *types.Body {
	data := GetBodyRLP(db, hash, number)
172 173
	if len(data) == 0 {
		return nil
174
	}
175
	body := new(types.Body)
176
	if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
177
		log.Error("Invalid block body RLP", "hash", hash, "err", err)
178
		return nil
179
	}
180
	return body
181 182
}

183 184
// GetTd retrieves a block's total difficulty corresponding to the hash, nil if
// none found.
185 186
func GetTd(db ethdb.Database, hash common.Hash, number uint64) *big.Int {
	data, _ := db.Get(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash[:]...), tdSuffix...))
187
	if len(data) == 0 {
188
		return nil
189
	}
190 191
	td := new(big.Int)
	if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
192
		log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err)
193 194
		return nil
	}
195
	return td
196 197
}

198
// GetBlock retrieves an entire block corresponding to the hash, assembling it
199 200 201 202 203
// 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).
204
func GetBlock(db ethdb.Database, hash common.Hash, number uint64) *types.Block {
205
	// Retrieve the block header and body contents
206
	header := GetHeader(db, hash, number)
207 208 209
	if header == nil {
		return nil
	}
210
	body := GetBody(db, hash, number)
211
	if body == nil {
212 213
		return nil
	}
214 215
	// Reassemble the block and return
	return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
216 217
}

218 219
// GetBlockReceipts retrieves the receipts generated by the transactions included
// in a block given by its hash.
220 221
func GetBlockReceipts(db ethdb.Database, hash common.Hash, number uint64) types.Receipts {
	data, _ := db.Get(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash[:]...))
222
	if len(data) == 0 {
223
		return nil
224 225 226
	}
	storageReceipts := []*types.ReceiptForStorage{}
	if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
227
		log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
228 229 230 231 232 233 234 235 236
		return nil
	}
	receipts := make(types.Receipts, len(storageReceipts))
	for i, receipt := range storageReceipts {
		receipts[i] = (*types.Receipt)(receipt)
	}
	return receipts
}

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
// GetTxLookupEntry retrieves the positional metadata associated with a transaction
// hash to allow retrieving the transaction or receipt by hash.
func GetTxLookupEntry(db ethdb.Database, hash common.Hash) (common.Hash, uint64, uint64) {
	// 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
}

254 255 256
// GetTransaction retrieves a specific transaction from the database, along with
// its added positional metadata.
func GetTransaction(db ethdb.Database, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
257 258 259 260 261 262 263 264 265 266 267 268
	// 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
269 270 271 272 273 274 275 276 277
	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
278
	data, _ = db.Get(append(hash.Bytes(), oldTxMetaSuffix...))
279 280 281
	if len(data) == 0 {
		return nil, common.Hash{}, 0, 0
	}
282 283
	var entry txLookupEntry
	if err := rlp.DecodeBytes(data, &entry); err != nil {
284 285
		return nil, common.Hash{}, 0, 0
	}
286
	return &tx, entry.BlockHash, entry.BlockIndex, entry.Index
287 288
}

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
// GetReceipt retrieves a specific transaction receipt from the database, along with
// its added positional metadata.
func GetReceipt(db ethdb.Database, hash common.Hash) (*types.Receipt, common.Hash, uint64, uint64) {
	// 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[:]...))
305
	if len(data) == 0 {
306
		return nil, common.Hash{}, 0, 0
307 308 309 310
	}
	var receipt types.ReceiptForStorage
	err := rlp.DecodeBytes(data, &receipt)
	if err != nil {
311
		log.Error("Invalid receipt RLP", "hash", hash, "err", err)
312
	}
313
	return (*types.Receipt)(&receipt), common.Hash{}, 0, 0
314 315
}

316
// WriteCanonicalHash stores the canonical hash for the given block number.
317
func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
318
	key := append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)
319
	if err := db.Put(key, hash.Bytes()); err != nil {
320
		log.Crit("Failed to store number to hash mapping", "err", err)
321
	}
322 323 324
	return nil
}

325
// WriteHeadHeaderHash stores the head header's hash.
326
func WriteHeadHeaderHash(db ethdb.Database, hash common.Hash) error {
327
	if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
328
		log.Crit("Failed to store last header's hash", "err", err)
329
	}
330 331 332 333
	return nil
}

// WriteHeadBlockHash stores the head block's hash.
334
func WriteHeadBlockHash(db ethdb.Database, hash common.Hash) error {
335
	if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
336
		log.Crit("Failed to store last block's hash", "err", err)
337 338 339
	}
	return nil
}
340

341 342 343
// WriteHeadFastBlockHash stores the fast head block's hash.
func WriteHeadFastBlockHash(db ethdb.Database, hash common.Hash) error {
	if err := db.Put(headFastKey, hash.Bytes()); err != nil {
344
		log.Crit("Failed to store last fast block's hash", "err", err)
345 346 347 348
	}
	return nil
}

349
// WriteHeader serializes a block header into the database.
350
func WriteHeader(db ethdb.Database, header *types.Header) error {
351
	data, err := rlp.EncodeToBytes(header)
352 353 354
	if err != nil {
		return err
	}
355 356 357 358 359
	hash := header.Hash().Bytes()
	num := header.Number.Uint64()
	encNum := encodeBlockNumber(num)
	key := append(blockHashPrefix, hash...)
	if err := db.Put(key, encNum); err != nil {
360
		log.Crit("Failed to store hash to number mapping", "err", err)
361 362
	}
	key = append(append(headerPrefix, encNum...), hash...)
363
	if err := db.Put(key, data); err != nil {
364
		log.Crit("Failed to store header", "err", err)
365 366 367
	}
	return nil
}
368

369
// WriteBody serializes the body of a block into the database.
370
func WriteBody(db ethdb.Database, hash common.Hash, number uint64, body *types.Body) error {
371
	data, err := rlp.EncodeToBytes(body)
372 373 374
	if err != nil {
		return err
	}
375 376 377 378 379
	return WriteBodyRLP(db, hash, number, data)
}

// WriteBodyRLP writes a serialized body of a block into the database.
func WriteBodyRLP(db ethdb.Database, hash common.Hash, number uint64, rlp rlp.RawValue) error {
380
	key := append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
381
	if err := db.Put(key, rlp); err != nil {
382
		log.Crit("Failed to store block body", "err", err)
383 384 385 386 387
	}
	return nil
}

// WriteTd serializes the total difficulty of a block into the database.
388
func WriteTd(db ethdb.Database, hash common.Hash, number uint64, td *big.Int) error {
389
	data, err := rlp.EncodeToBytes(td)
390 391
	if err != nil {
		return err
392
	}
393
	key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...)
394
	if err := db.Put(key, data); err != nil {
395
		log.Crit("Failed to store block total difficulty", "err", err)
396 397 398
	}
	return nil
}
399

400
// WriteBlock serializes a block into the database, header and body separately.
401
func WriteBlock(db ethdb.Database, block *types.Block) error {
402
	// Store the body first to retain database consistency
403
	if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
404 405 406 407 408 409
		return err
	}
	// Store the header too, signaling full block ownership
	if err := WriteHeader(db, block.Header()); err != nil {
		return err
	}
410 411
	return nil
}
412

413 414 415
// 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.
416
func WriteBlockReceipts(db ethdb.Database, hash common.Hash, number uint64, receipts types.Receipts) error {
417 418 419 420 421 422 423 424 425 426
	// 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
427 428
	key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
	if err := db.Put(key, bytes); err != nil {
429
		log.Crit("Failed to store block receipts", "err", err)
430 431 432 433
	}
	return nil
}

434 435 436
// 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 {
437 438
	batch := db.NewBatch()

439
	// Iterate over each transaction and encode its metadata
440
	for i, tx := range block.Transactions() {
441
		entry := txLookupEntry{
442 443 444 445
			BlockHash:  block.Hash(),
			BlockIndex: block.NumberU64(),
			Index:      uint64(i),
		}
446
		data, err := rlp.EncodeToBytes(entry)
447 448 449
		if err != nil {
			return err
		}
450
		if err := batch.Put(append(lookupPrefix, tx.Hash().Bytes()...), data); err != nil {
451 452 453 454 455
			return err
		}
	}
	// Write the scheduled data into the database
	if err := batch.Write(); err != nil {
456
		log.Crit("Failed to store lookup entries", "err", err)
457 458 459 460
	}
	return nil
}

461
// DeleteCanonicalHash removes the number to hash canonical mapping.
462
func DeleteCanonicalHash(db ethdb.Database, number uint64) {
463
	db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
464 465
}

466
// DeleteHeader removes all block header data associated with a hash.
467 468 469
func DeleteHeader(db ethdb.Database, hash common.Hash, number uint64) {
	db.Delete(append(blockHashPrefix, hash.Bytes()...))
	db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
470 471 472
}

// DeleteBody removes all block body data associated with a hash.
473 474
func DeleteBody(db ethdb.Database, hash common.Hash, number uint64) {
	db.Delete(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
475 476 477
}

// DeleteTd removes all block total difficulty data associated with a hash.
478 479
func DeleteTd(db ethdb.Database, hash common.Hash, number uint64) {
	db.Delete(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...))
480 481 482
}

// DeleteBlock removes all block data associated with a hash.
483 484 485 486 487
func DeleteBlock(db ethdb.Database, hash common.Hash, number uint64) {
	DeleteBlockReceipts(db, hash, number)
	DeleteHeader(db, hash, number)
	DeleteBody(db, hash, number)
	DeleteTd(db, hash, number)
488 489
}

490
// DeleteBlockReceipts removes all receipt data associated with a block hash.
491 492
func DeleteBlockReceipts(db ethdb.Database, hash common.Hash, number uint64) {
	db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
493 494
}

495 496 497
// DeleteTxLookupEntry removes all transaction data associated with a hash.
func DeleteTxLookupEntry(db ethdb.Database, hash common.Hash) {
	db.Delete(append(lookupPrefix, hash.Bytes()...))
498 499
}

500 501 502 503 504 505 506 507 508 509 510
// returns a formatted MIP mapped key by adding prefix, canonical number and level
//
// ex. fn(98, 1000) = (prefix || 1000 || 0)
func mipmapKey(num, level uint64) []byte {
	lkey := make([]byte, 8)
	binary.BigEndian.PutUint64(lkey, level)
	key := new(big.Int).SetUint64(num / level * level)

	return append(mipmapPre, append(lkey, key.Bytes()...)...)
}

511
// WriteMipmapBloom writes each address included in the receipts' logs to the
512 513
// MIP bloom bin.
func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
514 515 516
	mipmapBloomMu.Lock()
	defer mipmapBloomMu.Unlock()

517 518 519 520 521 522
	batch := db.NewBatch()
	for _, level := range MIPMapLevels {
		key := mipmapKey(number, level)
		bloomDat, _ := db.Get(key)
		bloom := types.BytesToBloom(bloomDat)
		for _, receipt := range receipts {
523
			for _, log := range receipt.Logs {
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
				bloom.Add(log.Address.Big())
			}
		}
		batch.Put(key, bloom.Bytes())
	}
	if err := batch.Write(); err != nil {
		return fmt.Errorf("mipmap write fail for: %d: %v", number, err)
	}
	return nil
}

// GetMipmapBloom returns a bloom filter using the number and level as input
// parameters. For available levels see MIPMapLevels.
func GetMipmapBloom(db ethdb.Database, number, level uint64) types.Bloom {
	bloomDat, _ := db.Get(mipmapKey(number, level))
	return types.BytesToBloom(bloomDat)
}
541

542 543 544 545 546 547 548 549 550 551 552 553 554 555
// 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)
556
			hitCount++
557 558 559 560 561 562 563 564 565 566 567 568
		}
	}
	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
}

569 570 571 572 573 574 575 576 577 578 579 580 581
// GetBlockChainVersion reads the version number from db.
func GetBlockChainVersion(db ethdb.Database) int {
	var vsn uint
	enc, _ := db.Get([]byte("BlockchainVersion"))
	rlp.DecodeBytes(enc, &vsn)
	return int(vsn)
}

// WriteBlockChainVersion writes vsn as the version number to db.
func WriteBlockChainVersion(db ethdb.Database, vsn int) {
	enc, _ := rlp.EncodeToBytes(uint(vsn))
	db.Put([]byte("BlockchainVersion"), enc)
}
582 583

// WriteChainConfig writes the chain config settings to the database.
584
func WriteChainConfig(db ethdb.Database, hash common.Hash, cfg *params.ChainConfig) error {
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
	// 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.
600
func GetChainConfig(db ethdb.Database, hash common.Hash) (*params.ChainConfig, error) {
601 602
	jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
	if len(jsonChainConfig) == 0 {
603
		return nil, ErrChainConfigNotFound
604 605
	}

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

	return &config, nil
}
613 614 615

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