Skip to content

Commit

Permalink
Merge pull request #3 from xiangjianmeng/master
Browse files Browse the repository at this point in the history
vm code optimize
  • Loading branch information
oakatplatform authored Feb 28, 2019
2 parents 9e588f0 + f4771cf commit 594918e
Show file tree
Hide file tree
Showing 7 changed files with 8 additions and 73 deletions.
2 changes: 2 additions & 0 deletions core/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,6 @@ var (
ErrNonceTooLow = errors.New("nonce too low")

ErrInsufficientBalance = errors.New("insufficient balance for transfer")

errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas")
)
2 changes: 0 additions & 2 deletions core/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,4 @@ func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool {
func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
db.SubBalanceAndWeight(sender, amount)
db.AddBalanceAndWeight(recipient, amount)
//db.SubBalance(sender, amount)
// db.AddBalance(recipient, amount)
}
3 changes: 1 addition & 2 deletions core/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func (h *storageJSON) UnmarshalText(text []byte) error {
}
offset := len(h) - len(text)/2 // pad on the left
if _, err := hex.Decode(h[offset:], text); err != nil {
fmt.Println(err)
coreLogger.Debug(err)
return fmt.Errorf("invalid hex storage key/value %q", text)
}
return nil
Expand Down Expand Up @@ -155,7 +155,6 @@ func SetupGenesisBlock(db database.Database, genesis *Genesis) (*config.ChainCon
// Just commit the new block if there is no stored genesis block.
stored := GetCanonicalHash(db, 0)
if (stored == common.Hash{}) {
//fmt.Println()
if genesis == nil {
log.Info("Writing default main-net genesis block")
genesis = DefaultGenesisBlock()
Expand Down
13 changes: 1 addition & 12 deletions core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package core

import (
"fmt"
"log"
"math/big"

Expand Down Expand Up @@ -57,12 +56,6 @@ func NewStateProcessor(config *config.ChainConfig, bc ChainContext) *StateProces
// Process returns the receipts and logs accumulated during the process. If any of the
// transactions failed to execute it will return an error.
func (p *StateProcessor) Process(block *protos.TxBlock, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
log.SetFlags(log.Lshortfile)
// log.Printf("Process\n")
// var (
// header = block.Header()
// //allLogs []*types.Log
// )
var (
receipts types.Receipts
usedGas = new(uint64)
Expand All @@ -74,14 +67,12 @@ func (p *StateProcessor) Process(block *protos.TxBlock, statedb *state.StateDB,
// Iterate over and process the individual transactions
for i, tx := range block.Body.Transactions {
statedb.Prepare(tx.Hash(), block.Hash(), block.Header.BlockNumber, i)
log.SetFlags(log.Lshortfile)
log.Printf("tx data: %+v\n", tx)
coreLogger.Debugf("tx data: %+v\n", tx)
receipt, gas, err := ApplyTransaction(p.config, p.bc, nil, gp, statedb, header, tx, usedGas, cfg)
if err != nil {
return nil, nil, 0, err
}
// set sharding leader reward according to tx gas used
fmt.Println("----------", p.peer.GetShardId(tx, block.Header.DSBlockNum), len(block.Header.ShardingLeadCoinBase))
statedb.AddBalance(common.BytesToAddress(block.Header.ShardingLeadCoinBase[p.peer.GetShardId(tx, block.Header.DSBlockNum)]), new(big.Int).SetUint64(gas*tx.GasPrice))
receipts = append(receipts, receipt)
allLogs = append(allLogs, receipt.Logs...)
Expand Down Expand Up @@ -123,12 +114,10 @@ func ApplyTransaction(config *config.ChainConfig, bc ChainContext, author *commo

// Apply the transaction to the current state (included in the env)
_, gas, failed, err := ApplyMessage(vmenv, msg, gp)
//err = ApplyMessage(statedb, msg)
if err != nil {
return nil, 0, err
}
// Update the state with pending changes

var root []byte
statedb.Finalise(true)
*usedGas += gas
Expand Down
42 changes: 1 addition & 41 deletions core/state_transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,15 @@
package core

import (
"errors"
"fmt"
"math"
"math/big"

"github.com/ok-chain/okchain/common"
"github.com/ok-chain/okchain/config"
"github.com/ok-chain/okchain/core/state"
"github.com/ok-chain/okchain/core/vm"
logging "github.com/ok-chain/okchain/log"
)

var (
//ErrNonceTooHigh = errors.New("Tx Nonce too high")
//ErrNonceTooLow = errors.New("Tx Nonce too low")
//ErrInsufficientBalance = errors.New("Tx InsufficientBalance error")
errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas")
)
var coreLogger = logging.MustGetLogger("CORE")

/*
Expand Down Expand Up @@ -192,9 +183,6 @@ func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bo
msg := st.msg
sender := vm.AccountRef(msg.From())
contractCreation := msg.To() == nil
coreLogger.Debugf("#########################################")
coreLogger.Debugf("#########################################")
coreLogger.Debugf("#########################################")
coreLogger.Debugf("msg.to:%+v", msg.To())

gas, err := IntrinsicGas(st.data, contractCreation, true)
Expand All @@ -220,7 +208,7 @@ func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bo
ret, st.gas, vmerr = evm.Call(sender, st.to(), st.data, st.gas, st.value)
}
if vmerr != nil {
fmt.Println("VM returned with error", "err", vmerr)
coreLogger.Debug("VM returned with error", "err", vmerr)
// The only possible consensus-error would be if there wasn't
// sufficient balance to make the transfer happen. The first
// balance transfer may never fail.
Expand All @@ -233,34 +221,6 @@ func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bo
return ret, st.gasUsed(), vmerr != nil, err
}

// Call executes the contract associated with the addr with the given input as
// parameters. It also handles any necessary value transfer required and takes
// the necessary steps to create accounts and reverses the state in case of an
// execution error or failed value transfer. XXX, should use EVM to execute transation. EVM to be added.
func Call(state *state.StateDB, from, to common.Address, value *big.Int) (err error) {

// Fail if we're trying to transfer more than the available balance
if !CanTransfer(state, from, value) {
return ErrInsufficientBalance
}

// var (
// snapshot = state.Snapshot()
// )
if !state.Exist(to) {
state.CreateAccount(to)
}
Transfer(state, from, to, value)

// Initialise a new contract and set the code that is to be used by the EVM.

// When an error was returned by the EVM or when setting the creation code
// above we revert to the snapshot. Additionally
// if err != nil {
// state.RevertToSnapshot(snapshot)
// }
return nil
}

func (st *StateTransition) refundGas() {
// Apply refund counter, capped to half of the used gas.
Expand Down
15 changes: 1 addition & 14 deletions core/vm/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,6 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
contract := NewContract(caller, to, value, gas)
contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))

vmLogger.Debugf("******************************************\n")
vmLogger.Debugf("******************************************\n")
vmLogger.Debugf("******************************************\n")
vmLogger.Debugf("******************************************\n")
vmLogger.Debugf("contract codehash: %+v\n", evm.StateDB.GetCodeHash(addr))

start := time.Now()
Expand Down Expand Up @@ -336,13 +332,8 @@ func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.I

contractAddr = crypto.CreateAddress(caller.Address(), nonce)
contractHash := evm.StateDB.GetCodeHash(contractAddr)
vmLogger.Debugf("******************************************\n")
vmLogger.Debugf("******************************************\n")
vmLogger.Debugf("******************************************\n")
vmLogger.Debugf("******************************************\n")
vmLogger.Debugf("contract address: %+v\n", contractAddr)

vmLogger.Debugf("contract address string: %s\n", contractAddr.Hex())
vmLogger.Debugf("contract codehash: %+v\n", contractHash)
vmLogger.Debugf("contract codehash string: %s\n", contractHash.Hex())

if evm.StateDB.GetNonce(contractAddr) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
Expand Down Expand Up @@ -380,8 +371,6 @@ func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.I
// be stored due to not enough gas set an error and let it be handled
// by the error checking condition below.
if err == nil && !maxCodeSizeExceeded {
//_, file, line, _ := runtime.Caller(0)
//fmt.Printf("file: %s, line: %d\n", file, line)
createDataGas := uint64(len(ret)) * config.CreateDataGas
if contract.UseGas(createDataGas) {
evm.StateDB.SetCode(contractAddr, ret)
Expand Down Expand Up @@ -412,9 +401,7 @@ func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.I
evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
}
contractHash = evm.StateDB.GetCodeHash(contractAddr)
vmLogger.Debugf("created contract address: %+v\n", contractAddr)
vmLogger.Debugf("created contract address string: %s\n", contractAddr.Hex())
vmLogger.Debugf("created contract codehash: %+v\n", contractHash)
vmLogger.Debugf("created contract codehash string: %s\n", contractHash.Hex())
return ret, contractAddr, contract.Gas, err
}
Expand Down
4 changes: 2 additions & 2 deletions core/vm/gas_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func gasSStore(gt config.GasTable, evm *EVM, contract *Contract, stack *Stack, m
// 0 => non 0
return config.SstoreSetGas, nil
} else if !common.EmptyHash(val) && common.EmptyHash(common.BigToHash(y)) {
// evm.StateDB.AddRefund(config.SstoreRefundGas)
evm.StateDB.AddRefund(config.SstoreRefundGas)

return config.SstoreClearGas, nil
} else {
Expand Down Expand Up @@ -394,7 +394,7 @@ func gasSuicide(gt config.GasTable, evm *EVM, contract *Contract, stack *Stack,
}

if !evm.StateDB.HasSuicided(contract.Address()) {
// evm.StateDB.AddRefund(config.SuicideRefundGas)
evm.StateDB.AddRefund(config.SuicideRefundGas)
}
return gas, nil
}
Expand Down

0 comments on commit 594918e

Please sign in to comment.