2016-04-14 16:18:24 +00:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-10-19 14:08:17 +00:00
|
|
|
// 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 (
|
|
|
|
"fmt"
|
|
|
|
"math/big"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
common: move big integer math to common/math (#3699)
* common: remove CurrencyToString
Move denomination values to params instead.
* common: delete dead code
* common: move big integer operations to common/math
This commit consolidates all big integer operations into common/math and
adds tests and documentation.
There should be no change in semantics for BigPow, BigMin, BigMax, S256,
U256, Exp and their behaviour is now locked in by tests.
The BigD, BytesToBig and Bytes2Big functions don't provide additional
value, all uses are replaced by new(big.Int).SetBytes().
BigToBytes is now called PaddedBigBytes, its minimum output size
parameter is now specified as the number of bytes instead of bits. The
single use of this function is in the EVM's MSTORE instruction.
Big and String2Big are replaced by ParseBig, which is slightly stricter.
It previously accepted leading zeros for hexadecimal inputs but treated
decimal inputs as octal if a leading zero digit was present.
ParseUint64 is used in places where String2Big was used to decode a
uint64.
The new functions MustParseBig and MustParseUint64 are now used in many
places where parsing errors were previously ignored.
* common: delete unused big integer variables
* accounts/abi: replace uses of BytesToBig with use of encoding/binary
* common: remove BytesToBig
* common: remove Bytes2Big
* common: remove BigTrue
* cmd/utils: add BigFlag and use it for error-checked integer flags
While here, remove environment variable processing for DirectoryFlag
because we don't use it.
* core: add missing error checks in genesis block parser
* common: remove String2Big
* cmd/evm: use utils.BigFlag
* common/math: check for 256 bit overflow in ParseBig
This is supposed to prevent silent overflow/truncation of values in the
genesis block JSON. Without this check, a genesis block that set a
balance larger than 256 bits would lead to weird behaviour in the VM.
* cmd/utils: fixup import
2017-02-26 21:21:51 +00:00
|
|
|
"github.com/ethereum/go-ethereum/common/math"
|
2015-10-19 14:08:17 +00:00
|
|
|
"github.com/ethereum/go-ethereum/core/state"
|
|
|
|
"github.com/ethereum/go-ethereum/core/types"
|
2017-02-22 12:10:07 +00:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2015-10-19 14:08:17 +00:00
|
|
|
"github.com/ethereum/go-ethereum/params"
|
|
|
|
"github.com/ethereum/go-ethereum/pow"
|
|
|
|
"gopkg.in/fatih/set.v0"
|
|
|
|
)
|
|
|
|
|
2015-11-27 14:40:29 +00:00
|
|
|
var (
|
|
|
|
ExpDiffPeriod = big.NewInt(100000)
|
|
|
|
big10 = big.NewInt(10)
|
|
|
|
bigMinus99 = big.NewInt(-99)
|
|
|
|
)
|
|
|
|
|
2015-10-19 14:08:17 +00:00
|
|
|
// BlockValidator is responsible for validating block headers, uncles and
|
|
|
|
// processed state.
|
|
|
|
//
|
|
|
|
// BlockValidator implements Validator.
|
|
|
|
type BlockValidator struct {
|
2016-10-20 11:36:29 +00:00
|
|
|
config *params.ChainConfig // Chain configuration options
|
|
|
|
bc *BlockChain // Canonical block chain
|
|
|
|
Pow pow.PoW // Proof of work used for validating
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewBlockValidator returns a new block validator which is safe for re-use
|
2016-10-20 11:36:29 +00:00
|
|
|
func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, pow pow.PoW) *BlockValidator {
|
2015-10-19 14:08:17 +00:00
|
|
|
validator := &BlockValidator{
|
2016-03-01 22:32:43 +00:00
|
|
|
config: config,
|
|
|
|
Pow: pow,
|
|
|
|
bc: blockchain,
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
return validator
|
|
|
|
}
|
|
|
|
|
|
|
|
// ValidateBlock validates the given block's header and uncles and verifies the
|
|
|
|
// the block header's transaction and uncle roots.
|
|
|
|
//
|
|
|
|
// ValidateBlock does not validate the header's pow. The pow work validated
|
2016-03-15 18:08:18 +00:00
|
|
|
// separately so we can process them in parallel.
|
2015-10-19 14:08:17 +00:00
|
|
|
//
|
|
|
|
// ValidateBlock also validates and makes sure that any previous state (or present)
|
|
|
|
// state that might or might not be present is checked to make sure that fast
|
2016-06-21 04:52:38 +00:00
|
|
|
// sync has done it's job proper. This prevents the block validator from accepting
|
2015-10-19 14:08:17 +00:00
|
|
|
// false positives where a header is present but the state is not.
|
|
|
|
func (v *BlockValidator) ValidateBlock(block *types.Block) error {
|
|
|
|
if v.bc.HasBlock(block.Hash()) {
|
|
|
|
if _, err := state.New(block.Root(), v.bc.chainDb); err == nil {
|
|
|
|
return &KnownBlockError{block.Number(), block.Hash()}
|
|
|
|
}
|
|
|
|
}
|
2016-04-05 13:22:04 +00:00
|
|
|
parent := v.bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
|
2015-10-19 14:08:17 +00:00
|
|
|
if parent == nil {
|
|
|
|
return ParentError(block.ParentHash())
|
|
|
|
}
|
|
|
|
if _, err := state.New(parent.Root(), v.bc.chainDb); err != nil {
|
|
|
|
return ParentError(block.ParentHash())
|
|
|
|
}
|
|
|
|
|
|
|
|
header := block.Header()
|
|
|
|
// validate the block header
|
2016-03-01 22:32:43 +00:00
|
|
|
if err := ValidateHeader(v.config, v.Pow, header, parent.Header(), false, false); err != nil {
|
2015-10-19 14:08:17 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
// verify the uncles are correctly rewarded
|
|
|
|
if err := v.VerifyUncles(block, parent); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Verify UncleHash before running other uncle validations
|
|
|
|
unclesSha := types.CalcUncleHash(block.Uncles())
|
|
|
|
if unclesSha != header.UncleHash {
|
2016-11-23 12:32:25 +00:00
|
|
|
return fmt.Errorf("invalid uncles root hash (remote: %x local: %x)", header.UncleHash, unclesSha)
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
|
|
|
|
// can be used by light clients to make sure they've received the correct Txs
|
|
|
|
txSha := types.DeriveSha(block.Transactions())
|
|
|
|
if txSha != header.TxHash {
|
2016-11-23 12:32:25 +00:00
|
|
|
return fmt.Errorf("invalid transaction root hash (remote: %x local: %x)", header.TxHash, txSha)
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ValidateState validates the various changes that happen after a state
|
|
|
|
// transition, such as amount of used gas, the receipt roots and the state root
|
2016-03-15 18:08:18 +00:00
|
|
|
// itself. ValidateState returns a database batch if the validation was a success
|
2015-10-19 14:08:17 +00:00
|
|
|
// otherwise nil and an error is returned.
|
|
|
|
func (v *BlockValidator) ValidateState(block, parent *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas *big.Int) (err error) {
|
|
|
|
header := block.Header()
|
|
|
|
if block.GasUsed().Cmp(usedGas) != 0 {
|
2016-11-23 12:32:25 +00:00
|
|
|
return ValidationError(fmt.Sprintf("invalid gas used (remote: %v local: %v)", block.GasUsed(), usedGas))
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
// Validate the received block's bloom with the one derived from the generated receipts.
|
|
|
|
// For valid blocks this should always validate to true.
|
|
|
|
rbloom := types.CreateBloom(receipts)
|
|
|
|
if rbloom != header.Bloom {
|
2016-11-23 12:32:25 +00:00
|
|
|
return fmt.Errorf("invalid bloom (remote: %x local: %x)", header.Bloom, rbloom)
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
|
|
|
|
receiptSha := types.DeriveSha(receipts)
|
|
|
|
if receiptSha != header.ReceiptHash {
|
2016-11-23 12:32:25 +00:00
|
|
|
return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
// Validate the state root against the received state root and throw
|
|
|
|
// an error if they don't match.
|
2016-10-20 11:36:29 +00:00
|
|
|
if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
|
2016-11-23 12:32:25 +00:00
|
|
|
return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// VerifyUncles verifies the given block's uncles and applies the Ethereum
|
|
|
|
// consensus rules to the various block headers included; it will return an
|
|
|
|
// error if any of the included uncle headers were invalid. It returns an error
|
|
|
|
// if the validation failed.
|
|
|
|
func (v *BlockValidator) VerifyUncles(block, parent *types.Block) error {
|
2016-06-21 04:52:38 +00:00
|
|
|
// validate that there are at most 2 uncles included in this block
|
2015-10-19 14:08:17 +00:00
|
|
|
if len(block.Uncles()) > 2 {
|
|
|
|
return ValidationError("Block can only contain maximum 2 uncles (contained %v)", len(block.Uncles()))
|
|
|
|
}
|
|
|
|
|
|
|
|
uncles := set.New()
|
|
|
|
ancestors := make(map[common.Hash]*types.Block)
|
|
|
|
for _, ancestor := range v.bc.GetBlocksFromHash(block.ParentHash(), 7) {
|
|
|
|
ancestors[ancestor.Hash()] = ancestor
|
|
|
|
// Include ancestors uncles in the uncle set. Uncles must be unique.
|
|
|
|
for _, uncle := range ancestor.Uncles() {
|
|
|
|
uncles.Add(uncle.Hash())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ancestors[block.Hash()] = block
|
|
|
|
uncles.Add(block.Hash())
|
|
|
|
|
|
|
|
for i, uncle := range block.Uncles() {
|
|
|
|
hash := uncle.Hash()
|
|
|
|
if uncles.Has(hash) {
|
|
|
|
// Error not unique
|
|
|
|
return UncleError("uncle[%d](%x) not unique", i, hash[:4])
|
|
|
|
}
|
|
|
|
uncles.Add(hash)
|
|
|
|
|
|
|
|
if ancestors[hash] != nil {
|
|
|
|
branch := fmt.Sprintf(" O - %x\n |\n", block.Hash())
|
|
|
|
for h := range ancestors {
|
|
|
|
branch += fmt.Sprintf(" O - %x\n |\n", h)
|
|
|
|
}
|
2017-02-28 11:35:17 +00:00
|
|
|
log.Warn(branch)
|
2015-10-19 14:08:17 +00:00
|
|
|
return UncleError("uncle[%d](%x) is ancestor", i, hash[:4])
|
|
|
|
}
|
|
|
|
|
|
|
|
if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == parent.Hash() {
|
|
|
|
return UncleError("uncle[%d](%x)'s parent is not ancestor (%x)", i, hash[:4], uncle.ParentHash[0:4])
|
|
|
|
}
|
|
|
|
|
2016-03-01 22:32:43 +00:00
|
|
|
if err := ValidateHeader(v.config, v.Pow, uncle, ancestors[uncle.ParentHash].Header(), true, true); err != nil {
|
2015-10-19 14:08:17 +00:00
|
|
|
return ValidationError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, hash[:4], err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ValidateHeader validates the given header and, depending on the pow arg,
|
|
|
|
// checks the proof of work of the given header. Returns an error if the
|
|
|
|
// validation failed.
|
|
|
|
func (v *BlockValidator) ValidateHeader(header, parent *types.Header, checkPow bool) error {
|
|
|
|
// Short circuit if the parent is missing.
|
|
|
|
if parent == nil {
|
|
|
|
return ParentError(header.ParentHash)
|
|
|
|
}
|
2016-06-21 04:52:38 +00:00
|
|
|
// Short circuit if the header's already known or its parent is missing
|
2015-10-19 14:08:17 +00:00
|
|
|
if v.bc.HasHeader(header.Hash()) {
|
|
|
|
return nil
|
|
|
|
}
|
2016-03-01 22:32:43 +00:00
|
|
|
return ValidateHeader(v.config, v.Pow, header, parent, checkPow, false)
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Validates a header. Returns an error if the header is invalid.
|
|
|
|
//
|
|
|
|
// See YP section 4.3.4. "Block Header Validity"
|
2016-10-20 11:36:29 +00:00
|
|
|
func ValidateHeader(config *params.ChainConfig, pow pow.PoW, header *types.Header, parent *types.Header, checkPow, uncle bool) error {
|
2017-01-04 19:17:24 +00:00
|
|
|
if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
|
2015-10-19 14:08:17 +00:00
|
|
|
return fmt.Errorf("Header extra data too long (%d)", len(header.Extra))
|
|
|
|
}
|
|
|
|
|
|
|
|
if uncle {
|
common: move big integer math to common/math (#3699)
* common: remove CurrencyToString
Move denomination values to params instead.
* common: delete dead code
* common: move big integer operations to common/math
This commit consolidates all big integer operations into common/math and
adds tests and documentation.
There should be no change in semantics for BigPow, BigMin, BigMax, S256,
U256, Exp and their behaviour is now locked in by tests.
The BigD, BytesToBig and Bytes2Big functions don't provide additional
value, all uses are replaced by new(big.Int).SetBytes().
BigToBytes is now called PaddedBigBytes, its minimum output size
parameter is now specified as the number of bytes instead of bits. The
single use of this function is in the EVM's MSTORE instruction.
Big and String2Big are replaced by ParseBig, which is slightly stricter.
It previously accepted leading zeros for hexadecimal inputs but treated
decimal inputs as octal if a leading zero digit was present.
ParseUint64 is used in places where String2Big was used to decode a
uint64.
The new functions MustParseBig and MustParseUint64 are now used in many
places where parsing errors were previously ignored.
* common: delete unused big integer variables
* accounts/abi: replace uses of BytesToBig with use of encoding/binary
* common: remove BytesToBig
* common: remove Bytes2Big
* common: remove BigTrue
* cmd/utils: add BigFlag and use it for error-checked integer flags
While here, remove environment variable processing for DirectoryFlag
because we don't use it.
* core: add missing error checks in genesis block parser
* common: remove String2Big
* cmd/evm: use utils.BigFlag
* common/math: check for 256 bit overflow in ParseBig
This is supposed to prevent silent overflow/truncation of values in the
genesis block JSON. Without this check, a genesis block that set a
balance larger than 256 bits would lead to weird behaviour in the VM.
* cmd/utils: fixup import
2017-02-26 21:21:51 +00:00
|
|
|
if header.Time.Cmp(math.MaxBig256) == 1 {
|
2015-10-19 14:08:17 +00:00
|
|
|
return BlockTSTooBigErr
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if header.Time.Cmp(big.NewInt(time.Now().Unix())) == 1 {
|
|
|
|
return BlockFutureErr
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if header.Time.Cmp(parent.Time) != 1 {
|
|
|
|
return BlockEqualTSErr
|
|
|
|
}
|
|
|
|
|
2016-03-01 22:32:43 +00:00
|
|
|
expd := CalcDifficulty(config, header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
|
2015-10-19 14:08:17 +00:00
|
|
|
if expd.Cmp(header.Difficulty) != 0 {
|
2016-11-23 12:32:25 +00:00
|
|
|
return fmt.Errorf("Difficulty check failed for header (remote: %v local: %v)", header.Difficulty, expd)
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
a := new(big.Int).Set(parent.GasLimit)
|
|
|
|
a = a.Sub(a, header.GasLimit)
|
|
|
|
a.Abs(a)
|
|
|
|
b := new(big.Int).Set(parent.GasLimit)
|
|
|
|
b = b.Div(b, params.GasLimitBoundDivisor)
|
|
|
|
if !(a.Cmp(b) < 0) || (header.GasLimit.Cmp(params.MinGasLimit) == -1) {
|
2016-11-23 12:32:25 +00:00
|
|
|
return fmt.Errorf("GasLimit check failed for header (remote: %v local_max: %v)", header.GasLimit, b)
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
num := new(big.Int).Set(parent.Number)
|
|
|
|
num.Sub(header.Number, num)
|
|
|
|
if num.Cmp(big.NewInt(1)) != 0 {
|
|
|
|
return BlockNumberErr
|
|
|
|
}
|
|
|
|
|
|
|
|
if checkPow {
|
|
|
|
// Verify the nonce of the header. Return an error if it's not valid
|
|
|
|
if !pow.Verify(types.NewBlockWithHeader(header)) {
|
|
|
|
return &BlockNonceErr{header.Number, header.Hash(), header.Nonce.Uint64()}
|
|
|
|
}
|
|
|
|
}
|
2016-07-08 17:59:11 +00:00
|
|
|
// If all checks passed, validate the extra-data field for hard forks
|
2016-10-24 08:40:58 +00:00
|
|
|
if err := ValidateDAOHeaderExtraData(config, header); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-18 11:01:54 +00:00
|
|
|
if !uncle && config.EIP150Block != nil && config.EIP150Block.Cmp(header.Number) == 0 {
|
2016-10-20 11:36:29 +00:00
|
|
|
if config.EIP150Hash != (common.Hash{}) && config.EIP150Hash != header.Hash() {
|
|
|
|
return ValidationError("Homestead gas reprice fork hash mismatch: have 0x%x, want 0x%x", header.Hash(), config.EIP150Hash)
|
2016-10-24 08:40:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2015-10-19 14:08:17 +00:00
|
|
|
}
|
2015-11-27 14:40:29 +00:00
|
|
|
|
|
|
|
// CalcDifficulty is the difficulty adjustment algorithm. It returns
|
|
|
|
// the difficulty that a new block should have when created at time
|
|
|
|
// given the parent block's time and difficulty.
|
2016-10-20 11:36:29 +00:00
|
|
|
func CalcDifficulty(config *params.ChainConfig, time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
|
2016-03-01 22:32:43 +00:00
|
|
|
if config.IsHomestead(new(big.Int).Add(parentNumber, common.Big1)) {
|
2015-11-27 14:40:29 +00:00
|
|
|
return calcDifficultyHomestead(time, parentTime, parentNumber, parentDiff)
|
|
|
|
} else {
|
|
|
|
return calcDifficultyFrontier(time, parentTime, parentNumber, parentDiff)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func calcDifficultyHomestead(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
|
|
|
|
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.mediawiki
|
|
|
|
// algorithm:
|
|
|
|
// diff = (parent_diff +
|
|
|
|
// (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
|
|
|
|
// ) + 2^(periodCount - 2)
|
|
|
|
|
|
|
|
bigTime := new(big.Int).SetUint64(time)
|
|
|
|
bigParentTime := new(big.Int).SetUint64(parentTime)
|
|
|
|
|
|
|
|
// holds intermediate values to make the algo easier to read & audit
|
|
|
|
x := new(big.Int)
|
|
|
|
y := new(big.Int)
|
|
|
|
|
|
|
|
// 1 - (block_timestamp -parent_timestamp) // 10
|
|
|
|
x.Sub(bigTime, bigParentTime)
|
|
|
|
x.Div(x, big10)
|
|
|
|
x.Sub(common.Big1, x)
|
|
|
|
|
|
|
|
// max(1 - (block_timestamp - parent_timestamp) // 10, -99)))
|
|
|
|
if x.Cmp(bigMinus99) < 0 {
|
|
|
|
x.Set(bigMinus99)
|
|
|
|
}
|
|
|
|
|
|
|
|
// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
|
|
|
|
y.Div(parentDiff, params.DifficultyBoundDivisor)
|
|
|
|
x.Mul(y, x)
|
|
|
|
x.Add(parentDiff, x)
|
|
|
|
|
|
|
|
// minimum difficulty can ever be (before exponential factor)
|
|
|
|
if x.Cmp(params.MinimumDifficulty) < 0 {
|
2016-05-12 14:58:05 +00:00
|
|
|
x.Set(params.MinimumDifficulty)
|
2015-11-27 14:40:29 +00:00
|
|
|
}
|
|
|
|
|
2016-01-19 22:50:00 +00:00
|
|
|
// for the exponential factor
|
|
|
|
periodCount := new(big.Int).Add(parentNumber, common.Big1)
|
|
|
|
periodCount.Div(periodCount, ExpDiffPeriod)
|
|
|
|
|
2016-03-15 18:08:18 +00:00
|
|
|
// the exponential factor, commonly referred to as "the bomb"
|
2015-11-27 14:40:29 +00:00
|
|
|
// diff = diff + 2^(periodCount - 2)
|
|
|
|
if periodCount.Cmp(common.Big1) > 0 {
|
|
|
|
y.Sub(periodCount, common.Big2)
|
|
|
|
y.Exp(common.Big2, y, nil)
|
|
|
|
x.Add(x, y)
|
|
|
|
}
|
|
|
|
|
|
|
|
return x
|
|
|
|
}
|
|
|
|
|
|
|
|
func calcDifficultyFrontier(time, parentTime uint64, parentNumber, 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 {
|
2016-05-12 14:58:05 +00:00
|
|
|
diff.Set(params.MinimumDifficulty)
|
2015-11-27 14:40:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
periodCount := new(big.Int).Add(parentNumber, common.Big1)
|
|
|
|
periodCount.Div(periodCount, ExpDiffPeriod)
|
|
|
|
if periodCount.Cmp(common.Big1) > 0 {
|
|
|
|
// diff = diff + 2^(periodCount - 2)
|
|
|
|
expDiff := periodCount.Sub(periodCount, common.Big2)
|
|
|
|
expDiff.Exp(common.Big2, expDiff, nil)
|
|
|
|
diff.Add(diff, expDiff)
|
common: move big integer math to common/math (#3699)
* common: remove CurrencyToString
Move denomination values to params instead.
* common: delete dead code
* common: move big integer operations to common/math
This commit consolidates all big integer operations into common/math and
adds tests and documentation.
There should be no change in semantics for BigPow, BigMin, BigMax, S256,
U256, Exp and their behaviour is now locked in by tests.
The BigD, BytesToBig and Bytes2Big functions don't provide additional
value, all uses are replaced by new(big.Int).SetBytes().
BigToBytes is now called PaddedBigBytes, its minimum output size
parameter is now specified as the number of bytes instead of bits. The
single use of this function is in the EVM's MSTORE instruction.
Big and String2Big are replaced by ParseBig, which is slightly stricter.
It previously accepted leading zeros for hexadecimal inputs but treated
decimal inputs as octal if a leading zero digit was present.
ParseUint64 is used in places where String2Big was used to decode a
uint64.
The new functions MustParseBig and MustParseUint64 are now used in many
places where parsing errors were previously ignored.
* common: delete unused big integer variables
* accounts/abi: replace uses of BytesToBig with use of encoding/binary
* common: remove BytesToBig
* common: remove Bytes2Big
* common: remove BigTrue
* cmd/utils: add BigFlag and use it for error-checked integer flags
While here, remove environment variable processing for DirectoryFlag
because we don't use it.
* core: add missing error checks in genesis block parser
* common: remove String2Big
* cmd/evm: use utils.BigFlag
* common/math: check for 256 bit overflow in ParseBig
This is supposed to prevent silent overflow/truncation of values in the
genesis block JSON. Without this check, a genesis block that set a
balance larger than 256 bits would lead to weird behaviour in the VM.
* cmd/utils: fixup import
2017-02-26 21:21:51 +00:00
|
|
|
diff = math.BigMax(diff, params.MinimumDifficulty)
|
2015-11-27 14:40:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return diff
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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.
|
|
|
|
func CalcGasLimit(parent *types.Block) *big.Int {
|
|
|
|
// contrib = (parentGasUsed * 3 / 2) / 1024
|
|
|
|
contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
|
|
|
|
contrib = contrib.Div(contrib, big.NewInt(2))
|
|
|
|
contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)
|
|
|
|
|
|
|
|
// decay = parentGasLimit / 1024 -1
|
|
|
|
decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
|
|
|
|
decay.Sub(decay, big.NewInt(1))
|
|
|
|
|
|
|
|
/*
|
|
|
|
strategy: gasLimit of block-to-mine is set based on parent's
|
|
|
|
gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we
|
|
|
|
increase it, otherwise lower it (or leave it unchanged if it's right
|
|
|
|
at that usage) the amount increased/decreased depends on how far away
|
|
|
|
from parentGasLimit * (2/3) parentGasUsed is.
|
|
|
|
*/
|
|
|
|
gl := new(big.Int).Sub(parent.GasLimit(), decay)
|
|
|
|
gl = gl.Add(gl, contrib)
|
common: move big integer math to common/math (#3699)
* common: remove CurrencyToString
Move denomination values to params instead.
* common: delete dead code
* common: move big integer operations to common/math
This commit consolidates all big integer operations into common/math and
adds tests and documentation.
There should be no change in semantics for BigPow, BigMin, BigMax, S256,
U256, Exp and their behaviour is now locked in by tests.
The BigD, BytesToBig and Bytes2Big functions don't provide additional
value, all uses are replaced by new(big.Int).SetBytes().
BigToBytes is now called PaddedBigBytes, its minimum output size
parameter is now specified as the number of bytes instead of bits. The
single use of this function is in the EVM's MSTORE instruction.
Big and String2Big are replaced by ParseBig, which is slightly stricter.
It previously accepted leading zeros for hexadecimal inputs but treated
decimal inputs as octal if a leading zero digit was present.
ParseUint64 is used in places where String2Big was used to decode a
uint64.
The new functions MustParseBig and MustParseUint64 are now used in many
places where parsing errors were previously ignored.
* common: delete unused big integer variables
* accounts/abi: replace uses of BytesToBig with use of encoding/binary
* common: remove BytesToBig
* common: remove Bytes2Big
* common: remove BigTrue
* cmd/utils: add BigFlag and use it for error-checked integer flags
While here, remove environment variable processing for DirectoryFlag
because we don't use it.
* core: add missing error checks in genesis block parser
* common: remove String2Big
* cmd/evm: use utils.BigFlag
* common/math: check for 256 bit overflow in ParseBig
This is supposed to prevent silent overflow/truncation of values in the
genesis block JSON. Without this check, a genesis block that set a
balance larger than 256 bits would lead to weird behaviour in the VM.
* cmd/utils: fixup import
2017-02-26 21:21:51 +00:00
|
|
|
gl.Set(math.BigMax(gl, params.MinGasLimit))
|
2015-11-27 14:40:29 +00:00
|
|
|
|
2016-03-01 22:32:43 +00:00
|
|
|
// however, if we're now below the target (TargetGasLimit) we increase the
|
2015-11-27 14:40:29 +00:00
|
|
|
// limit as much as we can (parentGasLimit / 1024 -1)
|
2016-03-01 22:32:43 +00:00
|
|
|
if gl.Cmp(params.TargetGasLimit) < 0 {
|
2015-11-27 14:40:29 +00:00
|
|
|
gl.Add(parent.GasLimit(), decay)
|
common: move big integer math to common/math (#3699)
* common: remove CurrencyToString
Move denomination values to params instead.
* common: delete dead code
* common: move big integer operations to common/math
This commit consolidates all big integer operations into common/math and
adds tests and documentation.
There should be no change in semantics for BigPow, BigMin, BigMax, S256,
U256, Exp and their behaviour is now locked in by tests.
The BigD, BytesToBig and Bytes2Big functions don't provide additional
value, all uses are replaced by new(big.Int).SetBytes().
BigToBytes is now called PaddedBigBytes, its minimum output size
parameter is now specified as the number of bytes instead of bits. The
single use of this function is in the EVM's MSTORE instruction.
Big and String2Big are replaced by ParseBig, which is slightly stricter.
It previously accepted leading zeros for hexadecimal inputs but treated
decimal inputs as octal if a leading zero digit was present.
ParseUint64 is used in places where String2Big was used to decode a
uint64.
The new functions MustParseBig and MustParseUint64 are now used in many
places where parsing errors were previously ignored.
* common: delete unused big integer variables
* accounts/abi: replace uses of BytesToBig with use of encoding/binary
* common: remove BytesToBig
* common: remove Bytes2Big
* common: remove BigTrue
* cmd/utils: add BigFlag and use it for error-checked integer flags
While here, remove environment variable processing for DirectoryFlag
because we don't use it.
* core: add missing error checks in genesis block parser
* common: remove String2Big
* cmd/evm: use utils.BigFlag
* common/math: check for 256 bit overflow in ParseBig
This is supposed to prevent silent overflow/truncation of values in the
genesis block JSON. Without this check, a genesis block that set a
balance larger than 256 bits would lead to weird behaviour in the VM.
* cmd/utils: fixup import
2017-02-26 21:21:51 +00:00
|
|
|
gl.Set(math.BigMin(gl, params.TargetGasLimit))
|
2015-11-27 14:40:29 +00:00
|
|
|
}
|
|
|
|
return gl
|
|
|
|
}
|