mirror of https://github.com/ethereum/go-ethereum
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
415 lines
11 KiB
415 lines
11 KiB
10 years ago
|
package core
|
||
11 years ago
|
|
||
|
import (
|
||
|
"bytes"
|
||
11 years ago
|
"container/list"
|
||
10 years ago
|
"errors"
|
||
11 years ago
|
"fmt"
|
||
10 years ago
|
"math/big"
|
||
|
"sync"
|
||
|
"time"
|
||
|
|
||
10 years ago
|
"github.com/ethereum/go-ethereum/core/types"
|
||
10 years ago
|
"github.com/ethereum/go-ethereum/crypto"
|
||
10 years ago
|
"github.com/ethereum/go-ethereum/ethutil"
|
||
|
"github.com/ethereum/go-ethereum/event"
|
||
10 years ago
|
"github.com/ethereum/go-ethereum/logger"
|
||
10 years ago
|
"github.com/ethereum/go-ethereum/state"
|
||
10 years ago
|
"github.com/ethereum/go-ethereum/wire"
|
||
11 years ago
|
)
|
||
|
|
||
10 years ago
|
var statelogger = logger.NewLogger("BLOCK")
|
||
11 years ago
|
|
||
11 years ago
|
type Peer interface {
|
||
|
Inbound() bool
|
||
|
LastSend() time.Time
|
||
|
LastPong() int64
|
||
|
Host() []byte
|
||
|
Port() uint16
|
||
|
Version() string
|
||
11 years ago
|
PingTime() string
|
||
11 years ago
|
Connected() *int32
|
||
10 years ago
|
Caps() *ethutil.Value
|
||
11 years ago
|
}
|
||
|
|
||
11 years ago
|
type EthManager interface {
|
||
10 years ago
|
BlockManager() *BlockManager
|
||
10 years ago
|
ChainManager() *ChainManager
|
||
11 years ago
|
TxPool() *TxPool
|
||
10 years ago
|
Broadcast(msgType wire.MsgType, data []interface{})
|
||
11 years ago
|
PeerCount() int
|
||
|
IsMining() bool
|
||
|
IsListening() bool
|
||
11 years ago
|
Peers() *list.List
|
||
10 years ago
|
KeyManager() *crypto.KeyManager
|
||
10 years ago
|
ClientIdentity() wire.ClientIdentity
|
||
10 years ago
|
Db() ethutil.Database
|
||
10 years ago
|
EventMux() *event.TypeMux
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
type BlockManager struct {
|
||
11 years ago
|
// Mutex for locking the block processor. Blocks can only be handled one at a time
|
||
|
mutex sync.Mutex
|
||
11 years ago
|
// Canonical block chain
|
||
10 years ago
|
bc *ChainManager
|
||
11 years ago
|
// non-persistent key/value memory storage
|
||
|
mem map[string]*big.Int
|
||
11 years ago
|
// Proof of work used for validating
|
||
11 years ago
|
Pow PoW
|
||
11 years ago
|
// The ethereum manager interface
|
||
10 years ago
|
eth EthManager
|
||
11 years ago
|
// The managed states
|
||
11 years ago
|
// Transiently state. The trans state isn't ever saved, validated and
|
||
|
// it could be used for setting account nonces without effecting
|
||
|
// the main states.
|
||
10 years ago
|
transState *state.State
|
||
11 years ago
|
// Mining state. The mining state is used purely and solely by the mining
|
||
|
// operation.
|
||
10 years ago
|
miningState *state.State
|
||
11 years ago
|
|
||
|
// The last attempted block is mainly used for debugging purposes
|
||
|
// This does not have to be a valid block and will be set during
|
||
|
// 'Process' & canonical validation.
|
||
10 years ago
|
lastAttemptedBlock *types.Block
|
||
10 years ago
|
|
||
10 years ago
|
events event.Subscription
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
func NewBlockManager(ethereum EthManager) *BlockManager {
|
||
|
sm := &BlockManager{
|
||
10 years ago
|
mem: make(map[string]*big.Int),
|
||
|
Pow: &EasyPow{},
|
||
|
eth: ethereum,
|
||
10 years ago
|
bc: ethereum.ChainManager(),
|
||
11 years ago
|
}
|
||
10 years ago
|
sm.transState = ethereum.ChainManager().CurrentBlock.State().Copy()
|
||
|
sm.miningState = ethereum.ChainManager().CurrentBlock.State().Copy()
|
||
11 years ago
|
|
||
11 years ago
|
return sm
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
func (self *BlockManager) Start() {
|
||
10 years ago
|
statelogger.Debugln("Starting block manager")
|
||
10 years ago
|
}
|
||
|
|
||
10 years ago
|
func (self *BlockManager) Stop() {
|
||
10 years ago
|
statelogger.Debugln("Stopping state manager")
|
||
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) CurrentState() *state.State {
|
||
10 years ago
|
return sm.eth.ChainManager().CurrentBlock.State()
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) TransState() *state.State {
|
||
11 years ago
|
return sm.transState
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) MiningState() *state.State {
|
||
11 years ago
|
return sm.miningState
|
||
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) NewMiningState() *state.State {
|
||
10 years ago
|
sm.miningState = sm.eth.ChainManager().CurrentBlock.State().Copy()
|
||
11 years ago
|
|
||
|
return sm.miningState
|
||
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) ChainManager() *ChainManager {
|
||
11 years ago
|
return sm.bc
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) TransitionState(statedb *state.State, parent, block *types.Block) (receipts types.Receipts, err error) {
|
||
10 years ago
|
coinbase := statedb.GetOrNewStateObject(block.Coinbase)
|
||
|
coinbase.SetGasPool(block.CalcGasLimit(parent))
|
||
|
|
||
|
// Process the transactions on to current block
|
||
|
receipts, _, _, _, err = sm.ProcessTransactions(coinbase, statedb, block, parent, block.Transactions())
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return receipts, nil
|
||
|
}
|
||
|
|
||
10 years ago
|
func (self *BlockManager) ProcessTransactions(coinbase *state.StateObject, state *state.State, block, parent *types.Block, txs types.Transactions) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
|
||
11 years ago
|
var (
|
||
10 years ago
|
receipts types.Receipts
|
||
|
handled, unhandled types.Transactions
|
||
|
erroneous types.Transactions
|
||
11 years ago
|
totalUsedGas = big.NewInt(0)
|
||
|
err error
|
||
10 years ago
|
cumulativeSum = new(big.Int)
|
||
11 years ago
|
)
|
||
|
|
||
|
done:
|
||
|
for i, tx := range txs {
|
||
10 years ago
|
// If we are mining this block and validating we want to set the logs back to 0
|
||
|
state.EmptyLogs()
|
||
|
|
||
11 years ago
|
txGas := new(big.Int).Set(tx.Gas)
|
||
11 years ago
|
|
||
|
cb := state.GetStateObject(coinbase.Address())
|
||
|
st := NewStateTransition(cb, tx, state, block)
|
||
11 years ago
|
err = st.TransitionState()
|
||
11 years ago
|
if err != nil {
|
||
10 years ago
|
statelogger.Infoln(err)
|
||
11 years ago
|
switch {
|
||
|
case IsNonceErr(err):
|
||
|
err = nil // ignore error
|
||
11 years ago
|
continue
|
||
11 years ago
|
case IsGasLimitErr(err):
|
||
|
unhandled = txs[i:]
|
||
11 years ago
|
|
||
11 years ago
|
break done
|
||
|
default:
|
||
11 years ago
|
statelogger.Infoln(err)
|
||
10 years ago
|
erroneous = append(erroneous, tx)
|
||
11 years ago
|
err = nil
|
||
10 years ago
|
continue
|
||
11 years ago
|
}
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
txGas.Sub(txGas, st.gas)
|
||
10 years ago
|
cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice))
|
||
10 years ago
|
|
||
11 years ago
|
// Update the state with pending changes
|
||
10 years ago
|
state.Update(txGas)
|
||
11 years ago
|
|
||
10 years ago
|
cumulative := new(big.Int).Set(totalUsedGas.Add(totalUsedGas, txGas))
|
||
10 years ago
|
receipt := types.NewReceipt(state.Root(), cumulative)
|
||
|
receipt.SetLogs(state.Logs())
|
||
|
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
|
||
11 years ago
|
|
||
10 years ago
|
// Notify all subscribers
|
||
10 years ago
|
go self.eth.EventMux().Post(TxPostEvent{tx})
|
||
10 years ago
|
|
||
11 years ago
|
receipts = append(receipts, receipt)
|
||
11 years ago
|
handled = append(handled, tx)
|
||
11 years ago
|
|
||
11 years ago
|
if ethutil.Config.Diff && ethutil.Config.DiffType == "all" {
|
||
11 years ago
|
state.CreateOutputForDiff()
|
||
|
}
|
||
11 years ago
|
}
|
||
11 years ago
|
|
||
10 years ago
|
block.Reward = cumulativeSum
|
||
10 years ago
|
block.GasUsed = totalUsedGas
|
||
11 years ago
|
|
||
10 years ago
|
return receipts, handled, unhandled, erroneous, err
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) Process(block *types.Block) (td *big.Int, msgs state.Messages, err error) {
|
||
11 years ago
|
// Processing a blocks may never happen simultaneously
|
||
11 years ago
|
sm.mutex.Lock()
|
||
|
defer sm.mutex.Unlock()
|
||
11 years ago
|
|
||
11 years ago
|
if sm.bc.HasBlock(block.Hash()) {
|
||
10 years ago
|
return nil, nil, &KnownBlockError{block.Number, block.Hash()}
|
||
11 years ago
|
}
|
||
|
|
||
11 years ago
|
if !sm.bc.HasBlock(block.PrevHash) {
|
||
10 years ago
|
return nil, nil, ParentError(block.PrevHash)
|
||
11 years ago
|
}
|
||
10 years ago
|
parent := sm.bc.GetBlock(block.PrevHash)
|
||
|
|
||
|
return sm.ProcessWithParent(block, parent)
|
||
|
}
|
||
11 years ago
|
|
||
10 years ago
|
func (sm *BlockManager) ProcessWithParent(block, parent *types.Block) (td *big.Int, messages state.Messages, err error) {
|
||
11 years ago
|
sm.lastAttemptedBlock = block
|
||
|
|
||
10 years ago
|
state := parent.State().Copy()
|
||
11 years ago
|
|
||
11 years ago
|
// Defer the Undo on the Trie. If the block processing happened
|
||
|
// we don't want to undo but since undo only happens on dirty
|
||
|
// nodes this won't happen because Commit would have been called
|
||
|
// before that.
|
||
11 years ago
|
defer state.Reset()
|
||
11 years ago
|
|
||
11 years ago
|
if ethutil.Config.Diff && ethutil.Config.DiffType == "all" {
|
||
|
fmt.Printf("## %x %x ##\n", block.Hash(), block.Number)
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
_, err = sm.TransitionState(state, parent, block)
|
||
10 years ago
|
if err != nil {
|
||
10 years ago
|
return
|
||
10 years ago
|
}
|
||
|
|
||
10 years ago
|
txSha := types.DeriveSha(block.Transactions())
|
||
10 years ago
|
if bytes.Compare(txSha, block.TxSha) != 0 {
|
||
10 years ago
|
err = fmt.Errorf("validating transaction root. received=%x got=%x", block.TxSha, txSha)
|
||
10 years ago
|
return
|
||
|
}
|
||
10 years ago
|
|
||
10 years ago
|
/*
|
||
10 years ago
|
receiptSha := types.DeriveSha(receipts)
|
||
10 years ago
|
if bytes.Compare(receiptSha, block.ReceiptSha) != 0 {
|
||
|
err = fmt.Errorf("validating receipt root. received=%x got=%x", block.ReceiptSha, receiptSha)
|
||
|
return
|
||
|
}
|
||
|
*/
|
||
10 years ago
|
|
||
11 years ago
|
// Block validation
|
||
10 years ago
|
if err = sm.ValidateBlock(block, parent); err != nil {
|
||
10 years ago
|
return
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
if err = sm.AccumelateRewards(state, block, parent); err != nil {
|
||
10 years ago
|
return
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
/*
|
||
10 years ago
|
//block.receipts = receipts // although this isn't necessary it be in the future
|
||
|
rbloom := types.CreateBloom(receipts)
|
||
10 years ago
|
if bytes.Compare(rbloom, block.LogsBloom) != 0 {
|
||
|
err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
|
||
|
return
|
||
|
}
|
||
|
*/
|
||
10 years ago
|
|
||
10 years ago
|
state.Update(ethutil.Big0)
|
||
10 years ago
|
|
||
11 years ago
|
if !block.State().Cmp(state) {
|
||
10 years ago
|
err = fmt.Errorf("invalid merkle root. received=%x got=%x", block.Root(), state.Root())
|
||
11 years ago
|
return
|
||
11 years ago
|
}
|
||
|
|
||
|
// Calculate the new total difficulty and sync back to the db
|
||
10 years ago
|
if td, ok := sm.CalculateTD(block); ok {
|
||
11 years ago
|
// Sync the current block's state to the database and cancelling out the deferred Undo
|
||
11 years ago
|
state.Sync()
|
||
11 years ago
|
|
||
10 years ago
|
messages := state.Manifest().Messages
|
||
10 years ago
|
state.Manifest().Reset()
|
||
11 years ago
|
|
||
10 years ago
|
chainlogger.Infof("Processed block #%d (%x...)\n", block.Number, block.Hash()[0:4])
|
||
10 years ago
|
|
||
|
sm.transState = state.Copy()
|
||
|
|
||
10 years ago
|
sm.eth.TxPool().RemoveSet(block.Transactions())
|
||
10 years ago
|
|
||
10 years ago
|
return td, messages, nil
|
||
11 years ago
|
} else {
|
||
10 years ago
|
return nil, nil, errors.New("total diff failed")
|
||
11 years ago
|
}
|
||
|
}
|
||
11 years ago
|
|
||
10 years ago
|
func (sm *BlockManager) CalculateTD(block *types.Block) (*big.Int, bool) {
|
||
11 years ago
|
uncleDiff := new(big.Int)
|
||
|
for _, uncle := range block.Uncles {
|
||
|
uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
|
||
|
}
|
||
|
|
||
|
// TD(genesis_block) = 0 and TD(B) = TD(B.parent) + sum(u.difficulty for u in B.uncles) + B.difficulty
|
||
|
td := new(big.Int)
|
||
11 years ago
|
td = td.Add(sm.bc.TD, uncleDiff)
|
||
11 years ago
|
td = td.Add(td, block.Difficulty)
|
||
|
|
||
|
// The new TD will only be accepted if the new difficulty is
|
||
|
// is greater than the previous.
|
||
11 years ago
|
if td.Cmp(sm.bc.TD) > 0 {
|
||
10 years ago
|
return td, true
|
||
11 years ago
|
}
|
||
|
|
||
10 years ago
|
return nil, false
|
||
11 years ago
|
}
|
||
|
|
||
|
// Validates the current block. Returns an error if the block was invalid,
|
||
|
// an uncle or anything that isn't on the current block chain.
|
||
|
// Validation validates easy over difficult (dagger takes longer time = difficult)
|
||
10 years ago
|
func (sm *BlockManager) ValidateBlock(block, parent *types.Block) error {
|
||
10 years ago
|
expd := CalcDifficulty(block, parent)
|
||
|
if expd.Cmp(block.Difficulty) < 0 {
|
||
|
return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
|
||
|
}
|
||
|
|
||
10 years ago
|
diff := block.Time - parent.Time
|
||
11 years ago
|
if diff < 0 {
|
||
11 years ago
|
return ValidationError("Block timestamp less then prev block %v (%v - %v)", diff, block.Time, sm.bc.CurrentBlock.Time)
|
||
11 years ago
|
}
|
||
|
|
||
11 years ago
|
/* XXX
|
||
11 years ago
|
// New blocks must be within the 15 minute range of the last block.
|
||
|
if diff > int64(15*time.Minute) {
|
||
|
return ValidationError("Block is too far in the future of last block (> 15 minutes)")
|
||
|
}
|
||
11 years ago
|
*/
|
||
11 years ago
|
|
||
|
// Verify the nonce of the block. Return an error if it's not valid
|
||
11 years ago
|
if !sm.Pow.Verify(block.HashNoNonce(), block.Difficulty, block.Nonce) {
|
||
11 years ago
|
return ValidationError("Block's nonce is invalid (= %v)", ethutil.Bytes2Hex(block.Nonce))
|
||
11 years ago
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) AccumelateRewards(statedb *state.State, block, parent *types.Block) error {
|
||
10 years ago
|
reward := new(big.Int).Set(BlockReward)
|
||
11 years ago
|
|
||
10 years ago
|
knownUncles := ethutil.Set(parent.Uncles)
|
||
|
nonces := ethutil.NewSet(block.Nonce)
|
||
|
for _, uncle := range block.Uncles {
|
||
|
if nonces.Include(uncle.Nonce) {
|
||
|
// Error not unique
|
||
|
return UncleError("Uncle not unique")
|
||
|
}
|
||
11 years ago
|
|
||
10 years ago
|
uncleParent := sm.bc.GetBlock(uncle.PrevHash)
|
||
|
if uncleParent == nil {
|
||
10 years ago
|
return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.PrevHash[0:4]))
|
||
10 years ago
|
}
|
||
11 years ago
|
|
||
10 years ago
|
if uncleParent.Number.Cmp(new(big.Int).Sub(parent.Number, big.NewInt(6))) < 0 {
|
||
|
return UncleError("Uncle too old")
|
||
|
}
|
||
11 years ago
|
|
||
10 years ago
|
if knownUncles.Include(uncle.Hash()) {
|
||
|
return UncleError("Uncle in chain")
|
||
|
}
|
||
|
|
||
10 years ago
|
nonces.Insert(uncle.Nonce)
|
||
|
|
||
10 years ago
|
r := new(big.Int)
|
||
|
r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
|
||
11 years ago
|
|
||
10 years ago
|
uncleAccount := statedb.GetAccount(uncle.Coinbase)
|
||
10 years ago
|
uncleAccount.AddAmount(r)
|
||
11 years ago
|
|
||
10 years ago
|
reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
|
||
11 years ago
|
}
|
||
11 years ago
|
|
||
10 years ago
|
// Get the account associated with the coinbase
|
||
10 years ago
|
account := statedb.GetAccount(block.Coinbase)
|
||
10 years ago
|
// Reward amount of ether to the coinbase address
|
||
|
account.AddAmount(reward)
|
||
|
|
||
10 years ago
|
statedb.Manifest().AddMessage(&state.Message{
|
||
|
To: block.Coinbase, From: block.Coinbase,
|
||
|
Input: nil,
|
||
|
Origin: nil,
|
||
|
Block: block.Hash(), Timestamp: block.Time, Coinbase: block.Coinbase, Number: block.Number,
|
||
|
Value: new(big.Int).Add(reward, block.Reward),
|
||
|
})
|
||
|
|
||
11 years ago
|
return nil
|
||
|
}
|
||
|
|
||
10 years ago
|
func (sm *BlockManager) GetMessages(block *types.Block) (messages []*state.Message, err error) {
|
||
10 years ago
|
if !sm.bc.HasBlock(block.PrevHash) {
|
||
|
return nil, ParentError(block.PrevHash)
|
||
|
}
|
||
|
|
||
|
sm.lastAttemptedBlock = block
|
||
|
|
||
|
var (
|
||
|
parent = sm.bc.GetBlock(block.PrevHash)
|
||
|
state = parent.State().Copy()
|
||
|
)
|
||
|
|
||
|
defer state.Reset()
|
||
|
|
||
10 years ago
|
sm.TransitionState(state, parent, block)
|
||
10 years ago
|
sm.AccumelateRewards(state, block, parent)
|
||
10 years ago
|
|
||
|
return state.Manifest().Messages, nil
|
||
11 years ago
|
}
|