diff --git a/XDCx/order_processor.go b/XDCx/order_processor.go index a950ca43b7887..bd8ae2334e9e0 100644 --- a/XDCx/order_processor.go +++ b/XDCx/order_processor.go @@ -7,6 +7,7 @@ import ( "time" "github.com/XinFinOrg/XDPoSChain/core/types" + "github.com/holiman/uint256" "github.com/XinFinOrg/XDPoSChain/consensus" @@ -591,7 +592,7 @@ func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *tradingsta tradingstate.SetSubRelayerFee(makerOrder.ExchangeAddress, newRelayerMakerFee, common.RelayerFee, statedb) masternodeOwner := statedb.GetOwner(coinbase) - statedb.AddBalance(masternodeOwner, matchingFee) + statedb.AddBalance(masternodeOwner, uint256.MustFromBig(matchingFee)) err = tradingstate.SetTokenBalance(takerOrder.UserAddress, newTakerInTotal, settleBalance.Taker.InToken, statedb) if err != nil { @@ -680,13 +681,13 @@ func (XDCx *XDCX) ProcessCancelOrder(header *types.Header, tradingStateDB *tradi } masternodeOwner := statedb.GetOwner(coinbase) // relayers pay XDC for masternode - statedb.AddBalance(masternodeOwner, common.RelayerCancelFee) + statedb.AddBalance(masternodeOwner, uint256.MustFromBig(common.RelayerCancelFee)) relayerOwner := tradingstate.GetRelayerOwner(originOrder.ExchangeAddress, statedb) switch originOrder.Side { case tradingstate.Ask: // users pay token (which they have) for relayer - err := tradingstate.SubTokenBalance(originOrder.UserAddress, tokenCancelFee, originOrder.BaseToken, statedb) + err := tradingstate.SubTokenBalance(originOrder.UserAddress, uint256.MustFromBig(tokenCancelFee), originOrder.BaseToken, statedb) if err != nil { log.Warn("ProcessCancelOrder SubTokenBalance", "err", err, "originOrder.UserAddress", originOrder.UserAddress, "tokenCancelFee", *tokenCancelFee, "originOrder.BaseToken", originOrder.BaseToken) } @@ -696,7 +697,7 @@ func (XDCx *XDCX) ProcessCancelOrder(header *types.Header, tradingStateDB *tradi } case tradingstate.Bid: // users pay token (which they have) for relayer - err := tradingstate.SubTokenBalance(originOrder.UserAddress, tokenCancelFee, originOrder.QuoteToken, statedb) + err := tradingstate.SubTokenBalance(originOrder.UserAddress, uint256.MustFromBig(tokenCancelFee), originOrder.QuoteToken, statedb) if err != nil { log.Warn("ProcessCancelOrder SubTokenBalance", "err", err, "originOrder.UserAddress", originOrder.UserAddress, "tokenCancelFee", *tokenCancelFee, "originOrder.QuoteToken", originOrder.QuoteToken) } diff --git a/XDCx/tradingstate/relayer_state.go b/XDCx/tradingstate/relayer_state.go index d5b79bf0c0c4d..d52d75055e797 100644 --- a/XDCx/tradingstate/relayer_state.go +++ b/XDCx/tradingstate/relayer_state.go @@ -8,6 +8,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/log" + "github.com/holiman/uint256" "github.com/pkg/errors" ) @@ -139,7 +140,7 @@ func SubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB) } else { balance = new(big.Int).Sub(balance, fee) statedb.SetState(common.HexToAddress(common.RelayerRegistrationSMC), locHashDeposit, common.BigToHash(balance)) - statedb.SubBalance(common.HexToAddress(common.RelayerRegistrationSMC), fee) + statedb.SubBalance(common.HexToAddress(common.RelayerRegistrationSMC), uint256.MustFromBig(fee)) log.Debug("ApplyXDCXMatchedTransaction settle balance: SubRelayerFee AFTER", "relayer", relayer.String(), "balance", balance) return nil } @@ -162,7 +163,7 @@ func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, if token == common.XDCNativeAddressBinary { balance := statedb.GetBalance(addr) log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) - statedb.AddBalance(addr, value) + statedb.AddBalance(addr, uint256.MustFromBig(value)) balance = statedb.GetBalance(addr) log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD XDC NATIVE BALANCE AFTER", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) @@ -184,7 +185,7 @@ func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, } } -func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error { +func SubTokenBalance(addr common.Address, value *uint256.Int, token common.Address, statedb *state.StateDB) error { // XDC native if token == common.XDCNativeAddressBinary { balance := statedb.GetBalance(addr) @@ -204,10 +205,10 @@ func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, locHash := common.BigToHash(GetLocMappingAtKey(addr.Hash(), slot)) balance := statedb.GetState(token, locHash).Big() log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB TOKEN BALANCE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) - if balance.Cmp(value) < 0 { + if balance.Cmp(value.ToBig()) < 0 { return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), token.String(), balance, value) } - balance = new(big.Int).Sub(balance, value) + balance = new(big.Int).Sub(balance, value.ToBig()) statedb.SetState(token, locHash, common.BigToHash(balance)) log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB TOKEN BALANCE AFTER", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) return nil @@ -223,7 +224,7 @@ func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Addr if value := mapBalances[token][addr]; value != nil { balance = value } else { - balance = statedb.GetBalance(addr) + balance = statedb.GetBalance(addr).ToBig() } if balance.Cmp(value) < 0 { return nil, errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), token.String(), balance, value) @@ -260,7 +261,7 @@ func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Addr if value := mapBalances[token][addr]; value != nil { balance = value } else { - balance = statedb.GetBalance(addr) + balance = statedb.GetBalance(addr).ToBig() } newBalance := new(big.Int).Add(balance, value) log.Debug("CheckAddTokenBalance settle balance: ADD XDC NATIVE BALANCE ", "token", token.String(), "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance) @@ -308,7 +309,7 @@ func CheckSubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.Sta func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int { // XDC native if token == common.XDCNativeAddressBinary { - return statedb.GetBalance(addr) + return statedb.GetBalance(addr).ToBig() } // TRC tokens if statedb.Exist(token) { @@ -323,7 +324,7 @@ func GetTokenBalance(addr common.Address, token common.Address, statedb *state.S func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error { // XDC native if token == common.XDCNativeAddressBinary { - statedb.SetBalance(addr, balance) + statedb.SetBalance(addr, uint256.MustFromBig(balance)) return nil } @@ -344,5 +345,5 @@ func SetSubRelayerFee(relayer common.Address, balance *big.Int, fee *big.Int, st locBigDeposit := new(big.Int).SetUint64(uint64(0)).Add(locBig, RelayerStructMappingSlot["_deposit"]) locHashDeposit := common.BigToHash(locBigDeposit) statedb.SetState(common.HexToAddress(common.RelayerRegistrationSMC), locHashDeposit, common.BigToHash(balance)) - statedb.SubBalance(common.HexToAddress(common.RelayerRegistrationSMC), fee) + statedb.SubBalance(common.HexToAddress(common.RelayerRegistrationSMC), uint256.MustFromBig(fee)) } diff --git a/XDCxlending/lendingstate/relayer.go b/XDCxlending/lendingstate/relayer.go index e7ca282d1b175..3c29ea29efd9c 100644 --- a/XDCxlending/lendingstate/relayer.go +++ b/XDCxlending/lendingstate/relayer.go @@ -8,6 +8,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/log" + "github.com/holiman/uint256" "github.com/pkg/errors" ) @@ -91,7 +92,7 @@ func SubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB) } else { balance = new(big.Int).Sub(balance, fee) statedb.SetState(common.HexToAddress(common.RelayerRegistrationSMC), locHashDeposit, common.BigToHash(balance)) - statedb.SubBalance(common.HexToAddress(common.RelayerRegistrationSMC), fee) + statedb.SubBalance(common.HexToAddress(common.RelayerRegistrationSMC), uint256.MustFromBig(fee)) log.Debug("ApplyXDCXMatchedTransaction settle balance: SubRelayerFee AFTER", "relayer", relayer.String(), "balance", balance) return nil } @@ -114,7 +115,7 @@ func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, if token == common.XDCNativeAddressBinary { balance := statedb.GetBalance(addr) log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) - statedb.AddBalance(addr, value) + statedb.AddBalance(addr, uint256.MustFromBig(value)) balance = statedb.GetBalance(addr) log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD XDC NATIVE BALANCE AFTER", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) @@ -141,10 +142,10 @@ func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, if token == common.XDCNativeAddressBinary { balance := statedb.GetBalance(addr) log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE BEFORE", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) - if balance.Cmp(value) < 0 { + if balance.Cmp(uint256.MustFromBig(value)) < 0 { return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), common.XDCNativeAddress, balance, value) } - statedb.SubBalance(addr, value) + statedb.SubBalance(addr, uint256.MustFromBig(value)) balance = statedb.GetBalance(addr) log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE AFTER", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) @@ -176,7 +177,7 @@ func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Addr if value := mapBalances[token][addr]; value != nil { balance = value } else { - balance = statedb.GetBalance(addr) + balance = statedb.GetBalance(addr).ToBig() } if balance.Cmp(value) < 0 { return nil, errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), common.XDCNativeAddress, balance, value) @@ -213,7 +214,7 @@ func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Addr if value := mapBalances[token][addr]; value != nil { balance = value } else { - balance = statedb.GetBalance(addr) + balance = statedb.GetBalance(addr).ToBig() } newBalance := new(big.Int).Add(balance, value) log.Debug("CheckAddTokenBalance settle balance: ADD XDC NATIVE BALANCE ", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance) @@ -261,7 +262,7 @@ func CheckSubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.Sta func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int { // XDC native if token == common.XDCNativeAddressBinary { - return statedb.GetBalance(addr) + return statedb.GetBalance(addr).ToBig() } // TRC tokens if statedb.Exist(token) { @@ -276,7 +277,7 @@ func GetTokenBalance(addr common.Address, token common.Address, statedb *state.S func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error { // XDC native if token == common.XDCNativeAddressBinary { - statedb.SetBalance(addr, balance) + statedb.SetBalance(addr, uint256.MustFromBig(balance)) return nil } @@ -297,5 +298,5 @@ func SetSubRelayerFee(relayer common.Address, balance *big.Int, fee *big.Int, st locBigDeposit := new(big.Int).SetUint64(uint64(0)).Add(locBig, RelayerStructMappingSlot["_deposit"]) locHashDeposit := common.BigToHash(locBigDeposit) statedb.SetState(common.HexToAddress(common.RelayerRegistrationSMC), locHashDeposit, common.BigToHash(balance)) - statedb.SubBalance(common.HexToAddress(common.RelayerRegistrationSMC), fee) + statedb.SubBalance(common.HexToAddress(common.RelayerRegistrationSMC), uint256.MustFromBig(fee)) } diff --git a/XDCxlending/order_processor.go b/XDCxlending/order_processor.go index 0a41347acdb86..5759b0116103c 100644 --- a/XDCxlending/order_processor.go +++ b/XDCxlending/order_processor.go @@ -13,6 +13,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/log" + "github.com/holiman/uint256" ) func (l *Lending) CommitOrder(header *types.Header, coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, lendingStateDB *lendingstate.LendingStateDB, tradingStateDb *tradingstate.TradingStateDB, lendingOrderBook common.Hash, order *lendingstate.LendingItem) ([]*lendingstate.LendingTrade, []*lendingstate.LendingItem, error) { @@ -670,7 +671,7 @@ func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *lendingsta mapBalances[settleBalance.Maker.OutToken][common.LendingLockAddressBinary] = newCollateralTokenLock } masternodeOwner := statedb.GetOwner(coinbase) - statedb.AddBalance(masternodeOwner, matchingFee) + statedb.AddBalance(masternodeOwner, uint256.MustFromBig(matchingFee)) for token, balances := range mapBalances { for adrr, value := range balances { err := lendingstate.SetTokenBalance(adrr, value, token, statedb) @@ -747,7 +748,7 @@ func (l *Lending) ProcessCancelOrder(header *types.Header, lendingStateDB *lendi // relayers pay XDC for masternode lendingstate.SubRelayerFee(originOrder.Relayer, common.RelayerLendingCancelFee, statedb) masternodeOwner := statedb.GetOwner(coinbase) - statedb.AddBalance(masternodeOwner, common.RelayerLendingCancelFee) + statedb.AddBalance(masternodeOwner, uint256.MustFromBig(common.RelayerLendingCancelFee)) relayerOwner := lendingstate.GetRelayerOwner(originOrder.Relayer, statedb) switch originOrder.Side { case lendingstate.Investing: diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index bbc8f4373ffda..024f08dda4091 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -49,6 +49,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/event" "github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/rpc" + "github.com/holiman/uint256" ) // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend. @@ -216,7 +217,7 @@ func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Addres return nil, errBlockNumberUnsupported } statedb, _ := b.blockchain.State() - return statedb.GetBalance(contract), nil + return statedb.GetBalance(contract).ToBig(), nil } // NonceAt returns the nonce of a certain account in the blockchain. @@ -461,7 +462,7 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call XDPoSChain.Cal } // Set infinite balance to the fake caller account. from := statedb.GetOrNewStateObject(call.From) - from.SetBalance(math.MaxBig256) + from.SetBalance(uint256.MustFromBig(math.MaxBig256)) // Execute the call. msg := callMsg{call} feeCapacity := state.GetTRC21FeeCapacityFromState(statedb) diff --git a/cmd/puppeth/genesis.go b/cmd/puppeth/genesis.go index 6aef1cf27e762..60c34ff8c326f 100644 --- a/cmd/puppeth/genesis.go +++ b/cmd/puppeth/genesis.go @@ -113,7 +113,7 @@ func newCppEthereumGenesisSpec(network string, genesis *core.Genesis) (*cppEther spec.Params.DifficultyBoundDivisor = (*hexutil.Big)(params.DifficultyBoundDivisor) spec.Params.GasLimitBoundDivisor = (hexutil.Uint64)(params.GasLimitBoundDivisor) spec.Params.DurationLimit = (*hexutil.Big)(params.DurationLimit) - spec.Params.BlockReward = (*hexutil.Big)(ethash.FrontierBlockReward) + spec.Params.BlockReward = (*hexutil.Big)(ethash.FrontierBlockReward.ToBig()) spec.Genesis.Nonce = (hexutil.Bytes)(make([]byte, 8)) binary.LittleEndian.PutUint64(spec.Genesis.Nonce[:], genesis.Nonce) @@ -271,13 +271,13 @@ func newParityChainSpec(network string, genesis *core.Genesis, bootnodes []strin spec.Engine.Ethash.Params.MinimumDifficulty = (*hexutil.Big)(params.MinimumDifficulty) spec.Engine.Ethash.Params.DifficultyBoundDivisor = (*hexutil.Big)(params.DifficultyBoundDivisor) spec.Engine.Ethash.Params.DurationLimit = (*hexutil.Big)(params.DurationLimit) - spec.Engine.Ethash.Params.BlockReward = (*hexutil.Big)(ethash.FrontierBlockReward) + spec.Engine.Ethash.Params.BlockReward = (*hexutil.Big)(ethash.FrontierBlockReward.ToBig()) spec.Engine.Ethash.Params.HomesteadTransition = genesis.Config.HomesteadBlock.Uint64() spec.Engine.Ethash.Params.EIP150Transition = genesis.Config.EIP150Block.Uint64() spec.Engine.Ethash.Params.EIP160Transition = genesis.Config.EIP155Block.Uint64() spec.Engine.Ethash.Params.EIP161abcTransition = genesis.Config.EIP158Block.Uint64() spec.Engine.Ethash.Params.EIP161dTransition = genesis.Config.EIP158Block.Uint64() - spec.Engine.Ethash.Params.EIP649Reward = (*hexutil.Big)(ethash.ByzantiumBlockReward) + spec.Engine.Ethash.Params.EIP649Reward = (*hexutil.Big)(ethash.ByzantiumBlockReward.ToBig()) spec.Engine.Ethash.Params.EIP100bTransition = genesis.Config.ByzantiumBlock.Uint64() spec.Engine.Ethash.Params.EIP649Transition = genesis.Config.ByzantiumBlock.Uint64() diff --git a/common/big.go b/common/big.go index 65d4377bf70c7..cbb562a28ef81 100644 --- a/common/big.go +++ b/common/big.go @@ -16,7 +16,11 @@ package common -import "math/big" +import ( + "math/big" + + "github.com/holiman/uint256" +) // Common big integers often used var ( @@ -27,4 +31,6 @@ var ( Big32 = big.NewInt(32) Big256 = big.NewInt(256) Big257 = big.NewInt(257) + + U2560 = uint256.NewInt(0) ) diff --git a/consensus/ethash/consensus.go b/consensus/ethash/consensus.go index 92806693aeb40..6933a55761ece 100644 --- a/consensus/ethash/consensus.go +++ b/consensus/ethash/consensus.go @@ -33,14 +33,15 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/params" mapset "github.com/deckarep/golang-set" + "github.com/holiman/uint256" ) // Ethash proof-of-work protocol constants. var ( - FrontierBlockReward *big.Int = big.NewInt(5e+18) // Block reward in wei for successfully mining a block - ByzantiumBlockReward *big.Int = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium - maxUncles = 2 // Maximum number of uncles allowed in a single block - allowedFutureBlockTime = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks + FrontierBlockReward *uint256.Int = uint256.NewInt(5e+18) // Block reward in wei for successfully mining a block + ByzantiumBlockReward *uint256.Int = uint256.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium + maxUncles = 2 // Maximum number of uncles allowed in a single block + allowedFutureBlockTime = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks ) // Various error messages to mark blocks invalid. These should be private to @@ -529,8 +530,8 @@ func (ethash *Ethash) Finalize(chain consensus.ChainReader, header *types.Header // Some weird constants to avoid constant memory allocs for them. var ( - big8 = big.NewInt(8) - big32 = big.NewInt(32) + u256_8 = uint256.NewInt(8) + u256_32 = uint256.NewInt(32) ) // AccumulateRewards credits the coinbase of the given block with the mining @@ -543,16 +544,18 @@ func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header blockReward = ByzantiumBlockReward } // Accumulate the rewards for the miner and any included uncles - reward := new(big.Int).Set(blockReward) - r := new(big.Int) + reward := new(uint256.Int).Set(blockReward) + r := new(uint256.Int) + hNum, _ := uint256.FromBig(header.Number) for _, uncle := range uncles { - r.Add(uncle.Number, big8) - r.Sub(r, header.Number) + uNum, _ := uint256.FromBig(uncle.Number) + r.AddUint64(uNum, 8) + r.Sub(r, hNum) r.Mul(r, blockReward) - r.Div(r, big8) + r.Div(r, u256_8) state.AddBalance(uncle.Coinbase, r) - r.Div(blockReward, big32) + r.Div(blockReward, u256_32) reward.Add(reward, r) } state.AddBalance(header.Coinbase, reward) diff --git a/consensus/misc/dao.go b/consensus/misc/dao.go index e8af25a69a6a1..253851c797dab 100644 --- a/consensus/misc/dao.go +++ b/consensus/misc/dao.go @@ -24,6 +24,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) var ( @@ -40,10 +41,11 @@ var ( // ensure it conforms to DAO hard-fork rules. // // DAO hard-fork extension to the header validity: -// a) if the node is no-fork, do not accept blocks in the [fork, fork+10) range -// with the fork specific extra-data set -// b) if the node is pro-fork, require blocks in the specific range to have the -// unique extra-data set. +// +// a) if the node is no-fork, do not accept blocks in the [fork, fork+10) range +// with the fork specific extra-data set +// b) if the node is pro-fork, require blocks in the specific range to have the +// unique extra-data set. func VerifyDAOHeaderExtraData(config *params.ChainConfig, header *types.Header) error { // Short circuit validation if the node doesn't care about the DAO fork if config.DAOForkBlock == nil { @@ -80,6 +82,6 @@ func ApplyDAOHardFork(statedb *state.StateDB) { // Move every DAO account and extra-balance account funds into the refund contract for _, addr := range params.DAODrainList() { statedb.AddBalance(params.DAORefundContract, statedb.GetBalance(addr)) - statedb.SetBalance(addr, new(big.Int)) + statedb.SetBalance(addr, new(uint256.Int)) } } diff --git a/consensus/tests/engine_v1_tests/block_signer_test.go b/consensus/tests/engine_v1_tests/block_signer_test.go index 459511ec2bf5f..7f3ffcdf520c1 100644 --- a/consensus/tests/engine_v1_tests/block_signer_test.go +++ b/consensus/tests/engine_v1_tests/block_signer_test.go @@ -9,6 +9,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" "github.com/stretchr/testify/assert" ) @@ -403,7 +404,7 @@ func TestStatesShouldBeUpdatedWhenForkedBlockBecameMainChainAtGapBlock(t *testin } t.Log("After transfer transaction at block 450 A, Account 1 have balance of: ", state.GetBalance(acc1Addr)) - if state.GetBalance(acc1Addr).Cmp(new(big.Int).SetUint64(10000000999)) != 0 { + if state.GetBalance(acc1Addr).Cmp(new(uint256.Int).SetUint64(10000000999)) != 0 { t.Fatalf("account 1 should have 10000000999 in balance") } @@ -445,7 +446,7 @@ func TestStatesShouldBeUpdatedWhenForkedBlockBecameMainChainAtGapBlock(t *testin if err != nil { t.Fatalf("Failed while trying to get blockchain state") } - if state.GetBalance(acc1Addr).Cmp(new(big.Int).SetUint64(10000000999)) != 0 { + if state.GetBalance(acc1Addr).Cmp(new(uint256.Int).SetUint64(10000000999)) != 0 { t.Fatalf("account 1 should have 10000000999 in balance as the block is forked, not on the main chain") } @@ -513,7 +514,7 @@ func TestStatesShouldBeUpdatedWhenForkedBlockBecameMainChainAtGapBlock(t *testin } t.Log("After transfer transaction at block 450 B and the B fork has been merged into main chain, Account 1 have balance of: ", state.GetBalance(acc1Addr)) - if state.GetBalance(acc1Addr).Cmp(new(big.Int).SetUint64(10000000888)) != 0 { + if state.GetBalance(acc1Addr).Cmp(new(uint256.Int).SetUint64(10000000888)) != 0 { t.Fatalf("account 1 should have 10000000888 in balance") } } diff --git a/consensus/tests/engine_v1_tests/blockchain_race_condition_test.go b/consensus/tests/engine_v1_tests/blockchain_race_condition_test.go index 17ea596b71cae..492f3d26e28ce 100644 --- a/consensus/tests/engine_v1_tests/blockchain_race_condition_test.go +++ b/consensus/tests/engine_v1_tests/blockchain_race_condition_test.go @@ -7,6 +7,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" "github.com/stretchr/testify/assert" ) @@ -61,7 +62,7 @@ func TestRaceConditionOnBlockchainReadAndWrite(t *testing.T) { } t.Log("After transfer transaction at block 450 A, Account 1 have balance of: ", state.GetBalance(acc1Addr)) - if state.GetBalance(acc1Addr).Cmp(new(big.Int).SetUint64(10000000999)) != 0 { + if state.GetBalance(acc1Addr).Cmp(new(uint256.Int).SetUint64(10000000999)) != 0 { t.Fatalf("account 1 should have 10000000999 in balance") } @@ -108,7 +109,7 @@ func TestRaceConditionOnBlockchainReadAndWrite(t *testing.T) { if err != nil { t.Fatalf("Failed while trying to get blockchain state") } - if state.GetBalance(acc1Addr).Cmp(new(big.Int).SetUint64(10000000888)) != 0 { + if state.GetBalance(acc1Addr).Cmp(new(uint256.Int).SetUint64(10000000888)) != 0 { t.Fatalf("account 1 should have 10000000888 in balance as the block replace previous head block at number 450") } @@ -173,7 +174,7 @@ func TestRaceConditionOnBlockchainReadAndWrite(t *testing.T) { } t.Log("After transfer transaction at block 450 B and the B fork has been merged into main chain, Account 1 have balance of: ", state.GetBalance(acc1Addr)) - if state.GetBalance(acc1Addr).Cmp(new(big.Int).SetUint64(10000000888)) != 0 { + if state.GetBalance(acc1Addr).Cmp(new(uint256.Int).SetUint64(10000000888)) != 0 { t.Fatalf("account 1 should have 10000000888 in balance") } } diff --git a/core/blockchain_test.go b/core/blockchain_test.go index de15d9ca6c5aa..6fcbc19d2bec6 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -1705,7 +1705,7 @@ func TestEIP3651(t *testing.T) { state, _ := chain.State() // 3: Ensure that miner received only the tx's tip. - actual := state.GetBalance(block.Coinbase()) + actual := state.GetBalance(block.Coinbase()).ToBig() expected := new(big.Int).Add( new(big.Int).SetUint64(block.GasUsed()*block.Transactions()[0].GasTipCap().Uint64()), ConstantinopleBlockReward, @@ -1715,7 +1715,7 @@ func TestEIP3651(t *testing.T) { } // 4: Ensure the tx sender paid for the gasUsed * (tip + block baseFee). - actual = new(big.Int).Sub(funds, state.GetBalance(addr1)) + actual = new(big.Int).Sub(funds, state.GetBalance(addr1).ToBig()) expected = new(big.Int).SetUint64(block.GasUsed() * (block.Transactions()[0].GasTipCap().Uint64() + block.BaseFee().Uint64())) if actual.Cmp(expected) != 0 { t.Fatalf("sender balance incorrect: expected %d, got %d", expected, actual) diff --git a/core/evm.go b/core/evm.go index 9847a8d790b19..0f914d7ab0276 100644 --- a/core/evm.go +++ b/core/evm.go @@ -24,6 +24,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/core/vm" "github.com/XinFinOrg/XDPoSChain/crypto" + "github.com/holiman/uint256" ) // NewEVMBlockContext creates a new context for use in the EVM. @@ -102,12 +103,12 @@ func GetHashFn(ref *types.Header, chain consensus.ChainContext) func(n uint64) c // CanTransfer checks wether there are enough funds in the address' account to make a transfer. // This does not take the necessary gas in to account to make the transfer valid. -func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool { +func CanTransfer(db vm.StateDB, addr common.Address, amount *uint256.Int) bool { return db.GetBalance(addr).Cmp(amount) >= 0 } // Transfer subtracts amount from sender and adds amount to recipient using the given Db -func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) { +func Transfer(db vm.StateDB, sender, recipient common.Address, amount *uint256.Int) { db.SubBalance(sender, amount) db.AddBalance(recipient, amount) } diff --git a/core/genesis.go b/core/genesis.go index d14b1c73d153a..4d0fd9597a255 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -27,6 +27,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/rawdb" "github.com/XinFinOrg/XDPoSChain/crypto" + "github.com/holiman/uint256" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common/hexutil" @@ -240,7 +241,7 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block { } statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) for addr, account := range g.Alloc { - statedb.AddBalance(addr, account.Balance) + statedb.AddBalance(addr, uint256.MustFromBig(account.Balance)) statedb.SetCode(addr, account.Code) statedb.SetNonce(addr, account.Nonce) for key, value := range account.Storage { diff --git a/core/state/journal.go b/core/state/journal.go index d8f748fa64d72..9d1a32280987c 100644 --- a/core/state/journal.go +++ b/core/state/journal.go @@ -17,9 +17,8 @@ package state import ( - "math/big" - "github.com/XinFinOrg/XDPoSChain/common" + "github.com/holiman/uint256" ) type journalEntry interface { @@ -44,13 +43,13 @@ type ( suicideChange struct { account *common.Address prev bool // whether account had already suicided - prevbalance *big.Int + prevbalance *uint256.Int } // Changes to individual accounts. balanceChange struct { account *common.Address - prev *big.Int + prev *uint256.Int } nonceChange struct { account *common.Address diff --git a/core/state/state_object.go b/core/state/state_object.go index bb19597cc6f93..271c4db911000 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -27,6 +27,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/rlp" + "github.com/holiman/uint256" ) type Code []byte @@ -100,7 +101,7 @@ func (s *stateObject) empty() bool { // These objects are stored in the main account trie. type Account struct { Nonce uint64 - Balance *big.Int + Balance *uint256.Int Root common.Hash // merkle root of the storage trie CodeHash []byte } @@ -108,7 +109,7 @@ type Account struct { // newObject creates a state object. func newObject(db *StateDB, address common.Address, data Account, onDirty func(addr common.Address)) *stateObject { if data.Balance == nil { - data.Balance = new(big.Int) + data.Balance = new(uint256.Int) } if data.CodeHash == nil { data.CodeHash = types.EmptyCodeHash.Bytes() @@ -317,7 +318,7 @@ func (s *stateObject) CommitTrie(db Database) error { // AddBalance removes amount from c's balance. // It is used to add funds to the destination account of a transfer. -func (s *stateObject) AddBalance(amount *big.Int) { +func (s *stateObject) AddBalance(amount *uint256.Int) { // EIP158: We must check emptiness for the objects such that the account // clearing (0,0,0 objects) can take effect. if amount.Sign() == 0 { @@ -327,27 +328,27 @@ func (s *stateObject) AddBalance(amount *big.Int) { return } - s.SetBalance(new(big.Int).Add(s.Balance(), amount)) + s.SetBalance(new(uint256.Int).Add(s.Balance(), amount)) } // SubBalance removes amount from c's balance. // It is used to remove funds from the origin account of a transfer. -func (s *stateObject) SubBalance(amount *big.Int) { +func (s *stateObject) SubBalance(amount *uint256.Int) { if amount.Sign() == 0 { return } - s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) + s.SetBalance(new(uint256.Int).Sub(s.Balance(), amount)) } -func (s *stateObject) SetBalance(amount *big.Int) { +func (s *stateObject) SetBalance(amount *uint256.Int) { s.db.journal = append(s.db.journal, balanceChange{ account: &s.address, - prev: new(big.Int).Set(s.data.Balance), + prev: new(uint256.Int).Set(s.data.Balance), }) s.setBalance(amount) } -func (s *stateObject) setBalance(amount *big.Int) { +func (s *stateObject) setBalance(amount *uint256.Int) { s.data.Balance = amount if s.onDirty != nil { s.onDirty(s.Address()) @@ -434,7 +435,7 @@ func (s *stateObject) CodeHash() []byte { return s.data.CodeHash } -func (s *stateObject) Balance() *big.Int { +func (s *stateObject) Balance() *uint256.Int { return s.data.Balance } diff --git a/core/state/state_test.go b/core/state/state_test.go index ddc7df61ce2e1..f28e25d709edd 100644 --- a/core/state/state_test.go +++ b/core/state/state_test.go @@ -18,10 +18,11 @@ package state import ( "bytes" - "github.com/XinFinOrg/XDPoSChain/core/rawdb" - "math/big" "testing" + "github.com/XinFinOrg/XDPoSChain/core/rawdb" + "github.com/holiman/uint256" + "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/ethdb" @@ -40,11 +41,11 @@ var toAddr = common.BytesToAddress func (s *StateSuite) TestDump(c *checker.C) { // generate a few entries obj1 := s.state.GetOrNewStateObject(toAddr([]byte{0x01})) - obj1.AddBalance(big.NewInt(22)) + obj1.AddBalance(uint256.NewInt(22)) obj2 := s.state.GetOrNewStateObject(toAddr([]byte{0x01, 0x02})) obj2.SetCode(crypto.Keccak256Hash([]byte{3, 3, 3, 3, 3, 3, 3}), []byte{3, 3, 3, 3, 3, 3, 3}) obj3 := s.state.GetOrNewStateObject(toAddr([]byte{0x02})) - obj3.SetBalance(big.NewInt(44)) + obj3.SetBalance(uint256.NewInt(44)) // write some of them to the trie s.state.updateStateObject(obj1) @@ -149,7 +150,7 @@ func TestSnapshot2(t *testing.T) { // db, trie are already non-empty values so0 := state.getStateObject(stateobjaddr0) - so0.SetBalance(big.NewInt(42)) + so0.SetBalance(uint256.NewInt(42)) so0.SetNonce(43) so0.SetCode(crypto.Keccak256Hash([]byte{'c', 'a', 'f', 'e'}), []byte{'c', 'a', 'f', 'e'}) so0.suicided = false @@ -161,7 +162,7 @@ func TestSnapshot2(t *testing.T) { // and one with deleted == true so1 := state.getStateObject(stateobjaddr1) - so1.SetBalance(big.NewInt(52)) + so1.SetBalance(uint256.NewInt(52)) so1.SetNonce(53) so1.SetCode(crypto.Keccak256Hash([]byte{'c', 'a', 'f', 'e', '2'}), []byte{'c', 'a', 'f', 'e', '2'}) so1.suicided = true diff --git a/core/state/statedb.go b/core/state/statedb.go index d357e6e1bf580..c853d35ad460f 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -31,6 +31,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/rlp" "github.com/XinFinOrg/XDPoSChain/trie" + "github.com/holiman/uint256" ) type revision struct { @@ -96,7 +97,7 @@ type StateDB struct { type AccountInfo struct { CodeSize int Nonce uint64 - Balance *big.Int + Balance *uint256.Int CodeHash common.Hash StorageHash common.Hash } @@ -227,12 +228,12 @@ func (s *StateDB) Empty(addr common.Address) bool { } // Retrieve the balance from the given address or 0 if object not found -func (s *StateDB) GetBalance(addr common.Address) *big.Int { +func (s *StateDB) GetBalance(addr common.Address) *uint256.Int { stateObject := s.getStateObject(addr) if stateObject != nil { return stateObject.Balance() } - return common.Big0 + return common.U2560 } func (s *StateDB) GetNonce(addr common.Address) uint64 { @@ -295,7 +296,7 @@ func (s *StateDB) GetAccountInfo(addr common.Address) *AccountInfo { stateObject := s.getStateObject(addr) if stateObject == nil { - result.Balance = common.Big0 + result.Balance = common.U2560 return &result } @@ -349,7 +350,7 @@ func (s *StateDB) HasSuicided(addr common.Address) bool { */ // AddBalance adds amount to the account associated with addr. -func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) { +func (s *StateDB) AddBalance(addr common.Address, amount *uint256.Int) { stateObject := s.GetOrNewStateObject(addr) if stateObject != nil { stateObject.AddBalance(amount) @@ -357,14 +358,14 @@ func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) { } // SubBalance subtracts amount from the account associated with addr. -func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) { +func (s *StateDB) SubBalance(addr common.Address, amount *uint256.Int) { stateObject := s.GetOrNewStateObject(addr) if stateObject != nil { stateObject.SubBalance(amount) } } -func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) { +func (s *StateDB) SetBalance(addr common.Address, amount *uint256.Int) { stateObject := s.GetOrNewStateObject(addr) if stateObject != nil { stateObject.SetBalance(amount) @@ -414,10 +415,10 @@ func (s *StateDB) Suicide(addr common.Address) bool { s.journal = append(s.journal, suicideChange{ account: &addr, prev: stateObject.suicided, - prevbalance: new(big.Int).Set(stateObject.Balance()), + prevbalance: new(uint256.Int).Set(stateObject.Balance()), }) stateObject.markSuicided() - stateObject.data.Balance = new(big.Int) + stateObject.data.Balance = new(uint256.Int) return true } diff --git a/core/state/statedb_test.go b/core/state/statedb_test.go index 5166224b352f3..fe03599fbaa26 100644 --- a/core/state/statedb_test.go +++ b/core/state/statedb_test.go @@ -21,7 +21,6 @@ import ( "encoding/binary" "fmt" "math" - "math/big" "math/rand" "reflect" "strings" @@ -33,6 +32,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/core/rawdb" "github.com/XinFinOrg/XDPoSChain/core/types" + "github.com/holiman/uint256" ) // Tests that updating a state trie does not leak any database writes prior to @@ -45,7 +45,7 @@ func TestUpdateLeaks(t *testing.T) { // Update it with some accounts for i := byte(0); i < 255; i++ { addr := common.BytesToAddress([]byte{i}) - state.AddBalance(addr, big.NewInt(int64(11*i))) + state.AddBalance(addr, uint256.NewInt(uint64(11*i))) state.SetNonce(addr, uint64(42*i)) if i%2 == 0 { state.SetState(addr, common.BytesToHash([]byte{i, i, i}), common.BytesToHash([]byte{i, i, i, i})) @@ -74,7 +74,7 @@ func TestIntermediateLeaks(t *testing.T) { finalState, _ := New(common.Hash{}, NewDatabase(finalDb)) modify := func(state *StateDB, addr common.Address, i, tweak byte) { - state.SetBalance(addr, big.NewInt(int64(11*i)+int64(tweak))) + state.SetBalance(addr, uint256.NewInt(uint64(11*i)+uint64(tweak))) state.SetNonce(addr, uint64(42*i+tweak)) if i%2 == 0 { state.SetState(addr, common.Hash{i, i, i, 0}, common.Hash{}) @@ -133,7 +133,7 @@ func TestCopy(t *testing.T) { for i := byte(0); i < 255; i++ { obj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i})) - obj.AddBalance(big.NewInt(int64(i))) + obj.AddBalance(uint256.NewInt(uint64(i))) orig.updateStateObject(obj) } orig.Finalise(false) @@ -145,8 +145,8 @@ func TestCopy(t *testing.T) { origObj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i})) copyObj := copy.GetOrNewStateObject(common.BytesToAddress([]byte{i})) - origObj.AddBalance(big.NewInt(2 * int64(i))) - copyObj.AddBalance(big.NewInt(3 * int64(i))) + origObj.AddBalance(uint256.NewInt(2 * uint64(i))) + copyObj.AddBalance(uint256.NewInt(3 * uint64(i))) orig.updateStateObject(origObj) copy.updateStateObject(copyObj) @@ -165,10 +165,10 @@ func TestCopy(t *testing.T) { origObj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i})) copyObj := copy.GetOrNewStateObject(common.BytesToAddress([]byte{i})) - if want := big.NewInt(3 * int64(i)); origObj.Balance().Cmp(want) != 0 { + if want := uint256.NewInt(3 * uint64(i)); origObj.Balance().Cmp(want) != 0 { t.Errorf("orig obj %d: balance mismatch: have %v, want %v", i, origObj.Balance(), want) } - if want := big.NewInt(4 * int64(i)); copyObj.Balance().Cmp(want) != 0 { + if want := uint256.NewInt(4 * uint64(i)); copyObj.Balance().Cmp(want) != 0 { t.Errorf("copy obj %d: balance mismatch: have %v, want %v", i, copyObj.Balance(), want) } } @@ -216,14 +216,14 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction { { name: "SetBalance", fn: func(a testAction, s *StateDB) { - s.SetBalance(addr, big.NewInt(a.args[0])) + s.SetBalance(addr, uint256.NewInt(uint64(a.args[0]))) }, args: make([]int64, 1), }, { name: "AddBalance", fn: func(a testAction, s *StateDB) { - s.AddBalance(addr, big.NewInt(a.args[0])) + s.SetBalance(addr, uint256.NewInt(uint64(a.args[0]))) }, args: make([]int64, 1), }, @@ -442,7 +442,7 @@ func (s *StateSuite) TestTouchDelete(c *check.C) { s.state.Reset(root) snapshot := s.state.Snapshot() - s.state.AddBalance(common.Address{}, new(big.Int)) + s.state.AddBalance(common.Address{}, new(uint256.Int)) if len(s.state.stateObjectsDirty) != 1 { c.Fatal("expected one dirty state object") } diff --git a/core/state/sync_test.go b/core/state/sync_test.go index 57fa80e7733ba..9b2cd1d2962b1 100644 --- a/core/state/sync_test.go +++ b/core/state/sync_test.go @@ -18,7 +18,6 @@ package state import ( "bytes" - "math/big" "testing" "github.com/XinFinOrg/XDPoSChain/common" @@ -28,12 +27,13 @@ import ( "github.com/XinFinOrg/XDPoSChain/ethdb" "github.com/XinFinOrg/XDPoSChain/ethdb/memorydb" "github.com/XinFinOrg/XDPoSChain/trie" + "github.com/holiman/uint256" ) // testAccount is the data associated with an account used by the state tests. type testAccount struct { address common.Address - balance *big.Int + balance *uint256.Int nonce uint64 code []byte } @@ -50,8 +50,8 @@ func makeTestState() (Database, common.Hash, []*testAccount) { obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i})) acc := &testAccount{address: common.BytesToAddress([]byte{i})} - obj.AddBalance(big.NewInt(int64(11 * i))) - acc.balance = big.NewInt(int64(11 * i)) + obj.AddBalance(uint256.NewInt(uint64(11 * i))) + acc.balance = uint256.NewInt(uint64(11 * i)) obj.SetNonce(uint64(42 * i)) acc.nonce = uint64(42 * i) diff --git a/core/state/trc21_reader.go b/core/state/trc21_reader.go index af5fd25b13901..e19b35616287b 100644 --- a/core/state/trc21_reader.go +++ b/core/state/trc21_reader.go @@ -6,7 +6,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/common" lru "github.com/hashicorp/golang-lru" - + "github.com/holiman/uint256" ) var ( @@ -150,5 +150,5 @@ func UpdateTRC21Fee(statedb *StateDB, newBalance map[common.Address]*big.Int, to balanceKey := GetLocMappingAtKey(token.Hash(), slotTokensState) statedb.SetState(common.TRC21IssuerSMC, common.BigToHash(balanceKey), common.BigToHash(value)) } - statedb.SubBalance(common.TRC21IssuerSMC, totalFeeUsed) + statedb.SubBalance(common.TRC21IssuerSMC, uint256.MustFromBig(totalFeeUsed)) } diff --git a/core/state_processor.go b/core/state_processor.go index 2f7980db6326e..c3dedd9794f13 100644 --- a/core/state_processor.go +++ b/core/state_processor.go @@ -34,6 +34,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/log" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) // StateProcessor is a basic Processor, which takes care of transitioning @@ -396,7 +397,7 @@ func applyTransaction(config *params.ChainConfig, tokensFee map[common.Address]* hBalance.SetString(bal+"000000000000000000", 10) log.Info("address", addr, "with_balance", bal, "XDC") addrBin := common.HexToAddress(addr) - statedb.SetBalance(addrBin, hBalance) + statedb.SetBalance(addrBin, uint256.MustFromBig(hBalance)) } } } diff --git a/core/state_processor_test.go b/core/state_processor_test.go index cce40167528d2..ecceb044d563b 100644 --- a/core/state_processor_test.go +++ b/core/state_processor_test.go @@ -183,7 +183,7 @@ func TestStateProcessorErrors(t *testing.T) { txs: []*types.Transaction{ mkDynamicTx(0, common.Address{}, params.TxGas, bigNumber, bigNumber), }, - want: "insufficient funds for gas * price + value: address xdc71562b71999873DB5b286dF957af199Ec94617F7 have 1000000000000000000 want 2431633873983640103894990685182446064918669677978451844828609264166175722438635000", + want: "insufficient funds for gas * price + value: address xdc71562b71999873DB5b286dF957af199Ec94617F7 required balance exceeds 256 bits", }, }[8:] { block := GenerateBadBlock(t, genesis, ethash.NewFaker(), tt.txs, gspec.Config) diff --git a/core/state_transition.go b/core/state_transition.go index e5f610265325b..2429a41669576 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -237,7 +237,11 @@ func (st *StateTransition) buyGas() error { balanceCheck = balanceCheck.Mul(balanceCheck, st.gasFeeCap) balanceCheck.Add(balanceCheck, st.value) } - if have, want := st.state.GetBalance(st.msg.From()), balanceCheck; have.Cmp(want) < 0 { + balanceCheckU256, overflow := uint256.FromBig(balanceCheck) + if overflow { + return fmt.Errorf("%w: address %v required balance exceeds 256 bits", ErrInsufficientFunds, st.msg.From().Hex()) + } + if have, want := st.state.GetBalance(st.msg.From()), balanceCheckU256; have.Cmp(want) < 0 { return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want) } } else if balanceTokenFee.Cmp(mgval) < 0 { @@ -250,7 +254,8 @@ func (st *StateTransition) buyGas() error { st.initialGas = st.msg.Gas() if balanceTokenFee == nil { - st.state.SubBalance(st.msg.From(), mgval) + mgvalU256, _ := uint256.FromBig(mgval) + st.state.SubBalance(st.msg.From(), mgvalU256) } return nil } @@ -367,7 +372,7 @@ func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult, if overflow { return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex()) } - if !value.IsZero() && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) { + if !value.IsZero() && !st.evm.Context.CanTransfer(st.state, msg.From(), value) { return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex()) } @@ -376,11 +381,11 @@ func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult, vmerr error // vm errors do not effect consensus and are therefore not assigned to err ) if contractCreation { - ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, st.value) + ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, value) } else { // Increment the nonce for the next transaction st.state.SetNonce(sender.Address(), st.state.GetNonce(sender.Address())+1) - ret, st.gas, vmerr = st.evm.Call(sender, st.to().Address(), st.data, st.gas, st.value) + ret, st.gas, vmerr = st.evm.Call(sender, st.to().Address(), st.data, st.gas, value) } if !eip3529 { // Before EIP-3529: refunds were capped to gasUsed / 2 @@ -392,14 +397,16 @@ func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult, if st.evm.Context.BlockNumber.Cmp(common.TIPTRC21Fee) > 0 { if (owner != common.Address{}) { - st.state.AddBalance(owner, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)) + st.state.AddBalance(owner, new(uint256.Int).Mul(new(uint256.Int).SetUint64(st.gasUsed()), uint256.MustFromBig(st.gasPrice))) } } else { effectiveTip := st.gasPrice if st.evm.ChainConfig().IsEIP1559(st.evm.Context.BlockNumber) { effectiveTip = cmath.BigMin(st.gasTipCap, new(big.Int).Sub(st.gasFeeCap, st.evm.Context.BaseFee)) } - st.state.AddBalance(st.evm.Context.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), effectiveTip)) + fee := new(uint256.Int).SetUint64(st.gasUsed()) + effectiveTipU256, _ := uint256.FromBig(effectiveTip) + fee.Mul(fee, effectiveTipU256) } return &ExecutionResult{ @@ -421,7 +428,7 @@ func (st *StateTransition) refundGas(refundQuotient uint64) { if balanceTokenFee == nil { from := st.from() // Return ETH for remaining gas, exchanged at the original rate. - remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice) + remaining := new(uint256.Int).Mul(new(uint256.Int).SetUint64(st.gas), uint256.MustFromBig(st.gasPrice)) st.state.AddBalance(from.Address(), remaining) } // Also return remaining gas to the block gas counter so it is diff --git a/core/token_validator.go b/core/token_validator.go index 070a3342ce8e4..4caa5b58701c5 100644 --- a/core/token_validator.go +++ b/core/token_validator.go @@ -30,6 +30,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/core/vm" "github.com/XinFinOrg/XDPoSChain/log" + "github.com/holiman/uint256" ) const ( @@ -76,7 +77,7 @@ func RunContract(chain consensus.ChainContext, statedb *state.StateDB, contractA return nil, err } fakeCaller := common.HexToAddress("0x0000000000000000000000000000000000000001") - statedb.SetBalance(fakeCaller, common.BasePrice) + statedb.SetBalance(fakeCaller, uint256.MustFromBig(common.BasePrice)) msg := ethereum.CallMsg{To: &contractAddr, Data: input, From: fakeCaller} result, err := CallContractWithState(msg, chain, statedb) if err != nil { diff --git a/core/txpool/txpool.go b/core/txpool/txpool.go index fc57d9355aa90..954597cab1a40 100644 --- a/core/txpool/txpool.go +++ b/core/txpool/txpool.go @@ -696,7 +696,7 @@ func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error { cost = tx.TxCost(number) } } - if new(big.Int).Add(balance, feeCapacity).Cmp(cost) < 0 { + if new(big.Int).Add(balance.ToBig(), feeCapacity).Cmp(cost) < 0 { return core.ErrInsufficientFunds } @@ -1476,7 +1476,7 @@ func (pool *TxPool) promoteExecutables(accounts []common.Address) []*types.Trans if pool.chain.CurrentHeader() != nil { number = pool.chain.CurrentHeader().Number } - drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas, pool.trc21FeeCapacity, number) + drops, _ := list.Filter(pool.currentState.GetBalance(addr).ToBig(), pool.currentMaxGas, pool.trc21FeeCapacity, number) for _, tx := range drops { hash := tx.Hash() pool.all.Remove(hash) @@ -1677,7 +1677,7 @@ func (pool *TxPool) demoteUnexecutables() { if pool.chain.CurrentHeader() != nil { number = pool.chain.CurrentHeader().Number } - drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas, pool.trc21FeeCapacity, number) + drops, invalids := list.Filter(pool.currentState.GetBalance(addr).ToBig(), pool.currentMaxGas, pool.trc21FeeCapacity, number) for _, tx := range drops { hash := tx.Hash() log.Trace("Removed unpayable pending transaction", "hash", hash) diff --git a/core/txpool/txpool_test.go b/core/txpool/txpool_test.go index 3b1ac21f62f83..af12759833827 100644 --- a/core/txpool/txpool_test.go +++ b/core/txpool/txpool_test.go @@ -35,6 +35,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/event" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) var ( @@ -227,7 +228,7 @@ func (c *testChain) State() (*state.StateDB, error) { c.statedb, _ = state.New(common.Hash{}, state.NewDatabase(db)) // simulate that the new head block included tx0 and tx1 c.statedb.SetNonce(c.address, 2) - c.statedb.SetBalance(c.address, new(big.Int).SetUint64(params.Ether)) + c.statedb.SetBalance(c.address, new(uint256.Int).SetUint64(params.Ether)) *c.trigger = false } return stdb, nil @@ -248,7 +249,7 @@ func TestStateChangeDuringReset(t *testing.T) { ) // setup pool with 2 transaction in it - statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether)) + statedb.SetBalance(address, new(uint256.Int).SetUint64(params.Ether)) blockchain := &testChain{&testBlockChain{statedb, 1000000000, new(event.Feed)}, address, &trigger} tx0 := transaction(0, 100000, key) @@ -281,7 +282,7 @@ func TestStateChangeDuringReset(t *testing.T) { func testAddBalance(pool *TxPool, addr common.Address, amount *big.Int) { pool.mu.Lock() - pool.currentState.AddBalance(addr, amount) + pool.currentState.AddBalance(addr, uint256.MustFromBig(amount)) pool.mu.Unlock() } @@ -443,7 +444,7 @@ func TestChainFork(t *testing.T) { resetState := func() { db := rawdb.NewMemoryDatabase() statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) - statedb.AddBalance(addr, big.NewInt(100000000000000)) + statedb.AddBalance(addr, uint256.NewInt(100000000000000)) pool.chain = &testBlockChain{statedb, 1000000, new(event.Feed)} <-pool.requestReset(nil, nil) @@ -473,7 +474,7 @@ func TestDoubleNonce(t *testing.T) { resetState := func() { db := rawdb.NewMemoryDatabase() statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) - statedb.AddBalance(addr, big.NewInt(100000000000000)) + statedb.AddBalance(addr, uint256.NewInt(100000000000000)) pool.chain = &testBlockChain{statedb, 1000000, new(event.Feed)} <-pool.requestReset(nil, nil) @@ -2587,7 +2588,7 @@ func BenchmarkMultiAccountBatchInsert(b *testing.B) { for i := 0; i < b.N; i++ { key, _ := crypto.GenerateKey() account := crypto.PubkeyToAddress(key.PublicKey) - pool.currentState.AddBalance(account, big.NewInt(1000000)) + pool.currentState.AddBalance(account, uint256.NewInt(1000000)) tx := transaction(uint64(0), 100000, key) batches[i] = tx } diff --git a/core/vm/contract.go b/core/vm/contract.go index 95dd59ee06339..7cd61c65745c4 100644 --- a/core/vm/contract.go +++ b/core/vm/contract.go @@ -17,8 +17,6 @@ package vm import ( - "math/big" - "github.com/XinFinOrg/XDPoSChain/common" "github.com/holiman/uint256" ) @@ -59,11 +57,11 @@ type Contract struct { Input []byte Gas uint64 - value *big.Int + value *uint256.Int } // NewContract returns a new contract environment for the execution of EVM. -func NewContract(caller ContractRef, object ContractRef, value *big.Int, gas uint64) *Contract { +func NewContract(caller ContractRef, object ContractRef, value *uint256.Int, gas uint64) *Contract { c := &Contract{CallerAddress: caller.Address(), caller: caller, self: object} if parent, ok := caller.(*Contract); ok { @@ -173,7 +171,7 @@ func (c *Contract) Address() common.Address { } // Value returns the contract's value (sent to it from it's caller) -func (c *Contract) Value() *big.Int { +func (c *Contract) Value() *uint256.Int { return c.value } diff --git a/core/vm/contracts.go b/core/vm/contracts.go index 7da6949ded53a..123dd9f03030a 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -265,7 +265,6 @@ type bigModExp struct { } var ( - big0 = big.NewInt(0) big1 = big.NewInt(1) big3 = big.NewInt(3) big4 = big.NewInt(4) diff --git a/core/vm/eips.go b/core/vm/eips.go index 532611dc940a2..ff011fb36ce59 100644 --- a/core/vm/eips.go +++ b/core/vm/eips.go @@ -69,7 +69,7 @@ func enable1884(jt *JumpTable) { } func opSelfBalance(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) { - balance, _ := uint256.FromBig(interpreter.evm.StateDB.GetBalance(scope.Contract.Address())) + balance := interpreter.evm.StateDB.GetBalance(scope.Contract.Address()) scope.Stack.push(balance) return nil, nil } diff --git a/core/vm/evm.go b/core/vm/evm.go index 1eff3428dbe9b..f93c064b57994 100644 --- a/core/vm/evm.go +++ b/core/vm/evm.go @@ -34,9 +34,9 @@ var emptyCodeHash = crypto.Keccak256Hash(nil) type ( // CanTransferFunc is the signature of a transfer guard function - CanTransferFunc func(StateDB, common.Address, *big.Int) bool + CanTransferFunc func(StateDB, common.Address, *uint256.Int) bool // TransferFunc is the signature of a transfer function - TransferFunc func(StateDB, common.Address, common.Address, *big.Int) + TransferFunc func(StateDB, common.Address, common.Address, *uint256.Int) // GetHashFunc returns the n'th block hash in the blockchain // and is used by the BLOCKHASH EVM op code. GetHashFunc func(uint64) common.Hash @@ -179,7 +179,7 @@ func (evm *EVM) SetBlockContext(blockCtx BlockContext) { // 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. -func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { +func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) { // Fail if we're trying to execute above the call depth limit if evm.depth > int(params.CallCreateDepth) { return nil, gas, ErrDepth @@ -196,10 +196,10 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas // Calling a non existing account, don't do anything, but ping the tracer if evm.Config.Debug { if evm.depth == 0 { - evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value) + evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value.ToBig()) evm.Config.Tracer.CaptureEnd(ret, 0, 0, nil) } else { - evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value) + evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value.ToBig()) evm.Config.Tracer.CaptureExit(ret, 0, nil) } } @@ -212,14 +212,14 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas // Capture the tracer start/end events in debug mode if evm.Config.Debug { if evm.depth == 0 { - evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value) + evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value.ToBig()) defer func(startGas uint64, startTime time.Time) { // Lazy evaluation of the parameters evm.Config.Tracer.CaptureEnd(ret, startGas-gas, time.Since(startTime), err) }(gas, time.Now()) } else { // Handle tracer events for entering and exiting a call frame - evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value) + evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value.ToBig()) defer func(startGas uint64) { evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) }(gas) @@ -266,7 +266,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas // // CallCode differs from Call in the sense that it executes the given address' // code with the caller as context. -func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { +func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) { // Fail if we're trying to execute above the call depth limit if evm.depth > int(params.CallCreateDepth) { return nil, gas, ErrDepth @@ -282,7 +282,7 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, // Invoke tracer hooks that signal entering/exiting a call frame if evm.Config.Debug { - evm.Config.Tracer.CaptureEnter(CALLCODE, caller.Address(), addr, input, gas, value) + evm.Config.Tracer.CaptureEnter(CALLCODE, caller.Address(), addr, input, gas, value.ToBig()) defer func(startGas uint64) { evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) }(gas) @@ -369,7 +369,7 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium, // but is the correct thing to do and matters on other networks, in tests, and potential // future scenarios - evm.StateDB.AddBalance(addr, big0) + evm.StateDB.AddBalance(addr, new(uint256.Int)) // Invoke tracer hooks that signal entering/exiting a call frame if evm.Config.Debug { @@ -388,7 +388,7 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte addrCopy := addr // Initialise a new contract and set the code that is to be used by the EVM. // The contract is a scoped environment for this execution context only. - contract := NewContract(caller, AccountRef(addrCopy), new(big.Int), gas) + contract := NewContract(caller, AccountRef(addrCopy), new(uint256.Int), gas) contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) // When an error was returned by the EVM or when setting the creation code // above we revert to the snapshot and consume any gas remaining. Additionally @@ -419,7 +419,7 @@ func (c *codeAndHash) Hash() common.Hash { } // create creates a new contract using code as deployment code. -func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address, typ OpCode) ([]byte, common.Address, uint64, error) { +func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *uint256.Int, address common.Address, typ OpCode) ([]byte, common.Address, uint64, error) { // Depth check execution. Fail if we're trying to execute above the // limit. if evm.depth > int(params.CallCreateDepth) { @@ -458,9 +458,9 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, if evm.Config.Debug { if evm.depth == 0 { - evm.Config.Tracer.CaptureStart(evm, caller.Address(), address, true, codeAndHash.code, gas, value) + evm.Config.Tracer.CaptureStart(evm, caller.Address(), address, true, codeAndHash.code, gas, value.ToBig()) } else { - evm.Config.Tracer.CaptureEnter(typ, caller.Address(), address, codeAndHash.code, gas, value) + evm.Config.Tracer.CaptureEnter(typ, caller.Address(), address, codeAndHash.code, gas, value.ToBig()) } } start := time.Now() @@ -511,7 +511,7 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, } // Create creates a new contract using code as deployment code. -func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { +func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address())) return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr, CREATE) } @@ -520,7 +520,7 @@ func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.I // // The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:] // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at. -func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { +func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *uint256.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { codeAndHash := &codeAndHash{code: code} contractAddr = crypto.CreateAddress2(caller.Address(), salt.Bytes32(), codeAndHash.Hash().Bytes()) return evm.create(caller, codeAndHash, gas, endowment, contractAddr, CREATE2) diff --git a/core/vm/gas_table_test.go b/core/vm/gas_table_test.go index 73132023d9b46..34696c80599c6 100644 --- a/core/vm/gas_table_test.go +++ b/core/vm/gas_table_test.go @@ -24,6 +24,7 @@ import ( "testing" "github.com/XinFinOrg/XDPoSChain/core/rawdb" + "github.com/holiman/uint256" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common/hexutil" @@ -91,12 +92,12 @@ func TestEIP2200(t *testing.T) { statedb.Finalise(true) // Push the state into the "original" slot vmctx := BlockContext{ - CanTransfer: func(StateDB, common.Address, *big.Int) bool { return true }, - Transfer: func(StateDB, common.Address, common.Address, *big.Int) {}, + CanTransfer: func(StateDB, common.Address, *uint256.Int) bool { return true }, + Transfer: func(StateDB, common.Address, common.Address, *uint256.Int) {}, } vmenv := NewEVM(vmctx, TxContext{}, statedb, nil, params.AllEthashProtocolChanges, Config{ExtraEips: []int{2200}}) - _, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, tt.gaspool, new(big.Int)) + _, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, tt.gaspool, new(uint256.Int)) if err != tt.failure { t.Errorf("test %d: failure mismatch: have %v, want %v", i, err, tt.failure) } @@ -140,8 +141,8 @@ func TestCreateGas(t *testing.T) { statedb.SetCode(address, hexutil.MustDecode(tt.code)) statedb.Finalise(true) vmctx := BlockContext{ - CanTransfer: func(StateDB, common.Address, *big.Int) bool { return true }, - Transfer: func(StateDB, common.Address, common.Address, *big.Int) {}, + CanTransfer: func(StateDB, common.Address, *uint256.Int) bool { return true }, + Transfer: func(StateDB, common.Address, common.Address, *uint256.Int) {}, BlockNumber: big.NewInt(0), } config := Config{} @@ -151,7 +152,7 @@ func TestCreateGas(t *testing.T) { vmenv := NewEVM(vmctx, TxContext{}, statedb, nil, params.AllEthashProtocolChanges, config) var startGas = uint64(testGas) - ret, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, startGas, new(big.Int)) + ret, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, startGas, new(uint256.Int)) if err != nil { return false } diff --git a/core/vm/instructions.go b/core/vm/instructions.go index 6a0ddea1b190a..232042476c30f 100644 --- a/core/vm/instructions.go +++ b/core/vm/instructions.go @@ -261,7 +261,7 @@ func opAddress(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([] func opBalance(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) { slot := scope.Stack.peek() address := common.Address(slot.Bytes20()) - slot.SetFromBig(interpreter.evm.StateDB.GetBalance(address)) + slot.Set(interpreter.evm.StateDB.GetBalance(address)) return nil, nil } @@ -275,8 +275,7 @@ func opCaller(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]b } func opCallValue(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) { - v, _ := uint256.FromBig(scope.Contract.value) - scope.Stack.push(v) + scope.Stack.push(scope.Contract.value) return nil, nil } @@ -605,13 +604,8 @@ func opCreate(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]b stackvalue := size scope.Contract.UseGas(gas) - //TODO: use uint256.Int instead of converting with toBig() - var bigVal = big0 - if !value.IsZero() { - bigVal = value.ToBig() - } - res, addr, returnGas, suberr := interpreter.evm.Create(scope.Contract, input, gas, bigVal) + res, addr, returnGas, suberr := interpreter.evm.Create(scope.Contract, input, gas, &value) // Push item on the stack based on the returned error. If the ruleset is // homestead we must check for CodeStoreOutOfGasError (homestead only // rule) and treat as an error, if the ruleset is frontier we must @@ -650,13 +644,9 @@ func opCreate2(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([] scope.Contract.UseGas(gas) // reuse size int for stackvalue stackvalue := size - //TODO: use uint256.Int instead of converting with toBig() - bigEndowment := big0 - if !endowment.IsZero() { - bigEndowment = endowment.ToBig() - } + res, addr, returnGas, suberr := interpreter.evm.Create2(scope.Contract, input, gas, - bigEndowment, &salt) + &endowment, &salt) // Push item on the stack based on the returned error. if suberr != nil { stackvalue.Clear() @@ -690,16 +680,11 @@ func opCall(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byt return nil, ErrWriteProtection } - var bigVal = big0 - //TODO: use uint256.Int instead of converting with toBig() - // By using big0 here, we save an alloc for the most common case (non-ether-transferring contract calls), - // but it would make more sense to extend the usage of uint256.Int if !value.IsZero() { gas += params.CallStipend - bigVal = value.ToBig() } - ret, returnGas, err := interpreter.evm.Call(scope.Contract, toAddr, args, gas, bigVal) + ret, returnGas, err := interpreter.evm.Call(scope.Contract, toAddr, args, gas, &value) if err != nil { temp.Clear() @@ -728,14 +713,11 @@ func opCallCode(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([ // Get arguments from the memory. args := scope.Memory.GetPtr(int64(inOffset.Uint64()), int64(inSize.Uint64())) - //TODO: use uint256.Int instead of converting with toBig() - var bigVal = big0 if !value.IsZero() { gas += params.CallStipend - bigVal = value.ToBig() } - ret, returnGas, err := interpreter.evm.CallCode(scope.Contract, toAddr, args, gas, bigVal) + ret, returnGas, err := interpreter.evm.CallCode(scope.Contract, toAddr, args, gas, &value) if err != nil { temp.Clear() } else { @@ -839,7 +821,7 @@ func opSelfdestruct(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext interpreter.evm.StateDB.AddBalance(beneficiary.Bytes20(), balance) interpreter.evm.StateDB.Suicide(scope.Contract.Address()) if interpreter.evm.Config.Debug { - interpreter.evm.Config.Tracer.CaptureEnter(SELFDESTRUCT, scope.Contract.Address(), beneficiary.Bytes20(), []byte{}, 0, balance) + interpreter.evm.Config.Tracer.CaptureEnter(SELFDESTRUCT, scope.Contract.Address(), beneficiary.Bytes20(), []byte{}, 0, balance.ToBig()) interpreter.evm.Config.Tracer.CaptureExit([]byte{}, 0, nil) } return nil, errStopToken diff --git a/core/vm/instructions_test.go b/core/vm/instructions_test.go index 1ccc7ff505191..0d01b983f254a 100644 --- a/core/vm/instructions_test.go +++ b/core/vm/instructions_test.go @@ -594,7 +594,7 @@ func TestOpTstore(t *testing.T) { caller = common.Address{} to = common.Address{1} contractRef = contractRef{caller} - contract = NewContract(contractRef, AccountRef(to), new(big.Int), 0) + contract = NewContract(contractRef, AccountRef(to), new(uint256.Int), 0) scopeContext = ScopeContext{mem, stack, contract} value = common.Hex2Bytes("abcdef00000000000000abba000000000deaf000000c0de00100000000133700") ) diff --git a/core/vm/interface.go b/core/vm/interface.go index c6c3ee1cfd98b..f8b298bafb378 100644 --- a/core/vm/interface.go +++ b/core/vm/interface.go @@ -22,15 +22,16 @@ import ( "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) // StateDB is an EVM database for full state querying. type StateDB interface { CreateAccount(common.Address) - SubBalance(common.Address, *big.Int) - AddBalance(common.Address, *big.Int) - GetBalance(common.Address) *big.Int + SubBalance(common.Address, *uint256.Int) + AddBalance(common.Address, *uint256.Int) + GetBalance(common.Address) *uint256.Int GetNonce(common.Address) uint64 SetNonce(common.Address, uint64) diff --git a/core/vm/logger_test.go b/core/vm/logger_test.go index 108656fee11c9..07d0db412d1c1 100644 --- a/core/vm/logger_test.go +++ b/core/vm/logger_test.go @@ -52,7 +52,7 @@ func TestStoreCapture(t *testing.T) { var ( env = NewEVM(BlockContext{}, TxContext{}, &dummyStatedb{}, nil, params.TestChainConfig, Config{}) logger = NewStructLogger(nil) - contract = NewContract(&dummyContractRef{}, &dummyContractRef{}, new(big.Int), 0) + contract = NewContract(&dummyContractRef{}, &dummyContractRef{}, new(uint256.Int), 0) scope = &ScopeContext{ Memory: NewMemory(), Stack: newstack(), diff --git a/core/vm/runtime/runtime.go b/core/vm/runtime/runtime.go index 5e7d7b8f55452..0c3e8ebff49b8 100644 --- a/core/vm/runtime/runtime.go +++ b/core/vm/runtime/runtime.go @@ -27,6 +27,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/vm" "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) // Config is a basic type specifying certain configuration flags for running @@ -136,7 +137,7 @@ func Execute(code, input []byte, cfg *Config) ([]byte, *state.StateDB, error) { common.BytesToAddress([]byte("contract")), input, cfg.GasLimit, - cfg.Value, + uint256.MustFromBig(cfg.Value), ) return ret, cfg.State, err } @@ -167,7 +168,7 @@ func Create(input []byte, cfg *Config) ([]byte, common.Address, uint64, error) { sender, input, cfg.GasLimit, - cfg.Value, + uint256.MustFromBig(cfg.Value), ) return code, address, leftOverGas, err } @@ -197,7 +198,7 @@ func Call(address common.Address, input []byte, cfg *Config) ([]byte, uint64, er address, input, cfg.GasLimit, - cfg.Value, + uint256.MustFromBig(cfg.Value), ) return ret, leftOverGas, err } diff --git a/core/vm/runtime/runtime_test.go b/core/vm/runtime/runtime_test.go index 48c707f006e98..493d5974abdc7 100644 --- a/core/vm/runtime/runtime_test.go +++ b/core/vm/runtime/runtime_test.go @@ -33,6 +33,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/core/vm" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) func TestDefaults(t *testing.T) { @@ -361,12 +362,12 @@ func benchmarkNonModifyingCode(gas uint64, code []byte, name string, b *testing. //cfg.State.CreateAccount(cfg.Origin) // set the receiver's (the executing contract) code for execution. cfg.State.SetCode(destination, code) - vmenv.Call(sender, destination, nil, gas, cfg.Value) + vmenv.Call(sender, destination, nil, gas, uint256.MustFromBig(cfg.Value)) b.Run(name, func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { - vmenv.Call(sender, destination, nil, gas, cfg.Value) + vmenv.Call(sender, destination, nil, gas, uint256.MustFromBig(cfg.Value)) } }) } diff --git a/eth/api_backend.go b/eth/api_backend.go index 183a0f1f4485a..9e4be90ee3beb 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -48,6 +48,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/log" "github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/rpc" + "github.com/holiman/uint256" ) // EthApiBackend implements ethapi.Backend for full nodes @@ -253,7 +254,7 @@ func (b *EthApiBackend) GetEVM(ctx context.Context, msg core.Message, state *sta if vmConfig == nil { vmConfig = b.eth.blockchain.GetVMConfig() } - state.SetBalance(msg.From(), math.MaxBig256) + state.SetBalance(msg.From(), uint256.MustFromBig(math.MaxBig256)) txContext := core.NewEVMTxContext(msg) context := core.NewEVMBlockContext(header, b.eth.BlockChain(), nil) return vm.NewEVM(context, txContext, state, XDCxState, b.eth.chainConfig, *vmConfig), vmError, nil diff --git a/eth/hooks/engine_v1_hooks.go b/eth/hooks/engine_v1_hooks.go index 553ffc5916718..4a0d573aa33e6 100644 --- a/eth/hooks/engine_v1_hooks.go +++ b/eth/hooks/engine_v1_hooks.go @@ -20,6 +20,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/eth/util" "github.com/XinFinOrg/XDPoSChain/log" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) func AttachConsensusV1Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConfig *params.ChainConfig) { @@ -294,7 +295,7 @@ func AttachConsensusV1Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConf } if len(rewards) > 0 { for holder, reward := range rewards { - stateBlock.AddBalance(holder, reward) + stateBlock.AddBalance(holder, uint256.MustFromBig(reward)) } } voterResults[signer] = rewards diff --git a/eth/hooks/engine_v2_hooks.go b/eth/hooks/engine_v2_hooks.go index fde8e924879ff..e68d32b4ea55c 100644 --- a/eth/hooks/engine_v2_hooks.go +++ b/eth/hooks/engine_v2_hooks.go @@ -15,6 +15,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/eth/util" "github.com/XinFinOrg/XDPoSChain/log" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) func AttachConsensusV2Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConfig *params.ChainConfig) { @@ -202,7 +203,7 @@ func AttachConsensusV2Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConf } if len(rewards) > 0 { for holder, reward := range rewards { - stateBlock.AddBalance(holder, reward) + stateBlock.AddBalance(holder, uint256.MustFromBig(reward)) } } voterResults[signer] = rewards diff --git a/eth/tracers/tracer.go b/eth/tracers/tracer.go index 2fa04cd1ad266..6daac97f43a6d 100644 --- a/eth/tracers/tracer.go +++ b/eth/tracers/tracer.go @@ -197,7 +197,7 @@ func (dw *dbWrapper) pushObject(vm *duktape.Context) { // Push the wrapper for statedb.GetBalance vm.PushGoFunction(func(ctx *duktape.Context) int { - pushBigInt(dw.db.GetBalance(common.BytesToAddress(popSlice(ctx))), ctx) + pushBigInt(dw.db.GetBalance(common.BytesToAddress(popSlice(ctx))).ToBig(), ctx) return 1 }) vm.PutPropString(obj, "getBalance") @@ -268,7 +268,7 @@ func (cw *contractWrapper) pushObject(vm *duktape.Context) { // Push the wrapper for contract.Value vm.PushGoFunction(func(ctx *duktape.Context) int { - pushBigInt(cw.contract.Value(), ctx) + pushBigInt(cw.contract.Value().ToBig(), ctx) return 1 }) vm.PutPropString(obj, "getValue") diff --git a/eth/tracers/tracer_test.go b/eth/tracers/tracer_test.go index 7721dbed303ac..83f93dd965a77 100644 --- a/eth/tracers/tracer_test.go +++ b/eth/tracers/tracer_test.go @@ -28,6 +28,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/vm" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) type account struct{} @@ -36,9 +37,9 @@ func (account) SubBalance(amount *big.Int) {} func (account) AddBalance(amount *big.Int) {} func (account) SetAddress(common.Address) {} func (account) Value() *big.Int { return nil } -func (account) SetBalance(*big.Int) {} +func (account) SetBalance(*uint256.Int) {} func (account) SetNonce(uint64) {} -func (account) Balance() *big.Int { return nil } +func (account) Balance() *uint256.Int { return nil } func (account) Address() common.Address { return common.Address{} } func (account) SetCode(common.Hash, []byte) {} func (account) ForEachStorage(cb func(key, value common.Hash) bool) {} @@ -47,8 +48,8 @@ type dummyStatedb struct { state.StateDB } -func (*dummyStatedb) GetRefund() uint64 { return 1337 } -func (*dummyStatedb) GetBalance(addr common.Address) *big.Int { return new(big.Int) } +func (*dummyStatedb) GetRefund() uint64 { return 1337 } +func (*dummyStatedb) GetBalance(addr common.Address) *uint256.Int { return new(uint256.Int) } type vmContext struct { ctx vm.BlockContext @@ -58,7 +59,7 @@ type vmContext struct { func runTrace(tracer Tracer, blockNumber *big.Int, chaincfg *params.ChainConfig) (json.RawMessage, error) { var ( startGas uint64 = 10000 - value = big.NewInt(0) + value = uint256.NewInt(0) ctx = vm.BlockContext{BlockNumber: blockNumber} txContext = vm.TxContext{GasPrice: big.NewInt(100000)} ) @@ -68,7 +69,7 @@ func runTrace(tracer Tracer, blockNumber *big.Int, chaincfg *params.ChainConfig) contract := vm.NewContract(account{}, account{}, value, startGas) contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x1, 0x0} - tracer.CaptureStart(env, contract.Caller(), contract.Address(), false, []byte{}, startGas, value) + tracer.CaptureStart(env, contract.Caller(), contract.Address(), false, []byte{}, startGas, value.ToBig()) ret, err := env.Interpreter().Run(contract, []byte{}, false) tracer.CaptureEnd(ret, startGas-contract.Gas, 1, err) if err != nil { @@ -151,7 +152,7 @@ func TestHaltBetweenSteps(t *testing.T) { } env := vm.NewEVM(vm.BlockContext{BlockNumber: big.NewInt(1)}, vm.TxContext{}, &dummyStatedb{}, nil, params.TestChainConfig, vm.Config{Debug: true, Tracer: tracer}) scope := &vm.ScopeContext{ - Contract: vm.NewContract(&account{}, &account{}, big.NewInt(0), 0), + Contract: vm.NewContract(&account{}, &account{}, uint256.NewInt(0), 0), } tracer.CaptureState(env, 0, 0, 0, 0, scope, nil, 0, nil) timeout := errors.New("stahp") @@ -171,7 +172,7 @@ func TestNoStepExec(t *testing.T) { txContext := vm.TxContext{GasPrice: big.NewInt(100000)} env := vm.NewEVM(ctx, txContext, &dummyStatedb{}, nil, params.TestChainConfig, vm.Config{Debug: true, Tracer: tracer}) startGas := uint64(10000) - contract := vm.NewContract(account{}, account{}, big.NewInt(0), startGas) + contract := vm.NewContract(account{}, account{}, uint256.NewInt(0), startGas) tracer.CaptureStart(env, contract.Caller(), contract.Address(), false, []byte{}, startGas, big.NewInt(0)) tracer.CaptureEnd(nil, startGas-contract.Gas, 1, nil) return tracer.GetResult() @@ -246,7 +247,7 @@ func TestEnterExit(t *testing.T) { } scope := &vm.ScopeContext{ - Contract: vm.NewContract(&account{}, &account{}, big.NewInt(0), 0), + Contract: vm.NewContract(&account{}, &account{}, uint256.NewInt(0), 0), } tracer.CaptureEnter(vm.CALL, scope.Contract.Caller(), scope.Contract.Address(), []byte{}, 1000, new(big.Int)) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 44c39bdc6495e..d68f6f2aaac7f 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -51,6 +51,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/rlp" "github.com/XinFinOrg/XDPoSChain/rpc" + "github.com/holiman/uint256" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/util" ) @@ -612,7 +613,8 @@ func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Add if state == nil || err != nil { return nil, err } - return (*hexutil.Big)(state.GetBalance(address)), state.Error() + b := state.GetBalance(address).ToBig() + return (*hexutil.Big)(b), state.Error() } // GetTransactionAndReceiptProof returns the Trie transaction and receipt proof of the given transaction hash. @@ -757,7 +759,7 @@ func (s *PublicBlockChainAPI) GetAccountInfo(ctx context.Context, address common info := state.GetAccountInfo(address) result := map[string]interface{}{ "address": address, - "balance": (*hexutil.Big)(info.Balance), + "balance": info.Balance, "codeSize": info.CodeSize, "codeHash": info.CodeHash, "nonce": info.Nonce, @@ -839,7 +841,8 @@ func (diff *StateOverride) Apply(state *state.StateDB) error { } // Override account balance. if account.Balance != nil { - state.SetBalance(addr, (*big.Int)(*account.Balance)) + u256Balance, _ := uint256.FromBig((*big.Int)(*account.Balance)) + state.SetBalance(addr, u256Balance) } if account.State != nil && account.StateDiff != nil { return fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex()) diff --git a/les/api_backend.go b/les/api_backend.go index fe8371c5a25d9..050eee39a046a 100644 --- a/les/api_backend.go +++ b/les/api_backend.go @@ -45,6 +45,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/light" "github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/rpc" + "github.com/holiman/uint256" ) type LesApiBackend struct { @@ -188,7 +189,7 @@ func (b *LesApiBackend) GetEVM(ctx context.Context, msg core.Message, state *sta if vmConfig == nil { vmConfig = new(vm.Config) } - state.SetBalance(msg.From(), math.MaxBig256) + state.SetBalance(msg.From(), uint256.MustFromBig(math.MaxBig256)) txContext := core.NewEVMTxContext(msg) context := core.NewEVMBlockContext(header, b.eth.blockchain, nil) return vm.NewEVM(context, txContext, state, XDCxState, b.eth.chainConfig, *vmConfig), state.Error, nil diff --git a/les/odr_test.go b/les/odr_test.go index 706853d504b2c..ea9cefc559012 100644 --- a/les/odr_test.go +++ b/les/odr_test.go @@ -35,6 +35,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/light" "github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/rlp" + "github.com/holiman/uint256" ) type odrTestFn func(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte @@ -127,7 +128,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai if err == nil { from := statedb.GetOrNewStateObject(testBankAddress) - from.SetBalance(math.MaxBig256) + from.SetBalance(uint256.MustFromBig(math.MaxBig256)) feeCapacity := state.GetTRC21FeeCapacityFromState(statedb) var balanceTokenFee *big.Int if value, ok := feeCapacity[testContractAddr]; ok { @@ -148,7 +149,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai } else { header := lc.GetHeaderByHash(bhash) statedb := light.NewState(ctx, header, lc.Odr()) - statedb.SetBalance(testBankAddress, math.MaxBig256) + statedb.SetBalance(testBankAddress, uint256.MustFromBig(math.MaxBig256)) feeCapacity := state.GetTRC21FeeCapacityFromState(statedb) var balanceTokenFee *big.Int if value, ok := feeCapacity[testContractAddr]; ok { diff --git a/light/odr_test.go b/light/odr_test.go index 79d3241c2048d..cfb5bd6047442 100644 --- a/light/odr_test.go +++ b/light/odr_test.go @@ -26,6 +26,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/consensus" "github.com/XinFinOrg/XDPoSChain/core/rawdb" + "github.com/holiman/uint256" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common/math" @@ -179,7 +180,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain } // Perform read-only call. - st.SetBalance(testBankAddress, math.MaxBig256) + st.SetBalance(testBankAddress, uint256.MustFromBig(math.MaxBig256)) feeCapacity := state.GetTRC21FeeCapacityFromState(st) var balanceTokenFee *big.Int if value, ok := feeCapacity[testContractAddr]; ok { diff --git a/light/txpool.go b/light/txpool.go index a1d9190a38748..a2c291ea1111c 100644 --- a/light/txpool.go +++ b/light/txpool.go @@ -32,6 +32,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/event" "github.com/XinFinOrg/XDPoSChain/log" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) const ( @@ -405,7 +406,7 @@ func (p *TxPool) validateTx(ctx context.Context, tx *types.Transaction) error { // Transactor should have enough funds to cover the costs // cost == V + GP * GL - if b := currentState.GetBalance(from); b.Cmp(tx.Cost()) < 0 { + if b := currentState.GetBalance(from); b.Cmp(uint256.MustFromBig(tx.Cost())) < 0 { return core.ErrInsufficientFunds } diff --git a/tests/block_test_util.go b/tests/block_test_util.go index 44d1c1b4d72ff..c72c810cd5143 100644 --- a/tests/block_test_util.go +++ b/tests/block_test_util.go @@ -262,7 +262,7 @@ func (t *BlockTest) validatePostState(statedb *state.StateDB) error { for addr, acct := range t.json.Post { // address is indirectly verified by the other fields, as it's the db key code2 := statedb.GetCode(addr) - balance2 := statedb.GetBalance(addr) + balance2 := statedb.GetBalance(addr).ToBig() nonce2 := statedb.GetNonce(addr) if !bytes.Equal(code2, acct.Code) { return fmt.Errorf("account code mismatch for addr: %s want: %v have: %s", addr, acct.Code, hex.EncodeToString(code2)) diff --git a/tests/state_test_util.go b/tests/state_test_util.go index 6f9ace8ec3ef5..2f30bcec40cf4 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -36,6 +36,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/ethdb" "github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/rlp" + "github.com/holiman/uint256" "golang.org/x/crypto/sha3" ) @@ -191,7 +192,7 @@ func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB for addr, a := range accounts { statedb.SetCode(addr, a.Code) statedb.SetNonce(addr, a.Nonce) - statedb.SetBalance(addr, a.Balance) + statedb.SetBalance(addr, uint256.MustFromBig(a.Balance)) for k, v := range a.Storage { statedb.SetState(addr, k, v) } diff --git a/tests/vm_test_util.go b/tests/vm_test_util.go index 0dfa4f634922d..2014b05e05de7 100644 --- a/tests/vm_test_util.go +++ b/tests/vm_test_util.go @@ -32,6 +32,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/vm" "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/params" + "github.com/holiman/uint256" ) // VMTest checks EVM execution without block or transaction context. @@ -119,19 +120,19 @@ func (t *VMTest) Run(vmconfig vm.Config) error { func (t *VMTest) exec(statedb *state.StateDB, vmconfig vm.Config) ([]byte, uint64, error) { evm := t.newEVM(statedb, vmconfig) e := t.json.Exec - return evm.Call(vm.AccountRef(e.Caller), e.Address, e.Data, e.GasLimit, e.Value) + return evm.Call(vm.AccountRef(e.Caller), e.Address, e.Data, e.GasLimit, uint256.MustFromBig(e.Value)) } func (t *VMTest) newEVM(statedb *state.StateDB, vmconfig vm.Config) *vm.EVM { initialCall := true - canTransfer := func(db vm.StateDB, address common.Address, amount *big.Int) bool { + canTransfer := func(db vm.StateDB, address common.Address, amount *uint256.Int) bool { if initialCall { initialCall = false return true } return core.CanTransfer(db, address, amount) } - transfer := func(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {} + transfer := func(db vm.StateDB, sender, recipient common.Address, amount *uint256.Int) {} txContext := vm.TxContext{ Origin: t.json.Exec.Origin, GasPrice: t.json.Exec.GasPrice,