Skip to content

Commit

Permalink
all: use uint256 in state (28598)
Browse files Browse the repository at this point in the history
  • Loading branch information
JukLee0ira committed Dec 16, 2024
1 parent 47c18c5 commit 3f8ee3f
Show file tree
Hide file tree
Showing 51 changed files with 245 additions and 217 deletions.
9 changes: 5 additions & 4 deletions XDCx/order_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"time"

"github.com/XinFinOrg/XDPoSChain/core/types"
"github.com/holiman/uint256"

"github.com/XinFinOrg/XDPoSChain/consensus"

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand All @@ -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)
}
Expand Down
21 changes: 11 additions & 10 deletions XDCx/tradingstate/relayer_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
}
Expand All @@ -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)

Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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) {
Expand All @@ -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
}

Expand All @@ -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))
}
19 changes: 10 additions & 9 deletions XDCxlending/lendingstate/relayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
}
Expand All @@ -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)

Expand All @@ -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)

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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) {
Expand All @@ -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
}

Expand All @@ -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))
}
5 changes: 3 additions & 2 deletions XDCxlending/order_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 3 additions & 2 deletions accounts/abi/bind/backends/simulated.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions cmd/puppeth/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()

Expand Down
8 changes: 7 additions & 1 deletion common/big.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@

package common

import "math/big"
import (
"math/big"

"github.com/holiman/uint256"
)

// Common big integers often used
var (
Expand All @@ -27,4 +31,6 @@ var (
Big32 = big.NewInt(32)
Big256 = big.NewInt(256)
Big257 = big.NewInt(257)

U2560 = uint256.NewInt(0)
)
27 changes: 15 additions & 12 deletions consensus/ethash/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down
Loading

0 comments on commit 3f8ee3f

Please sign in to comment.