database_util.go 18.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
	"fmt"
24 25 26 27
	"math/big"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
28
	"github.com/ethereum/go-ethereum/ethdb"
29 30 31 32 33
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
	"github.com/ethereum/go-ethereum/rlp"
)

34
var (
35 36
	headHeaderKey = []byte("LastHeader")
	headBlockKey  = []byte("LastBlock")
37
	headFastKey   = []byte("LastFast")
38

39 40 41 42 43 44
	blockPrefix    = []byte("block-")
	blockNumPrefix = []byte("block-num-")

	headerSuffix = []byte("-header")
	bodySuffix   = []byte("-body")
	tdSuffix     = []byte("-td")
45

46 47 48
	txMetaSuffix        = []byte{0x01}
	receiptsPrefix      = []byte("receipts-")
	blockReceiptsPrefix = []byte("receipts-block-")
49 50 51

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

	blockHashPrefix = []byte("block-hash-") // [deprecated by the header/block split, remove eventually]
54 55

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

58
// GetCanonicalHash retrieves a hash assigned to a canonical block number.
59
func GetCanonicalHash(db ethdb.Database, number uint64) common.Hash {
60 61 62 63 64
	data, _ := db.Get(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
65 66
}

67 68 69 70
// 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
71
// light synchronization mechanism.
72
func GetHeadHeaderHash(db ethdb.Database) common.Hash {
73
	data, _ := db.Get(headHeaderKey)
74 75 76 77 78 79
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
}

80
// GetHeadBlockHash retrieves the hash of the current canonical head block.
81
func GetHeadBlockHash(db ethdb.Database) common.Hash {
82
	data, _ := db.Get(headBlockKey)
83 84 85 86 87 88
	if len(data) == 0 {
		return common.Hash{}
	}
	return common.BytesToHash(data)
}

89 90 91 92 93 94 95 96 97 98 99 100
// 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)
}

101 102
// GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
// if the header's not found.
103
func GetHeaderRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
104
	data, _ := db.Get(append(append(blockPrefix, hash[:]...), headerSuffix...))
105 106 107
	return data
}

108 109
// GetHeader retrieves the block header corresponding to the hash, nil if none
// found.
110
func GetHeader(db ethdb.Database, hash common.Hash) *types.Header {
111
	data := GetHeaderRLP(db, hash)
112 113 114
	if len(data) == 0 {
		return nil
	}
115 116 117
	header := new(types.Header)
	if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
		glog.V(logger.Error).Infof("invalid block header RLP for hash %x: %v", hash, err)
118 119
		return nil
	}
120
	return header
121 122
}

123
// GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
124
func GetBodyRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
125 126
	data, _ := db.Get(append(append(blockPrefix, hash[:]...), bodySuffix...))
	return data
127 128
}

129 130
// GetBody retrieves the block body (transactons, uncles) corresponding to the
// hash, nil if none found.
131
func GetBody(db ethdb.Database, hash common.Hash) *types.Body {
132 133 134
	data := GetBodyRLP(db, hash)
	if len(data) == 0 {
		return nil
135
	}
136
	body := new(types.Body)
137 138
	if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
		glog.V(logger.Error).Infof("invalid block body RLP for hash %x: %v", hash, err)
139
		return nil
140
	}
141
	return body
142 143
}

144 145
// GetTd retrieves a block's total difficulty corresponding to the hash, nil if
// none found.
146
func GetTd(db ethdb.Database, hash common.Hash) *big.Int {
147 148
	data, _ := db.Get(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
	if len(data) == 0 {
149 150
		return nil
	}
151 152 153
	td := new(big.Int)
	if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
		glog.V(logger.Error).Infof("invalid block total difficulty RLP for hash %x: %v", hash, err)
154 155
		return nil
	}
156
	return td
157 158
}

159 160
// GetBlock retrieves an entire block corresponding to the hash, assembling it
// back from the stored header and body.
161
func GetBlock(db ethdb.Database, hash common.Hash) *types.Block {
162 163 164 165 166 167 168
	// Retrieve the block header and body contents
	header := GetHeader(db, hash)
	if header == nil {
		return nil
	}
	body := GetBody(db, hash)
	if body == nil {
169 170
		return nil
	}
171 172
	// Reassemble the block and return
	return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
173 174
}

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
// GetBlockReceipts retrieves the receipts generated by the transactions included
// in a block given by its hash.
func GetBlockReceipts(db ethdb.Database, hash common.Hash) types.Receipts {
	data, _ := db.Get(append(blockReceiptsPrefix, hash[:]...))
	if len(data) == 0 {
		return nil
	}
	storageReceipts := []*types.ReceiptForStorage{}
	if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
		glog.V(logger.Error).Infof("invalid receipt array RLP for hash %x: %v", hash, err)
		return nil
	}
	receipts := make(types.Receipts, len(storageReceipts))
	for i, receipt := range storageReceipts {
		receipts[i] = (*types.Receipt)(receipt)
	}
	return receipts
}

// 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) {
	// Retrieve the transaction itself from the database
	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
	data, _ = db.Get(append(hash.Bytes(), txMetaSuffix...))
	if len(data) == 0 {
		return nil, common.Hash{}, 0, 0
	}
	var meta struct {
		BlockHash  common.Hash
		BlockIndex uint64
		Index      uint64
	}
	if err := rlp.DecodeBytes(data, &meta); err != nil {
		return nil, common.Hash{}, 0, 0
	}
	return &tx, meta.BlockHash, meta.BlockIndex, meta.Index
}

// GetReceipt returns a receipt by hash
func GetReceipt(db ethdb.Database, txHash common.Hash) *types.Receipt {
	data, _ := db.Get(append(receiptsPrefix, txHash[:]...))
	if len(data) == 0 {
		return nil
	}
	var receipt types.ReceiptForStorage
	err := rlp.DecodeBytes(data, &receipt)
	if err != nil {
		glog.V(logger.Core).Infoln("GetReceipt err:", err)
	}
	return (*types.Receipt)(&receipt)
}

236
// WriteCanonicalHash stores the canonical hash for the given block number.
237
func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
238
	key := append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...)
239 240
	if err := db.Put(key, hash.Bytes()); err != nil {
		glog.Fatalf("failed to store number to hash mapping into database: %v", err)
241 242
		return err
	}
243 244 245
	return nil
}

246
// WriteHeadHeaderHash stores the head header's hash.
247
func WriteHeadHeaderHash(db ethdb.Database, hash common.Hash) error {
248 249
	if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
		glog.Fatalf("failed to store last header's hash into database: %v", err)
250 251
		return err
	}
252 253 254 255
	return nil
}

// WriteHeadBlockHash stores the head block's hash.
256
func WriteHeadBlockHash(db ethdb.Database, hash common.Hash) error {
257 258
	if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
		glog.Fatalf("failed to store last block's hash into database: %v", err)
259 260 261 262
		return err
	}
	return nil
}
263

264 265 266 267 268 269 270 271 272
// 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 {
		glog.Fatalf("failed to store last fast block's hash into database: %v", err)
		return err
	}
	return nil
}

273
// WriteHeader serializes a block header into the database.
274
func WriteHeader(db ethdb.Database, header *types.Header) error {
275
	data, err := rlp.EncodeToBytes(header)
276 277 278
	if err != nil {
		return err
	}
279
	key := append(append(blockPrefix, header.Hash().Bytes()...), headerSuffix...)
280 281 282 283 284 285 286
	if err := db.Put(key, data); err != nil {
		glog.Fatalf("failed to store header into database: %v", err)
		return err
	}
	glog.V(logger.Debug).Infof("stored header #%v [%x…]", header.Number, header.Hash().Bytes()[:4])
	return nil
}
287

288
// WriteBody serializes the body of a block into the database.
289
func WriteBody(db ethdb.Database, hash common.Hash, body *types.Body) error {
290
	data, err := rlp.EncodeToBytes(body)
291 292 293
	if err != nil {
		return err
	}
294 295 296 297 298 299 300 301 302 303
	key := append(append(blockPrefix, hash.Bytes()...), bodySuffix...)
	if err := db.Put(key, data); err != nil {
		glog.Fatalf("failed to store block body into database: %v", err)
		return err
	}
	glog.V(logger.Debug).Infof("stored block body [%x…]", hash.Bytes()[:4])
	return nil
}

// WriteTd serializes the total difficulty of a block into the database.
304
func WriteTd(db ethdb.Database, hash common.Hash, td *big.Int) error {
305
	data, err := rlp.EncodeToBytes(td)
306 307
	if err != nil {
		return err
308
	}
309 310 311
	key := append(append(blockPrefix, hash.Bytes()...), tdSuffix...)
	if err := db.Put(key, data); err != nil {
		glog.Fatalf("failed to store block total difficulty into database: %v", err)
312 313
		return err
	}
314
	glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
315 316
	return nil
}
317

318
// WriteBlock serializes a block into the database, header and body separately.
319
func WriteBlock(db ethdb.Database, block *types.Block) error {
320
	// Store the body first to retain database consistency
321
	if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
322 323 324 325 326 327
		return err
	}
	// Store the header too, signaling full block ownership
	if err := WriteHeader(db, block.Header()); err != nil {
		return err
	}
328 329
	return nil
}
330

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 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 408 409 410 411 412 413 414 415 416 417 418
// 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.
func WriteBlockReceipts(db ethdb.Database, hash common.Hash, receipts types.Receipts) error {
	// 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
	if err := db.Put(append(blockReceiptsPrefix, hash.Bytes()...), bytes); err != nil {
		glog.Fatalf("failed to store block receipts into database: %v", err)
		return err
	}
	glog.V(logger.Debug).Infof("stored block receipts [%x…]", hash.Bytes()[:4])
	return nil
}

// WriteTransactions stores the transactions associated with a specific block
// into the given database. Beside writing the transaction, the function also
// stores a metadata entry along with the transaction, detailing the position
// of this within the blockchain.
func WriteTransactions(db ethdb.Database, block *types.Block) error {
	batch := db.NewBatch()

	// Iterate over each transaction and encode it with its metadata
	for i, tx := range block.Transactions() {
		// Encode and queue up the transaction for storage
		data, err := rlp.EncodeToBytes(tx)
		if err != nil {
			return err
		}
		if err := batch.Put(tx.Hash().Bytes(), data); err != nil {
			return err
		}
		// Encode and queue up the transaction metadata for storage
		meta := struct {
			BlockHash  common.Hash
			BlockIndex uint64
			Index      uint64
		}{
			BlockHash:  block.Hash(),
			BlockIndex: block.NumberU64(),
			Index:      uint64(i),
		}
		data, err = rlp.EncodeToBytes(meta)
		if err != nil {
			return err
		}
		if err := batch.Put(append(tx.Hash().Bytes(), txMetaSuffix...), data); err != nil {
			return err
		}
	}
	// Write the scheduled data into the database
	if err := batch.Write(); err != nil {
		glog.Fatalf("failed to store transactions into database: %v", err)
		return err
	}
	return nil
}

// WriteReceipts stores a batch of transaction receipts into the database.
func WriteReceipts(db ethdb.Database, receipts types.Receipts) error {
	batch := db.NewBatch()

	// Iterate over all the receipts and queue them for database injection
	for _, receipt := range receipts {
		storageReceipt := (*types.ReceiptForStorage)(receipt)
		data, err := rlp.EncodeToBytes(storageReceipt)
		if err != nil {
			return err
		}
		if err := batch.Put(append(receiptsPrefix, receipt.TxHash.Bytes()...), data); err != nil {
			return err
		}
	}
	// Write the scheduled data into the database
	if err := batch.Write(); err != nil {
		glog.Fatalf("failed to store receipts into database: %v", err)
		return err
	}
	return nil
}

419
// DeleteCanonicalHash removes the number to hash canonical mapping.
420
func DeleteCanonicalHash(db ethdb.Database, number uint64) {
421 422 423
	db.Delete(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
}

424
// DeleteHeader removes all block header data associated with a hash.
425
func DeleteHeader(db ethdb.Database, hash common.Hash) {
426
	db.Delete(append(append(blockPrefix, hash.Bytes()...), headerSuffix...))
427 428 429
}

// DeleteBody removes all block body data associated with a hash.
430
func DeleteBody(db ethdb.Database, hash common.Hash) {
431 432 433 434
	db.Delete(append(append(blockPrefix, hash.Bytes()...), bodySuffix...))
}

// DeleteTd removes all block total difficulty data associated with a hash.
435
func DeleteTd(db ethdb.Database, hash common.Hash) {
436
	db.Delete(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
437 438 439
}

// DeleteBlock removes all block data associated with a hash.
440
func DeleteBlock(db ethdb.Database, hash common.Hash) {
441
	DeleteBlockReceipts(db, hash)
442 443
	DeleteHeader(db, hash)
	DeleteBody(db, hash)
444
	DeleteTd(db, hash)
445 446
}

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
// DeleteBlockReceipts removes all receipt data associated with a block hash.
func DeleteBlockReceipts(db ethdb.Database, hash common.Hash) {
	db.Delete(append(blockReceiptsPrefix, hash.Bytes()...))
}

// DeleteTransaction removes all transaction data associated with a hash.
func DeleteTransaction(db ethdb.Database, hash common.Hash) {
	db.Delete(hash.Bytes())
	db.Delete(append(hash.Bytes(), txMetaSuffix...))
}

// DeleteReceipt removes all receipt data associated with a transaction hash.
func DeleteReceipt(db ethdb.Database, hash common.Hash) {
	db.Delete(append(receiptsPrefix, hash.Bytes()...))
}

// [deprecated by the header/block split, remove eventually]
464 465 466 467
// GetBlockByHashOld returns the old combined block corresponding to the hash
// or nil if not found. This method is only used by the upgrade mechanism to
// access the old combined block representation. It will be dropped after the
// network transitions to eth/63.
468
func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *types.Block {
469
	data, _ := db.Get(append(blockHashPrefix, hash[:]...))
470 471 472 473 474 475 476 477 478 479
	if len(data) == 0 {
		return nil
	}
	var block types.StorageBlock
	if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
		glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
		return nil
	}
	return (*types.Block)(&block)
}
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500

// 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()...)...)
}

// WriteMapmapBloom writes each address included in the receipts' logs to the
// MIP bloom bin.
func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
	batch := db.NewBatch()
	for _, level := range MIPMapLevels {
		key := mipmapKey(number, level)
		bloomDat, _ := db.Get(key)
		bloom := types.BytesToBloom(bloomDat)
		for _, receipt := range receipts {
501
			for _, log := range receipt.Logs {
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
				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)
}
519 520 521 522 523 524 525 526 527 528 529 530 531 532

// 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)
}
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

// WriteChainConfig writes the chain config settings to the database.
func WriteChainConfig(db ethdb.Database, hash common.Hash, cfg *ChainConfig) error {
	// 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.
func GetChainConfig(db ethdb.Database, hash common.Hash) (*ChainConfig, error) {
	jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
	if len(jsonChainConfig) == 0 {
		return nil, ChainConfigNotFoundErr
	}

	var config ChainConfig
	if err := json.Unmarshal(jsonChainConfig, &config); err != nil {
		return nil, err
	}

	return &config, nil
}