From 3764cb3d842b7680c3d1acbcfcd9daa57eb29c89 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 16 Oct 2023 11:22:19 +0800 Subject: [PATCH 01/30] add gas price variables and function --- common/constants.go | 1 + common/gas.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 common/gas.go diff --git a/common/constants.go b/common/constants.go index c0d9004c67..9566b4bf42 100644 --- a/common/constants.go +++ b/common/constants.go @@ -77,6 +77,7 @@ var BaseTopUp = big.NewInt(100) var BaseRecall = big.NewInt(100) var TIPTRC21Fee = big.NewInt(38383838) var TIPTRC21FeeTestnet = big.NewInt(38383838) +var BlockNumberGas50x = big.NewInt(TIPTRC21Fee.Int64() + 30000000) var LimitTimeFinality = uint64(30) // limit in 30 block var IgnoreSignerCheckBlockArray = map[uint64]bool{ diff --git a/common/gas.go b/common/gas.go new file mode 100644 index 0000000000..a5b5690a76 --- /dev/null +++ b/common/gas.go @@ -0,0 +1,34 @@ +package common + +import "math/big" + +var MinGasPrice50x = big.NewInt(12500000000) +var GasPrice50x = big.NewInt(12500000000) + +func GetGasFee(blockNumber, gas uint64) *big.Int { + fee := new(big.Int).SetUint64(gas) + + if blockNumber >= BlockNumberGas50x.Uint64() { + fee = fee.Mul(fee, GasPrice50x) + } else if blockNumber > TIPTRC21Fee.Uint64() { + fee = fee.Mul(fee, TRC21GasPrice) + } + + return fee +} + +func GetGasPrice(number *big.Int) *big.Int { + if number == nil || number.Cmp(BlockNumberGas50x) < 0 { + return new(big.Int).Set(TRC21GasPrice) + } else { + return new(big.Int).Set(GasPrice50x) + } +} + +func GetMinGasPrice(number *big.Int) *big.Int { + if number == nil || number.Cmp(BlockNumberGas50x) < 0 { + return new(big.Int).Set(MinGasPrice) + } else { + return new(big.Int).Set(MinGasPrice50x) + } +} From 72c51e2bc97cd56c79cf7ff195c3524cb68b0009 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 17 Jul 2023 18:13:53 +0800 Subject: [PATCH 02/30] set new MinGasPrice in function makeConfigNode --- cmd/XDC/config.go | 1 + 1 file changed, 1 insertion(+) diff --git a/cmd/XDC/config.go b/cmd/XDC/config.go index 4dad8306ae..948e59f417 100644 --- a/cmd/XDC/config.go +++ b/cmd/XDC/config.go @@ -185,6 +185,7 @@ func makeConfigNode(ctx *cli.Context) (*node.Node, XDCConfig) { common.MinGasPrice = big.NewInt(gasPrice) } } + common.MinGasPrice50x = common.MinGasPrice50x.Mul(common.MinGasPrice, big.NewInt(50)) // read passwords from environment passwords := []string{} From 726172903ba87c1e987471746d2fe25723381b38 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 17 Jul 2023 17:54:49 +0800 Subject: [PATCH 03/30] change min and max gas price in SuggestPrice --- eth/gasprice/gasprice.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eth/gasprice/gasprice.go b/eth/gasprice/gasprice.go index fec29cd436..8dfaeec43a 100644 --- a/eth/gasprice/gasprice.go +++ b/eth/gasprice/gasprice.go @@ -141,7 +141,7 @@ func (gpo *Oracle) SuggestPrice(ctx context.Context) (*big.Int, error) { } // Check gas price min. - minGasPrice := common.MinGasPrice + minGasPrice := common.GetMinGasPrice(head.Number) if price.Cmp(minGasPrice) < 0 { price = new(big.Int).Set(minGasPrice) } From 05ad74830752856e1294af649e2f2b9cadfc90e0 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 17 Jul 2023 18:16:10 +0800 Subject: [PATCH 04/30] change MinGasPrice in function Call --- accounts/abi/bind/base.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/accounts/abi/bind/base.go b/accounts/abi/bind/base.go index 7d3304511a..56bf28530d 100644 --- a/accounts/abi/bind/base.go +++ b/accounts/abi/bind/base.go @@ -128,7 +128,7 @@ func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, return err } var ( - msg = XDPoSChain.CallMsg{From: opts.From, To: &c.address, Data: input, GasPrice: common.MinGasPrice, Gas: uint64(4200000)} + msg = XDPoSChain.CallMsg{From: opts.From, To: &c.address, Data: input, GasPrice: common.MinGasPrice50x, Gas: uint64(4200000)} ctx = ensureContext(opts.Context) code []byte output []byte From 845d3d49e530fe86838e939a7fa6be99bd127972 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 17 Jul 2023 18:19:56 +0800 Subject: [PATCH 05/30] change minGasPrice in function validateTx --- core/tx_pool.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core/tx_pool.go b/core/tx_pool.go index abb55e4948..d7a97ee1c2 100644 --- a/core/tx_pool.go +++ b/core/tx_pool.go @@ -632,7 +632,11 @@ func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error { // cost == V + GP * GL balance := pool.currentState.GetBalance(from) cost := tx.Cost() - minGasPrice := common.MinGasPrice + var number *big.Int = nil + if pool.chain.CurrentHeader() != nil { + number = pool.chain.CurrentHeader().Number + } + minGasPrice := common.GetMinGasPrice(number) feeCapacity := big.NewInt(0) if tx.To() != nil { From 9a7ffaa09fdb522405bf65c40dba38fc1b471243 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Tue, 18 Jul 2023 19:40:05 +0800 Subject: [PATCH 06/30] change msg.gasPrice in function AsMessage --- core/types/transaction.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/types/transaction.go b/core/types/transaction.go index 1a87a679a9..6c94f1b6cd 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -262,7 +262,9 @@ func (tx *Transaction) AsMessage(s Signer, balanceFee *big.Int, number *big.Int) var err error msg.from, err = Sender(s, tx) if balanceFee != nil { - if number.Cmp(common.TIPTRC21Fee) > 0 { + if number.Cmp(common.BlockNumberGas50x) >= 0 { + msg.gasPrice = common.GasPrice50x + } else if number.Cmp(common.TIPTRC21Fee) > 0 { msg.gasPrice = common.TRC21GasPrice } else { msg.gasPrice = common.TRC21GasPriceBefore From 0e8b3f1d3118f2bef8e0057ee1b2560379e33769 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 21 Aug 2023 20:04:49 +0800 Subject: [PATCH 07/30] replace TRC21Cost with TxCost --- core/tx_list.go | 4 ++-- core/tx_pool.go | 15 +++++++++++---- core/types/transaction.go | 4 ++-- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/core/tx_list.go b/core/tx_list.go index 523d24430b..030c4cd300 100644 --- a/core/tx_list.go +++ b/core/tx_list.go @@ -290,7 +290,7 @@ func (l *txList) Forward(threshold uint64) types.Transactions { // a point in calculating all the costs or if the balance covers all. If the threshold // is lower than the costgas cap, the caps will be reset to a new high after removing // the newly invalidated transactions. -func (l *txList) Filter(costLimit *big.Int, gasLimit uint64, trc21Issuers map[common.Address]*big.Int) (types.Transactions, types.Transactions) { +func (l *txList) Filter(costLimit *big.Int, gasLimit uint64, trc21Issuers map[common.Address]*big.Int, number *big.Int) (types.Transactions, types.Transactions) { // If all transactions are below the threshold, short circuit if l.costcap.Cmp(costLimit) <= 0 && l.gascap <= gasLimit { return nil, nil @@ -303,7 +303,7 @@ func (l *txList) Filter(costLimit *big.Int, gasLimit uint64, trc21Issuers map[co maximum := costLimit if tx.To() != nil { if feeCapacity, ok := trc21Issuers[*tx.To()]; ok { - return new(big.Int).Add(costLimit, feeCapacity).Cmp(tx.TRC21Cost()) < 0 || tx.Gas() > gasLimit + return new(big.Int).Add(costLimit, feeCapacity).Cmp(tx.TxCost(number)) < 0 || tx.Gas() > gasLimit } } return tx.Cost().Cmp(maximum) > 0 || tx.Gas() > gasLimit diff --git a/core/tx_pool.go b/core/tx_pool.go index d7a97ee1c2..7866371827 100644 --- a/core/tx_pool.go +++ b/core/tx_pool.go @@ -645,8 +645,7 @@ func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error { if !state.ValidateTRC21Tx(pool.pendingState.StateDB, from, *tx.To(), tx.Data()) { return ErrInsufficientFunds } - cost = tx.TRC21Cost() - minGasPrice = common.TRC21GasPrice + cost = tx.TxCost(number) } } if new(big.Int).Add(balance, feeCapacity).Cmp(cost) < 0 { @@ -1070,7 +1069,11 @@ func (pool *TxPool) promoteExecutables(accounts []common.Address) { pool.priced.Removed() } // Drop all transactions that are too costly (low balance or out of gas) - drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas, pool.trc21FeeCapacity) + var number *big.Int = nil + if pool.chain.CurrentHeader() != nil { + number = pool.chain.CurrentHeader().Number + } + drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas, pool.trc21FeeCapacity, number) for _, tx := range drops { hash := tx.Hash() log.Trace("Removed unpayable queued transaction", "hash", hash) @@ -1228,7 +1231,11 @@ func (pool *TxPool) demoteUnexecutables() { pool.priced.Removed() } // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later - drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas, pool.trc21FeeCapacity) + var number *big.Int = nil + if pool.chain.CurrentHeader() != nil { + number = pool.chain.CurrentHeader().Number + } + drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas, pool.trc21FeeCapacity, number) for _, tx := range drops { hash := tx.Hash() log.Trace("Removed unpayable pending transaction", "hash", hash) diff --git a/core/types/transaction.go b/core/types/transaction.go index 6c94f1b6cd..57f69ea0d8 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -293,8 +293,8 @@ func (tx *Transaction) Cost() *big.Int { } // Cost returns amount + gasprice * gaslimit. -func (tx *Transaction) TRC21Cost() *big.Int { - total := new(big.Int).Mul(common.TRC21GasPrice, new(big.Int).SetUint64(tx.data.GasLimit)) +func (tx *Transaction) TxCost(number *big.Int) *big.Int { + total := new(big.Int).Mul(common.GetGasPrice(number), new(big.Int).SetUint64(tx.data.GasLimit)) total.Add(total, tx.data.Amount) return total } From 148e2f1699321f21f7f481390d1cf3ef948ace2a Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 21 Aug 2023 20:07:39 +0800 Subject: [PATCH 08/30] add parameter number for function NewMessage --- core/types/transaction.go | 4 ++-- internal/ethapi/api.go | 2 +- les/odr_test.go | 4 ++-- light/odr_test.go | 2 +- tests/state_test_util.go | 6 +++--- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/core/types/transaction.go b/core/types/transaction.go index 57f69ea0d8..03f1bbe39a 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -702,9 +702,9 @@ type Message struct { balanceTokenFee *big.Int } -func NewMessage(from common.Address, to *common.Address, nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte, checkNonce bool, balanceTokenFee *big.Int) Message { +func NewMessage(from common.Address, to *common.Address, nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte, checkNonce bool, balanceTokenFee *big.Int, number *big.Int) Message { if balanceTokenFee != nil { - gasPrice = common.TRC21GasPrice + gasPrice = common.GetGasPrice(number) } return Message{ from: from, diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 9facea5937..1a0ec61881 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1066,7 +1066,7 @@ func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr balanceTokenFee := big.NewInt(0).SetUint64(gas) balanceTokenFee = balanceTokenFee.Mul(balanceTokenFee, gasPrice) // Create new call message - msg := types.NewMessage(addr, args.To, 0, args.Value.ToInt(), gas, gasPrice, args.Data, false, balanceTokenFee) + msg := types.NewMessage(addr, args.To, 0, args.Value.ToInt(), gas, gasPrice, args.Data, false, balanceTokenFee, header.Number) // Setup context so it may be cancelled the call has completed // or, in case of unmetered gas, setup a context with a timeout. diff --git a/les/odr_test.go b/les/odr_test.go index a9eb41baeb..bbaa7c0dfa 100644 --- a/les/odr_test.go +++ b/les/odr_test.go @@ -133,7 +133,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai if value, ok := feeCapacity[testContractAddr]; ok { balanceTokenFee = value } - msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false, balanceTokenFee)} + msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false, balanceTokenFee, header.Number)} context := core.NewEVMContext(msg, header, bc, nil) vmenv := vm.NewEVM(context, statedb, nil, config, vm.Config{}) @@ -153,7 +153,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai if value, ok := feeCapacity[testContractAddr]; ok { balanceTokenFee = value } - msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false, balanceTokenFee)} + msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false, balanceTokenFee, header.Number)} context := core.NewEVMContext(msg, header, lc, nil) vmenv := vm.NewEVM(context, statedb, nil, config, vm.Config{}) gp := new(core.GasPool).AddGas(math.MaxUint64) diff --git a/light/odr_test.go b/light/odr_test.go index da50255041..4905260ade 100644 --- a/light/odr_test.go +++ b/light/odr_test.go @@ -183,7 +183,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain if value, ok := feeCapacity[testContractAddr]; ok { balanceTokenFee = value } - msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 1000000, new(big.Int), data, false, balanceTokenFee)} + msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 1000000, new(big.Int), data, false, balanceTokenFee, header.Number)} context := core.NewEVMContext(msg, header, chain, nil) vmenv := vm.NewEVM(context, st, nil, config, vm.Config{}) gp := new(core.GasPool).AddGas(math.MaxUint64) diff --git a/tests/state_test_util.go b/tests/state_test_util.go index 301fba6aef..f0db5bd40e 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -131,7 +131,7 @@ func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config) (*state.StateD statedb := MakePreState(db, t.json.Pre) post := t.json.Post[subtest.Fork][subtest.Index] - msg, err := t.json.Tx.toMessage(post) + msg, err := t.json.Tx.toMessage(post, block.Number()) if err != nil { return nil, err } @@ -190,7 +190,7 @@ func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis { } } -func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) { +func (tx *stTransaction) toMessage(ps stPostState, number *big.Int) (core.Message, error) { // Derive sender from private key if present. var from common.Address if len(tx.PrivateKey) > 0 { @@ -235,7 +235,7 @@ func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) { if err != nil { return nil, fmt.Errorf("invalid tx data %q", dataHex) } - msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true, nil) + msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true, nil, number) return msg, nil } From 7adb98fbe8d0cc7699904cf49a64a6c12df8e53f Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Tue, 18 Jul 2023 19:43:36 +0800 Subject: [PATCH 09/30] update gas fee --- contracts/trc21issuer/simulation/test/main.go | 34 +++++++++---------- contracts/trc21issuer/trc21issuer_test.go | 15 +++----- core/chain_makers.go | 5 +-- core/state_processor.go | 10 ++---- eth/api_tracer.go | 5 +-- miner/worker.go | 10 ++---- 6 files changed, 27 insertions(+), 52 deletions(-) diff --git a/contracts/trc21issuer/simulation/test/main.go b/contracts/trc21issuer/simulation/test/main.go index ef2eb197e8..1ee2aff60e 100644 --- a/contracts/trc21issuer/simulation/test/main.go +++ b/contracts/trc21issuer/simulation/test/main.go @@ -4,15 +4,16 @@ import ( "context" "encoding/json" "fmt" + "log" + "math/big" + "time" + "github.com/XinFinOrg/XDPoSChain/accounts/abi/bind" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common/hexutil" "github.com/XinFinOrg/XDPoSChain/contracts/trc21issuer" "github.com/XinFinOrg/XDPoSChain/contracts/trc21issuer/simulation" "github.com/XinFinOrg/XDPoSChain/ethclient" - "log" - "math/big" - "time" ) var ( @@ -48,11 +49,10 @@ func airDropTokenToAccountNoXDC() { if err != nil { log.Fatal("can't transaction's receipt ", err, "hash", tx.Hash().Hex()) } - fee := big.NewInt(0).SetUint64(hexutil.MustDecodeUint64(receipt["gasUsed"].(string))) - if hexutil.MustDecodeUint64(receipt["blockNumber"].(string)) > common.TIPTRC21Fee.Uint64() { - fee = fee.Mul(fee, common.TRC21GasPrice) - } - fmt.Println("fee", fee.Uint64(), "number", hexutil.MustDecodeUint64(receipt["blockNumber"].(string))) + gasUsed := hexutil.MustDecodeUint64(receipt["gasUsed"].(string)) + blockNumber := hexutil.MustDecodeUint64(receipt["blockNumber"].(string)) + fee := common.GetGasFee(blockNumber, gasUsed) + fmt.Println("fee", fee.Uint64(), "number", blockNumber) remainFee = big.NewInt(0).Sub(remainFee, fee) //check balance fee balanceIssuerFee, err := trc21IssuerInstance.GetTokenCapacity(trc21TokenAddr) @@ -111,11 +111,10 @@ func testTransferTRC21TokenWithAccountNoXDC() { if err != nil { log.Fatal("can't transaction's receipt ", err, "hash", tx.Hash().Hex()) } - fee := big.NewInt(0).SetUint64(hexutil.MustDecodeUint64(receipt["gasUsed"].(string))) - if hexutil.MustDecodeUint64(receipt["blockNumber"].(string)) > common.TIPTRC21Fee.Uint64() { - fee = fee.Mul(fee, common.TRC21GasPrice) - } - fmt.Println("fee", fee.Uint64(), "number", hexutil.MustDecodeUint64(receipt["blockNumber"].(string))) + gasUsed := hexutil.MustDecodeUint64(receipt["gasUsed"].(string)) + blockNumber := hexutil.MustDecodeUint64(receipt["blockNumber"].(string)) + fee := common.GetGasFee(blockNumber, gasUsed) + fmt.Println("fee", fee.Uint64(), "number", blockNumber) remainFee = big.NewInt(0).Sub(remainFee, fee) //check balance fee balanceIssuerFee, err := trc21IssuerInstance.GetTokenCapacity(trc21TokenAddr) @@ -178,11 +177,10 @@ func testTransferTrc21Fail() { if err != nil { log.Fatal("can't transaction's receipt ", err, "hash", tx.Hash().Hex()) } - fee := big.NewInt(0).SetUint64(hexutil.MustDecodeUint64(receipt["gasUsed"].(string))) - if hexutil.MustDecodeUint64(receipt["blockNumber"].(string)) > common.TIPTRC21Fee.Uint64() { - fee = fee.Mul(fee, common.TRC21GasPrice) - } - fmt.Println("fee", fee.Uint64(), "number", hexutil.MustDecodeUint64(receipt["blockNumber"].(string))) + gasUsed := hexutil.MustDecodeUint64(receipt["gasUsed"].(string)) + blockNumber := hexutil.MustDecodeUint64(receipt["blockNumber"].(string)) + fee := common.GetGasFee(blockNumber, gasUsed) + fmt.Println("fee", fee.Uint64(), "number", blockNumber) remainFee = big.NewInt(0).Sub(remainFee, fee) //check balance fee balanceIssuerFee, err = trc21IssuerInstance.GetTokenCapacity(trc21TokenAddr) diff --git a/contracts/trc21issuer/trc21issuer_test.go b/contracts/trc21issuer/trc21issuer_test.go index e28344caf0..e0744b26d1 100644 --- a/contracts/trc21issuer/trc21issuer_test.go +++ b/contracts/trc21issuer/trc21issuer_test.go @@ -1,13 +1,14 @@ package trc21issuer import ( + "math/big" + "testing" + "github.com/XinFinOrg/XDPoSChain/accounts/abi/bind" "github.com/XinFinOrg/XDPoSChain/accounts/abi/bind/backends" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/crypto" - "math/big" - "testing" ) var ( @@ -81,10 +82,7 @@ func TestFeeTxWithTRC21Token(t *testing.T) { if err != nil { t.Fatal("can't transaction's receipt ", err, "hash", tx.Hash()) } - fee := big.NewInt(0).SetUint64(receipt.GasUsed) - if receipt.Logs[0].BlockNumber > common.TIPTRC21Fee.Uint64() { - fee = fee.Mul(fee, common.TRC21GasPrice) - } + fee := common.GetGasFee(receipt.Logs[0].BlockNumber, receipt.GasUsed) remainFee := big.NewInt(0).Sub(minApply, fee) // check balance trc21 again @@ -133,10 +131,7 @@ func TestFeeTxWithTRC21Token(t *testing.T) { if err != nil { t.Fatal("can't transaction's receipt ", err, "hash", tx.Hash()) } - fee = big.NewInt(0).SetUint64(receipt.GasUsed) - if receipt.Logs[0].BlockNumber > common.TIPTRC21Fee.Uint64() { - fee = fee.Mul(fee, common.TRC21GasPrice) - } + fee = common.GetGasFee(receipt.Logs[0].BlockNumber, receipt.GasUsed) remainFee = big.NewInt(0).Sub(remainFee, fee) //check balance fee balanceIssuerFee, err = trc21Issuer.GetTokenCapacity(trc21TokenAddr) diff --git a/core/chain_makers.go b/core/chain_makers.go index a19cf0c5a5..348d68d168 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -108,10 +108,7 @@ func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) { b.txs = append(b.txs, tx) b.receipts = append(b.receipts, receipt) if tokenFeeUsed { - fee := new(big.Int).SetUint64(gas) - if b.header.Number.Cmp(common.TIPTRC21Fee) > 0 { - fee = fee.Mul(fee, common.TRC21GasPrice) - } + fee := common.GetGasFee(b.header.Number.Uint64(), gas) state.UpdateTRC21Fee(b.statedb, map[common.Address]*big.Int{*tx.To(): new(big.Int).Sub(feeCapacity[*tx.To()], new(big.Int).SetUint64(gas))}, fee) } } diff --git a/core/state_processor.go b/core/state_processor.go index 97e45f3f6a..acfec0c8fd 100644 --- a/core/state_processor.go +++ b/core/state_processor.go @@ -120,10 +120,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, tra receipts = append(receipts, receipt) allLogs = append(allLogs, receipt.Logs...) if tokenFeeUsed { - fee := new(big.Int).SetUint64(gas) - if block.Header().Number.Cmp(common.TIPTRC21Fee) > 0 { - fee = fee.Mul(fee, common.TRC21GasPrice) - } + fee := common.GetGasFee(block.Header().Number.Uint64(), gas) balanceFee[*tx.To()] = new(big.Int).Sub(balanceFee[*tx.To()], fee) balanceUpdated[*tx.To()] = balanceFee[*tx.To()] totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) @@ -201,10 +198,7 @@ func (p *StateProcessor) ProcessBlockNoValidator(cBlock *CalculatedBlock, stated receipts[i] = receipt allLogs = append(allLogs, receipt.Logs...) if tokenFeeUsed { - fee := new(big.Int).SetUint64(gas) - if block.Header().Number.Cmp(common.TIPTRC21Fee) > 0 { - fee = fee.Mul(fee, common.TRC21GasPrice) - } + fee := common.GetGasFee(block.Header().Number.Uint64(), gas) balanceFee[*tx.To()] = new(big.Int).Sub(balanceFee[*tx.To()], fee) balanceUpdated[*tx.To()] = balanceFee[*tx.To()] totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) diff --git a/eth/api_tracer.go b/eth/api_tracer.go index be95e78d87..218781b57b 100644 --- a/eth/api_tracer.go +++ b/eth/api_tracer.go @@ -706,10 +706,7 @@ func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, ree } if tokenFeeUsed { - fee := new(big.Int).SetUint64(gas) - if block.Header().Number.Cmp(common.TIPTRC21Fee) > 0 { - fee = fee.Mul(fee, common.TRC21GasPrice) - } + fee := common.GetGasFee(block.Header().Number.Uint64(), gas) feeCapacity[*tx.To()] = new(big.Int).Sub(feeCapacity[*tx.To()], fee) balanceUpdated[*tx.To()] = feeCapacity[*tx.To()] totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) diff --git a/miner/worker.go b/miner/worker.go index 76b5562b00..bc3982094e 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -931,10 +931,7 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad log.Debug("Add Special Transaction failed, account skipped", "hash", tx.Hash(), "sender", from, "nonce", tx.Nonce(), "to", tx.To(), "err", err) } if tokenFeeUsed { - fee := new(big.Int).SetUint64(gas) - if env.header.Number.Cmp(common.TIPTRC21Fee) > 0 { - fee = fee.Mul(fee, common.TRC21GasPrice) - } + 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()] totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) @@ -1049,10 +1046,7 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad txs.Shift() } if tokenFeeUsed { - fee := new(big.Int).SetUint64(gas) - if env.header.Number.Cmp(common.TIPTRC21Fee) > 0 { - fee = fee.Mul(fee, common.TRC21GasPrice) - } + 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()] totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) From 41c149916bb98f8f543dec4154b7dae0f4b5933b Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 16 Oct 2023 11:41:33 +0800 Subject: [PATCH 10/30] set new gas price for devnet --- common/constants/constants.go.devnet | 1 + 1 file changed, 1 insertion(+) diff --git a/common/constants/constants.go.devnet b/common/constants/constants.go.devnet index bf756ca3ba..2cd660802f 100644 --- a/common/constants/constants.go.devnet +++ b/common/constants/constants.go.devnet @@ -77,6 +77,7 @@ var BaseTopUp = big.NewInt(100) var BaseRecall = big.NewInt(100) var TIPTRC21Fee = big.NewInt(13523400) var TIPTRC21FeeTestnet = big.NewInt(225000) +var BlockNumberGas50x = big.NewInt(11818181) var LimitTimeFinality = uint64(30) // limit in 30 block var IgnoreSignerCheckBlockArray = map[uint64]bool{ From 446f3fd580670cf0e7eab57018626993b7e59002 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 23 Oct 2023 13:43:32 +0800 Subject: [PATCH 11/30] set new gas price number for testnet and mainnet --- common/constants.go | 2 +- common/constants/constants.go.testnet | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/common/constants.go b/common/constants.go index 9566b4bf42..6d9119f21d 100644 --- a/common/constants.go +++ b/common/constants.go @@ -77,7 +77,7 @@ var BaseTopUp = big.NewInt(100) var BaseRecall = big.NewInt(100) var TIPTRC21Fee = big.NewInt(38383838) var TIPTRC21FeeTestnet = big.NewInt(38383838) -var BlockNumberGas50x = big.NewInt(TIPTRC21Fee.Int64() + 30000000) +var BlockNumberGas50x = big.NewInt(TIPTRC21Fee.Int64() + 40000000) var LimitTimeFinality = uint64(30) // limit in 30 block var IgnoreSignerCheckBlockArray = map[uint64]bool{ diff --git a/common/constants/constants.go.testnet b/common/constants/constants.go.testnet index 7fec041a78..3d0c3cdb2f 100644 --- a/common/constants/constants.go.testnet +++ b/common/constants/constants.go.testnet @@ -77,6 +77,7 @@ var BaseTopUp = big.NewInt(100) var BaseRecall = big.NewInt(100) var TIPTRC21Fee = big.NewInt(23779191) var TIPTRC21FeeTestnet = big.NewInt(23779191) +var BlockNumberGas50x = big.NewInt(TIPTRC21Fee.Int64() + 40000000) var LimitTimeFinality = uint64(30) // limit in 30 block var IgnoreSignerCheckBlockArray = map[uint64]bool{ From 8339e133ee46bde5d3f9a41db5005a3c626440d8 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 11:25:22 +0800 Subject: [PATCH 12/30] add function IsZero for type Hash --- common/types.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/common/types.go b/common/types.go index eea1201b11..72234a226b 100644 --- a/common/types.go +++ b/common/types.go @@ -73,6 +73,9 @@ func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) } func Uint64ToHash(b uint64) Hash { return BytesToHash(new(big.Int).SetUint64(b).Bytes()) } func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) } +// IsZero returns if a Hash is empty +func (h Hash) IsZero() bool { return h == Hash{} } + // Get the string representation of the underlying hash func (h Hash) Str() string { return string(h[:]) } func (h Hash) Bytes() []byte { return h[:] } From 4a59bdf15ab30c37d62696d325f2140d79ac7034 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 11:23:08 +0800 Subject: [PATCH 13/30] add function IsZero for type Address --- common/types.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/common/types.go b/common/types.go index 72234a226b..905c7d5a4e 100644 --- a/common/types.go +++ b/common/types.go @@ -193,6 +193,9 @@ func IsHexAddress(s string) bool { return len(s) == 2*AddressLength && isHex(s) } +// IsZero returns if a address is empty +func (a Address) IsZero() bool { return a == Address{} } + // Get the string representation of the underlying address func (a Address) Str() string { return string(a[:]) } func (a Address) Bytes() []byte { return a[:] } From e2359d9b8cbf80baa382cd5e78adbeca4d874ce9 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 11:46:36 +0800 Subject: [PATCH 14/30] filter zero address in function GetCandidates --- core/state/statedb_utils.go | 15 ++++++++------- eth/hooks/engine_v1_hooks.go | 4 +--- internal/ethapi/api.go | 8 ++------ 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/core/state/statedb_utils.go b/core/state/statedb_utils.go index 4a0c9d45e6..a9c210b569 100644 --- a/core/state/statedb_utils.go +++ b/core/state/statedb_utils.go @@ -93,16 +93,17 @@ 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) - keys := []common.Hash{} - for i := uint64(0); i < arrLength.Big().Uint64(); i++ { + count := arrLength.Big().Uint64() + rets := make([]common.Address, 0, count) + + for i := uint64(0); i < count; i++ { key := GetLocDynamicArrAtElement(slotHash, i, 1) - keys = append(keys, key) - } - rets := []common.Address{} - for _, key := range keys { ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), key) - rets = append(rets, common.HexToAddress(ret.Hex())) + if !ret.IsZero() { + rets = append(rets, common.HexToAddress(ret.Hex())) + } } + return rets } diff --git a/eth/hooks/engine_v1_hooks.go b/eth/hooks/engine_v1_hooks.go index 9d14e7a3a4..78ec7a1e19 100644 --- a/eth/hooks/engine_v1_hooks.go +++ b/eth/hooks/engine_v1_hooks.go @@ -238,9 +238,7 @@ func AttachConsensusV1Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConf if err != nil { return nil, err } - if address.String() != "xdc0000000000000000000000000000000000000000" { - candidates = append(candidates, utils.Masternode{Address: address, Stake: v}) - } + candidates = append(candidates, utils.Masternode{Address: address, Stake: v}) } // sort candidates by stake descending sort.Slice(candidates, func(i, j int) bool { diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 1a0ec61881..1ca90b7e40 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -756,9 +756,7 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd candidatesAddresses := state.GetCandidates(statedb) for _, address := range candidatesAddresses { v := state.GetCandidateCap(statedb, address) - if address.String() != "xdc0000000000000000000000000000000000000000" { - candidates = append(candidates, utils.Masternode{Address: address, Stake: v}) - } + candidates = append(candidates, utils.Masternode{Address: address, Stake: v}) } } if err != nil || len(candidates) == 0 { @@ -882,9 +880,7 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch candidatesAddresses := state.GetCandidates(statedb) for _, address := range candidatesAddresses { v := state.GetCandidateCap(statedb, address) - if address.String() != "xdc0000000000000000000000000000000000000000" { - candidates = append(candidates, utils.Masternode{Address: address, Stake: v}) - } + candidates = append(candidates, utils.Masternode{Address: address, Stake: v}) } } From 2c02ddc2d9a3526cde07f392eb620a92f4cbbf40 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 11:55:07 +0800 Subject: [PATCH 15/30] remove xdc0000000000000000000000000000000000000000 --- core/blockchain.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/blockchain.go b/core/blockchain.go index 7998b493cc..7fac44c075 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -2554,8 +2554,8 @@ func (bc *BlockChain) UpdateM1() error { if err != nil { return err } - //TODO: smart contract shouldn't return "0x0000000000000000000000000000000000000000" - if candidate.String() != "xdc0000000000000000000000000000000000000000" { + // TODO: smart contract shouldn't return "0x0000000000000000000000000000000000000000" + if !candidate.IsZero() { ms = append(ms, utils.Masternode{Address: candidate, Stake: v}) } } From fbb8c54d8635712feb3f747293e38b9d3b9df7ce Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 12:04:24 +0800 Subject: [PATCH 16/30] remove 0x0000000000000000000000000000000000000000 --- internal/ethapi/api.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 1ca90b7e40..4514f630f5 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1008,11 +1008,12 @@ func (s *PublicBlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masterno var candidatesWithStakeInfo []utils.Masternode for _, candidate := range candidates { - v, err := validator.GetCandidateCap(opts, candidate) - if err != nil { - return []utils.Masternode{}, err - } - if candidate.String() != "xdc0000000000000000000000000000000000000000" { + if !candidate.IsZero() { + v, err := validator.GetCandidateCap(opts, candidate) + if err != nil { + return []utils.Masternode{}, err + } + candidatesWithStakeInfo = append(candidatesWithStakeInfo, utils.Masternode{Address: candidate, Stake: v}) } @@ -1022,6 +1023,7 @@ func (s *PublicBlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masterno }) } } + return candidatesWithStakeInfo, nil } From f4154d0479b3eb47aa7cdf819bdaa5dec773c9da Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 13:45:35 +0800 Subject: [PATCH 17/30] remove lendingstate.EmptyAddress --- XDCxlending/lendingstate/common.go | 5 ++--- XDCxlending/lendingstate/lendingitem.go | 11 ++++++----- XDCxlending/order_processor.go | 16 ++++++++-------- core/lending_pool.go | 4 ++-- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/XDCxlending/lendingstate/common.go b/XDCxlending/lendingstate/common.go index 3f52854640..d22abc37da 100644 --- a/XDCxlending/lendingstate/common.go +++ b/XDCxlending/lendingstate/common.go @@ -2,16 +2,15 @@ package lendingstate import ( "encoding/json" - "github.com/XinFinOrg/XDPoSChain/crypto" "math/big" "time" "github.com/XinFinOrg/XDPoSChain/common" + "github.com/XinFinOrg/XDPoSChain/crypto" ) var ( - EmptyAddress = "xdc0000000000000000000000000000000000000000" - EmptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") + EmptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") ) var EmptyHash = common.Hash{} diff --git a/XDCxlending/lendingstate/lendingitem.go b/XDCxlending/lendingstate/lendingitem.go index 13d9ff0ecf..09006738eb 100644 --- a/XDCxlending/lendingstate/lendingitem.go +++ b/XDCxlending/lendingstate/lendingitem.go @@ -2,14 +2,15 @@ package lendingstate import ( "fmt" + "math/big" + "strconv" + "time" + "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/crypto/sha3" "github.com/globalsign/mgo/bson" - "math/big" - "strconv" - "time" ) const ( @@ -243,7 +244,7 @@ func (l *LendingItem) VerifyLendingSide() error { } func (l *LendingItem) VerifyCollateral(state *state.StateDB) error { - if l.CollateralToken.String() == EmptyAddress || l.CollateralToken.String() == l.LendingToken.String() { + if l.CollateralToken.IsZero() || l.CollateralToken == l.LendingToken { return fmt.Errorf("invalid collateral %s", l.CollateralToken.Hex()) } validCollateral := false @@ -329,7 +330,7 @@ func (l *LendingItem) EncodedSide() *big.Int { return big.NewInt(1) } -//verify signatures +// verify signatures func (l *LendingItem) VerifyLendingSignature() error { V := big.NewInt(int64(l.Signature.V)) R := l.Signature.R.Big() diff --git a/XDCxlending/order_processor.go b/XDCxlending/order_processor.go index 3ee8e6aade..2dcfb560e6 100644 --- a/XDCxlending/order_processor.go +++ b/XDCxlending/order_processor.go @@ -3,6 +3,8 @@ package XDCxlending import ( "encoding/json" "fmt" + "math/big" + "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" "github.com/XinFinOrg/XDPoSChain/XDCxlending/lendingstate" "github.com/XinFinOrg/XDPoSChain/common" @@ -10,7 +12,6 @@ import ( "github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/log" - "math/big" ) func (l *Lending) CommitOrder(header *types.Header, coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, lendingStateDB *lendingstate.LendingStateDB, tradingStateDb *tradingstate.TradingStateDB, lendingOrderBook common.Hash, order *lendingstate.LendingItem) ([]*lendingstate.LendingTrade, []*lendingstate.LendingItem, error) { @@ -262,10 +263,9 @@ func (l *Lending) processOrderList(header *types.Header, coinbase common.Address collateralToken = oldestOrder.CollateralToken borrowFee = lendingstate.GetFee(statedb, oldestOrder.Relayer) } - if collateralToken.String() == lendingstate.EmptyAddress { + if collateralToken.IsZero() { return nil, nil, nil, fmt.Errorf("empty collateral") } - collateralPrice := common.BasePrice depositRate, liquidationRate, recallRate := lendingstate.GetCollateralDetail(statedb, collateralToken) if depositRate == nil || depositRate.Sign() <= 0 { return nil, nil, nil, fmt.Errorf("invalid depositRate %v", depositRate) @@ -953,11 +953,11 @@ func (l *Lending) GetMediumTradePriceBeforeEpoch(chain consensus.ChainContext, s return nil, nil } -//LendToken and CollateralToken must meet at least one of following conditions -//- Have direct pair in XDCX: lendToken/CollateralToken or CollateralToken/LendToken -//- Have pairs with XDC: -//- lendToken/XDC and CollateralToken/XDC -//- XDC/lendToken and XDC/CollateralToken +// LendToken and CollateralToken must meet at least one of following conditions +// - Have direct pair in XDCX: lendToken/CollateralToken or CollateralToken/LendToken +// - Have pairs with XDC: +// - lendToken/XDC and CollateralToken/XDC +// - XDC/lendToken and XDC/CollateralToken func (l *Lending) GetCollateralPrices(header *types.Header, chain consensus.ChainContext, statedb *state.StateDB, tradingStateDb *tradingstate.TradingStateDB, collateralToken common.Address, lendingToken common.Address) (*big.Int, *big.Int, error) { // lendTokenXDCPrice: price of ticker lendToken/XDC // collateralXDCPrice: price of ticker collateralToken/XDC diff --git a/core/lending_pool.go b/core/lending_pool.go index 4f600b2e58..26d7a1395a 100644 --- a/core/lending_pool.go +++ b/core/lending_pool.go @@ -431,7 +431,7 @@ func (pool *LendingPool) validateNewLending(cloneStateDb *state.StateDB, cloneLe return ErrInvalidLendingType } if tx.Side() == lendingstate.Borrowing { - if tx.CollateralToken().String() == lendingstate.EmptyAddress || tx.CollateralToken().String() == tx.LendingToken().String() { + if tx.CollateralToken().IsZero() || tx.CollateralToken() == tx.LendingToken() { return ErrInvalidLendingCollateral } validCollateral := false @@ -541,7 +541,7 @@ func (pool *LendingPool) validateBalance(cloneStateDb *state.StateDB, cloneLendi // collateralPrice = BTC/USD (eg: 8000 USD) // lendTokenXDCPrice: price of lendingToken in XDC quote var lendTokenXDCPrice, collateralPrice, collateralTokenDecimal *big.Int - if collateralToken.String() != lendingstate.EmptyAddress { + if !collateralToken.IsZero() { collateralTokenDecimal, err = XDCXServ.GetTokenDecimal(pool.chain, cloneStateDb, collateralToken) if err != nil { return fmt.Errorf("validateOrder: failed to get collateralTokenDecimal. err: %v", err) From ebf1002c67b30b7ca30af6fd270bdb843e2031e0 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 17 Jul 2023 11:53:56 +0800 Subject: [PATCH 18/30] fix function GetPreviousCheckpointFromEpoch --- internal/ethapi/api.go | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 4514f630f5..45342e931a 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -962,28 +962,23 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch // GetPreviousCheckpointFromEpoch returns header of the previous checkpoint func (s *PublicBlockChainAPI) GetPreviousCheckpointFromEpoch(ctx context.Context, epochNum rpc.EpochNumber) (rpc.BlockNumber, rpc.EpochNumber) { var checkpointNumber uint64 + epoch := s.b.ChainConfig().XDPoS.Epoch - if engine, ok := s.b.GetEngine().(*XDPoS.XDPoS); ok { - currentCheckpointNumber, epochNumber, err := engine.GetCurrentEpochSwitchBlock(s.chainReader, s.b.CurrentBlock().Number()) - if err != nil { - log.Error("[GetPreviousCheckpointFromEpoch] Error while trying to get current epoch switch block information", "Block", s.b.CurrentBlock(), "Error", err) + if epochNum == rpc.LatestEpochNumber { + blockNumer := s.b.CurrentBlock().Number().Uint64() + diff := blockNumer % epoch + // checkpoint number + checkpointNumber = blockNumer - diff + epochNum = rpc.EpochNumber(checkpointNumber / epoch) + if diff > 0 { + epochNum += 1 } - if epochNum == rpc.LatestEpochNumber { - checkpointNumber = currentCheckpointNumber - epochNum = rpc.EpochNumber(epochNumber) - } else if epochNum < 2 { - checkpointNumber = 0 - } else { - blockNumberBeforeCurrentEpochSwitch := currentCheckpointNumber - 1 - checkpointNumber, _, err = engine.GetCurrentEpochSwitchBlock(s.chainReader, big.NewInt(int64(blockNumberBeforeCurrentEpochSwitch))) - if err != nil { - log.Error("[GetPreviousCheckpointFromEpoch] Error while trying to get last epoch switch block information", "Number", blockNumberBeforeCurrentEpochSwitch, "Error", err) - } - } - return rpc.BlockNumber(checkpointNumber), epochNum + } else if epochNum < 2 { + checkpointNumber = 0 } else { - panic("[GetPreviousCheckpointFromEpoch] Error while trying to get XDPoS consensus engine") + checkpointNumber = epoch * (uint64(epochNum) - 1) } + return rpc.BlockNumber(checkpointNumber), epochNum } // getCandidatesFromSmartContract returns all candidates with their capacities at the current time From 3214bbeeba35a3a0eba20280887ca444b3e43346 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 14:36:42 +0800 Subject: [PATCH 19/30] sort candidates in function GetCandidates --- internal/ethapi/api.go | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 45342e931a..7aa6a4736f 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -878,6 +878,7 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch return result, err } candidatesAddresses := state.GetCandidates(statedb) + candidates = make([]utils.Masternode, 0, len(candidatesAddresses)) for _, address := range candidatesAddresses { v := state.GetCandidateCap(statedb, address) candidates = append(candidates, utils.Masternode{Address: address, Stake: v}) @@ -889,15 +890,8 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch result[fieldSuccess] = false return result, err } - // First, set all candidate to propose - for _, candidate := range candidates { - candidatesStatusMap[candidate.Address.String()] = map[string]interface{}{ - fieldStatus: statusProposed, - fieldCapacity: candidate.Stake, - } - } - // Second, Find candidates that have masternode status + // Find candidates that have masternode status if engine, ok := s.b.GetEngine().(*XDPoS.XDPoS); ok { masternodes = engine.GetMasternodesFromCheckpointHeader(header) if len(masternodes) == 0 { @@ -908,6 +902,15 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch } else { log.Error("Undefined XDPoS consensus engine") } + + // Set all candidate to propose + for _, candidate := range candidates { + candidatesStatusMap[candidate.Address.String()] = map[string]interface{}{ + fieldStatus: statusProposed, + fieldCapacity: candidate.Stake, + } + } + // Set masternode status for _, masternode := range masternodes { if candidatesStatusMap[masternode.String()] != nil { @@ -915,7 +918,20 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch } } - // Third, Get penalties list + var maxMasternodes int + if s.b.ChainConfig().IsTIPIncreaseMasternodes(block.Number()) { + maxMasternodes = common.MaxMasternodesV2 + } else { + maxMasternodes = common.MaxMasternodes + } + + if len(candidates) > maxMasternodes { + sort.Slice(candidates, func(i, j int) bool { + return candidates[i].Stake.Cmp(candidates[j].Stake) > 0 + }) + } + + // Get penalties list penalties = append(penalties, header.Penalties...) // check last 5 epochs to find penalize masternodes for i := 1; i <= common.LimitPenaltyEpoch; i++ { From 7dc5ffe45a5b66d0e0134e773750f0a7c55b1ed3 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 14:47:38 +0800 Subject: [PATCH 20/30] fix topCandidates in function GetCandidates --- internal/ethapi/api.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 7aa6a4736f..9bcff052e9 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -954,8 +954,8 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch penaltyList = common.ExtractAddressFromBytes(penalties) var topCandidates []utils.Masternode - if len(candidates) > common.MaxMasternodes { - topCandidates = candidates[:common.MaxMasternodes] + if len(candidates) > maxMasternodes { + topCandidates = candidates[:maxMasternodes] } else { topCandidates = candidates } From 5d24dfdf7e5b498a3d955b450af8e2c92a08dd11 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 14:50:16 +0800 Subject: [PATCH 21/30] not sort candidates in getCandidatesFromSmartContract --- internal/ethapi/api.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 9bcff052e9..f62ce241fd 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1016,7 +1016,7 @@ func (s *PublicBlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masterno return []utils.Masternode{}, err } - var candidatesWithStakeInfo []utils.Masternode + candidatesWithStakeInfo := make([]utils.Masternode, 0, len(candidates)) for _, candidate := range candidates { if !candidate.IsZero() { @@ -1027,12 +1027,6 @@ func (s *PublicBlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masterno candidatesWithStakeInfo = append(candidatesWithStakeInfo, utils.Masternode{Address: candidate, Stake: v}) } - - if len(candidatesWithStakeInfo) > 0 { - sort.Slice(candidatesWithStakeInfo, func(i, j int) bool { - return candidatesWithStakeInfo[i].Stake.Cmp(candidatesWithStakeInfo[j].Stake) >= 0 - }) - } } return candidatesWithStakeInfo, nil From 6e7d7f500285b9f11cf070b9178868f8140e886c Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 15:10:19 +0800 Subject: [PATCH 22/30] return non-candidate masternode in GetCandidates --- internal/ethapi/api.go | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index f62ce241fd..bc4ff76224 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -851,7 +851,6 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch fieldSuccess: true, } epochConfig := s.b.ChainConfig().XDPoS.Epoch - candidatesStatusMap := map[string]map[string]interface{}{} checkpointNumber, epochNumber = s.GetPreviousCheckpointFromEpoch(ctx, epoch) result[fieldEpoch] = epochNumber.Int64() @@ -903,7 +902,8 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch log.Error("Undefined XDPoS consensus engine") } - // Set all candidate to propose + // Set all candidate to statusProposed + candidatesStatusMap := make(map[string]map[string]interface{}, len(candidates)) for _, candidate := range candidates { candidatesStatusMap[candidate.Address.String()] = map[string]interface{}{ fieldStatus: statusProposed, @@ -911,10 +911,17 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch } } - // Set masternode status + // Set masternodes to statusMasternode for _, masternode := range masternodes { - if candidatesStatusMap[masternode.String()] != nil { - candidatesStatusMap[masternode.String()][fieldStatus] = statusMasternode + key := masternode.String() + if candidatesStatusMap[key] != nil { + candidatesStatusMap[key][fieldStatus] = statusMasternode + } else { + candidatesStatusMap[key] = map[string]interface{}{ + fieldStatus: statusMasternode, + fieldCapacity: -1, + } + log.Warn("Masternode is not candidate", "masternode", key, "checkpointNumber", checkpointNumber, "epoch", epoch, "epochNumber", epochNumber) } } @@ -925,6 +932,11 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch maxMasternodes = common.MaxMasternodes } + if len(masternodes) >= maxMasternodes { + result[fieldCandidates] = candidatesStatusMap + return result, nil + } + if len(candidates) > maxMasternodes { sort.Slice(candidates, func(i, j int) bool { return candidates[i].Stake.Cmp(candidates[j].Stake) > 0 From 8ed9a754b297122e4910064ca1d514edb8bf42ee Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 15:30:13 +0800 Subject: [PATCH 23/30] return more slashed nodes in GetCandidates --- internal/ethapi/api.go | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index bc4ff76224..44ad2ed51a 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -965,20 +965,19 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch } penaltyList = common.ExtractAddressFromBytes(penalties) - var topCandidates []utils.Masternode - if len(candidates) > maxMasternodes { - topCandidates = candidates[:maxMasternodes] - } else { - topCandidates = candidates - } - // check penalties from checkpoint headers and modify status of a node to SLASHED if it's in top 150 candidates - // if it's SLASHED but it's out of top 150, the status should be still PROPOSED - for _, pen := range penaltyList { - for _, candidate := range topCandidates { - if candidate.Address == pen && candidatesStatusMap[pen.String()] != nil { + // check penalties from checkpoint headers and modify status of a node to SLASHED if it's in top maxMasternodes candidates. + // if it's SLASHED but it's out of top maxMasternodes, the status should be still PROPOSED. + total := len(masternodes) + for _, candidate := range candidates { + for _, pen := range penaltyList { + if candidate.Address == pen { candidatesStatusMap[pen.String()][fieldStatus] = statusSlashed + total++ + if total >= maxMasternodes { + result[fieldCandidates] = candidatesStatusMap + return result, nil + } } - penalties = append(penalties, block.Penalties()...) } } From 745e0970408f726046d64b40cf011aa10d1e8229 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 14:22:20 +0800 Subject: [PATCH 24/30] sort candidates in function GetCandidateStatus --- internal/ethapi/api.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 44ad2ed51a..2e61139e7d 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -754,6 +754,7 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd return result, err } candidatesAddresses := state.GetCandidates(statedb) + candidates = make([]utils.Masternode, 0, len(candidatesAddresses)) for _, address := range candidatesAddresses { v := state.GetCandidateCap(statedb, address) candidates = append(candidates, utils.Masternode{Address: address, Stake: v}) @@ -764,6 +765,7 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd result[fieldSuccess] = false return result, err } + var maxMasternodes int if s.b.ChainConfig().IsTIPIncreaseMasternodes(block.Number()) { maxMasternodes = common.MaxMasternodesV2 @@ -807,6 +809,12 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd } } + if len(candidates) > maxMasternodes { + sort.Slice(candidates, func(i, j int) bool { + return candidates[i].Stake.Cmp(candidates[j].Stake) > 0 + }) + } + // Third, Get penalties list penalties = append(penalties, header.Penalties...) // check last 5 epochs to find penalize masternodes From e17a0869e5f4b8c19917263ef891054a0a4e588d Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 16:04:44 +0800 Subject: [PATCH 25/30] check masternode before candidate in GetCandidateStatus --- internal/ethapi/api.go | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 2e61139e7d..a3138ca257 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -773,24 +773,19 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd maxMasternodes = common.MaxMasternodes } - isTopCandidate := false - // check penalties from checkpoint headers and modify status of a node to SLASHED if it's in top 150 candidates - // if it's SLASHED but it's out of top 150, the status should be still PROPOSED + // check penalties from checkpoint headers and modify status of a node to SLASHED if it's in top maxMasternodes candidates. + // if it's SLASHED but it's out of top maxMasternodes, the status should be still PROPOSED. + isCandidate := false for i := 0; i < len(candidates); i++ { if coinbaseAddress == candidates[i].Address { - if i < maxMasternodes { - isTopCandidate = true - } + isCandidate = true result[fieldStatus] = statusProposed result[fieldCapacity] = candidates[i].Stake break } } - if !isTopCandidate { - return result, nil - } - // Second, Find candidates that have masternode status + // Get masternode list if engine, ok := s.b.GetEngine().(*XDPoS.XDPoS); ok { masternodes = engine.GetMasternodesFromCheckpointHeader(header) if len(masternodes) == 0 { @@ -801,14 +796,23 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd } else { log.Error("Undefined XDPoS consensus engine") } - // Set masternode status + + // Set to statusMasternode if it is masternode for _, masternode := range masternodes { if coinbaseAddress == masternode { result[fieldStatus] = statusMasternode + if !isCandidate { + result[fieldCapacity] = -1 + log.Warn("Find non-candidate masternode", "masternode", masternode.String(), "checkpointNumber", checkpointNumber, "epoch", epoch, "epochNumber", epochNumber) + } return result, nil } } + if !isCandidate || len(masternodes) >= maxMasternodes { + return result, nil + } + if len(candidates) > maxMasternodes { sort.Slice(candidates, func(i, j int) bool { return candidates[i].Stake.Cmp(candidates[j].Stake) > 0 From f32c66ebc171123d18553d006e35386c4ef13f6e Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Fri, 14 Jul 2023 16:30:47 +0800 Subject: [PATCH 26/30] check slashed status in GetCandidateStatus --- internal/ethapi/api.go | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index a3138ca257..eedde75d18 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -819,7 +819,7 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd }) } - // Third, Get penalties list + // Get penalties list penalties = append(penalties, header.Penalties...) // check last 5 epochs to find penalize masternodes for i := 1; i <= common.LimitPenaltyEpoch; i++ { @@ -837,12 +837,22 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd penaltyList = common.ExtractAddressFromBytes(penalties) // map slashing status - for _, pen := range penaltyList { - if coinbaseAddress == pen { - result[fieldStatus] = statusSlashed - return result, nil + total := len(masternodes) + for _, candidate := range candidates { + for _, pen := range penaltyList { + if candidate.Address == pen { + if coinbaseAddress == pen { + result[fieldStatus] = statusSlashed + return result, nil + } + total++ + if total >= maxMasternodes { + return result, nil + } + } } } + return result, nil } From 3b7f29a5a3f3d401b318aed9611f6194111a8dcd Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 23 Oct 2023 19:33:50 +0800 Subject: [PATCH 27/30] bump version to 1.4.10.beta1 --- params/version.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/params/version.go b/params/version.go index 8cf553f207..56e0d6f749 100644 --- a/params/version.go +++ b/params/version.go @@ -21,10 +21,10 @@ import ( ) const ( - VersionMajor = 1 // Major version component of the current release - VersionMinor = 4 // Minor version component of the current release - VersionPatch = 9 // Patch version component of the current release - VersionMeta = "beta" // Version metadata to append to the version string + VersionMajor = 1 // Major version component of the current release + VersionMinor = 4 // Minor version component of the current release + VersionPatch = 10 // Patch version component of the current release + VersionMeta = "beta1" // Version metadata to append to the version string ) // Version holds the textual version string. From 24d02fe2b416fa70fbdd0bd4c4369cf73035ff74 Mon Sep 17 00:00:00 2001 From: Liam Date: Mon, 30 Oct 2023 19:03:34 +1100 Subject: [PATCH 28/30] check v2 switch block is epoch number (#342) * check v2 switch block is epoch number * revert sync pr * add test * make default block number valid * fix log * fix test --- cmd/puppeth/wizard_genesis.go | 4 ++-- common/constants.go | 2 +- common/constants/constants.go.testnet | 2 +- consensus/XDPoS/XDPoS.go | 7 ++++++- consensus/XDPoS/engines/engine_v2/engine.go | 12 +++++++++--- .../tests/engine_v2_tests/initial_test.go | 19 +++++++++++++++++++ params/config.go | 14 +++++--------- 7 files changed, 43 insertions(+), 17 deletions(-) diff --git a/cmd/puppeth/wizard_genesis.go b/cmd/puppeth/wizard_genesis.go index c312e91a8a..510c99a23d 100644 --- a/cmd/puppeth/wizard_genesis.go +++ b/cmd/puppeth/wizard_genesis.go @@ -77,7 +77,7 @@ func (w *wizard) makeGenesis() { genesis.Difficulty = big.NewInt(1) genesis.Config.Clique = ¶ms.CliqueConfig{ Period: 15, - Epoch: 30000, + Epoch: 900, } fmt.Println() fmt.Println("How many seconds should blocks take? (default = 15)") @@ -114,7 +114,7 @@ func (w *wizard) makeGenesis() { genesis.Difficulty = big.NewInt(1) genesis.Config.XDPoS = ¶ms.XDPoSConfig{ Period: 15, - Epoch: 30000, + Epoch: 900, Reward: 0, V2: ¶ms.V2{ SwitchBlock: big.NewInt(0), diff --git a/common/constants.go b/common/constants.go index 6d9119f21d..9cf18eb9f7 100644 --- a/common/constants.go +++ b/common/constants.go @@ -36,7 +36,7 @@ var TIP2019Block = big.NewInt(1) var TIPSigning = big.NewInt(3000000) var TIPRandomize = big.NewInt(3464000) -var TIPV2SwitchBlock = big.NewInt(99999999999) +var TIPV2SwitchBlock = big.NewInt(99999999900) var TIPIncreaseMasternodes = big.NewInt(5000000) // Upgrade MN Count at Block. var TIPNoHalvingMNReward = big.NewInt(38383838) // hardfork no halving masternodes reward diff --git a/common/constants/constants.go.testnet b/common/constants/constants.go.testnet index 3d0c3cdb2f..23b847be64 100644 --- a/common/constants/constants.go.testnet +++ b/common/constants/constants.go.testnet @@ -36,7 +36,7 @@ var TIP2019Block = big.NewInt(1) var TIPSigning = big.NewInt(3000000) var TIPRandomize = big.NewInt(3464000) -var TIPV2SwitchBlock = big.NewInt(56000000) +var TIPV2SwitchBlock = big.NewInt(56430000) var TIPIncreaseMasternodes = big.NewInt(5000000) // Upgrade MN Count at Block. var TIPNoHalvingMNReward = big.NewInt(23779191) // hardfork no halving masternodes reward diff --git a/consensus/XDPoS/XDPoS.go b/consensus/XDPoS/XDPoS.go index ca76b0d000..d03f324d4c 100644 --- a/consensus/XDPoS/XDPoS.go +++ b/consensus/XDPoS/XDPoS.go @@ -17,6 +17,7 @@ package XDPoS import ( + "fmt" "math/big" "github.com/XinFinOrg/XDPoSChain/common" @@ -95,7 +96,11 @@ func New(chainConfig *params.ChainConfig, db ethdb.Database) *XDPoS { } } - log.Info("xdc config loading", "config", config) + if config.V2.SwitchBlock.Uint64()%config.Epoch != 0 { + panic(fmt.Sprintf("v2 switch number is not epoch switch block %d, epoch %d", config.V2.SwitchBlock.Uint64(), config.Epoch)) + } + + log.Info("xdc config loading", "v2 config", config.V2) minePeriodCh := make(chan int) diff --git a/consensus/XDPoS/engines/engine_v2/engine.go b/consensus/XDPoS/engines/engine_v2/engine.go index cff0c57b9e..7c20c50059 100644 --- a/consensus/XDPoS/engines/engine_v2/engine.go +++ b/consensus/XDPoS/engines/engine_v2/engine.go @@ -164,7 +164,7 @@ func (x *XDPoS_v2) Initial(chain consensus.ChainReader, header *types.Header) er } func (x *XDPoS_v2) initial(chain consensus.ChainReader, header *types.Header) error { - log.Info("[initial] initial v2 related parameters") + log.Warn("[initial] initial v2 related parameters") if x.highestQuorumCert.ProposedBlockInfo.Hash != (common.Hash{}) { // already initialized log.Info("[initial] Already initialized", "x.highestQuorumCert.ProposedBlockInfo.Hash", x.highestQuorumCert.ProposedBlockInfo.Hash) @@ -219,6 +219,12 @@ func (x *XDPoS_v2) initial(chain consensus.ChainReader, header *types.Header) er log.Error("[initial] Error while get masternodes", "error", err) return err } + + if len(masternodes) == 0 { + log.Error("[initial] masternodes are empty", "v2switch", x.config.V2.SwitchBlock.Uint64()) + return fmt.Errorf("masternodes are empty v2 switch number: %d", x.config.V2.SwitchBlock.Uint64()) + } + snap := newSnapshot(lastGapNum, lastGapHeader.Hash(), masternodes) x.snapshots.Add(snap.Hash, snap) err = storeSnapshot(snap, x.db) @@ -229,7 +235,7 @@ func (x *XDPoS_v2) initial(chain consensus.ChainReader, header *types.Header) er } // Initial timeout - log.Info("[initial] miner wait period", "period", x.config.V2.CurrentConfig.MinePeriod) + log.Warn("[initial] miner wait period", "period", x.config.V2.CurrentConfig.MinePeriod) // avoid deadlock go func() { x.minePeriodCh <- x.config.V2.CurrentConfig.MinePeriod @@ -239,7 +245,7 @@ func (x *XDPoS_v2) initial(chain consensus.ChainReader, header *types.Header) er x.timeoutWorker.Reset(chain) x.isInitilised = true - log.Info("[initial] finish initialisation") + log.Warn("[initial] finish initialisation") return nil } diff --git a/consensus/tests/engine_v2_tests/initial_test.go b/consensus/tests/engine_v2_tests/initial_test.go index 70d3f9e95b..5224ae6b1c 100644 --- a/consensus/tests/engine_v2_tests/initial_test.go +++ b/consensus/tests/engine_v2_tests/initial_test.go @@ -1,6 +1,7 @@ package engine_v2_tests import ( + "encoding/json" "math/big" "testing" @@ -124,3 +125,21 @@ func TestSnapshotShouldAlreadyCreatedByUpdateM1(t *testing.T) { assert.Nil(t, err) assert.Equal(t, uint64(1350), snap.Number) } + +func TestInitialWithWrongSwitchNumber(t *testing.T) { + b, err := json.Marshal(params.TestXDPoSMockChainConfig) + assert.Nil(t, err) + configString := string(b) + + var config params.ChainConfig + err = json.Unmarshal([]byte(configString), &config) + assert.Nil(t, err) + + blockchain, _, currentBlock, _, _, _ := PrepareXDCTestBlockChainForV2Engine(t, 800, &config, nil) + adaptor := blockchain.Engine().(*XDPoS.XDPoS) + header := currentBlock.Header() + config.XDPoS.V2.SwitchBlock = big.NewInt(800) // not epoch number + + err = adaptor.EngineV2.Initial(blockchain, header) + assert.NotNil(t, err) +} diff --git a/params/config.go b/params/config.go index dbc2a61ad4..e93238a8dd 100644 --- a/params/config.go +++ b/params/config.go @@ -45,7 +45,7 @@ var ( CertThreshold: 73, // based on masternode is 108 TimeoutSyncThreshold: 3, TimeoutPeriod: 60, - MinePeriod: 10, + MinePeriod: 2, }, } @@ -197,7 +197,7 @@ var ( ConstantinopleBlock: nil, XDPoS: &XDPoSConfig{ Period: 15, - Epoch: 30000, + Epoch: 900, V2: &V2{ SwitchBlock: big.NewInt(9999999999), CurrentConfig: MainnetV2Configs[0], @@ -218,8 +218,8 @@ var ( // // This configuration is intentionally not using keyed fields to force anyone // adding flags to the config to also have to set these fields. - AllXDPoSProtocolChanges = &ChainConfig{big.NewInt(89), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, nil, nil, &XDPoSConfig{Period: 0, Epoch: 30000}} - AllCliqueProtocolChanges = &ChainConfig{big.NewInt(1337), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, nil, &CliqueConfig{Period: 0, Epoch: 30000}, nil} + AllXDPoSProtocolChanges = &ChainConfig{big.NewInt(89), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, nil, nil, &XDPoSConfig{Period: 0, Epoch: 900}} + AllCliqueProtocolChanges = &ChainConfig{big.NewInt(1337), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, nil, &CliqueConfig{Period: 0, Epoch: 900}, nil} // XDPoS config with v2 engine after block 901 TestXDPoSMockChainConfig = &ChainConfig{ @@ -337,10 +337,6 @@ func (c *XDPoSConfig) String() string { } func (c *XDPoSConfig) BlockConsensusVersion(num *big.Int, extraByte []byte, extraCheck bool) string { - if extraCheck && (len(extraByte) == 0 || extraByte[0] != 2) { - return ConsensusEngineVersion1 - } - if c.V2 != nil && c.V2.SwitchBlock != nil && num.Cmp(c.V2.SwitchBlock) > 0 { return ConsensusEngineVersion2 } @@ -361,7 +357,7 @@ func (v *V2) UpdateConfig(round uint64) { } } // update to current config - log.Info("[updateV2Config] Update config", "index", index, "round", round, "SwitchRound", v.AllConfigs[index].SwitchRound) + log.Warn("[updateV2Config] Update config", "index", index, "round", round, "SwitchRound", v.AllConfigs[index].SwitchRound) v.CurrentConfig = v.AllConfigs[index] } From f5cdfb273042ce49d09b772daa930063c1905578 Mon Sep 17 00:00:00 2001 From: Felix Lange Date: Wed, 9 Aug 2023 16:00:31 +0200 Subject: [PATCH 29/30] p2p: move ping handling into pingLoop goroutine (#27887) Moving the response sending there allows tracking all peer goroutines in the peer WaitGroup. --- p2p/peer.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/p2p/peer.go b/p2p/peer.go index c4eaa2390a..a7eb05621f 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -105,6 +105,7 @@ type Peer struct { wg sync.WaitGroup protoErr chan error closed chan struct{} + pingRecv chan struct{} disc chan DiscReason // events receives message send / receive events if set @@ -175,6 +176,7 @@ func newPeer(conn *conn, protocols []Protocol) *Peer { disc: make(chan DiscReason), protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop closed: make(chan struct{}), + pingRecv: make(chan struct{}, 16), log: log.New("id", conn.id, "conn", conn.flags), } return p @@ -236,9 +238,11 @@ loop: } func (p *Peer) pingLoop() { - ping := time.NewTimer(pingInterval) defer p.wg.Done() + + ping := time.NewTimer(pingInterval) defer ping.Stop() + for { select { case <-ping.C: @@ -247,6 +251,10 @@ func (p *Peer) pingLoop() { return } ping.Reset(pingInterval) + + case <-p.pingRecv: + SendItems(p.rw, pongMsg) + case <-p.closed: return } @@ -273,7 +281,10 @@ func (p *Peer) handle(msg Msg) error { switch { case msg.Code == pingMsg: msg.Discard() - go SendItems(p.rw, pongMsg) + select { + case p.pingRecv <- struct{}{}: + case <-p.closed: + } case msg.Code == discMsg: var reason [1]DiscReason // This is the last message. We don't need to discard or From 64a2c84ed39ab6e13bbaaf922dc14a19529c370e Mon Sep 17 00:00:00 2001 From: Liam Date: Thu, 2 Nov 2023 10:57:37 +1100 Subject: [PATCH 30/30] add testnet block for v2 (#345) --- common/constants/constants.go.testnet | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/constants/constants.go.testnet b/common/constants/constants.go.testnet index 23b847be64..114913111d 100644 --- a/common/constants/constants.go.testnet +++ b/common/constants/constants.go.testnet @@ -36,7 +36,7 @@ var TIP2019Block = big.NewInt(1) var TIPSigning = big.NewInt(3000000) var TIPRandomize = big.NewInt(3464000) -var TIPV2SwitchBlock = big.NewInt(56430000) +var TIPV2SwitchBlock = big.NewInt(56828700) // Target 13rd Nov 2023 var TIPIncreaseMasternodes = big.NewInt(5000000) // Upgrade MN Count at Block. var TIPNoHalvingMNReward = big.NewInt(23779191) // hardfork no halving masternodes reward