aboutsummaryrefslogtreecommitdiffstats
path: root/core/chain_util.go
blob: 4e6665568489fa232ee972f5dec88e07ed4d050b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// Copyright 2015 The go-ethereum Authors
// 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 core

import (
    "bytes"
    "math/big"
    "time"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/logger"
    "github.com/ethereum/go-ethereum/logger/glog"
    "github.com/ethereum/go-ethereum/params"
    "github.com/ethereum/go-ethereum/rlp"
)

var (
    blockHashPre = []byte("block-hash-")
    blockNumPre  = []byte("block-num-")
)

// CalcDifficulty is the difficulty adjustment algorithm. It returns
// the difficulty that a new block b should have when created at time
// given the parent block's time and difficulty.
func CalcDifficulty(time, parentTime uint64, parentDiff *big.Int) *big.Int {
    diff := new(big.Int)
    adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
    bigTime := new(big.Int)
    bigParentTime := new(big.Int)

    bigTime.SetUint64(time)
    bigParentTime.SetUint64(parentTime)

    if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
        diff.Add(parentDiff, adjust)
    } else {
        diff.Sub(parentDiff, adjust)
    }
    if diff.Cmp(params.MinimumDifficulty) < 0 {
        return params.MinimumDifficulty
    }
    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.
func CalcGasLimit(parent *types.Block) *big.Int {
    decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
    contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
    contrib = contrib.Div(contrib, big.NewInt(2))
    contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)

    gl := new(big.Int).Sub(parent.GasLimit(), decay)
    gl = gl.Add(gl, contrib)
    gl = gl.Add(gl, big.NewInt(1))
    gl.Set(common.BigMax(gl, params.MinGasLimit))

    if gl.Cmp(params.GenesisGasLimit) < 0 {
        gl.Add(parent.GasLimit(), decay)
        gl.Set(common.BigMin(gl, params.GenesisGasLimit))
    }
    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[:]...))
    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)
}

// 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 {
        return nil
    }

    return GetBlockByHash(db, common.BytesToHash(key))
}

// WriteHead force writes the current head
func WriteHead(db common.Database, block *types.Block) error {
    key := append(blockNumPre, block.Number().Bytes()...)
    err := db.Put(key, block.Hash().Bytes())
    if err != nil {
        return err
    }
    err = db.Put([]byte("LastBlock"), block.Hash().Bytes())
    if err != nil {
        return err
    }
    return nil
}

// WriteBlock writes a block to the database
func WriteBlock(db common.Database, block *types.Block) error {
    tstart := time.Now()

    enc, _ := rlp.EncodeToBytes((*types.StorageBlock)(block))
    key := append(blockHashPre, block.Hash().Bytes()...)
    err := db.Put(key, enc)
    if err != nil {
        glog.Fatal("db write fail:", err)
        return err
    }

    if glog.V(logger.Debug) {
        glog.Infof("wrote block #%v %s. Took %v\n", block.Number(), common.PP(block.Hash().Bytes()), time.Since(tstart))
    }

    return nil
}