core: typos and comments improve

1. fix typos
2. methods recevier of struct should be same
3. comments improve

(cherry picked from commit 1ba9795395)
pull/14515/head
changhong 8 years ago committed by Péter Szilágyi
parent 07aae19e5d
commit 17f0b11942
No known key found for this signature in database
GPG Key ID: E9AE538CEDF8293D
  1. 473
      core/blockchain.go
  2. 2
      core/blocks.go
  3. 4
      core/chain_makers.go
  4. 6
      core/database_util.go
  5. 2
      core/events.go
  6. 2
      core/fees.go
  7. 2
      core/genesis.go
  8. 17
      core/headerchain.go
  9. 14
      core/helper_test.go
  10. 103
      core/state_transition.go
  11. 22
      core/tx_pool.go

File diff suppressed because it is too large Load Diff

@ -18,7 +18,7 @@ package core
import "github.com/ethereum/go-ethereum/common" import "github.com/ethereum/go-ethereum/common"
// Set of manually tracked bad hashes (usually hard forks) // BadHashes represent a set of manually tracked bad hashes (usually hard forks)
var BadHashes = map[common.Hash]bool{ var BadHashes = map[common.Hash]bool{
common.HexToHash("05bef30ef572270f654746da22639a7a0c97dd97a7050b9e252391996aaeb689"): true, common.HexToHash("05bef30ef572270f654746da22639a7a0c97dd97a7050b9e252391996aaeb689"): true,
common.HexToHash("7d05d08cbc596a2e5e4f13b80a743e53e09221b5323c3a61946b20873e58583f"): true, common.HexToHash("7d05d08cbc596a2e5e4f13b80a743e53e09221b5323c3a61946b20873e58583f"): true,

@ -98,10 +98,10 @@ func (b *BlockGen) Number() *big.Int {
return new(big.Int).Set(b.header.Number) return new(big.Int).Set(b.header.Number)
} }
// AddUncheckedReceipts forcefully adds a receipts to the block without a // AddUncheckedReceipt forcefully adds a receipts to the block without a
// backing transaction. // backing transaction.
// //
// AddUncheckedReceipts will cause consensus failures when used during real // AddUncheckedReceipt will cause consensus failures when used during real
// chain processing. This is best used in conjunction with raw block insertion. // chain processing. This is best used in conjunction with raw block insertion.
func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) { func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
b.receipts = append(b.receipts, receipt) b.receipts = append(b.receipts, receipt)

@ -64,7 +64,7 @@ var (
oldBlockReceiptsPrefix = []byte("receipts-block-") oldBlockReceiptsPrefix = []byte("receipts-block-")
oldBlockHashPrefix = []byte("block-hash-") // [deprecated by the header/block split, remove eventually] oldBlockHashPrefix = []byte("block-hash-") // [deprecated by the header/block split, remove eventually]
ChainConfigNotFoundErr = errors.New("ChainConfig not found") // general config not found error ErrChainConfigNotFound = errors.New("ChainConfig not found") // general config not found error
mipmapBloomMu sync.Mutex // protect against race condition when updating mipmap blooms mipmapBloomMu sync.Mutex // protect against race condition when updating mipmap blooms
@ -546,7 +546,7 @@ func mipmapKey(num, level uint64) []byte {
return append(mipmapPre, append(lkey, key.Bytes()...)...) return append(mipmapPre, append(lkey, key.Bytes()...)...)
} }
// WriteMapmapBloom writes each address included in the receipts' logs to the // WriteMipmapBloom writes each address included in the receipts' logs to the
// MIP bloom bin. // MIP bloom bin.
func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error { func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
mipmapBloomMu.Lock() mipmapBloomMu.Lock()
@ -638,7 +638,7 @@ func WriteChainConfig(db ethdb.Database, hash common.Hash, cfg *params.ChainConf
func GetChainConfig(db ethdb.Database, hash common.Hash) (*params.ChainConfig, error) { func GetChainConfig(db ethdb.Database, hash common.Hash) (*params.ChainConfig, error) {
jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...)) jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
if len(jsonChainConfig) == 0 { if len(jsonChainConfig) == 0 {
return nil, ChainConfigNotFoundErr return nil, ErrChainConfigNotFound
} }
var config params.ChainConfig var config params.ChainConfig

@ -41,7 +41,7 @@ type NewMinedBlockEvent struct{ Block *types.Block }
// RemovedTransactionEvent is posted when a reorg happens // RemovedTransactionEvent is posted when a reorg happens
type RemovedTransactionEvent struct{ Txs types.Transactions } type RemovedTransactionEvent struct{ Txs types.Transactions }
// RemovedLogEvent is posted when a reorg happens // RemovedLogsEvent is posted when a reorg happens
type RemovedLogsEvent struct{ Logs []*types.Log } type RemovedLogsEvent struct{ Logs []*types.Log }
type ChainEvent struct { type ChainEvent struct {

@ -20,4 +20,4 @@ import (
"math/big" "math/big"
) )
var BlockReward *big.Int = big.NewInt(5e+18) var BlockReward = big.NewInt(5e+18)

@ -133,7 +133,7 @@ func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig
newcfg := genesis.configOrDefault(stored) newcfg := genesis.configOrDefault(stored)
storedcfg, err := GetChainConfig(db, stored) storedcfg, err := GetChainConfig(db, stored)
if err != nil { if err != nil {
if err == ChainConfigNotFoundErr { if err == ErrChainConfigNotFound {
// This case happens if a genesis write was interrupted. // This case happens if a genesis write was interrupted.
log.Warn("Found genesis block without chain config") log.Warn("Found genesis block without chain config")
err = WriteChainConfig(db, stored, newcfg) err = WriteChainConfig(db, stored, newcfg)

@ -201,15 +201,6 @@ func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, er
// header writes should be protected by the parent chain mutex individually. // header writes should be protected by the parent chain mutex individually.
type WhCallback func(*types.Header) error type WhCallback func(*types.Header) error
// InsertHeaderChain attempts to insert the given header chain in to the local
// chain, possibly creating a reorg. If an error is returned, it will return the
// index number of the failing header as well an error describing what went wrong.
//
// The verify parameter can be used to fine tune whether nonce verification
// should be done or not. The reason behind the optional check is because some
// of the header retrieval mechanisms already need to verfy nonces, as well as
// because nonces can be verified sparsely, not needing to check each.
func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) { func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
// Do a sanity check that the provided chain is actually ordered and linked // Do a sanity check that the provided chain is actually ordered and linked
for i := 1; i < len(chain); i++ { for i := 1; i < len(chain); i++ {
@ -257,6 +248,14 @@ func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int)
return 0, nil return 0, nil
} }
// InsertHeaderChain attempts to insert the given header chain in to the local
// chain, possibly creating a reorg. If an error is returned, it will return the
// index number of the failing header as well an error describing what went wrong.
//
// The verify parameter can be used to fine tune whether nonce verification
// should be done or not. The reason behind the optional check is because some
// of the header retrieval mechanisms already need to verfy nonces, as well as
// because nonces can be verified sparsely, not needing to check each.
func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) { func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
// Collect some import statistics to report on // Collect some import statistics to report on
stats := struct{ processed, ignored int }{} stats := struct{ processed, ignored int }{}

@ -21,8 +21,6 @@ import (
"fmt" "fmt"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
// "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
) )
@ -38,24 +36,24 @@ type TestManager struct {
Blocks []*types.Block Blocks []*types.Block
} }
func (s *TestManager) IsListening() bool { func (tm *TestManager) IsListening() bool {
return false return false
} }
func (s *TestManager) IsMining() bool { func (tm *TestManager) IsMining() bool {
return false return false
} }
func (s *TestManager) PeerCount() int { func (tm *TestManager) PeerCount() int {
return 0 return 0
} }
func (s *TestManager) Peers() *list.List { func (tm *TestManager) Peers() *list.List {
return list.New() return list.New()
} }
func (s *TestManager) BlockChain() *BlockChain { func (tm *TestManager) BlockChain() *BlockChain {
return s.blockChain return tm.blockChain
} }
func (tm *TestManager) TxPool() *TxPool { func (tm *TestManager) TxPool() *TxPool {

@ -134,112 +134,113 @@ func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, *big.Int, erro
return ret, gasUsed, err return ret, gasUsed, err
} }
func (self *StateTransition) from() vm.AccountRef { func (st *StateTransition) from() vm.AccountRef {
f := self.msg.From() f := st.msg.From()
if !self.state.Exist(f) { if !st.state.Exist(f) {
self.state.CreateAccount(f) st.state.CreateAccount(f)
} }
return vm.AccountRef(f) return vm.AccountRef(f)
} }
func (self *StateTransition) to() vm.AccountRef { func (st *StateTransition) to() vm.AccountRef {
if self.msg == nil { if st.msg == nil {
return vm.AccountRef{} return vm.AccountRef{}
} }
to := self.msg.To() to := st.msg.To()
if to == nil { if to == nil {
return vm.AccountRef{} // contract creation return vm.AccountRef{} // contract creation
} }
reference := vm.AccountRef(*to) reference := vm.AccountRef(*to)
if !self.state.Exist(*to) { if !st.state.Exist(*to) {
self.state.CreateAccount(*to) st.state.CreateAccount(*to)
} }
return reference return reference
} }
func (self *StateTransition) useGas(amount uint64) error { func (st *StateTransition) useGas(amount uint64) error {
if self.gas < amount { if st.gas < amount {
return vm.ErrOutOfGas return vm.ErrOutOfGas
} }
self.gas -= amount st.gas -= amount
return nil return nil
} }
func (self *StateTransition) buyGas() error { func (st *StateTransition) buyGas() error {
mgas := self.msg.Gas() mgas := st.msg.Gas()
if mgas.BitLen() > 64 { if mgas.BitLen() > 64 {
return vm.ErrOutOfGas return vm.ErrOutOfGas
} }
mgval := new(big.Int).Mul(mgas, self.gasPrice) mgval := new(big.Int).Mul(mgas, st.gasPrice)
var ( var (
state = self.state state = st.state
sender = self.from() sender = st.from()
) )
if state.GetBalance(sender.Address()).Cmp(mgval) < 0 { if state.GetBalance(sender.Address()).Cmp(mgval) < 0 {
return errInsufficientBalanceForGas return errInsufficientBalanceForGas
} }
if err := self.gp.SubGas(mgas); err != nil { if err := st.gp.SubGas(mgas); err != nil {
return err return err
} }
self.gas += mgas.Uint64() st.gas += mgas.Uint64()
self.initialGas.Set(mgas) st.initialGas.Set(mgas)
state.SubBalance(sender.Address(), mgval) state.SubBalance(sender.Address(), mgval)
return nil return nil
} }
func (self *StateTransition) preCheck() error { func (st *StateTransition) preCheck() error {
msg := self.msg msg := st.msg
sender := self.from() sender := st.from()
// Make sure this transaction's nonce is correct // Make sure this transaction's nonce is correct
if msg.CheckNonce() { if msg.CheckNonce() {
if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() { if n := st.state.GetNonce(sender.Address()); n != msg.Nonce() {
return fmt.Errorf("invalid nonce: have %d, expected %d", msg.Nonce(), n) return fmt.Errorf("invalid nonce: have %d, expected %d", msg.Nonce(), n)
} }
} }
return self.buyGas() return st.buyGas()
} }
// TransitionDb will transition the state by applying the current message and returning the result // TransitionDb will transition the state by applying the current message and returning the result
// including the required gas for the operation as well as the used gas. It returns an error if it // including the required gas for the operation as well as the used gas. It returns an error if it
// failed. An error indicates a consensus issue. // failed. An error indicates a consensus issue.
func (self *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, err error) { func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, err error) {
if err = self.preCheck(); err != nil { if err = st.preCheck(); err != nil {
return return
} }
msg := self.msg msg := st.msg
sender := self.from() // err checked in preCheck sender := st.from() // err checked in preCheck
homestead := self.evm.ChainConfig().IsHomestead(self.evm.BlockNumber) homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
contractCreation := msg.To() == nil contractCreation := msg.To() == nil
// Pay intrinsic gas // Pay intrinsic gas
// TODO convert to uint64 // TODO convert to uint64
intrinsicGas := IntrinsicGas(self.data, contractCreation, homestead) intrinsicGas := IntrinsicGas(st.data, contractCreation, homestead)
if intrinsicGas.BitLen() > 64 { if intrinsicGas.BitLen() > 64 {
return nil, nil, nil, vm.ErrOutOfGas return nil, nil, nil, vm.ErrOutOfGas
} }
if err = self.useGas(intrinsicGas.Uint64()); err != nil { if err = st.useGas(intrinsicGas.Uint64()); err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
var ( var (
evm = self.evm evm = st.evm
// vm errors do not effect consensus and are therefor // vm errors do not effect consensus and are therefor
// not assigned to err, except for insufficient balance // not assigned to err, except for insufficient balance
// error. // error.
vmerr error vmerr error
) )
if contractCreation { if contractCreation {
ret, _, self.gas, vmerr = evm.Create(sender, self.data, self.gas, self.value) ret, _, st.gas, vmerr = evm.Create(sender, st.data, st.gas, st.value)
} else { } else {
// Increment the nonce for the next transaction // Increment the nonce for the next transaction
self.state.SetNonce(sender.Address(), self.state.GetNonce(sender.Address())+1) st.state.SetNonce(sender.Address(), st.state.GetNonce(sender.Address())+1)
ret, self.gas, vmerr = evm.Call(sender, self.to().Address(), self.data, self.gas, self.value) ret, st.gas, vmerr = evm.Call(sender, st.to().Address(), st.data, st.gas, st.value)
} }
if vmerr != nil { if vmerr != nil {
log.Debug("VM returned with error", "err", err) log.Debug("VM returned with error", "err", err)
@ -250,33 +251,33 @@ func (self *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *b
return nil, nil, nil, vmerr return nil, nil, nil, vmerr
} }
} }
requiredGas = new(big.Int).Set(self.gasUsed()) requiredGas = new(big.Int).Set(st.gasUsed())
self.refundGas() st.refundGas()
self.state.AddBalance(self.evm.Coinbase, new(big.Int).Mul(self.gasUsed(), self.gasPrice)) st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(st.gasUsed(), st.gasPrice))
return ret, requiredGas, self.gasUsed(), err return ret, requiredGas, st.gasUsed(), err
} }
func (self *StateTransition) refundGas() { func (st *StateTransition) refundGas() {
// Return eth for remaining gas to the sender account, // Return eth for remaining gas to the sender account,
// exchanged at the original rate. // exchanged at the original rate.
sender := self.from() // err already checked sender := st.from() // err already checked
remaining := new(big.Int).Mul(new(big.Int).SetUint64(self.gas), self.gasPrice) remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
self.state.AddBalance(sender.Address(), remaining) st.state.AddBalance(sender.Address(), remaining)
// Apply refund counter, capped to half of the used gas. // Apply refund counter, capped to half of the used gas.
uhalf := remaining.Div(self.gasUsed(), common.Big2) uhalf := remaining.Div(st.gasUsed(), common.Big2)
refund := math.BigMin(uhalf, self.state.GetRefund()) refund := math.BigMin(uhalf, st.state.GetRefund())
self.gas += refund.Uint64() st.gas += refund.Uint64()
self.state.AddBalance(sender.Address(), refund.Mul(refund, self.gasPrice)) st.state.AddBalance(sender.Address(), refund.Mul(refund, st.gasPrice))
// Also return remaining gas to the block gas counter so it is // Also return remaining gas to the block gas counter so it is
// available for the next transaction. // available for the next transaction.
self.gp.AddGas(new(big.Int).SetUint64(self.gas)) st.gp.AddGas(new(big.Int).SetUint64(st.gas))
} }
func (self *StateTransition) gasUsed() *big.Int { func (st *StateTransition) gasUsed() *big.Int {
return new(big.Int).Sub(self.initialGas, new(big.Int).SetUint64(self.gas)) return new(big.Int).Sub(st.initialGas, new(big.Int).SetUint64(st.gas))
} }

@ -209,6 +209,7 @@ func (pool *TxPool) resetState() {
pool.promoteExecutables(currentState) pool.promoteExecutables(currentState)
} }
// Stop stops a TxPool
func (pool *TxPool) Stop() { func (pool *TxPool) Stop() {
pool.events.Unsubscribe() pool.events.Unsubscribe()
close(pool.quit) close(pool.quit)
@ -238,6 +239,7 @@ func (pool *TxPool) SetGasPrice(price *big.Int) {
log.Info("Transaction pool price threshold updated", "price", price) log.Info("Transaction pool price threshold updated", "price", price)
} }
// State returns the state of TxPool
func (pool *TxPool) State() *state.ManagedState { func (pool *TxPool) State() *state.ManagedState {
pool.mu.RLock() pool.mu.RLock()
defer pool.mu.RUnlock() defer pool.mu.RUnlock()
@ -850,22 +852,22 @@ func newTxSet() *txSet {
// contains returns true if the set contains the given transaction hash // contains returns true if the set contains the given transaction hash
// (not thread safe, should be called from a locked environment) // (not thread safe, should be called from a locked environment)
func (self *txSet) contains(hash common.Hash) bool { func (ts *txSet) contains(hash common.Hash) bool {
_, ok := self.txMap[hash] _, ok := ts.txMap[hash]
return ok return ok
} }
// add adds a transaction hash to the set, then removes entries older than txSetDuration // add adds a transaction hash to the set, then removes entries older than txSetDuration
// (not thread safe, should be called from a locked environment) // (not thread safe, should be called from a locked environment)
func (self *txSet) add(hash common.Hash) { func (ts *txSet) add(hash common.Hash) {
self.txMap[hash] = struct{}{} ts.txMap[hash] = struct{}{}
now := time.Now() now := time.Now()
self.txOrd[self.addPtr] = txOrdType{hash: hash, time: now} ts.txOrd[ts.addPtr] = txOrdType{hash: hash, time: now}
self.addPtr++ ts.addPtr++
delBefore := now.Add(-txSetDuration) delBefore := now.Add(-txSetDuration)
for self.delPtr < self.addPtr && self.txOrd[self.delPtr].time.Before(delBefore) { for ts.delPtr < ts.addPtr && ts.txOrd[ts.delPtr].time.Before(delBefore) {
delete(self.txMap, self.txOrd[self.delPtr].hash) delete(ts.txMap, ts.txOrd[ts.delPtr].hash)
delete(self.txOrd, self.delPtr) delete(ts.txOrd, ts.delPtr)
self.delPtr++ ts.delPtr++
} }
} }

Loading…
Cancel
Save