aboutsummaryrefslogtreecommitdiffstats
path: root/core/chain_util.go
diff options
context:
space:
mode:
Diffstat (limited to 'core/chain_util.go')
-rw-r--r--core/chain_util.go258
1 files changed, 213 insertions, 45 deletions
diff --git a/core/chain_util.go b/core/chain_util.go
index 84b462ce3..0e3fa31f9 100644
--- a/core/chain_util.go
+++ b/core/chain_util.go
@@ -19,7 +19,6 @@ package core
import (
"bytes"
"math/big"
- "time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
@@ -30,9 +29,18 @@ import (
)
var (
- blockHashPre = []byte("block-hash-")
- blockNumPre = []byte("block-num-")
+ headHeaderKey = []byte("LastHeader")
+ headBlockKey = []byte("LastBlock")
+
+ blockPrefix = []byte("block-")
+ blockNumPrefix = []byte("block-num-")
+
+ headerSuffix = []byte("-header")
+ bodySuffix = []byte("-body")
+ tdSuffix = []byte("-td")
+
ExpDiffPeriod = big.NewInt(100000)
+ blockHashPre = []byte("block-hash-") // [deprecated by eth/63]
)
// CalcDifficulty is the difficulty adjustment algorithm. It returns
@@ -69,16 +77,6 @@ func CalcDifficulty(time, parentTime uint64, parentNumber, parentDiff *big.Int)
return diff
}
-// CalcTD computes the total difficulty of block.
-func CalcTD(block, parent *types.Block) *big.Int {
- if parent == nil {
- return block.Difficulty()
- }
- d := block.Difficulty()
- d.Add(d, parent.Td)
- return d
-}
-
// CalcGasLimit computes the gas limit of the next block after parent.
// The result may be modified by the caller.
// This is miner strategy, not consensus protocol.
@@ -112,68 +110,238 @@ func CalcGasLimit(parent *types.Block) *big.Int {
return gl
}
-// GetBlockByHash returns the block corresponding to the hash or nil if not found
-func GetBlockByHash(db common.Database, hash common.Hash) *types.Block {
- data, _ := db.Get(append(blockHashPre, hash[:]...))
+// GetCanonicalHash retrieves a hash assigned to a canonical block number.
+func GetCanonicalHash(db common.Database, number uint64) common.Hash {
+ data, _ := db.Get(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
+ if len(data) == 0 {
+ return common.Hash{}
+ }
+ return common.BytesToHash(data)
+}
+
+// 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
+// fast synchronization mechanism.
+func GetHeadHeaderHash(db common.Database) common.Hash {
+ data, _ := db.Get(headHeaderKey)
+ if len(data) == 0 {
+ return common.Hash{}
+ }
+ return common.BytesToHash(data)
+}
+
+// GetHeadBlockHash retrieves the hash of the current canonical head block.
+func GetHeadBlockHash(db common.Database) common.Hash {
+ data, _ := db.Get(headBlockKey)
+ if len(data) == 0 {
+ return common.Hash{}
+ }
+ return common.BytesToHash(data)
+}
+
+// GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
+// if the header's not found.
+func GetHeaderRLP(db common.Database, hash common.Hash) rlp.RawValue {
+ data, _ := db.Get(append(append(blockPrefix, hash[:]...), headerSuffix...))
+ return data
+}
+
+// GetHeader retrieves the block header corresponding to the hash, nil if none
+// found.
+func GetHeader(db common.Database, hash common.Hash) *types.Header {
+ data := GetHeaderRLP(db, hash)
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)
+ 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)
return nil
}
- return (*types.Block)(&block)
+ return header
+}
+
+// GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
+func GetBodyRLP(db common.Database, hash common.Hash) rlp.RawValue {
+ data, _ := db.Get(append(append(blockPrefix, hash[:]...), bodySuffix...))
+ return data
}
-// GetBlockByHash returns the canonical block by number or nil if not found
-func GetBlockByNumber(db common.Database, number uint64) *types.Block {
- key, _ := db.Get(append(blockNumPre, big.NewInt(int64(number)).Bytes()...))
- if len(key) == 0 {
+// GetBody retrieves the block body (transactons, uncles) corresponding to the
+// hash, nil if none found.
+func GetBody(db common.Database, hash common.Hash) *types.Body {
+ data := GetBodyRLP(db, hash)
+ if len(data) == 0 {
+ return nil
+ }
+ body := new(types.Body)
+ 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)
return nil
}
+ return body
+}
- return GetBlockByHash(db, common.BytesToHash(key))
+// GetTd retrieves a block's total difficulty corresponding to the hash, nil if
+// none found.
+func GetTd(db common.Database, hash common.Hash) *big.Int {
+ data, _ := db.Get(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
+ if len(data) == 0 {
+ return nil
+ }
+ 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)
+ return nil
+ }
+ return td
}
-// WriteCanonNumber writes the canonical hash for the given block
-func WriteCanonNumber(db common.Database, block *types.Block) error {
- key := append(blockNumPre, block.Number().Bytes()...)
- err := db.Put(key, block.Hash().Bytes())
- if err != nil {
+// GetBlock retrieves an entire block corresponding to the hash, assembling it
+// back from the stored header and body.
+func GetBlock(db common.Database, hash common.Hash) *types.Block {
+ // Retrieve the block header and body contents
+ header := GetHeader(db, hash)
+ if header == nil {
+ return nil
+ }
+ body := GetBody(db, hash)
+ if body == nil {
+ return nil
+ }
+ // Reassemble the block and return
+ return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
+}
+
+// WriteCanonicalHash stores the canonical hash for the given block number.
+func WriteCanonicalHash(db common.Database, hash common.Hash, number uint64) error {
+ key := append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...)
+ if err := db.Put(key, hash.Bytes()); err != nil {
+ glog.Fatalf("failed to store number to hash mapping into database: %v", err)
return err
}
return nil
}
-// WriteHead force writes the current head
-func WriteHead(db common.Database, block *types.Block) error {
- err := WriteCanonNumber(db, block)
- if err != nil {
+// WriteHeadHeaderHash stores the head header's hash.
+func WriteHeadHeaderHash(db common.Database, hash common.Hash) error {
+ if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
+ glog.Fatalf("failed to store last header's hash into database: %v", err)
return err
}
- err = db.Put([]byte("LastBlock"), block.Hash().Bytes())
- if err != nil {
+ return nil
+}
+
+// WriteHeadBlockHash stores the head block's hash.
+func WriteHeadBlockHash(db common.Database, hash common.Hash) error {
+ if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
+ glog.Fatalf("failed to store last block's hash into database: %v", err)
return err
}
return nil
}
-// WriteBlock writes a block to the database
-func WriteBlock(db common.Database, block *types.Block) error {
- tstart := time.Now()
+// WriteHeader serializes a block header into the database.
+func WriteHeader(db common.Database, header *types.Header) error {
+ data, err := rlp.EncodeToBytes(header)
+ if err != nil {
+ return err
+ }
+ key := append(append(blockPrefix, header.Hash().Bytes()...), headerSuffix...)
+ 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
+}
- enc, _ := rlp.EncodeToBytes((*types.StorageBlock)(block))
- key := append(blockHashPre, block.Hash().Bytes()...)
- err := db.Put(key, enc)
+// WriteBody serializes the body of a block into the database.
+func WriteBody(db common.Database, hash common.Hash, body *types.Body) error {
+ data, err := rlp.EncodeToBytes(body)
if err != nil {
- glog.Fatal("db write fail:", err)
return err
}
+ 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
+}
- if glog.V(logger.Debug) {
- glog.Infof("wrote block #%v %s. Took %v\n", block.Number(), common.PP(block.Hash().Bytes()), time.Since(tstart))
+// WriteTd serializes the total difficulty of a block into the database.
+func WriteTd(db common.Database, hash common.Hash, td *big.Int) error {
+ data, err := rlp.EncodeToBytes(td)
+ if err != nil {
+ return err
}
+ 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)
+ return err
+ }
+ glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
+ return nil
+}
+// WriteBlock serializes a block into the database, header and body separately.
+func WriteBlock(db common.Database, block *types.Block) error {
+ // Store the body first to retain database consistency
+ if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
+ return err
+ }
+ // Store the header too, signaling full block ownership
+ if err := WriteHeader(db, block.Header()); err != nil {
+ return err
+ }
return nil
}
+
+// DeleteCanonicalHash removes the number to hash canonical mapping.
+func DeleteCanonicalHash(db common.Database, number uint64) {
+ db.Delete(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
+}
+
+// DeleteHeader removes all block header data associated with a hash.
+func DeleteHeader(db common.Database, hash common.Hash) {
+ db.Delete(append(append(blockPrefix, hash.Bytes()...), headerSuffix...))
+}
+
+// DeleteBody removes all block body data associated with a hash.
+func DeleteBody(db common.Database, hash common.Hash) {
+ db.Delete(append(append(blockPrefix, hash.Bytes()...), bodySuffix...))
+}
+
+// DeleteTd removes all block total difficulty data associated with a hash.
+func DeleteTd(db common.Database, hash common.Hash) {
+ db.Delete(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
+}
+
+// DeleteBlock removes all block data associated with a hash.
+func DeleteBlock(db common.Database, hash common.Hash) {
+ DeleteHeader(db, hash)
+ DeleteBody(db, hash)
+ DeleteTd(db, hash)
+}
+
+// [deprecated by eth/63]
+// 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.
+func GetBlockByHashOld(db common.Database, hash common.Hash) *types.Block {
+ data, _ := db.Get(append(blockHashPre, hash[:]...))
+ 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)
+}