diff --git a/XDCx/XDCx.go b/XDCx/XDCx.go index 6506929984..3dc3386d92 100644 --- a/XDCx/XDCx.go +++ b/XDCx/XDCx.go @@ -292,10 +292,10 @@ func (XDCx *XDCX) GetAveragePriceLastEpoch(chain consensus.ChainContext, statedb // return tokenQuantity (after convert from XDC to token), tokenPriceInXDC, error func (XDCx *XDCX) ConvertXDCToToken(chain consensus.ChainContext, statedb *state.StateDB, tradingStateDb *tradingstate.TradingStateDB, token common.Address, quantity *big.Int) (*big.Int, *big.Int, error) { - if token.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { return quantity, common.BasePrice, nil } - tokenPriceInXDC, err := XDCx.GetAveragePriceLastEpoch(chain, statedb, tradingStateDb, token, common.HexToAddress(common.XDCNativeAddress)) + tokenPriceInXDC, err := XDCx.GetAveragePriceLastEpoch(chain, statedb, tradingStateDb, token, common.XDCNativeAddressBinary) if err != nil || tokenPriceInXDC == nil || tokenPriceInXDC.Sign() <= 0 { return common.Big0, common.Big0, err } @@ -595,10 +595,11 @@ func (XDCx *XDCX) GetTriegc() *prque.Prque { func (XDCx *XDCX) GetTradingStateRoot(block *types.Block, author common.Address) (common.Hash, error) { for _, tx := range block.Transactions() { - from := *(tx.From()) - if tx.To() != nil && tx.To().Hex() == common.TradingStateAddr && from.String() == author.String() { - if len(tx.Data()) >= 32 { - return common.BytesToHash(tx.Data()[:32]), nil + to := tx.To() + if to != nil && *to == common.TradingStateAddrBinary && *tx.From() == author { + data := tx.Data() + if len(data) >= 32 { + return common.BytesToHash(data[:32]), nil } } } diff --git a/XDCx/order_processor.go b/XDCx/order_processor.go index ca9ca496e3..86d156fec8 100644 --- a/XDCx/order_processor.go +++ b/XDCx/order_processor.go @@ -236,11 +236,11 @@ func (XDCx *XDCX) processOrderList(coinbase common.Address, chain consensus.Chai maxTradedQuantity = tradingstate.CloneBigInt(amount) } var quotePrice *big.Int - if oldestOrder.QuoteToken.String() != common.XDCNativeAddress { - quotePrice = tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(oldestOrder.QuoteToken, common.HexToAddress(common.XDCNativeAddress))) + if oldestOrder.QuoteToken != common.XDCNativeAddressBinary { + quotePrice = tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(oldestOrder.QuoteToken, common.XDCNativeAddressBinary)) log.Debug("TryGet quotePrice QuoteToken/XDC", "quotePrice", quotePrice) if quotePrice == nil || quotePrice.Sign() == 0 { - inversePrice := tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(common.HexToAddress(common.XDCNativeAddress), oldestOrder.QuoteToken)) + inversePrice := tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(common.XDCNativeAddressBinary, oldestOrder.QuoteToken)) quoteTokenDecimal, err := XDCx.GetTokenDecimal(chain, statedb, oldestOrder.QuoteToken) if err != nil || quoteTokenDecimal.Sign() == 0 { return nil, nil, nil, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", oldestOrder.QuoteToken.String(), err) @@ -374,10 +374,10 @@ func (XDCx *XDCX) getTradeQuantity(quotePrice *big.Int, coinbase common.Address, if err != nil || quoteTokenDecimal.Sign() == 0 { return tradingstate.Zero, false, nil, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", makerOrder.QuoteToken.String(), err) } - if makerOrder.QuoteToken.String() == common.XDCNativeAddress { + if makerOrder.QuoteToken == common.XDCNativeAddressBinary { quotePrice = quoteTokenDecimal } - if takerOrder.ExchangeAddress.String() == makerOrder.ExchangeAddress.String() { + if takerOrder.ExchangeAddress == makerOrder.ExchangeAddress { if err := tradingstate.CheckRelayerFee(takerOrder.ExchangeAddress, new(big.Int).Mul(common.RelayerFee, big.NewInt(2)), statedb); err != nil { log.Debug("Reject order Taker Exchnage = Maker Exchange , relayer not enough fee ", "err", err) return tradingstate.Zero, false, nil, nil diff --git a/XDCx/order_processor_test.go b/XDCx/order_processor_test.go index 7ab396f83f..b3a651ae98 100644 --- a/XDCx/order_processor_test.go +++ b/XDCx/order_processor_test.go @@ -1,12 +1,13 @@ package XDCx import ( - "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" - "github.com/XinFinOrg/XDPoSChain/common" - "github.com/XinFinOrg/XDPoSChain/core/rawdb" "math/big" "reflect" "testing" + + "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" + "github.com/XinFinOrg/XDPoSChain/common" + "github.com/XinFinOrg/XDPoSChain/core/rawdb" ) func Test_getCancelFeeV1(t *testing.T) { @@ -103,9 +104,9 @@ func Test_getCancelFee(t *testing.T) { XDCx.SetTokenDecimal(testTokenB, tokenBDecimal) // set tokenAPrice = 1 XDC - tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenA, common.HexToAddress(common.XDCNativeAddress)), common.BasePrice) + tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenA, common.XDCNativeAddressBinary), common.BasePrice) // set tokenBPrice = 1 XDC - tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(common.HexToAddress(common.XDCNativeAddress), testTokenB), tokenBDecimal) + tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(common.XDCNativeAddressBinary, testTokenB), tokenBDecimal) type CancelFeeArg struct { feeRate *big.Int @@ -127,7 +128,7 @@ func Test_getCancelFee(t *testing.T) { feeRate: common.Big0, order: &tradingstate.OrderItem{ BaseToken: testTokenA, - QuoteToken: common.HexToAddress(common.XDCNativeAddress), + QuoteToken: common.XDCNativeAddressBinary, Quantity: new(big.Int).SetUint64(10000), Side: tradingstate.Ask, }, @@ -142,7 +143,7 @@ func Test_getCancelFee(t *testing.T) { feeRate: common.Big0, order: &tradingstate.OrderItem{ BaseToken: testTokenA, - QuoteToken: common.HexToAddress(common.XDCNativeAddress), + QuoteToken: common.XDCNativeAddressBinary, Quantity: new(big.Int).SetUint64(10000), Side: tradingstate.Bid, }, @@ -156,7 +157,7 @@ func Test_getCancelFee(t *testing.T) { CancelFeeArg{ feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1% order: &tradingstate.OrderItem{ - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: testTokenA, Quantity: new(big.Int).SetUint64(10000), Side: tradingstate.Ask, @@ -172,7 +173,7 @@ func Test_getCancelFee(t *testing.T) { feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1% order: &tradingstate.OrderItem{ Quantity: new(big.Int).SetUint64(10000), - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: testTokenA, Side: tradingstate.Bid, }, @@ -188,7 +189,7 @@ func Test_getCancelFee(t *testing.T) { CancelFeeArg{ feeRate: common.Big0, order: &tradingstate.OrderItem{ - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: testTokenA, Quantity: new(big.Int).SetUint64(10000), Side: tradingstate.Ask, @@ -203,7 +204,7 @@ func Test_getCancelFee(t *testing.T) { CancelFeeArg{ feeRate: common.Big0, order: &tradingstate.OrderItem{ - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: testTokenA, Quantity: new(big.Int).SetUint64(10000), Side: tradingstate.Bid, @@ -218,7 +219,7 @@ func Test_getCancelFee(t *testing.T) { CancelFeeArg{ feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1% order: &tradingstate.OrderItem{ - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: testTokenA, Quantity: new(big.Int).SetUint64(10000), Side: tradingstate.Ask, @@ -234,7 +235,7 @@ func Test_getCancelFee(t *testing.T) { feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1% order: &tradingstate.OrderItem{ Quantity: new(big.Int).SetUint64(10000), - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: testTokenA, Side: tradingstate.Bid, }, diff --git a/XDCx/token.go b/XDCx/token.go index 2bf37e3f2f..5aa8554cf9 100644 --- a/XDCx/token.go +++ b/XDCx/token.go @@ -48,7 +48,7 @@ func (XDCx *XDCX) GetTokenDecimal(chain consensus.ChainContext, statedb *state.S if tokenDecimal, ok := XDCx.tokenDecimalCache.Get(tokenAddr); ok { return tokenDecimal.(*big.Int), nil } - if tokenAddr.String() == common.XDCNativeAddress { + if tokenAddr == common.XDCNativeAddressBinary { XDCx.tokenDecimalCache.Add(tokenAddr, common.BasePrice) return common.BasePrice, nil } diff --git a/XDCx/tradingstate/orderitem.go b/XDCx/tradingstate/orderitem.go index f28e978435..8c39375b5f 100644 --- a/XDCx/tradingstate/orderitem.go +++ b/XDCx/tradingstate/orderitem.go @@ -239,7 +239,7 @@ func (o *OrderItem) verifyRelayer(state *state.StateDB) error { return nil } -//verify signatures +// verify signatures func (o *OrderItem) verifySignature() error { bigstr := o.Nonce.String() n, err := strconv.ParseInt(bigstr, 10, 64) @@ -269,7 +269,7 @@ func (o *OrderItem) verifyOrderType() error { return nil } -//verify order side +// verify order side func (o *OrderItem) verifyOrderSide() error { if o.Side != Bid && o.Side != Ask { @@ -356,11 +356,11 @@ func VerifyPair(statedb *state.StateDB, exchangeAddress, baseToken, quoteToken c func VerifyBalance(statedb *state.StateDB, XDCxStateDb *TradingStateDB, order *types.OrderTransaction, baseDecimal, quoteDecimal *big.Int) error { var quotePrice *big.Int - if order.QuoteToken().String() != common.XDCNativeAddress { - quotePrice = XDCxStateDb.GetLastPrice(GetTradingOrderBookHash(order.QuoteToken(), common.HexToAddress(common.XDCNativeAddress))) + if order.QuoteToken() != common.XDCNativeAddressBinary { + quotePrice = XDCxStateDb.GetLastPrice(GetTradingOrderBookHash(order.QuoteToken(), common.XDCNativeAddressBinary)) log.Debug("TryGet quotePrice QuoteToken/XDC", "quotePrice", quotePrice) if quotePrice == nil || quotePrice.Sign() == 0 { - inversePrice := XDCxStateDb.GetLastPrice(GetTradingOrderBookHash(common.HexToAddress(common.XDCNativeAddress), order.QuoteToken())) + inversePrice := XDCxStateDb.GetLastPrice(GetTradingOrderBookHash(common.XDCNativeAddressBinary, order.QuoteToken())) log.Debug("TryGet inversePrice XDC/QuoteToken", "inversePrice", inversePrice) if inversePrice != nil && inversePrice.Sign() > 0 { quotePrice = new(big.Int).Mul(common.BasePrice, quoteDecimal) diff --git a/XDCx/tradingstate/relayer_state.go b/XDCx/tradingstate/relayer_state.go index 2a1892492d..348f213041 100644 --- a/XDCx/tradingstate/relayer_state.go +++ b/XDCx/tradingstate/relayer_state.go @@ -159,9 +159,9 @@ func CheckRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateD } func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error { // XDC native - if token.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { balance := statedb.GetBalance(addr) - log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) + log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) statedb.AddBalance(addr, 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) @@ -186,10 +186,9 @@ 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 { // XDC native - if token.String() == common.XDCNativeAddress { - + if token == common.XDCNativeAddressBinary { balance := statedb.GetBalance(addr) - log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) + 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 { return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), token.String(), balance, value) } @@ -219,7 +218,7 @@ func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) { // XDC native - if token.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { var balance *big.Int if value := mapBalances[token][addr]; value != nil { balance = value @@ -256,7 +255,7 @@ func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Addr func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) { // XDC native - if token.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { var balance *big.Int if value := mapBalances[token][addr]; value != nil { balance = value @@ -308,7 +307,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.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { return statedb.GetBalance(addr) } // TRC tokens @@ -323,7 +322,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.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { statedb.SetBalance(addr, balance) return nil } diff --git a/XDCx/tradingstate/settle_balance.go b/XDCx/tradingstate/settle_balance.go index 66996ae5b2..771da0c29b 100644 --- a/XDCx/tradingstate/settle_balance.go +++ b/XDCx/tradingstate/settle_balance.go @@ -52,7 +52,7 @@ func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.I log.Debug("quantity trade too small", "quoteTokenQuantity", quoteTokenQuantity, "makerFee", makerFee, "defaultFee", defaultFee) return result, ErrQuantityTradeTooSmall } - if quoteToken.String() != common.XDCNativeAddress && quotePrice != nil && quotePrice.Cmp(common.Big0) > 0 { + if quoteToken != common.XDCNativeAddressBinary && quotePrice != nil && quotePrice.Cmp(common.Big0) > 0 { // defaultFeeInXDC defaultFeeInXDC := new(big.Int).Mul(defaultFee, quotePrice) defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, quoteTokenDecimal) @@ -69,7 +69,7 @@ func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.I log.Debug("takerFee too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "quotePrice", quotePrice, "defaultFeeInXDC", defaultFeeInXDC) return result, ErrQuantityTradeTooSmall } - } else if quoteToken.String() == common.XDCNativeAddress { + } else if quoteToken == common.XDCNativeAddressBinary { exMakerReceivedFee := makerFee if (exMakerReceivedFee.Cmp(common.RelayerFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerFee) <= 0 { log.Debug("makerFee too small", "quantityToTrade", quantityToTrade, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "makerFeeRate", makerFeeRate, "defaultFee", defaultFee) @@ -108,7 +108,7 @@ func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.I log.Debug("quantity trade too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee) return result, ErrQuantityTradeTooSmall } - if quoteToken.String() != common.XDCNativeAddress && quotePrice != nil && quotePrice.Cmp(common.Big0) > 0 { + if quoteToken != common.XDCNativeAddressBinary && quotePrice != nil && quotePrice.Cmp(common.Big0) > 0 { // defaultFeeInXDC defaultFeeInXDC := new(big.Int).Mul(defaultFee, quotePrice) defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, quoteTokenDecimal) @@ -126,7 +126,7 @@ func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.I log.Debug("takerFee too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "quotePrice", quotePrice, "defaultFeeInXDC", defaultFeeInXDC) return result, ErrQuantityTradeTooSmall } - } else if quoteToken.String() == common.XDCNativeAddress { + } else if quoteToken == common.XDCNativeAddressBinary { exMakerReceivedFee := makerFee if (exMakerReceivedFee.Cmp(common.RelayerFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerFee) <= 0 { log.Debug("makerFee too small", "quantityToTrade", quantityToTrade, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "makerFeeRate", makerFeeRate, "defaultFee", defaultFee) diff --git a/XDCx/tradingstate/settle_balance_test.go b/XDCx/tradingstate/settle_balance_test.go index 674e381fd8..d340226fc7 100644 --- a/XDCx/tradingstate/settle_balance_test.go +++ b/XDCx/tradingstate/settle_balance_test.go @@ -1,10 +1,11 @@ package tradingstate import ( - "github.com/XinFinOrg/XDPoSChain/common" "math/big" "reflect" "testing" + + "github.com/XinFinOrg/XDPoSChain/common" ) func TestGetSettleBalance(t *testing.T) { @@ -89,7 +90,7 @@ func TestGetSettleBalance(t *testing.T) { takerSide: Bid, takerFeeRate: big.NewInt(10), // feeRate 0.1% baseToken: testToken, - quoteToken: common.HexToAddress(common.XDCNativeAddress), + quoteToken: common.XDCNativeAddressBinary, makerPrice: common.BasePrice, makerFeeRate: big.NewInt(10), // feeRate 0.1% baseTokenDecimal: common.BasePrice, @@ -106,7 +107,7 @@ func TestGetSettleBalance(t *testing.T) { takerSide: Bid, takerFeeRate: big.NewInt(5), // feeRate 0.05% baseToken: testToken, - quoteToken: common.HexToAddress(common.XDCNativeAddress), + quoteToken: common.XDCNativeAddressBinary, makerPrice: common.BasePrice, makerFeeRate: big.NewInt(10), // feeRate 0.1% baseTokenDecimal: common.BasePrice, @@ -124,7 +125,7 @@ func TestGetSettleBalance(t *testing.T) { takerSide: Bid, takerFeeRate: big.NewInt(10), // feeRate 0.1% baseToken: testToken, - quoteToken: common.HexToAddress(common.XDCNativeAddress), + quoteToken: common.XDCNativeAddressBinary, makerPrice: common.BasePrice, makerFeeRate: big.NewInt(10), // feeRate 0.1% baseTokenDecimal: common.BasePrice, @@ -132,8 +133,8 @@ func TestGetSettleBalance(t *testing.T) { quantityToTrade: new(big.Int).Mul(big.NewInt(1000), common.BasePrice), }, &SettleBalance{ - Taker: TradeResult{Fee: testFee, InToken: testToken, InTotal: tradeQuantity, OutToken: common.HexToAddress(common.XDCNativeAddress), OutTotal: tradeQuantityIncludedFee}, - Maker: TradeResult{Fee: testFee, InToken: common.HexToAddress(common.XDCNativeAddress), InTotal: tradeQuantityExcludedFee, OutToken: testToken, OutTotal: tradeQuantity}, + Taker: TradeResult{Fee: testFee, InToken: testToken, InTotal: tradeQuantity, OutToken: common.XDCNativeAddressBinary, OutTotal: tradeQuantityIncludedFee}, + Maker: TradeResult{Fee: testFee, InToken: common.XDCNativeAddressBinary, InTotal: tradeQuantityExcludedFee, OutToken: testToken, OutTotal: tradeQuantity}, }, false, }, @@ -196,7 +197,7 @@ func TestGetSettleBalance(t *testing.T) { takerSide: Ask, takerFeeRate: big.NewInt(10), // feeRate 0.1% baseToken: testToken, - quoteToken: common.HexToAddress(common.XDCNativeAddress), + quoteToken: common.XDCNativeAddressBinary, makerPrice: common.BasePrice, makerFeeRate: big.NewInt(10), // feeRate 0.1% baseTokenDecimal: common.BasePrice, @@ -213,7 +214,7 @@ func TestGetSettleBalance(t *testing.T) { takerSide: Ask, takerFeeRate: big.NewInt(5), // feeRate 0.05% baseToken: testToken, - quoteToken: common.HexToAddress(common.XDCNativeAddress), + quoteToken: common.XDCNativeAddressBinary, makerPrice: common.BasePrice, makerFeeRate: big.NewInt(10), // feeRate 0.1% baseTokenDecimal: common.BasePrice, @@ -231,7 +232,7 @@ func TestGetSettleBalance(t *testing.T) { takerSide: Ask, takerFeeRate: big.NewInt(10), // feeRate 15% baseToken: testToken, - quoteToken: common.HexToAddress(common.XDCNativeAddress), + quoteToken: common.XDCNativeAddressBinary, makerPrice: common.BasePrice, makerFeeRate: big.NewInt(10), // feeRate 0.1% baseTokenDecimal: common.BasePrice, @@ -239,8 +240,8 @@ func TestGetSettleBalance(t *testing.T) { quantityToTrade: new(big.Int).Mul(big.NewInt(1000), common.BasePrice), }, &SettleBalance{ - Maker: TradeResult{Fee: testFee, InToken: testToken, InTotal: tradeQuantity, OutToken: common.HexToAddress(common.XDCNativeAddress), OutTotal: tradeQuantityIncludedFee}, - Taker: TradeResult{Fee: testFee, InToken: common.HexToAddress(common.XDCNativeAddress), InTotal: tradeQuantityExcludedFee, OutToken: testToken, OutTotal: tradeQuantity}, + Maker: TradeResult{Fee: testFee, InToken: testToken, InTotal: tradeQuantity, OutToken: common.XDCNativeAddressBinary, OutTotal: tradeQuantityIncludedFee}, + Taker: TradeResult{Fee: testFee, InToken: common.XDCNativeAddressBinary, InTotal: tradeQuantityExcludedFee, OutToken: testToken, OutTotal: tradeQuantity}, }, false, }, diff --git a/XDCxlending/XDCxlending.go b/XDCxlending/XDCxlending.go index 352c224d0a..48ff540778 100644 --- a/XDCxlending/XDCxlending.go +++ b/XDCxlending/XDCxlending.go @@ -696,10 +696,11 @@ func (l *Lending) GetTriegc() *prque.Prque { func (l *Lending) GetLendingStateRoot(block *types.Block, author common.Address) (common.Hash, error) { for _, tx := range block.Transactions() { - from := *(tx.From()) - if tx.To() != nil && tx.To().Hex() == common.TradingStateAddr && from.String() == author.String() { - if len(tx.Data()) >= 64 { - return common.BytesToHash(tx.Data()[32:]), nil + to := tx.To() + if to != nil && *to == common.TradingStateAddrBinary && *tx.From() == author { + data := tx.Data() + if len(data) >= 64 { + return common.BytesToHash(data[32:]), nil } } } diff --git a/XDCxlending/lendingstate/lendingitem.go b/XDCxlending/lendingstate/lendingitem.go index 235a77fa60..67469b651c 100644 --- a/XDCxlending/lendingstate/lendingitem.go +++ b/XDCxlending/lendingstate/lendingitem.go @@ -260,7 +260,7 @@ func (l *LendingItem) VerifyCollateral(state *state.StateDB) error { validCollateral := false collateralList := GetCollaterals(state, l.Relayer, l.LendingToken, l.Term) for _, collateral := range collateralList { - if l.CollateralToken.String() == collateral.String() { + if l.CollateralToken == collateral { validCollateral = true break } @@ -411,7 +411,7 @@ func VerifyBalance(isXDCXLendingFork bool, statedb *state.StateDB, lendingStateD defaultFee := new(big.Int).Mul(quantity, new(big.Int).SetUint64(DefaultFeeRate)) defaultFee = new(big.Int).Div(defaultFee, common.XDCXBaseFee) defaultFeeInXDC := common.Big0 - if lendingToken.String() != common.XDCNativeAddress { + if lendingToken != common.XDCNativeAddressBinary { defaultFeeInXDC = new(big.Int).Mul(defaultFee, lendTokenXDCPrice) defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, lendingTokenDecimal) } else { diff --git a/XDCxlending/lendingstate/relayer.go b/XDCxlending/lendingstate/relayer.go index 571ecdcd15..536784741b 100644 --- a/XDCxlending/lendingstate/relayer.go +++ b/XDCxlending/lendingstate/relayer.go @@ -114,12 +114,12 @@ func CheckRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateD } func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error { // XDC native - if token.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { balance := statedb.GetBalance(addr) - log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) + log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) statedb.AddBalance(addr, 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) + log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD XDC NATIVE BALANCE AFTER", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) return nil } @@ -141,15 +141,15 @@ 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 { // XDC native - if token.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { balance := statedb.GetBalance(addr) - log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) + 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 { - return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), token.String(), balance, value) + return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), common.XDCNativeAddress, balance, value) } statedb.SubBalance(addr, value) balance = statedb.GetBalance(addr) - log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE AFTER", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) + log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE AFTER", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value) return nil } @@ -174,7 +174,7 @@ func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) { // XDC native - if token.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { var balance *big.Int if value := mapBalances[token][addr]; value != nil { balance = value @@ -182,10 +182,10 @@ func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Addr balance = statedb.GetBalance(addr) } 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) + return nil, errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), common.XDCNativeAddress, balance, value) } newBalance := new(big.Int).Sub(balance, value) - log.Debug("CheckSubTokenBalance settle balance: SUB XDC NATIVE BALANCE ", "token", token.String(), "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance) + log.Debug("CheckSubTokenBalance settle balance: SUB XDC NATIVE BALANCE ", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance) return newBalance, nil } // TRC tokens @@ -211,7 +211,7 @@ func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Addr func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) { // XDC native - if token.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { var balance *big.Int if value := mapBalances[token][addr]; value != nil { balance = value @@ -219,7 +219,7 @@ func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Addr balance = statedb.GetBalance(addr) } 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) + log.Debug("CheckAddTokenBalance settle balance: ADD XDC NATIVE BALANCE ", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance) return newBalance, nil } // TRC tokens @@ -263,7 +263,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.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { return statedb.GetBalance(addr) } // TRC tokens @@ -278,7 +278,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.String() == common.XDCNativeAddress { + if token == common.XDCNativeAddressBinary { statedb.SetBalance(addr, balance) return nil } diff --git a/XDCxlending/lendingstate/settle_balance.go b/XDCxlending/lendingstate/settle_balance.go index 108a459afe..93ee96d936 100644 --- a/XDCxlending/lendingstate/settle_balance.go +++ b/XDCxlending/lendingstate/settle_balance.go @@ -3,9 +3,10 @@ package lendingstate import ( "encoding/json" "errors" + "math/big" + "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/log" - "math/big" ) const DefaultFeeRate = 100 // 100 / XDCXBaseFee = 100 / 10000 = 1% @@ -71,7 +72,7 @@ func GetSettleBalance(isXDCXLendingFork bool, log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "takerFee", takerFee) return result, ErrQuantityTradeTooSmall } - if lendingToken.String() != common.XDCNativeAddress && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { + if lendingToken != common.XDCNativeAddressBinary && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { exTakerReceivedFee := new(big.Int).Mul(takerFee, lendTokenXDCPrice) exTakerReceivedFee = new(big.Int).Div(exTakerReceivedFee, lendTokenDecimal) @@ -82,7 +83,7 @@ func GetSettleBalance(isXDCXLendingFork bool, log.Debug("takerFee too small", "quantityToLend", quantityToLend, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC) return result, ErrQuantityTradeTooSmall } - } else if lendingToken.String() == common.XDCNativeAddress { + } else if lendingToken == common.XDCNativeAddressBinary { exTakerReceivedFee := takerFee if (exTakerReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exTakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 { log.Debug("takerFee too small", "quantityToLend", quantityToLend, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee) @@ -121,7 +122,7 @@ func GetSettleBalance(isXDCXLendingFork bool, log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "makerFee", makerFee) return result, ErrQuantityTradeTooSmall } - if lendingToken.String() != common.XDCNativeAddress && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { + if lendingToken != common.XDCNativeAddressBinary && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { exMakerReceivedFee := new(big.Int).Mul(makerFee, lendTokenXDCPrice) exMakerReceivedFee = new(big.Int).Div(exMakerReceivedFee, lendTokenDecimal) @@ -132,7 +133,7 @@ func GetSettleBalance(isXDCXLendingFork bool, log.Debug("makerFee too small", "quantityToLend", quantityToLend, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC) return result, ErrQuantityTradeTooSmall } - } else if lendingToken.String() == common.XDCNativeAddress { + } else if lendingToken == common.XDCNativeAddressBinary { exMakerReceivedFee := makerFee if (exMakerReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 { log.Debug("makerFee too small", "quantityToLend", quantityToLend, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee) @@ -171,7 +172,7 @@ func GetSettleBalance(isXDCXLendingFork bool, log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee) return result, ErrQuantityTradeTooSmall } - if lendingToken.String() != common.XDCNativeAddress && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { + if lendingToken != common.XDCNativeAddressBinary && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { // exReceivedFee: the fee amount which borrowingRelayer will receive exReceivedFee := new(big.Int).Mul(borrowFee, lendTokenXDCPrice) exReceivedFee = new(big.Int).Div(exReceivedFee, lendTokenDecimal) @@ -183,7 +184,7 @@ func GetSettleBalance(isXDCXLendingFork bool, log.Debug("takerFee too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee, "exReceivedFee", exReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC) return result, ErrQuantityTradeTooSmall } - } else if lendingToken.String() == common.XDCNativeAddress { + } else if lendingToken == common.XDCNativeAddressBinary { exReceivedFee := borrowFee if (exReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 { log.Debug("takerFee too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee, "exReceivedFee", exReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee) diff --git a/XDCxlending/lendingstate/settle_balance_test.go b/XDCxlending/lendingstate/settle_balance_test.go index e4b318b6cf..711777503c 100644 --- a/XDCxlending/lendingstate/settle_balance_test.go +++ b/XDCxlending/lendingstate/settle_balance_test.go @@ -1,10 +1,11 @@ package lendingstate import ( - "github.com/XinFinOrg/XDPoSChain/common" "math/big" "reflect" "testing" + + "github.com/XinFinOrg/XDPoSChain/common" ) func TestCalculateInterestRate(t *testing.T) { @@ -171,7 +172,7 @@ func TestGetSettleBalance(t *testing.T) { common.BasePrice, big.NewInt(150), big.NewInt(100), // 1% - common.HexToAddress(common.XDCNativeAddress), + common.XDCNativeAddressBinary, common.Address{}, common.BasePrice, common.BasePrice, @@ -277,7 +278,7 @@ func TestGetSettleBalance(t *testing.T) { common.BasePrice, big.NewInt(150), big.NewInt(100), // 1% - common.HexToAddress(common.XDCNativeAddress), + common.XDCNativeAddressBinary, collateral, common.BasePrice, common.BasePrice, @@ -288,12 +289,12 @@ func TestGetSettleBalance(t *testing.T) { Fee: common.Big0, InToken: common.Address{}, InTotal: common.Big0, - OutToken: common.HexToAddress(common.XDCNativeAddress), + OutToken: common.XDCNativeAddressBinary, OutTotal: lendQuantity, }, Maker: TradeResult{ Fee: fee, - InToken: common.HexToAddress(common.XDCNativeAddress), + InToken: common.XDCNativeAddressBinary, InTotal: lendQuantityExcluded, OutToken: collateral, OutTotal: collateralLocked, @@ -312,7 +313,7 @@ func TestGetSettleBalance(t *testing.T) { common.BasePrice, big.NewInt(150), big.NewInt(100), // 1% - common.HexToAddress(common.XDCNativeAddress), + common.XDCNativeAddressBinary, collateral, common.BasePrice, common.BasePrice, @@ -323,12 +324,12 @@ func TestGetSettleBalance(t *testing.T) { Fee: common.Big0, InToken: common.Address{}, InTotal: common.Big0, - OutToken: common.HexToAddress(common.XDCNativeAddress), + OutToken: common.XDCNativeAddressBinary, OutTotal: lendQuantity, }, Taker: TradeResult{ Fee: fee, - InToken: common.HexToAddress(common.XDCNativeAddress), + InToken: common.XDCNativeAddressBinary, InTotal: lendQuantityExcluded, OutToken: collateral, OutTotal: collateralLocked, diff --git a/XDCxlending/order_processor.go b/XDCxlending/order_processor.go index 5725c2003b..15343de2a6 100644 --- a/XDCxlending/order_processor.go +++ b/XDCxlending/order_processor.go @@ -447,7 +447,7 @@ func (l *Lending) getLendQuantity( if err != nil || collateralTokenDecimal.Sign() == 0 { return lendingstate.Zero, lendingstate.Zero, false, nil, fmt.Errorf("fail to get tokenDecimal. Token: %v . Err: %v", collateralToken.String(), err) } - if takerOrder.Relayer.String() == makerOrder.Relayer.String() { + if takerOrder.Relayer == makerOrder.Relayer { if err := lendingstate.CheckRelayerFee(takerOrder.Relayer, new(big.Int).Mul(common.RelayerLendingFee, big.NewInt(2)), statedb); err != nil { log.Debug("Reject order Taker Exchnage = Maker Exchange , relayer not enough fee ", "err", err) return lendingstate.Zero, lendingstate.Zero, false, nil, nil @@ -621,11 +621,11 @@ func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *lendingsta } mapBalances[settleBalance.Taker.InToken][takerExOwner] = newTakerFee - newCollateralTokenLock, err := lendingstate.CheckAddTokenBalance(common.HexToAddress(common.LendingLockAddress), settleBalance.Taker.OutTotal, settleBalance.Taker.OutToken, statedb, mapBalances) + newCollateralTokenLock, err := lendingstate.CheckAddTokenBalance(common.LendingLockAddressBinary, settleBalance.Taker.OutTotal, settleBalance.Taker.OutToken, statedb, mapBalances) if err != nil { return err } - mapBalances[settleBalance.Taker.OutToken][common.HexToAddress(common.LendingLockAddress)] = newCollateralTokenLock + mapBalances[settleBalance.Taker.OutToken][common.LendingLockAddressBinary] = newCollateralTokenLock } else { relayerFee, err := lendingstate.CheckSubRelayerFee(makerOrder.Relayer, common.RelayerLendingFee, statedb, map[common.Address]*big.Int{}) if err != nil { @@ -662,11 +662,11 @@ func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *lendingsta } mapBalances[settleBalance.Maker.InToken][makerExOwner] = newMakerFee - newCollateralTokenLock, err := lendingstate.CheckAddTokenBalance(common.HexToAddress(common.LendingLockAddress), settleBalance.Maker.OutTotal, settleBalance.Maker.OutToken, statedb, mapBalances) + newCollateralTokenLock, err := lendingstate.CheckAddTokenBalance(common.LendingLockAddressBinary, settleBalance.Maker.OutTotal, settleBalance.Maker.OutToken, statedb, mapBalances) if err != nil { return err } - mapBalances[settleBalance.Maker.OutToken][common.HexToAddress(common.LendingLockAddress)] = newCollateralTokenLock + mapBalances[settleBalance.Maker.OutToken][common.LendingLockAddressBinary] = newCollateralTokenLock } masternodeOwner := statedb.GetOwner(coinbase) statedb.AddBalance(masternodeOwner, matchingFee) @@ -789,10 +789,10 @@ func (l *Lending) ProcessTopUp(lendingStateDB *lendingstate.LendingStateDB, stat if lendingTrade == lendingstate.EmptyLendingTrade { return fmt.Errorf("process deposit for emptyLendingTrade is not allowed. lendingTradeId: %v", lendingTradeId.Hex()), true, nil } - if order.UserAddress.String() != lendingTrade.Borrower.String() { + if order.UserAddress != lendingTrade.Borrower { return fmt.Errorf("ProcessTopUp: invalid userAddress . UserAddress: %s . Borrower: %s", order.UserAddress.Hex(), lendingTrade.Borrower.Hex()), true, nil } - if order.Relayer.String() != lendingTrade.BorrowingRelayer.String() { + if order.Relayer != lendingTrade.BorrowingRelayer { return fmt.Errorf("ProcessTopUp: invalid relayerAddress . Got: %s . Expect: %s", order.Relayer.Hex(), lendingTrade.BorrowingRelayer.Hex()), true, nil } if order.Quantity.Sign() <= 0 || lendingTrade.TradeId != lendingTradeId.Big().Uint64() { @@ -810,10 +810,10 @@ func (l *Lending) ProcessRepay(header *types.Header, chain consensus.ChainContex if lendingTrade == lendingstate.EmptyLendingTrade || lendingTrade.TradeId != lendingTradeIdHash.Big().Uint64() { return nil, fmt.Errorf("ProcessRepay for emptyLendingTrade is not allowed. lendingTradeId: %v", lendingTradeId) } - if order.UserAddress.String() != lendingTrade.Borrower.String() { + if order.UserAddress != lendingTrade.Borrower { return nil, fmt.Errorf("ProcessRepay: invalid userAddress . UserAddress: %s . Borrower: %s", order.UserAddress.Hex(), lendingTrade.Borrower.Hex()) } - if order.Relayer.String() != lendingTrade.BorrowingRelayer.String() { + if order.Relayer != lendingTrade.BorrowingRelayer { return nil, fmt.Errorf("ProcessRepay: invalid relayerAddress . Got: %s . Expect: %s", order.Relayer.Hex(), lendingTrade.BorrowingRelayer.Hex()) } return l.ProcessRepayLendingTrade(header, chain, lendingStateDB, statedb, tradingstateDB, lendingBook, lendingTradeId) @@ -854,9 +854,9 @@ func (l *Lending) LiquidationExpiredTrade(header *types.Header, chain consensus. } else { repayAmount = lendingTrade.CollateralLockedAmount } - err = lendingstate.SubTokenBalance(common.HexToAddress(common.LendingLockAddress), lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) + err = lendingstate.SubTokenBalance(common.LendingLockAddressBinary, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) if err != nil { - log.Warn("LiquidationExpiredTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) + log.Warn("LiquidationExpiredTrade SubTokenBalance", "err", err, "LendingLockAddress", common.LendingLockAddress, "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) } err = lendingstate.AddTokenBalance(lendingTrade.Investor, repayAmount, lendingTrade.CollateralToken, statedb) if err != nil { @@ -897,9 +897,9 @@ func (l *Lending) LiquidationTrade(lendingStateDB *lendingstate.LendingStateDB, if lendingTrade.TradeId != lendingTradeId { return nil, fmt.Errorf("Lending Trade Id not found : %d ", lendingTradeId) } - err := lendingstate.SubTokenBalance(common.HexToAddress(common.LendingLockAddress), lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) + err := lendingstate.SubTokenBalance(common.LendingLockAddressBinary, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) if err != nil { - log.Warn("LiquidationTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) + log.Warn("LiquidationTrade SubTokenBalance", "err", err, "LendingLockAddress", common.LendingLockAddress, "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) } err = lendingstate.AddTokenBalance(lendingTrade.Investor, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) if err != nil { @@ -1052,10 +1052,10 @@ func (l *Lending) GetCollateralPrices(header *types.Header, chain consensus.Chai func (l *Lending) GetXDCBasePrices(header *types.Header, chain consensus.ChainContext, statedb *state.StateDB, tradingStateDb *tradingstate.TradingStateDB, token common.Address) (*big.Int, error) { - tokenXDCPriceFromContract, updatedBlock := lendingstate.GetCollateralPrice(statedb, token, common.HexToAddress(common.XDCNativeAddress)) + tokenXDCPriceFromContract, updatedBlock := lendingstate.GetCollateralPrice(statedb, token, common.XDCNativeAddressBinary) tokenXDCPriceUpdatedFromContract := updatedBlock.Uint64()/chain.Config().XDPoS.Epoch == header.Number.Uint64()/chain.Config().XDPoS.Epoch - if token == common.HexToAddress(common.XDCNativeAddress) { + if token == common.XDCNativeAddressBinary { return common.BasePrice, nil } else if tokenXDCPriceUpdatedFromContract { // getting lendToken price from contract first @@ -1063,7 +1063,7 @@ func (l *Lending) GetXDCBasePrices(header *types.Header, chain consensus.ChainCo log.Debug("Getting token/XDC price from contract", "price", tokenXDCPriceFromContract) return tokenXDCPriceFromContract, nil } else { - XDCTokenPriceFromContract, updatedBlock := lendingstate.GetCollateralPrice(statedb, common.HexToAddress(common.XDCNativeAddress), token) + XDCTokenPriceFromContract, updatedBlock := lendingstate.GetCollateralPrice(statedb, common.XDCNativeAddressBinary, token) XDCTokenPriceUpdatedFromContract := updatedBlock.Uint64()/chain.Config().XDPoS.Epoch == header.Number.Uint64()/chain.Config().XDPoS.Epoch if XDCTokenPriceUpdatedFromContract && XDCTokenPriceFromContract != nil && XDCTokenPriceFromContract.Sign() > 0 { // getting lendToken price from contract first @@ -1078,7 +1078,7 @@ func (l *Lending) GetXDCBasePrices(header *types.Header, chain consensus.ChainCo tokenXDCPrice = new(big.Int).Div(tokenXDCPrice, XDCTokenPriceFromContract) return tokenXDCPrice, nil } - tokenXDCPrice, err := l.GetMediumTradePriceBeforeEpoch(chain, statedb, tradingStateDb, token, common.HexToAddress(common.XDCNativeAddress)) + tokenXDCPrice, err := l.GetMediumTradePriceBeforeEpoch(chain, statedb, tradingStateDb, token, common.XDCNativeAddressBinary) if err != nil { return nil, err } @@ -1133,9 +1133,9 @@ func (l *Lending) ProcessTopUpLendingTrade(lendingStateDB *lendingstate.LendingS if err != nil { log.Warn("ProcessTopUpLendingTrade SubTokenBalance", "err", err, "lendingTrade.Borrower", lendingTrade.Borrower, "quantity", *quantity, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) } - err = lendingstate.AddTokenBalance(common.HexToAddress(common.LendingLockAddress), quantity, lendingTrade.CollateralToken, statedb) + err = lendingstate.AddTokenBalance(common.LendingLockAddressBinary, quantity, lendingTrade.CollateralToken, statedb) if err != nil { - log.Warn("ProcessTopUpLendingTrade AddTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "quantity", *quantity, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) + log.Warn("ProcessTopUpLendingTrade AddTokenBalance", "err", err, "LendingLockAddress", common.LendingLockAddress, "quantity", *quantity, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) } oldLockedAmount := lendingTrade.CollateralLockedAmount newLockedAmount := new(big.Int).Add(quantity, oldLockedAmount) @@ -1199,9 +1199,9 @@ func (l *Lending) ProcessRepayLendingTrade(header *types.Header, chain consensus if err != nil { log.Warn("ProcessRepayLendingTrade AddTokenBalance", "err", err, "lendingTrade.Investor", lendingTrade.Investor, "paymentBalance", *paymentBalance, "lendingTrade.LendingToken", lendingTrade.LendingToken) } - err = lendingstate.SubTokenBalance(common.HexToAddress(common.LendingLockAddress), lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) + err = lendingstate.SubTokenBalance(common.LendingLockAddressBinary, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) if err != nil { - log.Warn("ProcessRepayLendingTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) + log.Warn("ProcessRepayLendingTrade SubTokenBalance", "err", err, "LendingLockAddress", common.LendingLockAddress, "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) } err = lendingstate.AddTokenBalance(lendingTrade.Borrower, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) if err != nil { @@ -1255,9 +1255,9 @@ func (l *Lending) ProcessRecallLendingTrade(lendingStateDB *lendingstate.Lending if err != nil { log.Warn("ProcessRecallLendingTrade AddTokenBalance", "err", err, "lendingTrade.Borrower", lendingTrade.Borrower, "recallAmount", *recallAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) } - err = lendingstate.SubTokenBalance(common.HexToAddress(common.LendingLockAddress), recallAmount, lendingTrade.CollateralToken, statedb) + err = lendingstate.SubTokenBalance(common.LendingLockAddressBinary, recallAmount, lendingTrade.CollateralToken, statedb) if err != nil { - log.Warn("ProcessRecallLendingTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "recallAmount", *recallAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) + log.Warn("ProcessRecallLendingTrade SubTokenBalance", "err", err, "LendingLockAddress", common.LendingLockAddress, "recallAmount", *recallAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) } lendingStateDB.UpdateLiquidationPrice(lendingBook, lendingTrade.TradeId, newLiquidationPrice) diff --git a/XDCxlending/order_processor_test.go b/XDCxlending/order_processor_test.go index 028ed09aed..172caa90a2 100644 --- a/XDCxlending/order_processor_test.go +++ b/XDCxlending/order_processor_test.go @@ -1,14 +1,15 @@ package XDCxlending import ( + "math/big" + "reflect" + "testing" + "github.com/XinFinOrg/XDPoSChain/XDCx" "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" "github.com/XinFinOrg/XDPoSChain/XDCxlending/lendingstate" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/core/rawdb" - "math/big" - "reflect" - "testing" ) func Test_getCancelFeeV1(t *testing.T) { @@ -107,9 +108,9 @@ func Test_getCancelFee(t *testing.T) { XDCx.SetTokenDecimal(testTokenB, new(big.Int).Exp(big.NewInt(10), big.NewInt(8), nil)) // set tokenAPrice = 1 XDC - tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenA, common.HexToAddress(common.XDCNativeAddress)), common.BasePrice) + tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenA, common.XDCNativeAddressBinary), common.BasePrice) // set tokenBPrice = 1 XDC - tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenB, common.HexToAddress(common.XDCNativeAddress)), common.BasePrice) + tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenB, common.XDCNativeAddressBinary), common.BasePrice) l := New(XDCx) @@ -132,7 +133,7 @@ func Test_getCancelFee(t *testing.T) { borrowFeeRate: common.Big0, order: &lendingstate.LendingItem{ LendingToken: testTokenA, - CollateralToken: common.HexToAddress(common.XDCNativeAddress), + CollateralToken: common.XDCNativeAddressBinary, Quantity: new(big.Int).SetUint64(10000), Side: lendingstate.Investing, }, @@ -147,7 +148,7 @@ func Test_getCancelFee(t *testing.T) { borrowFeeRate: common.Big0, order: &lendingstate.LendingItem{ LendingToken: testTokenA, - CollateralToken: common.HexToAddress(common.XDCNativeAddress), + CollateralToken: common.XDCNativeAddressBinary, Quantity: new(big.Int).SetUint64(10000), Side: lendingstate.Borrowing, }, @@ -162,7 +163,7 @@ func Test_getCancelFee(t *testing.T) { borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3% order: &lendingstate.LendingItem{ LendingToken: testTokenA, - CollateralToken: common.HexToAddress(common.XDCNativeAddress), + CollateralToken: common.XDCNativeAddressBinary, Quantity: new(big.Int).SetUint64(10000), Side: lendingstate.Investing, }, @@ -177,7 +178,7 @@ func Test_getCancelFee(t *testing.T) { borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3% order: &lendingstate.LendingItem{ LendingToken: testTokenA, - CollateralToken: common.HexToAddress(common.XDCNativeAddress), + CollateralToken: common.XDCNativeAddressBinary, Quantity: new(big.Int).SetUint64(10000), Side: lendingstate.Borrowing, }, @@ -194,7 +195,7 @@ func Test_getCancelFee(t *testing.T) { CancelFeeArg{ borrowFeeRate: common.Big0, order: &lendingstate.LendingItem{ - LendingToken: common.HexToAddress(common.XDCNativeAddress), + LendingToken: common.XDCNativeAddressBinary, CollateralToken: testTokenA, Quantity: new(big.Int).SetUint64(10000), Side: lendingstate.Investing, @@ -209,7 +210,7 @@ func Test_getCancelFee(t *testing.T) { CancelFeeArg{ borrowFeeRate: common.Big0, order: &lendingstate.LendingItem{ - LendingToken: common.HexToAddress(common.XDCNativeAddress), + LendingToken: common.XDCNativeAddressBinary, CollateralToken: testTokenA, Quantity: new(big.Int).SetUint64(10000), Side: lendingstate.Borrowing, @@ -224,7 +225,7 @@ func Test_getCancelFee(t *testing.T) { CancelFeeArg{ borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3% order: &lendingstate.LendingItem{ - LendingToken: common.HexToAddress(common.XDCNativeAddress), + LendingToken: common.XDCNativeAddressBinary, CollateralToken: testTokenA, Quantity: new(big.Int).SetUint64(10000), Side: lendingstate.Investing, @@ -239,7 +240,7 @@ func Test_getCancelFee(t *testing.T) { CancelFeeArg{ borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3% order: &lendingstate.LendingItem{ - LendingToken: common.HexToAddress(common.XDCNativeAddress), + LendingToken: common.XDCNativeAddressBinary, CollateralToken: testTokenA, Quantity: new(big.Int).SetUint64(10000), Side: lendingstate.Borrowing, diff --git a/cmd/gc/main.go b/cmd/gc/main.go index ce48f0aae8..4b3b004b77 100644 --- a/cmd/gc/main.go +++ b/cmd/gc/main.go @@ -28,7 +28,7 @@ var ( cacheSize = flag.Int("size", 1000000, "LRU cache size") sercureKey = []byte("secure-key-") nWorker = runtime.NumCPU() / 2 - cleanAddress = []common.Address{common.HexToAddress(common.BlockSigners)} + cleanAddress = []common.Address{common.BlockSignersBinary} cache *lru.Cache finish = int32(0) running = true diff --git a/cmd/puppeth/wizard_genesis.go b/cmd/puppeth/wizard_genesis.go index aefac61cc6..c1e077c595 100644 --- a/cmd/puppeth/wizard_genesis.go +++ b/cmd/puppeth/wizard_genesis.go @@ -197,7 +197,7 @@ func (w *wizard) makeGenesis() { fmt.Println() fmt.Println("What is foundation wallet address? (default = xdc0000000000000000000000000000000000000068)") - genesis.Config.XDPoS.FoudationWalletAddr = w.readDefaultAddress(common.HexToAddress(common.FoudationAddr)) + genesis.Config.XDPoS.FoudationWalletAddr = w.readDefaultAddress(common.FoudationAddrBinary) // Validator Smart Contract Code pKey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") @@ -225,7 +225,7 @@ func (w *wizard) makeGenesis() { return true } contractBackend.ForEachStorageAt(ctx, validatorAddress, nil, f) - genesis.Alloc[common.HexToAddress(common.MasternodeVotingSMC)] = core.GenesisAccount{ + genesis.Alloc[common.MasternodeVotingSMCBinary] = core.GenesisAccount{ Balance: validatorCap.Mul(validatorCap, big.NewInt(int64(len(validatorCaps)))), Code: code, Storage: storage, @@ -259,7 +259,7 @@ func (w *wizard) makeGenesis() { fBalance := big.NewInt(0) // 16m fBalance.Add(fBalance, big.NewInt(16*1000*1000)) fBalance.Mul(fBalance, big.NewInt(1000000000000000000)) - genesis.Alloc[common.HexToAddress(common.FoudationAddr)] = core.GenesisAccount{ + genesis.Alloc[common.FoudationAddrBinary] = core.GenesisAccount{ Balance: fBalance, Code: code, Storage: storage, @@ -275,7 +275,7 @@ func (w *wizard) makeGenesis() { code, _ = contractBackend.CodeAt(ctx, blockSignerAddress, nil) storage = make(map[common.Hash]common.Hash) contractBackend.ForEachStorageAt(ctx, blockSignerAddress, nil, f) - genesis.Alloc[common.HexToAddress(common.BlockSigners)] = core.GenesisAccount{ + genesis.Alloc[common.BlockSignersBinary] = core.GenesisAccount{ Balance: big.NewInt(0), Code: code, Storage: storage, @@ -291,7 +291,7 @@ func (w *wizard) makeGenesis() { code, _ = contractBackend.CodeAt(ctx, randomizeAddress, nil) storage = make(map[common.Hash]common.Hash) contractBackend.ForEachStorageAt(ctx, randomizeAddress, nil, f) - genesis.Alloc[common.HexToAddress(common.RandomizeSMC)] = core.GenesisAccount{ + genesis.Alloc[common.RandomizeSMCBinary] = core.GenesisAccount{ Balance: big.NewInt(0), Code: code, Storage: storage, @@ -330,7 +330,7 @@ func (w *wizard) makeGenesis() { subBalance.Add(subBalance, big.NewInt(int64(len(signers))*50*1000)) subBalance.Mul(subBalance, big.NewInt(1000000000000000000)) balance.Sub(balance, subBalance) // 12m - i * 50k - genesis.Alloc[common.HexToAddress(common.TeamAddr)] = core.GenesisAccount{ + genesis.Alloc[common.TeamAddrBinary] = core.GenesisAccount{ Balance: balance, Code: code, Storage: storage, diff --git a/common/types.go b/common/types.go index 905c7d5a4e..c7abab289b 100644 --- a/common/types.go +++ b/common/types.go @@ -50,6 +50,20 @@ const ( XDCZApplyMethod = "0xc6b32f34" ) +var ( + BlockSignersBinary = Address{19: 0x89} // xdc0000000000000000000000000000000000000089 + MasternodeVotingSMCBinary = Address{19: 0x88} // xdc0000000000000000000000000000000000000088 + RandomizeSMCBinary = Address{19: 0x90} // xdc0000000000000000000000000000000000000090 + FoudationAddrBinary = Address{19: 0x68} // xdc0000000000000000000000000000000000000068 + TeamAddrBinary = Address{19: 0x99} // xdc0000000000000000000000000000000000000099 + XDCXAddrBinary = Address{19: 0x91} // xdc0000000000000000000000000000000000000091 + TradingStateAddrBinary = Address{19: 0x92} // xdc0000000000000000000000000000000000000092 + XDCXLendingAddressBinary = Address{19: 0x93} // xdc0000000000000000000000000000000000000093 + XDCXLendingFinalizedTradeAddressBinary = Address{19: 0x94} // xdc0000000000000000000000000000000000000094 + XDCNativeAddressBinary = Address{19: 0x01} // xdc0000000000000000000000000000000000000001 + LendingLockAddressBinary = Address{19: 0x11} // xdc0000000000000000000000000000000000000011 +) + var ( hashT = reflect.TypeOf(Hash{}) addressT = reflect.TypeOf(Address{}) @@ -256,7 +270,7 @@ func (a *Address) Set(other Address) { // MarshalText returns the hex representation of a. func (a Address) MarshalText() ([]byte, error) { // Handle '0x' or 'xdc' prefix here. - if (Enable0xPrefix) { + if Enable0xPrefix { return hexutil.Bytes(a[:]).MarshalText() } else { return hexutil.Bytes(a[:]).MarshalXDCText() diff --git a/common/types_test.go b/common/types_test.go index 1ec2bfc26c..7621a6e4b8 100644 --- a/common/types_test.go +++ b/common/types_test.go @@ -167,3 +167,39 @@ func TestRemoveItemInArray(t *testing.T) { t.Error("fail remove item from array address") } } + +var testCases = []struct { + bin Address + str string +}{ + {BlockSignersBinary, BlockSigners}, + {MasternodeVotingSMCBinary, MasternodeVotingSMC}, + {RandomizeSMCBinary, RandomizeSMC}, + {FoudationAddrBinary, FoudationAddr}, + {TeamAddrBinary, TeamAddr}, + {XDCXAddrBinary, XDCXAddr}, + {TradingStateAddrBinary, TradingStateAddr}, + {XDCXLendingAddressBinary, XDCXLendingAddress}, + {XDCXLendingFinalizedTradeAddressBinary, XDCXLendingFinalizedTradeAddress}, + {XDCNativeAddressBinary, XDCNativeAddress}, + {LendingLockAddressBinary, LendingLockAddress}, +} + +func TestBinaryAddressToString(t *testing.T) { + for _, tt := range testCases { + have := tt.bin.String() + want := tt.str + if have != want { + t.Errorf("fail to convert binary address to string address\nwant:%s\nhave:%s", have, want) + } + } +} +func TestStringToBinaryAddress(t *testing.T) { + for _, tt := range testCases { + want := tt.bin + have := HexToAddress(tt.str) + if have != want { + t.Errorf("fail to convert string address to binary address\nwant:%s\nhave:%s", have, want) + } + } +} diff --git a/consensus/XDPoS/api.go b/consensus/XDPoS/api.go index a922e57f78..7209939662 100644 --- a/consensus/XDPoS/api.go +++ b/consensus/XDPoS/api.go @@ -259,7 +259,7 @@ func (api *API) GetV2BlockByHash(blockHash common.Hash) *V2BlockInfo { func (api *API) NetworkInformation() NetworkInformation { info := NetworkInformation{} info.NetworkId = api.chain.Config().ChainId - info.XDCValidatorAddress = common.HexToAddress(common.MasternodeVotingSMC) + info.XDCValidatorAddress = common.MasternodeVotingSMCBinary if common.IsTestnet { info.LendingAddress = common.HexToAddress(common.LendingRegistrationSMCTestnet) info.RelayerRegistrationAddress = common.HexToAddress(common.RelayerRegistrationSMCTestnet) diff --git a/consensus/XDPoS/engines/engine_v2/snapshot.go b/consensus/XDPoS/engines/engine_v2/snapshot.go index 78ce0aff55..ccae598412 100644 --- a/consensus/XDPoS/engines/engine_v2/snapshot.go +++ b/consensus/XDPoS/engines/engine_v2/snapshot.go @@ -64,7 +64,7 @@ func (s *SnapshotV2) GetMappedCandidates() map[common.Address]struct{} { func (s *SnapshotV2) IsCandidates(address common.Address) bool { for _, n := range s.NextEpochCandidates { - if n.String() == address.String() { + if n == address { return true } } diff --git a/consensus/tests/engine_v1_tests/helper.go b/consensus/tests/engine_v1_tests/helper.go index be64d0c050..fb9bb79d89 100644 --- a/consensus/tests/engine_v1_tests/helper.go +++ b/consensus/tests/engine_v1_tests/helper.go @@ -144,11 +144,11 @@ func getCommonBackend(t *testing.T, chainConfig *params.ChainConfig) *backends.S // create test backend with smart contract in it contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{ - acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, - common.HexToAddress(common.MasternodeVotingSMC): {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution + acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, + common.MasternodeVotingSMCBinary: {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution }, 10000000, chainConfig) return contractBackend2 @@ -180,7 +180,7 @@ func voteTX(gasLimit uint64, nonce uint64, addr string) (*types.Transaction, err if !ok { return nil, fmt.Errorf("big int init failed") } - to := common.HexToAddress(common.MasternodeVotingSMC) + to := common.MasternodeVotingSMCBinary tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) signedTX, err := types.SignTx(tx, types.LatestSignerForChainID(big.NewInt(chainID)), voterKey) @@ -213,7 +213,7 @@ func GetSnapshotSigner(bc *BlockChain, header *types.Header) (signersList, error } func GetCandidateFromCurrentSmartContract(backend bind.ContractBackend, t *testing.T) masterNodes { - addr := common.HexToAddress(common.MasternodeVotingSMC) + addr := common.MasternodeVotingSMCBinary validator, err := contractValidator.NewXDCValidator(addr, backend) if err != nil { t.Fatal(err) diff --git a/consensus/tests/engine_v2_tests/helper.go b/consensus/tests/engine_v2_tests/helper.go index 2856b55f9f..041aaf7831 100644 --- a/consensus/tests/engine_v2_tests/helper.go +++ b/consensus/tests/engine_v2_tests/helper.go @@ -105,7 +105,7 @@ func voteTX(gasLimit uint64, nonce uint64, addr string) (*types.Transaction, err if !ok { return nil, fmt.Errorf("big int init failed") } - to := common.HexToAddress(common.MasternodeVotingSMC) + to := common.MasternodeVotingSMCBinary tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) signedTX, err := types.SignTx(tx, types.LatestSignerForChainID(big.NewInt(chainID)), voterKey) @@ -189,11 +189,11 @@ func getCommonBackend(t *testing.T, chainConfig *params.ChainConfig) *backends.S // create test backend with smart contract in it contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{ - acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, - common.HexToAddress(common.MasternodeVotingSMC): {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution + acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, + common.MasternodeVotingSMCBinary: {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution }, 10000000, chainConfig) return contractBackend2 @@ -273,18 +273,18 @@ func getMultiCandidatesBackend(t *testing.T, chainConfig *params.ChainConfig, n // create test backend with smart contract in it contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{ - acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, - voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, - common.HexToAddress(common.MasternodeVotingSMC): {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution + acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, + voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, + common.MasternodeVotingSMCBinary: {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution }, 10000000, chainConfig) return contractBackend2 } func signingTxWithKey(header *types.Header, nonce uint64, privateKey *ecdsa.PrivateKey) (*types.Transaction, error) { - tx := contracts.CreateTxSign(header.Number, header.Hash(), nonce, common.HexToAddress(common.BlockSigners)) + tx := contracts.CreateTxSign(header.Number, header.Hash(), nonce, common.BlockSignersBinary) s := types.LatestSignerForChainID(big.NewInt(chainID)) h := s.Hash(tx) sig, err := crypto.Sign(h[:], privateKey) @@ -299,7 +299,7 @@ func signingTxWithKey(header *types.Header, nonce uint64, privateKey *ecdsa.Priv } func signingTxWithSignerFn(header *types.Header, nonce uint64, signer common.Address, signFn func(account accounts.Account, hash []byte) ([]byte, error)) (*types.Transaction, error) { - tx := contracts.CreateTxSign(header.Number, header.Hash(), nonce, common.HexToAddress(common.BlockSigners)) + tx := contracts.CreateTxSign(header.Number, header.Hash(), nonce, common.BlockSignersBinary) s := types.LatestSignerForChainID(big.NewInt(chainID)) h := s.Hash(tx) sig, err := signFn(accounts.Account{Address: signer}, h[:]) @@ -335,7 +335,7 @@ func GetSnapshotSigner(bc *BlockChain, header *types.Header) (signersList, error } func GetCandidateFromCurrentSmartContract(backend bind.ContractBackend, t *testing.T) masterNodes { - addr := common.HexToAddress(common.MasternodeVotingSMC) + addr := common.MasternodeVotingSMCBinary validator, err := contractValidator.NewXDCValidator(addr, backend) if err != nil { t.Fatal(err) diff --git a/contracts/utils.go b/contracts/utils.go index 8f605a5e86..6aba084f9a 100644 --- a/contracts/utils.go +++ b/contracts/utils.go @@ -87,7 +87,7 @@ func CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, m // Create and send tx to smart contract for sign validate block. nonce := pool.Nonce(account.Address) - tx := CreateTxSign(block.Number(), block.Hash(), nonce, common.HexToAddress(common.BlockSigners)) + tx := CreateTxSign(block.Number(), block.Hash(), nonce, common.BlockSignersBinary) txSigned, err := wallet.SignTx(account, tx, chainConfig.ChainId) if err != nil { log.Error("Fail to create tx sign", "error", err) @@ -112,7 +112,7 @@ func CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, m // Only process when private key empty in state db. // Save randomize key into state db. randomizeKeyValue := RandStringByte(32) - tx, err := BuildTxSecretRandomize(nonce+1, common.HexToAddress(common.RandomizeSMC), chainConfig.XDPoS.Epoch, randomizeKeyValue) + tx, err := BuildTxSecretRandomize(nonce+1, common.RandomizeSMCBinary, chainConfig.XDPoS.Epoch, randomizeKeyValue) if err != nil { log.Error("Fail to get tx opening for randomize", "error", err) return err @@ -141,7 +141,7 @@ func CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, m return err } - tx, err := BuildTxOpeningRandomize(nonce+1, common.HexToAddress(common.RandomizeSMC), randomizeKeyValue) + tx, err := BuildTxOpeningRandomize(nonce+1, common.RandomizeSMCBinary, randomizeKeyValue) if err != nil { log.Error("Fail to get tx opening for randomize", "error", err) return err @@ -232,7 +232,7 @@ func GetSignersByExecutingEVM(addrBlockSigner common.Address, client bind.Contra // Get random from randomize contract. func GetRandomizeFromContract(client bind.ContractBackend, addrMasternode common.Address) (int64, error) { - randomize, err := randomizeContract.NewXDCRandomize(common.HexToAddress(common.RandomizeSMC), client) + randomize, err := randomizeContract.NewXDCRandomize(common.RandomizeSMCBinary, client) if err != nil { log.Error("Fail to get instance of randomize", "error", err) } diff --git a/contracts/validator/validator_test.go b/contracts/validator/validator_test.go index 047f34deac..6ebe924b5c 100644 --- a/contracts/validator/validator_test.go +++ b/contracts/validator/validator_test.go @@ -150,7 +150,7 @@ func TestRewardBalance(t *testing.T) { logCaps[i] = &logCap{accounts[randIndex].From.String(), randCap} } - foundationAddr := common.HexToAddress(common.FoudationAddr) + foundationAddr := common.FoudationAddrBinary totalReward := new(big.Int).SetInt64(15 * 1000) rewards, err := GetRewardBalancesRate(foundationAddr, acc3Addr, totalReward, baseValidator) if err != nil { @@ -309,13 +309,13 @@ func TestStatedbUtils(t *testing.T) { return true } contractBackend.ForEachStorageAt(ctx, validatorAddress, nil, f) - genesisAlloc[common.HexToAddress(common.MasternodeVotingSMC)] = core.GenesisAccount{ + genesisAlloc[common.MasternodeVotingSMCBinary] = core.GenesisAccount{ Balance: validatorCap, Code: code, Storage: storage, } contractBackendForValidator := backends.NewXDCSimulatedBackend(genesisAlloc, 10000000, params.TestXDPoSMockChainConfig) - validator, err := NewValidator(transactOpts, common.HexToAddress(common.MasternodeVotingSMC), contractBackendForValidator) + validator, err := NewValidator(transactOpts, common.MasternodeVotingSMCBinary, contractBackendForValidator) if err != nil { t.Fatalf("can't get validator object: %v", err) } @@ -379,4 +379,4 @@ func TestStatedbUtils(t *testing.T) { t.Fatalf("cap should not be zero") } } -} \ No newline at end of file +} diff --git a/core/blockchain.go b/core/blockchain.go index c1fefaa3d1..ce31a6bc27 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -2562,7 +2562,7 @@ func (bc *BlockChain) UpdateM1() error { if err != nil { return err } - addr := common.HexToAddress(common.MasternodeVotingSMC) + addr := common.MasternodeVotingSMCBinary validator, err := contractValidator.NewXDCValidator(addr, client) if err != nil { return err diff --git a/core/lending_pool.go b/core/lending_pool.go index fc0deb1821..d4f570f66e 100644 --- a/core/lending_pool.go +++ b/core/lending_pool.go @@ -435,7 +435,7 @@ func (pool *LendingPool) validateNewLending(cloneStateDb *state.StateDB, cloneLe validCollateral := false collateralList := lendingstate.GetCollaterals(cloneStateDb, tx.RelayerAddress(), tx.LendingToken(), tx.Term()) for _, collateral := range collateralList { - if tx.CollateralToken().String() == collateral.String() { + if tx.CollateralToken() == collateral { validCollateral = true break } @@ -476,10 +476,10 @@ func (pool *LendingPool) validateRepayLending(cloneStateDb *state.StateDB, clone if lendingTrade == lendingstate.EmptyLendingTrade { return ErrInvalidLendingTradeID } - if tx.UserAddress().String() != lendingTrade.Borrower.String() { + if tx.UserAddress() != lendingTrade.Borrower { return ErrInvalidLendingUserAddress } - if tx.RelayerAddress().String() != lendingTrade.BorrowingRelayer.String() { + if tx.RelayerAddress() != lendingTrade.BorrowingRelayer { return ErrInvalidLendingRelayer } if err := pool.validateBalance(cloneStateDb, cloneLendingStateDb, tx, tx.CollateralToken()); err != nil { @@ -499,10 +499,10 @@ func (pool *LendingPool) validateTopupLending(cloneStateDb *state.StateDB, clone if lendingTrade == lendingstate.EmptyLendingTrade { return ErrInvalidLendingTradeID } - if tx.UserAddress().String() != lendingTrade.Borrower.String() { + if tx.UserAddress() != lendingTrade.Borrower { return ErrInvalidLendingUserAddress } - if tx.RelayerAddress().String() != lendingTrade.BorrowingRelayer.String() { + if tx.RelayerAddress() != lendingTrade.BorrowingRelayer { return ErrInvalidLendingRelayer } if err := pool.validateBalance(cloneStateDb, cloneLendingStateDb, tx, lendingTrade.CollateralToken); err != nil { @@ -554,10 +554,10 @@ func (pool *LendingPool) validateBalance(cloneStateDb *state.StateDB, cloneLendi } } if lendTokenXDCPrice == nil || lendTokenXDCPrice.Sign() == 0 { - if tx.LendingToken().String() == common.XDCNativeAddress { + if tx.LendingToken() == common.XDCNativeAddressBinary { lendTokenXDCPrice = common.BasePrice } else { - lendTokenXDCPrice, err = lendingServ.GetMediumTradePriceBeforeEpoch(pool.chain, cloneStateDb, cloneTradingStateDb, tx.LendingToken(), common.HexToAddress(common.XDCNativeAddress)) + lendTokenXDCPrice, err = lendingServ.GetMediumTradePriceBeforeEpoch(pool.chain, cloneStateDb, cloneTradingStateDb, tx.LendingToken(), common.XDCNativeAddressBinary) if err != nil { return err } diff --git a/core/lending_pool_test.go b/core/lending_pool_test.go index 2d8104403f..5ffe82d58c 100644 --- a/core/lending_pool_test.go +++ b/core/lending_pool_test.go @@ -3,6 +3,13 @@ package core import ( "context" "fmt" + "log" + "math/big" + "strconv" + "strings" + "testing" + "time" + "github.com/XinFinOrg/XDPoSChain/XDCxlending/lendingstate" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/core/types" @@ -10,12 +17,6 @@ import ( "github.com/XinFinOrg/XDPoSChain/crypto/sha3" "github.com/XinFinOrg/XDPoSChain/ethclient" "github.com/XinFinOrg/XDPoSChain/rpc" - "log" - "math/big" - "strconv" - "strings" - "testing" - "time" ) type LendingMsg struct { @@ -197,7 +198,7 @@ func TestSendLending(t *testing.T) { testSendLending(key, nonce, USDAddress, common.Address{}, new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") nonce++ time.Sleep(time.Second) - testSendLending(key, nonce, USDAddress, common.HexToAddress(common.XDCNativeAddress), new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") + testSendLending(key, nonce, USDAddress, common.XDCNativeAddressBinary, new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") nonce++ time.Sleep(time.Second) @@ -206,7 +207,7 @@ func TestSendLending(t *testing.T) { testSendLending(key, nonce, BTCAddress, common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") nonce++ time.Sleep(time.Second) - testSendLending(key, nonce, BTCAddress, common.HexToAddress(common.XDCNativeAddress), new(big.Int).Mul(_1E18, big.NewInt(1)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") + testSendLending(key, nonce, BTCAddress, common.XDCNativeAddressBinary, new(big.Int).Mul(_1E18, big.NewInt(1)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") nonce++ time.Sleep(time.Second) @@ -221,19 +222,19 @@ func TestSendLending(t *testing.T) { // lendToken: XDC, collateral: BTC // amount 1000 XDC - testSendLending(key, nonce, common.HexToAddress(common.XDCNativeAddress), common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") + testSendLending(key, nonce, common.XDCNativeAddressBinary, common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") nonce++ time.Sleep(time.Second) - testSendLending(key, nonce, common.HexToAddress(common.XDCNativeAddress), BTCAddress, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") + testSendLending(key, nonce, common.XDCNativeAddressBinary, BTCAddress, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") nonce++ time.Sleep(time.Second) // lendToken: XDC, collateral: ETH // amount 1000 XDC - testSendLending(key, nonce, common.HexToAddress(common.XDCNativeAddress), common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") + testSendLending(key, nonce, common.XDCNativeAddressBinary, common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") nonce++ time.Sleep(time.Second) - testSendLending(key, nonce, common.HexToAddress(common.XDCNativeAddress), ETHAddress, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") + testSendLending(key, nonce, common.XDCNativeAddressBinary, ETHAddress, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") nonce++ time.Sleep(time.Second) } @@ -282,6 +283,6 @@ func TestRecallLending(t *testing.T) { t.Error("fail to get nonce") t.FailNow() } - testSendLending(key, nonce, USDAddress, common.HexToAddress(common.XDCNativeAddress), new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") + testSendLending(key, nonce, USDAddress, common.XDCNativeAddressBinary, new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") time.Sleep(2 * time.Second) } diff --git a/core/order_pool_test.go b/core/order_pool_test.go index ea11b265bc..1f03c692ee 100644 --- a/core/order_pool_test.go +++ b/core/order_pool_test.go @@ -2,17 +2,18 @@ package core import ( "context" - "github.com/XinFinOrg/XDPoSChain/common" - "github.com/XinFinOrg/XDPoSChain/core/types" - "github.com/XinFinOrg/XDPoSChain/crypto" - "github.com/XinFinOrg/XDPoSChain/ethclient" - "github.com/XinFinOrg/XDPoSChain/rpc" "log" "math/big" "strconv" "strings" "testing" "time" + + "github.com/XinFinOrg/XDPoSChain/common" + "github.com/XinFinOrg/XDPoSChain/core/types" + "github.com/XinFinOrg/XDPoSChain/crypto" + "github.com/XinFinOrg/XDPoSChain/ethclient" + "github.com/XinFinOrg/XDPoSChain/rpc" ) type OrderMsg struct { @@ -89,7 +90,7 @@ func testSendOrder(t *testing.T, amount, price *big.Int, side string, status str Price: price, ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"), UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey), - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: BTCAddress, Status: status, Side: side, @@ -124,7 +125,7 @@ func testSendOrderXDCUSD(t *testing.T, amount, price *big.Int, side string, stat Price: price, ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"), UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey), - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: USDAddress, Status: status, Side: side, @@ -194,7 +195,7 @@ func testSendOrderXDCBTC(t *testing.T, amount, price *big.Int, side string, stat Price: price, ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"), UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey), - BaseToken: common.HexToAddress(common.XDCNativeAddress), + BaseToken: common.XDCNativeAddressBinary, QuoteToken: BTCAddress, Status: status, Side: side, diff --git a/core/state/statedb.go b/core/state/statedb.go index 15ca9ca67e..bac5106f5b 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -796,6 +796,6 @@ func (s *StateDB) GetOwner(candidate common.Address) common.Address { // validatorsState[_candidate].owner; locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot) locCandidateOwner := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(0))) - ret := s.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BigToHash(locCandidateOwner)) + ret := s.GetState(common.MasternodeVotingSMCBinary, common.BigToHash(locCandidateOwner)) return common.HexToAddress(ret.Hex()) } diff --git a/core/state/statedb_utils.go b/core/state/statedb_utils.go index a9c210b569..7bd2c4d355 100644 --- a/core/state/statedb_utils.go +++ b/core/state/statedb_utils.go @@ -20,7 +20,7 @@ func GetSigners(statedb *StateDB, block *types.Block) []common.Address { slot := slotBlockSignerMapping["blockSigners"] keys := []common.Hash{} keyArrSlot := GetLocMappingAtKey(block.Hash(), slot) - arrSlot := statedb.GetState(common.HexToAddress(common.BlockSigners), common.BigToHash(keyArrSlot)) + arrSlot := statedb.GetState(common.BlockSignersBinary, common.BigToHash(keyArrSlot)) arrLength := arrSlot.Big().Uint64() for i := uint64(0); i < arrLength; i++ { key := GetLocDynamicArrAtElement(common.BigToHash(keyArrSlot), i, 1) @@ -28,7 +28,7 @@ func GetSigners(statedb *StateDB, block *types.Block) []common.Address { } rets := []common.Address{} for _, key := range keys { - ret := statedb.GetState(common.HexToAddress(common.BlockSigners), key) + ret := statedb.GetState(common.BlockSignersBinary, key) rets = append(rets, common.HexToAddress(ret.Hex())) } @@ -45,7 +45,7 @@ var ( func GetSecret(statedb *StateDB, address common.Address) [][32]byte { slot := slotRandomizeMapping["randomSecret"] locSecret := GetLocMappingAtKey(address.Hash(), slot) - arrLength := statedb.GetState(common.HexToAddress(common.RandomizeSMC), common.BigToHash(locSecret)) + arrLength := statedb.GetState(common.RandomizeSMCBinary, common.BigToHash(locSecret)) keys := []common.Hash{} for i := uint64(0); i < arrLength.Big().Uint64(); i++ { key := GetLocDynamicArrAtElement(common.BigToHash(locSecret), i, 1) @@ -53,7 +53,7 @@ func GetSecret(statedb *StateDB, address common.Address) [][32]byte { } rets := [][32]byte{} for _, key := range keys { - ret := statedb.GetState(common.HexToAddress(common.RandomizeSMC), key) + ret := statedb.GetState(common.RandomizeSMCBinary, key) rets = append(rets, ret) } return rets @@ -62,7 +62,7 @@ func GetSecret(statedb *StateDB, address common.Address) [][32]byte { func GetOpening(statedb *StateDB, address common.Address) [32]byte { slot := slotRandomizeMapping["randomOpening"] locOpening := GetLocMappingAtKey(address.Hash(), slot) - ret := statedb.GetState(common.HexToAddress(common.RandomizeSMC), common.BigToHash(locOpening)) + ret := statedb.GetState(common.RandomizeSMCBinary, common.BigToHash(locOpening)) return ret } @@ -92,13 +92,13 @@ var ( func GetCandidates(statedb *StateDB) []common.Address { slot := slotValidatorMapping["candidates"] slotHash := common.BigToHash(new(big.Int).SetUint64(slot)) - arrLength := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), slotHash) + arrLength := statedb.GetState(common.MasternodeVotingSMCBinary, slotHash) count := arrLength.Big().Uint64() rets := make([]common.Address, 0, count) for i := uint64(0); i < count; i++ { key := GetLocDynamicArrAtElement(slotHash, i, 1) - ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), key) + ret := statedb.GetState(common.MasternodeVotingSMCBinary, key) if !ret.IsZero() { rets = append(rets, common.HexToAddress(ret.Hex())) } @@ -112,7 +112,7 @@ func GetCandidateOwner(statedb *StateDB, candidate common.Address) common.Addres // validatorsState[_candidate].owner; locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot) locCandidateOwner := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(0))) - ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BigToHash(locCandidateOwner)) + ret := statedb.GetState(common.MasternodeVotingSMCBinary, common.BigToHash(locCandidateOwner)) return common.HexToAddress(ret.Hex()) } @@ -121,7 +121,7 @@ func GetCandidateCap(statedb *StateDB, candidate common.Address) *big.Int { // validatorsState[_candidate].cap; locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot) locCandidateCap := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(1))) - ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BigToHash(locCandidateCap)) + ret := statedb.GetState(common.MasternodeVotingSMCBinary, common.BigToHash(locCandidateCap)) return ret.Big() } @@ -129,7 +129,7 @@ func GetVoters(statedb *StateDB, candidate common.Address) []common.Address { //mapping(address => address[]) voters; slot := slotValidatorMapping["voters"] locVoters := GetLocMappingAtKey(candidate.Hash(), slot) - arrLength := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BigToHash(locVoters)) + arrLength := statedb.GetState(common.MasternodeVotingSMCBinary, common.BigToHash(locVoters)) keys := []common.Hash{} for i := uint64(0); i < arrLength.Big().Uint64(); i++ { key := GetLocDynamicArrAtElement(common.BigToHash(locVoters), i, 1) @@ -137,7 +137,7 @@ func GetVoters(statedb *StateDB, candidate common.Address) []common.Address { } rets := []common.Address{} for _, key := range keys { - ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), key) + ret := statedb.GetState(common.MasternodeVotingSMCBinary, key) rets = append(rets, common.HexToAddress(ret.Hex())) } @@ -149,6 +149,6 @@ func GetVoterCap(statedb *StateDB, candidate, voter common.Address) *big.Int { locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot) locCandidateVoters := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(2))) retByte := crypto.Keccak256(voter.Hash().Bytes(), common.BigToHash(locCandidateVoters).Bytes()) - ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BytesToHash(retByte)) + ret := statedb.GetState(common.MasternodeVotingSMCBinary, common.BytesToHash(retByte)) return ret.Big() } diff --git a/core/state_processor.go b/core/state_processor.go index cc5697e069..e4bab6797b 100644 --- a/core/state_processor.go +++ b/core/state_processor.go @@ -80,7 +80,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, tra misc.ApplyDAOHardFork(statedb) } if common.TIPSigning.Cmp(header.Number) == 0 { - statedb.DeleteAddress(common.HexToAddress(common.BlockSigners)) + statedb.DeleteAddress(common.BlockSignersBinary) } parentState := statedb.Copy() InitSignerInTransactions(p.config, header, block.Transactions()) @@ -146,7 +146,7 @@ func (p *StateProcessor) ProcessBlockNoValidator(cBlock *CalculatedBlock, stated misc.ApplyDAOHardFork(statedb) } if common.TIPSigning.Cmp(header.Number) == 0 { - statedb.DeleteAddress(common.HexToAddress(common.BlockSigners)) + statedb.DeleteAddress(common.BlockSignersBinary) } if cBlock.stop { return nil, nil, 0, ErrStopPreparingBlock @@ -215,13 +215,14 @@ func (p *StateProcessor) ProcessBlockNoValidator(cBlock *CalculatedBlock, stated // for the transaction, gas used and an error if the transaction failed, // indicating the block was invalid. func ApplyTransaction(config *params.ChainConfig, tokensFee map[common.Address]*big.Int, bc *BlockChain, author *common.Address, gp *GasPool, statedb *state.StateDB, XDCxState *tradingstate.TradingStateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error, bool) { - if tx.To() != nil && tx.To().String() == common.BlockSigners && config.IsTIPSigning(header.Number) { + to := tx.To() + if to != nil && *to == common.BlockSignersBinary && config.IsTIPSigning(header.Number) { return ApplySignTransaction(config, statedb, header, tx, usedGas) } - if tx.To() != nil && tx.To().String() == common.TradingStateAddr && config.IsTIPXDCXReceiver(header.Number) { + if to != nil && *to == common.TradingStateAddrBinary && config.IsTIPXDCXReceiver(header.Number) { return ApplyEmptyTransaction(config, statedb, header, tx, usedGas) } - if tx.To() != nil && tx.To().String() == common.XDCXLendingAddress && config.IsTIPXDCXReceiver(header.Number) { + if to != nil && *to == common.XDCXLendingAddressBinary && config.IsTIPXDCXReceiver(header.Number) { return ApplyEmptyTransaction(config, statedb, header, tx, usedGas) } if tx.IsTradingTransaction() && config.IsTIPXDCXReceiver(header.Number) { @@ -233,8 +234,8 @@ func ApplyTransaction(config *params.ChainConfig, tokensFee map[common.Address]* } var balanceFee *big.Int - if tx.To() != nil { - if value, ok := tokensFee[*tx.To()]; ok { + if to != nil { + if value, ok := tokensFee[*to]; ok { balanceFee = value } } @@ -441,7 +442,7 @@ func ApplyTransaction(config *params.ChainConfig, tokensFee map[common.Address]* receipt.BlockNumber = header.Number receipt.TransactionIndex = uint(statedb.TxIndex()) if balanceFee != nil && failed { - state.PayFeeWithTRC21TxFail(statedb, msg.From(), *tx.To()) + state.PayFeeWithTRC21TxFail(statedb, msg.From(), *to) } return receipt, gas, err, balanceFee != nil } @@ -473,7 +474,7 @@ func ApplySignTransaction(config *params.ChainConfig, statedb *state.StateDB, he // if the transaction created a contract, store the creation address in the receipt. // Set the receipt logs and create a bloom for filtering log := &types.Log{} - log.Address = common.HexToAddress(common.BlockSigners) + log.Address = common.BlockSignersBinary log.BlockNumber = header.Number.Uint64() statedb.AddLog(log) receipt.Logs = statedb.GetLogs(tx.Hash()) diff --git a/core/types/transaction.go b/core/types/transaction.go index 983162943c..b26c0fc206 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -32,7 +32,6 @@ import ( ) //go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go - var ( ErrInvalidSig = errors.New("invalid transaction v, r, s values") ErrUnexpectedProtection = errors.New("transaction type does not supported EIP-155 protected signatures") @@ -45,11 +44,11 @@ var ( errVYParityMissing = errors.New("missing 'yParity' or 'v' field in transaction") errEmptyTypedTx = errors.New("empty typed transaction bytes") errNoSigner = errors.New("missing signing methods") - skipNonceDestinationAddress = map[string]bool{ - common.XDCXAddr: true, - common.TradingStateAddr: true, - common.XDCXLendingAddress: true, - common.XDCXLendingFinalizedTradeAddress: true, + skipNonceDestinationAddress = map[common.Address]bool{ + common.XDCXAddrBinary: true, + common.TradingStateAddrBinary: true, + common.XDCXLendingAddressBinary: true, + common.XDCXLendingFinalizedTradeAddressBinary: true, } ) @@ -406,121 +405,68 @@ func (tx *Transaction) TxCost(number *big.Int) *big.Int { } func (tx *Transaction) IsSpecialTransaction() bool { - if tx.To() == nil { - return false - } - toBytes := tx.To().Bytes() - randomizeSMCBytes := common.HexToAddress(common.RandomizeSMC).Bytes() - blockSignersBytes := common.HexToAddress(common.BlockSigners).Bytes() - return bytes.Equal(toBytes, randomizeSMCBytes) || bytes.Equal(toBytes, blockSignersBytes) + to := tx.To() + return to != nil && (*to == common.RandomizeSMCBinary || *to == common.BlockSignersBinary) } func (tx *Transaction) IsTradingTransaction() bool { - if tx.To() == nil { - return false - } - - if tx.To().String() != common.XDCXAddr { - return false - } - - return true + to := tx.To() + return to != nil && *to == common.XDCXAddrBinary } func (tx *Transaction) IsLendingTransaction() bool { - if tx.To() == nil { - return false - } - - if tx.To().String() != common.XDCXLendingAddress { - return false - } - return true + to := tx.To() + return to != nil && *to == common.XDCXLendingAddressBinary } func (tx *Transaction) IsLendingFinalizedTradeTransaction() bool { - if tx.To() == nil { - return false - } - - if tx.To().String() != common.XDCXLendingFinalizedTradeAddress { - return false - } - return true + to := tx.To() + return to != nil && *to == common.XDCXLendingFinalizedTradeAddressBinary } func (tx *Transaction) IsSkipNonceTransaction() bool { - if tx.To() == nil { - return false - } - if skip := skipNonceDestinationAddress[tx.To().String()]; skip { - return true - } - return false + to := tx.To() + return to != nil && skipNonceDestinationAddress[*to] } func (tx *Transaction) IsSigningTransaction() bool { - if tx.To() == nil { + to := tx.To() + if to == nil || *to != common.BlockSignersBinary { return false } - - if tx.To().String() != common.BlockSigners { + data := tx.Data() + if len(data) != (32*2 + 4) { return false } - - method := common.ToHex(tx.Data()[0:4]) - - if method != common.SignMethod { - return false - } - - if len(tx.Data()) != (32*2 + 4) { - return false - } - - return true + method := common.ToHex(data[0:4]) + return method == common.SignMethod } func (tx *Transaction) IsVotingTransaction() (bool, *common.Address) { - if tx.To() == nil { + to := tx.To() + if to == nil || *to != common.MasternodeVotingSMCBinary { return false, nil } - b := (tx.To().String() == common.MasternodeVotingSMC) - - if !b { - return b, nil + var end int + data := tx.Data() + method := common.ToHex(data[0:4]) + if method == common.VoteMethod || method == common.ProposeMethod || method == common.ResignMethod { + end = len(data) + } else if method == common.UnvoteMethod { + end = len(data) - 32 + } else { + return false, nil } - method := common.ToHex(tx.Data()[0:4]) - if b = (method == common.VoteMethod); b { - addr := tx.Data()[len(tx.Data())-20:] - m := common.BytesToAddress(addr) - return b, &m - } + addr := data[end-20 : end] + m := common.BytesToAddress(addr) + return true, &m - if b = (method == common.UnvoteMethod); b { - addr := tx.Data()[len(tx.Data())-32-20 : len(tx.Data())-32] - m := common.BytesToAddress(addr) - return b, &m - } - - if b = (method == common.ProposeMethod); b { - addr := tx.Data()[len(tx.Data())-20:] - m := common.BytesToAddress(addr) - return b, &m - } - - if b = (method == common.ResignMethod); b { - addr := tx.Data()[len(tx.Data())-20:] - m := common.BytesToAddress(addr) - return b, &m - } - - return b, nil } func (tx *Transaction) IsXDCXApplyTransaction() bool { - if tx.To() == nil { + to := tx.To() + if to == nil { return false } @@ -528,26 +474,22 @@ func (tx *Transaction) IsXDCXApplyTransaction() bool { if common.IsTestnet { addr = common.XDCXListingSMCTestNet } - if tx.To().String() != addr.String() { + if *to != addr { return false } - - method := common.ToHex(tx.Data()[0:4]) - - if method != common.XDCXApplyMethod { - return false - } - + data := tx.Data() // 4 bytes for function name // 32 bytes for 1 parameter - if len(tx.Data()) != (32 + 4) { + if len(data) != (32 + 4) { return false } - return true + method := common.ToHex(data[0:4]) + return method == common.XDCXApplyMethod } func (tx *Transaction) IsXDCZApplyTransaction() bool { - if tx.To() == nil { + to := tx.To() + if to == nil { return false } @@ -555,22 +497,17 @@ func (tx *Transaction) IsXDCZApplyTransaction() bool { if common.IsTestnet { addr = common.TRC21IssuerSMCTestNet } - if tx.To().String() != addr.String() { + if *to != addr { return false } - - method := common.ToHex(tx.Data()[0:4]) - if method != common.XDCZApplyMethod { - return false - } - + data := tx.Data() // 4 bytes for function name // 32 bytes for 1 parameter - if len(tx.Data()) != (32 + 4) { + if len(data) != (32 + 4) { return false } - - return true + method := common.ToHex(data[0:4]) + return method == common.XDCZApplyMethod } func (tx *Transaction) String() string { diff --git a/eth/api_tracer.go b/eth/api_tracer.go index 78788e41bb..01abc14b34 100644 --- a/eth/api_tracer.go +++ b/eth/api_tracer.go @@ -765,7 +765,7 @@ func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, ree // Recompute transactions up to the target index. feeCapacity := state.GetTRC21FeeCapacityFromState(statedb) if common.TIPSigning.Cmp(block.Header().Number) == 0 { - statedb.DeleteAddress(common.HexToAddress(common.BlockSigners)) + statedb.DeleteAddress(common.BlockSignersBinary) } core.InitSignerInTransactions(api.config, block.Header(), block.Transactions()) balanceUpdated := map[common.Address]*big.Int{} diff --git a/eth/hooks/engine_v1_hooks.go b/eth/hooks/engine_v1_hooks.go index c6919c7fe8..950e231ba0 100644 --- a/eth/hooks/engine_v1_hooks.go +++ b/eth/hooks/engine_v1_hooks.go @@ -216,7 +216,7 @@ func AttachConsensusV1Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConf if err != nil { return nil, err } - addr := common.HexToAddress(common.MasternodeVotingSMC) + addr := common.MasternodeVotingSMCBinary validator, err := contractValidator.NewXDCValidator(addr, client) if err != nil { return nil, err diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 2d93455f66..80ea1c1a31 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1197,7 +1197,7 @@ func (s *PublicBlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masterno return []utils.Masternode{}, err } - addr := common.HexToAddress(common.MasternodeVotingSMC) + addr := common.MasternodeVotingSMCBinary validator, err := contractValidator.NewXDCValidator(addr, client) if err != nil { return []utils.Masternode{}, err diff --git a/miner/worker.go b/miner/worker.go index 3de0328bf8..a97f55ceab 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -614,7 +614,7 @@ func (self *worker) commitNewWork() { misc.ApplyDAOHardFork(work.state) } if common.TIPSigning.Cmp(header.Number) == 0 { - work.state.DeleteAddress(common.HexToAddress(common.BlockSigners)) + work.state.DeleteAddress(common.BlockSignersBinary) } // won't grasp txs at checkpoint var ( @@ -699,7 +699,7 @@ func (self *worker) commitNewWork() { return } nonce := work.state.GetNonce(self.coinbase) - tx := types.NewTransaction(nonce, common.HexToAddress(common.XDCXAddr), big.NewInt(0), txMatchGasLimit, big.NewInt(0), txMatchBytes) + tx := types.NewTransaction(nonce, common.XDCXAddrBinary, big.NewInt(0), txMatchGasLimit, big.NewInt(0), txMatchBytes) txM, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, tx, self.config.ChainId) if err != nil { log.Error("Fail to create tx matches", "error", err) @@ -729,7 +729,7 @@ func (self *worker) commitNewWork() { return } nonce := work.state.GetNonce(self.coinbase) - lendingTx := types.NewTransaction(nonce, common.HexToAddress(common.XDCXLendingAddress), big.NewInt(0), txMatchGasLimit, big.NewInt(0), lendingDataBytes) + lendingTx := types.NewTransaction(nonce, common.XDCXLendingAddressBinary, big.NewInt(0), txMatchGasLimit, big.NewInt(0), lendingDataBytes) signedLendingTx, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, lendingTx, self.config.ChainId) if err != nil { log.Error("Fail to create lending tx", "error", err) @@ -753,7 +753,7 @@ func (self *worker) commitNewWork() { return } nonce := work.state.GetNonce(self.coinbase) - finalizedTx := types.NewTransaction(nonce, common.HexToAddress(common.XDCXLendingFinalizedTradeAddress), big.NewInt(0), txMatchGasLimit, big.NewInt(0), finalizedTradeData) + finalizedTx := types.NewTransaction(nonce, common.XDCXLendingFinalizedTradeAddressBinary, big.NewInt(0), txMatchGasLimit, big.NewInt(0), finalizedTradeData) signedFinalizedTx, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, finalizedTx, self.config.ChainId) if err != nil { log.Error("Fail to create lending tx", "error", err) @@ -772,7 +772,7 @@ func (self *worker) commitNewWork() { XDCxStateRoot := work.tradingState.IntermediateRoot() LendingStateRoot := work.lendingState.IntermediateRoot() txData := append(XDCxStateRoot.Bytes(), LendingStateRoot.Bytes()...) - tx := types.NewTransaction(work.state.GetNonce(self.coinbase), common.HexToAddress(common.TradingStateAddr), big.NewInt(0), txMatchGasLimit, big.NewInt(0), txData) + tx := types.NewTransaction(work.state.GetNonce(self.coinbase), common.TradingStateAddrBinary, big.NewInt(0), txMatchGasLimit, big.NewInt(0), txData) txStateRoot, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, tx, self.config.ChainId) if err != nil { log.Error("Fail to create tx state root", "error", err) @@ -808,26 +808,27 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad var coalescedLogs []*types.Log // first priority for special Txs for _, tx := range specialTxs { - + to := tx.To() //HF number for black-list if (env.header.Number.Uint64() >= common.BlackListHFNumber) && !common.IsTestnet { + from := tx.From() // check if sender is in black list - if tx.From() != nil && common.Blacklist[*tx.From()] { - log.Debug("Skipping transaction with sender in black-list", "sender", tx.From().Hex()) + if from != nil && common.Blacklist[*from] { + log.Debug("Skipping transaction with sender in black-list", "sender", from.Hex()) continue } // check if receiver is in black list - if tx.To() != nil && common.Blacklist[*tx.To()] { - log.Debug("Skipping transaction with receiver in black-list", "receiver", tx.To().Hex()) + if to != nil && common.Blacklist[*to] { + log.Debug("Skipping transaction with receiver in black-list", "receiver", to.Hex()) continue } } - + data := tx.Data() // validate minFee slot for XDCZ if tx.IsXDCZApplyTransaction() { copyState, _ := bc.State() - if err := core.ValidateXDCZApplyTransaction(bc, nil, copyState, common.BytesToAddress(tx.Data()[4:])); err != nil { - log.Debug("XDCZApply: invalid token", "token", common.BytesToAddress(tx.Data()[4:]).Hex()) + if err := core.ValidateXDCZApplyTransaction(bc, nil, copyState, common.BytesToAddress(data[4:])); err != nil { + log.Debug("XDCZApply: invalid token", "token", common.BytesToAddress(data[4:]).Hex()) txs.Pop() continue } @@ -835,8 +836,8 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad // validate balance slot, token decimal for XDCX if tx.IsXDCXApplyTransaction() { copyState, _ := bc.State() - if err := core.ValidateXDCXApplyTransaction(bc, nil, copyState, common.BytesToAddress(tx.Data()[4:])); err != nil { - log.Debug("XDCXApply: invalid token", "token", common.BytesToAddress(tx.Data()[4:]).Hex()) + if err := core.ValidateXDCXApplyTransaction(bc, nil, copyState, common.BytesToAddress(data[4:])); err != nil { + log.Debug("XDCXApply: invalid token", "token", common.BytesToAddress(data[4:]).Hex()) txs.Pop() continue } @@ -853,38 +854,39 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad from, _ := types.Sender(env.signer, tx) // Check whether the tx is replay protected. If we're not in the EIP155 hf // phase, start ignoring the sender until we do. + hash := tx.Hash() if tx.Protected() && !env.config.IsEIP155(env.header.Number) { - log.Trace("Ignoring reply protected special transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block) + log.Trace("Ignoring reply protected special transaction", "hash", hash, "eip155", env.config.EIP155Block) continue } - if tx.To().Hex() == common.BlockSigners { - if len(tx.Data()) < 68 { - log.Trace("Data special transaction invalid length", "hash", tx.Hash(), "data", len(tx.Data())) + if *to == common.BlockSignersBinary { + if len(data) < 68 { + log.Trace("Data special transaction invalid length", "hash", hash, "data", len(data)) continue } - blkNumber := binary.BigEndian.Uint64(tx.Data()[8:40]) + blkNumber := binary.BigEndian.Uint64(data[8:40]) if blkNumber >= env.header.Number.Uint64() || blkNumber <= env.header.Number.Uint64()-env.config.XDPoS.Epoch*2 { - log.Trace("Data special transaction invalid number", "hash", tx.Hash(), "blkNumber", blkNumber, "miner", env.header.Number) + log.Trace("Data special transaction invalid number", "hash", hash, "blkNumber", blkNumber, "miner", env.header.Number) continue } } // Start executing the transaction - env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount) + env.state.Prepare(hash, common.Hash{}, env.tcount) nonce := env.state.GetNonce(from) if nonce != tx.Nonce() && !tx.IsSkipNonceTransaction() { - log.Trace("Skipping account with special transaction invalid nonce", "sender", from, "nonce", nonce, "tx nonce ", tx.Nonce(), "to", tx.To()) + log.Trace("Skipping account with special transaction invalid nonce", "sender", from, "nonce", nonce, "tx nonce ", tx.Nonce(), "to", to) continue } err, logs, tokenFeeUsed, gas := env.commitTransaction(balanceFee, tx, bc, coinbase, gp) switch err { case core.ErrNonceTooLow: // New head notification data race between the transaction pool and miner, shift - log.Trace("Skipping special transaction with low nonce", "sender", from, "nonce", tx.Nonce(), "to", tx.To()) + log.Trace("Skipping special transaction with low nonce", "sender", from, "nonce", tx.Nonce(), "to", to) case core.ErrNonceTooHigh: // Reorg notification data race between the transaction pool and miner, skip account = - log.Trace("Skipping account with special transaction hight nonce", "sender", from, "nonce", tx.Nonce(), "to", tx.To()) + log.Trace("Skipping account with special transaction hight nonce", "sender", from, "nonce", tx.Nonce(), "to", to) case nil: // Everything ok, collect the logs and shift in the next transaction from the same account coalescedLogs = append(coalescedLogs, logs...) @@ -893,12 +895,12 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad default: // Strange error, discard the transaction and get the next in line (note, the // nonce-too-high clause will prevent us from executing in vain). - log.Debug("Add Special Transaction failed, account skipped", "hash", tx.Hash(), "sender", from, "nonce", tx.Nonce(), "to", tx.To(), "err", err) + log.Debug("Add Special Transaction failed, account skipped", "hash", hash, "sender", from, "nonce", tx.Nonce(), "to", to, "err", err) } if tokenFeeUsed { fee := common.GetGasFee(env.header.Number.Uint64(), gas) - balanceFee[*tx.To()] = new(big.Int).Sub(balanceFee[*tx.To()], fee) - balanceUpdated[*tx.To()] = balanceFee[*tx.To()] + balanceFee[*to] = new(big.Int).Sub(balanceFee[*to], fee) + balanceUpdated[*to] = balanceFee[*to] totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) } } @@ -920,26 +922,28 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad } //HF number for black-list + to := tx.To() if (env.header.Number.Uint64() >= common.BlackListHFNumber) && !common.IsTestnet { + from := tx.From() // check if sender is in black list - if tx.From() != nil && common.Blacklist[*tx.From()] { - log.Debug("Skipping transaction with sender in black-list", "sender", tx.From().Hex()) + if from != nil && common.Blacklist[*from] { + log.Debug("Skipping transaction with sender in black-list", "sender", from.Hex()) txs.Pop() continue } // check if receiver is in black list - if tx.To() != nil && common.Blacklist[*tx.To()] { - log.Debug("Skipping transaction with receiver in black-list", "receiver", tx.To().Hex()) + if to != nil && common.Blacklist[*to] { + log.Debug("Skipping transaction with receiver in black-list", "receiver", to.Hex()) txs.Shift() continue } } - + data := tx.Data() // validate minFee slot for XDCZ if tx.IsXDCZApplyTransaction() { copyState, _ := bc.State() - if err := core.ValidateXDCZApplyTransaction(bc, nil, copyState, common.BytesToAddress(tx.Data()[4:])); err != nil { - log.Debug("XDCZApply: invalid token", "token", common.BytesToAddress(tx.Data()[4:]).Hex()) + if err := core.ValidateXDCZApplyTransaction(bc, nil, copyState, common.BytesToAddress(data[4:])); err != nil { + log.Debug("XDCZApply: invalid token", "token", common.BytesToAddress(data[4:]).Hex()) txs.Pop() continue } @@ -947,8 +951,8 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad // validate balance slot, token decimal for XDCX if tx.IsXDCXApplyTransaction() { copyState, _ := bc.State() - if err := core.ValidateXDCXApplyTransaction(bc, nil, copyState, common.BytesToAddress(tx.Data()[4:])); err != nil { - log.Debug("XDCXApply: invalid token", "token", common.BytesToAddress(tx.Data()[4:]).Hex()) + if err := core.ValidateXDCXApplyTransaction(bc, nil, copyState, common.BytesToAddress(data[4:])); err != nil { + log.Debug("XDCXApply: invalid token", "token", common.BytesToAddress(data[4:]).Hex()) txs.Pop() continue } @@ -959,15 +963,16 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad // // We use the eip155 signer regardless of the current hf. from, _ := types.Sender(env.signer, tx) + hash := tx.Hash() // Check whether the tx is replay protected. If we're not in the EIP155 hf // phase, start ignoring the sender until we do. if tx.Protected() && !env.config.IsEIP155(env.header.Number) { - log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block) + log.Trace("Ignoring reply protected transaction", "hash", hash, "eip155", env.config.EIP155Block) txs.Pop() continue } // Start executing the transaction - env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount) + env.state.Prepare(hash, common.Hash{}, env.tcount) nonce := env.state.GetNonce(from) if nonce > tx.Nonce() { // New head notification data race between the transaction pool and miner, shift @@ -1012,13 +1017,13 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad default: // Strange error, discard the transaction and get the next in line (note, the // nonce-too-high clause will prevent us from executing in vain). - log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err) + log.Debug("Transaction failed, account skipped", "hash", hash, "err", err) txs.Shift() } if tokenFeeUsed { fee := common.GetGasFee(env.header.Number.Uint64(), gas) - balanceFee[*tx.To()] = new(big.Int).Sub(balanceFee[*tx.To()], fee) - balanceUpdated[*tx.To()] = balanceFee[*tx.To()] + balanceFee[*to] = new(big.Int).Sub(balanceFee[*to], fee) + balanceUpdated[*to] = balanceFee[*to] totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) } }