2016-04-14 19:18:24 +03:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-10-19 17:08:17 +03: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-27 00:21:51 +03:00
|
|
|
"github.com/ethereum/go-ethereum/common/math"
|
2015-10-19 17:08:17 +03:00
|
|
|
"github.com/ethereum/go-ethereum/core/state"
|
|
|
|
"github.com/ethereum/go-ethereum/core/types"
|
2017-02-22 15:10:07 +03:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2015-10-19 17:08:17 +03:00
|
|
|
"github.com/ethereum/go-ethereum/params"
|
|
|
|
"github.com/ethereum/go-ethereum/pow"
|
|
|
|
"gopkg.in/fatih/set.v0"
|
|
|
|
)
|
|
|
|
|
2015-11-27 16:40:29 +02:00
|
|
|
var (
|
|
|
|
ExpDiffPeriod = big.NewInt(100000)
|
|
|
|
big10 = big.NewInt(10)
|
|
|
|
bigMinus99 = big.NewInt(-99)
|
|
|
|
)
|
|
|
|
|
2015-10-19 17:08:17 +03:00
|
|
|
// BlockValidator is responsible for validating block headers, uncles and
|
|
|
|
// processed state.
|
|
|
|
//
|
|
|
|
// BlockValidator implements Validator.
|
|
|
|
type BlockValidator struct {
|
2016-10-20 14:36:29 +03:00
|
|
|
config *params.ChainConfig // Chain configuration options
|
|
|
|
bc *BlockChain // Canonical block chain
|
|
|
|
Pow pow.PoW // Proof of work used for validating
|
2015-10-19 17:08:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewBlockValidator returns a new block validator which is safe for re-use
|
2016-10-20 14:36:29 +03:00
|
|
|
func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, pow pow.PoW) *BlockValidator {
|
2015-10-19 17:08:17 +03:00
|
|
|
validator := &BlockValidator{
|
2016-03-02 00:32:43 +02:00
|
|
|
config: config,
|
|
|
|
Pow: pow,
|
|
|
|
bc: blockchain,
|
2015-10-19 17:08:17 +03: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 20:08:18 +02:00
|
|
|
// separately so we can process them in parallel.
|
2015-10-19 17:08:17 +03: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 07:52:38 +03:00
|
|
|
// sync has done it's job proper. This prevents the block validator from accepting
|
2015-10-19 17:08:17 +03: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 16:22:04 +03:00
|
|
|
parent := v.bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
|
2015-10-19 17:08:17 +03: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-02 00:32:43 +02:00
|
|
|
if err := ValidateHeader(v.config, v.Pow, header, parent.Header(), false, false); err != nil {
|
2015-10-19 17:08:17 +03: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 15:32:25 +03:00
|
|
|
return fmt.Errorf("invalid uncles root hash (remote: %x local: %x)", header.UncleHash, unclesSha)
|
2015-10-19 17:08:17 +03: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 15:32:25 +03:00
|
|
|
return fmt.Errorf("invalid transaction root hash (remote: %x local: %x)", header.TxHash, txSha)
|
2015-10-19 17:08:17 +03: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 20:08:18 +02:00
|
|
|
// itself. ValidateState returns a database batch if the validation was a success
|
2015-10-19 17:08:17 +03: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 15:32:25 +03:00
|
|
|
return ValidationError(fmt.Sprintf("invalid gas used (remote: %v local: %v)", block.GasUsed(), usedGas))
|
2015-10-19 17:08:17 +03: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 15:32:25 +03:00
|
|
|
return fmt.Errorf("invalid bloom (remote: %x local: %x)", header.Bloom, rbloom)
|
2015-10-19 17:08:17 +03:00
|
|
|
}
|
|
|
|
// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
|
|
|
|
receiptSha := types.DeriveSha(receipts)
|
|
|
|
if receiptSha != header.ReceiptHash {
|
2016-11-23 15:32:25 +03:00
|
|
|
return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
|
2015-10-19 17:08:17 +03:00
|
|
|
}
|
|
|
|
// Validate the state root against the received state root and throw
|
|
|
|
// an error if they don't match.
|
2016-10-20 14:36:29 +03:00
|
|
|
if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
|
2016-11-23 15:32:25 +03:00
|
|
|
return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
|
2015-10-19 17:08:17 +03: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 07:52:38 +03:00
|
|
|
// validate that there are at most 2 uncles included in this block
|
2015-10-19 17:08:17 +03: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 14:35:17 +03:00
|
|
|
log.Warn(branch)
|
2015-10-19 17:08:17 +03: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-02 00:32:43 +02:00
|
|
|
if err := ValidateHeader(v.config, v.Pow, uncle, ancestors[uncle.ParentHash].Header(), true, true); err != nil {
|
2015-10-19 17:08:17 +03: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 07:52:38 +03:00
|
|
|
// Short circuit if the header's already known or its parent is missing
|
2015-10-19 17:08:17 +03:00
|
|
|
if v.bc.HasHeader(header.Hash()) {
|
|
|
|
return nil
|
|
|
|
}
|
2016-03-02 00:32:43 +02:00
|
|
|
return ValidateHeader(v.config, v.Pow, header, parent, checkPow, false)
|
2015-10-19 17:08:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Validates a header. Returns an error if the header is invalid.
|
|
|
|
//
|
|
|
|
// See YP section 4.3.4. "Block Header Validity"
|
2016-10-20 14:36:29 +03:00
|
|
|
func ValidateHeader(config *params.ChainConfig, pow pow.PoW, header *types.Header, parent *types.Header, checkPow, uncle bool) error {
|
2017-01-04 22:17:24 +03:00
|
|
|
if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
|
2015-10-19 17:08:17 +03: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-27 00:21:51 +03:00
|
|
|
if header.Time.Cmp(math.MaxBig256) == 1 {
|
2015-10-19 17:08:17 +03: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-02 00:32:43 +02:00
|
|
|
expd := CalcDifficulty(config, header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
|
2015-10-19 17:08:17 +03:00
|
|
|
if expd.Cmp(header.Difficulty) != 0 {
|
2016-11-23 15:32:25 +03:00
|
|
|
return fmt.Errorf("Difficulty check failed for header (remote: %v local: %v)", header.Difficulty, expd)
|
2015-10-19 17:08:17 +03: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 15:32:25 +03:00
|
|
|
return fmt.Errorf("GasLimit check failed for header (remote: %v local_max: %v)", header.GasLimit, b)
|
2015-10-19 17:08:17 +03: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 20:59:11 +03:00
|
|
|
// If all checks passed, validate the extra-data field for hard forks
|
2016-10-24 11:40:58 +03:00
|
|
|
if err := ValidateDAOHeaderExtraData(config, header); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-18 14:01:54 +03:00
|
|
|
if !uncle && config.EIP150Block != nil && config.EIP150Block.Cmp(header.Number) == 0 {
|
2016-10-20 14:36:29 +03: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 11:40:58 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2015-10-19 17:08:17 +03:00
|
|
|
}
|
2015-11-27 16:40:29 +02: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 14:36:29 +03:00
|
|
|
func CalcDifficulty(config *params.ChainConfig, time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
|
2016-03-02 00:32:43 +02:00
|
|
|
if config.IsHomestead(new(big.Int).Add(parentNumber, common.Big1)) {
|
2015-11-27 16:40:29 +02: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 17:58:05 +03:00
|
|
|
x.Set(params.MinimumDifficulty)
|
2015-11-27 16:40:29 +02:00
|
|
|
}
|
|
|
|
|
2016-01-20 00:50:00 +02:00
|
|
|
// for the exponential factor
|
|
|
|
periodCount := new(big.Int).Add(parentNumber, common.Big1)
|
|
|
|
periodCount.Div(periodCount, ExpDiffPeriod)
|
|
|
|
|
2016-03-15 20:08:18 +02:00
|
|
|
// the exponential factor, commonly referred to as "the bomb"
|
2015-11-27 16:40:29 +02: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 17:58:05 +03:00
|
|
|
diff.Set(params.MinimumDifficulty)
|
2015-11-27 16:40:29 +02: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-27 00:21:51 +03:00
|
|
|
diff = math.BigMax(diff, params.MinimumDifficulty)
|
2015-11-27 16:40:29 +02: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-27 00:21:51 +03:00
|
|
|
gl.Set(math.BigMax(gl, params.MinGasLimit))
|
2015-11-27 16:40:29 +02:00
|
|
|
|
2016-03-02 00:32:43 +02:00
|
|
|
// however, if we're now below the target (TargetGasLimit) we increase the
|
2015-11-27 16:40:29 +02:00
|
|
|
// limit as much as we can (parentGasLimit / 1024 -1)
|
2016-03-02 00:32:43 +02:00
|
|
|
if gl.Cmp(params.TargetGasLimit) < 0 {
|
2015-11-27 16:40:29 +02: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-27 00:21:51 +03:00
|
|
|
gl.Set(math.BigMin(gl, params.TargetGasLimit))
|
2015-11-27 16:40:29 +02:00
|
|
|
}
|
|
|
|
return gl
|
|
|
|
}
|