From e8bfd7090191382c63ef8fd0fe6fdace657e75e7 Mon Sep 17 00:00:00 2001 From: Dmytro Kostenko Date: Mon, 24 Apr 2023 12:46:24 +0200 Subject: [PATCH] refactor: rewards stats passing --- taraxa/C/state.go | 35 ++++++++----------- taraxa/state/api.go | 4 +-- .../state/dpos/precompiled/dpos_contract.go | 3 +- taraxa/state/dpos/tests/dpos_test.go | 16 ++++++--- taraxa/state/dpos/tests/dpos_test_utils.go | 5 +-- .../state/internal/coin_trx_perftest/main.go | 4 +-- taraxa/state/internal/tests/eth_mainnet.go | 3 +- taraxa/state/rewards_stats/rewards_stats.go | 13 ++++--- .../state_transifiton_integration_test.go | 2 +- .../state_transition/state_transition.go | 10 ++++-- 10 files changed, 50 insertions(+), 45 deletions(-) diff --git a/taraxa/C/state.go b/taraxa/C/state.go index 4866bc791..8f2a38f5a 100644 --- a/taraxa/C/state.go +++ b/taraxa/C/state.go @@ -5,7 +5,6 @@ package main //#include import "C" import ( - "fmt" "math/big" "sync" "unsafe" @@ -17,8 +16,6 @@ import ( "github.com/Taraxa-project/taraxa-evm/taraxa/state/state_db_rocksdb" - "github.com/Taraxa-project/taraxa-evm/taraxa/state/state_common" - "github.com/Taraxa-project/taraxa-evm/common" "github.com/Taraxa-project/taraxa-evm/core/types" "github.com/Taraxa-project/taraxa-evm/core/vm" @@ -209,9 +206,7 @@ func taraxa_evm_state_api_transition_state( var params struct { Blk vm.BlockInfo Txs []vm.Transaction - TxsValidators []common.Address // Transactions stats: tx hash -> validator that included it as first in his block - Uncles []state_common.UncleBlock - Rewards_stats rewards_stats.RewardsStats + Rewards_stats []rewards_stats.RewardsStats } dec_rlp(params_enc, ¶ms) @@ -223,15 +218,6 @@ func taraxa_evm_state_api_transition_state( self := state_API_instances[ptr] st := self.GetStateTransition() - disabled_contract_distribution := st.GetChainConfig().RewardsEnabled() - if !disabled_contract_distribution && len(params.Txs) != len(params.TxsValidators) { - errorString := fmt.Sprintf("Number of txs (%d) != number of txs validators (%d)", len(params.Txs), len(params.TxsValidators)) - panic(errorString) - } - - // What rewards should be distributed to which accounts - feesRewards := dpos.NewFeesRewards() - st.BeginBlock(¶ms.Blk) for i := range params.Txs { @@ -244,16 +230,25 @@ func taraxa_evm_state_api_transition_state( // Contract distribution is disabled - just add fee to the block author balance // TODO: once there is a stabilized version - remove this flag and use only dpos contract - if disabled_contract_distribution { + // rewards are distributed directly to the validator balances + if st.GetChainConfig().RewardsEnabled() { st.AddTxFeeToBalance(¶ms.Blk.Author, txFee) - } else { - // Reward dag block author, who included specified tx as first - feesRewards.AddTrxFeeReward(params.TxsValidators[i], txFee) } + // else { + // // Reward dag block author, who included specified tx as first + // feesRewards.AddTrxFeeReward(params.Rewards_stats.TxsValidators[i], txFee) + // } retval.ExecutionResults = append(retval.ExecutionResults, txResult) } - totalReward := st.EndBlock(params.Uncles, ¶ms.Rewards_stats, &feesRewards) + totalReward := uint256.NewInt(0) + for i := range params.Rewards_stats { + reward := st.DistributeRewards(¶ms.Rewards_stats[i], &dpos.FeesRewards{}) + if reward != nil { + totalReward.Add(totalReward, reward) + } + } + st.EndBlock() if totalReward != nil { retval.TotalReward = totalReward.ToBig() } diff --git a/taraxa/state/api.go b/taraxa/state/api.go index 85513c813..510e46065 100644 --- a/taraxa/state/api.go +++ b/taraxa/state/api.go @@ -10,7 +10,6 @@ import ( "github.com/Taraxa-project/taraxa-evm/taraxa/state/chain_config" dpos "github.com/Taraxa-project/taraxa-evm/taraxa/state/dpos/precompiled" "github.com/Taraxa-project/taraxa-evm/taraxa/state/rewards_stats" - "github.com/Taraxa-project/taraxa-evm/taraxa/state/state_common" "github.com/Taraxa-project/taraxa-evm/taraxa/state/state_db" "github.com/Taraxa-project/taraxa-evm/taraxa/state/state_db_rocksdb" "github.com/Taraxa-project/taraxa-evm/taraxa/state/state_dry_runner" @@ -109,7 +108,8 @@ type StateTransition interface { AddTxFeeToBalance(account *common.Address, tx_fee *uint256.Int) GetChainConfig() *chain_config.ChainConfig GetEvmState() *state_evm.EVMState - EndBlock([]state_common.UncleBlock, *rewards_stats.RewardsStats, *dpos.FeesRewards) *uint256.Int + DistributeRewards(*rewards_stats.RewardsStats, *dpos.FeesRewards) *uint256.Int + EndBlock() PrepareCommit() (state_root common.Hash) Commit() (state_root common.Hash) } diff --git a/taraxa/state/dpos/precompiled/dpos_contract.go b/taraxa/state/dpos/precompiled/dpos_contract.go index 2b1e19792..faee2c206 100644 --- a/taraxa/state/dpos/precompiled/dpos_contract.go +++ b/taraxa/state/dpos/precompiled/dpos_contract.go @@ -572,9 +572,10 @@ func (self *Contract) Run(ctx vm.CallFrame, evm *vm.EVM) ([]byte, error) { // - If less reward votes are included, rest of the bonus reward it is just burned // - Then for each validator vote and transaction proportion rewards are calculated and distributed -func (self *Contract) DistributeRewards(blockAuthorAddr *common.Address, rewardsStats *rewards_stats.RewardsStats, feesRewards *FeesRewards) *uint256.Int { +func (self *Contract) DistributeRewards(rewardsStats *rewards_stats.RewardsStats, feesRewards *FeesRewards) *uint256.Int { // When calling DistributeRewards, internal structures must be always initialized self.lazy_init() + blockAuthorAddr := &rewardsStats.BlockAuthor // Calculates number of tokens to be generated as block reward blockReward := new(uint256.Int).Mul(self.amount_delegated, self.yield_percentage) diff --git a/taraxa/state/dpos/tests/dpos_test.go b/taraxa/state/dpos/tests/dpos_test.go index 3ffe45054..2511e81e0 100644 --- a/taraxa/state/dpos/tests/dpos_test.go +++ b/taraxa/state/dpos/tests/dpos_test.go @@ -33,6 +33,14 @@ var CommissionSetEventHash = *keccak256.Hash([]byte("CommissionSet(address,uint1 var ValidatorRegisteredEventHash = *keccak256.Hash([]byte("ValidatorRegistered(address)")) var ValidatorInfoSetEventHash = *keccak256.Hash([]byte("ValidatorInfoSet(address)")) +func NewRewardsStats(author *common.Address) rewards_stats.RewardsStats { + rewardsStats := rewards_stats.RewardsStats{} + rewardsStats.BlockAuthor = *author + rewardsStats.ValidatorsStats = make(map[common.Address]rewards_stats.ValidatorStats) + + return rewardsStats +} + func TestProof(t *testing.T) { pubkey, seckey := generateKeyPair() addr := common.BytesToAddress(keccak256.Hash(pubkey[1:])[12:]) @@ -402,7 +410,7 @@ func TestRewardsAndCommission(t *testing.T) { test.CheckContractBalance(total_stake) // Simulated rewards statistics - tmp_rewards_stats := rewards_stats.NewRewardsStats() + tmp_rewards_stats := NewRewardsStats(&validator1_addr) fees_rewards := dpos.NewFeesRewards() validator1_stats := rewards_stats.ValidatorStats{} @@ -575,10 +583,6 @@ func TestClaimAllRewards(t *testing.T) { // Simulated rewards statistics fees_rewards := dpos.NewFeesRewards() - tmp_rewards_stats := rewards_stats.NewRewardsStats() - tmp_rewards_stats.TotalDagBlocksCount = 0 - tmp_rewards_stats.TotalVotesWeight = 0 - tmp_rewards_stats.MaxVotesWeight = 0 // Create single delegator delegator_addr := addr(1) @@ -590,6 +594,7 @@ func TestClaimAllRewards(t *testing.T) { validator_commission := uint16(0) // 0% var block_author common.Address + var tmp_rewards_stats rewards_stats.RewardsStats // Add 1 extra validator, who is going to be block author with zero delegation for idx := uint64(1); idx <= validators_count+1; idx++ { validator_addr, validator_proof := generateAddrAndProof() @@ -597,6 +602,7 @@ func TestClaimAllRewards(t *testing.T) { test.ExecuteAndCheck(validator_owner, validator_stake, test.pack("registerValidator", validator_addr, validator_proof, DefaultVrfKey, validator_commission, "test", "test"), util.ErrorString(""), util.ErrorString("")) if idx == 1 { block_author = validator_addr + tmp_rewards_stats = NewRewardsStats(&block_author) continue } diff --git a/taraxa/state/dpos/tests/dpos_test_utils.go b/taraxa/state/dpos/tests/dpos_test_utils.go index e1e6bbdd0..cb853e421 100644 --- a/taraxa/state/dpos/tests/dpos_test_utils.go +++ b/taraxa/state/dpos/tests/dpos_test_utils.go @@ -168,7 +168,7 @@ func (self *DposTest) execute(from common.Address, value *big.Int, input []byte) Nonce: senderNonce, }) - self.st.EndBlock(nil, nil, nil) + self.st.EndBlock() self.st.Commit() return res } @@ -180,7 +180,8 @@ func (self *DposTest) AdvanceBlock(author *common.Address, rewardsStats *rewards } else { self.st.BeginBlock(&vm.BlockInfo{*author, 0, 0, nil}) } - ret = self.st.EndBlock(nil, rewardsStats, feesRewards) + ret = self.st.DistributeRewards(rewardsStats, feesRewards) + self.st.EndBlock() self.st.Commit() return } diff --git a/taraxa/state/internal/coin_trx_perftest/main.go b/taraxa/state/internal/coin_trx_perftest/main.go index 1c34c632c..1f225965e 100644 --- a/taraxa/state/internal/coin_trx_perftest/main.go +++ b/taraxa/state/internal/coin_trx_perftest/main.go @@ -143,7 +143,7 @@ func main() { }) batch_size++ } - st.EndBlock(nil, nil, nil) + st.EndBlock() if batch_size >= prepare_trx_batch_size || blk_n == num_prepare_blocks-1 { st.Commit() batch_size = 0 @@ -233,7 +233,7 @@ func main() { } st.ExecuteTransaction(&trx) } - st.EndBlock(nil, nil, nil) + st.EndBlock() }) with_timer("trie_commit", func() { st.PrepareCommit() diff --git a/taraxa/state/internal/tests/eth_mainnet.go b/taraxa/state/internal/tests/eth_mainnet.go index 4d1de2353..3e764893e 100644 --- a/taraxa/state/internal/tests/eth_mainnet.go +++ b/taraxa/state/internal/tests/eth_mainnet.go @@ -25,7 +25,6 @@ import ( "github.com/Taraxa-project/taraxa-evm/common" "github.com/Taraxa-project/taraxa-evm/common/hexutil" - "github.com/Taraxa-project/taraxa-evm/consensus/ethash" "github.com/Taraxa-project/taraxa-evm/core" "github.com/Taraxa-project/taraxa-evm/core/types" "github.com/Taraxa-project/taraxa-evm/core/vm" @@ -182,7 +181,7 @@ func main() { asserts.EQ(*receipt.ContractAddress, res.NewContractAddr) } } - st.EndBlock(*(*[]ethash.BlockNumAndCoinbase)(unsafe.Pointer(&b.UncleBlocks)), nil, nil) + st.EndBlock() } state_root := st.PrepareCommit() asserts.EQ(block_buf[len(block_buf)-1].StateRoot.Hex(), state_root.Hex()) diff --git a/taraxa/state/rewards_stats/rewards_stats.go b/taraxa/state/rewards_stats/rewards_stats.go index f97cddb96..697ecb8f8 100644 --- a/taraxa/state/rewards_stats/rewards_stats.go +++ b/taraxa/state/rewards_stats/rewards_stats.go @@ -15,9 +15,15 @@ type ValidatorStats struct { } type RewardsStats struct { + // Pbft block author + BlockAuthor common.Address + // Validator stats ValidatorsStats map[common.Address]ValidatorStats + // List of transactions validators + TxsValidators []common.Address + // Total unique transactions counter TotalDagBlocksCount uint32 @@ -27,10 +33,3 @@ type RewardsStats struct { // Max weight of votes in block MaxVotesWeight uint64 } - -func NewRewardsStats() RewardsStats { - rewardsStats := RewardsStats{} - rewardsStats.ValidatorsStats = make(map[common.Address]ValidatorStats) - - return rewardsStats -} diff --git a/taraxa/state/state_transifiton_integration_test.go b/taraxa/state/state_transifiton_integration_test.go index 8dd08e4a3..e4481bbdb 100644 --- a/taraxa/state/state_transifiton_integration_test.go +++ b/taraxa/state/state_transifiton_integration_test.go @@ -53,7 +53,7 @@ func TestEthMainnetSmoke(t *testing.T) { for i := range blk.Transactions { st.ExecuteTransaction(&blk.Transactions[i]) } - st.EndBlock(blk.UncleBlocks, nil, nil) + st.EndBlock() asserts.EQ(st.Commit().Hex(), blk.StateRoot.Hex()) progress_bar.Add(1) } diff --git a/taraxa/state/state_transition/state_transition.go b/taraxa/state/state_transition/state_transition.go index 45da3a358..ad2d730cc 100644 --- a/taraxa/state/state_transition/state_transition.go +++ b/taraxa/state/state_transition/state_transition.go @@ -118,15 +118,19 @@ func (self *StateTransition) GetEvmState() *state_evm.EVMState { return &self.evm_state } -func (self *StateTransition) EndBlock(uncles []state_common.UncleBlock, rewardsStats *rewards_stats.RewardsStats, feesRewards *dpos.FeesRewards) (totalReward *uint256.Int) { +func (self *StateTransition) DistributeRewards(rewardsStats *rewards_stats.RewardsStats, feesRewards *dpos.FeesRewards) (totalReward *uint256.Int) { if self.chain_config.RewardsEnabled() && rewardsStats != nil && feesRewards != nil { - evm_block := self.evm.GetBlock() if self.dpos_contract == nil { panic("Stats rewards enabled but no dpos contract registered") } - totalReward = self.dpos_contract.DistributeRewards(&evm_block.Author, rewardsStats, feesRewards) + totalReward = self.dpos_contract.DistributeRewards(rewardsStats, feesRewards) self.evm_state_checkpoint() } + + return +} + +func (self *StateTransition) EndBlock() { self.LastBlockNum = self.evm.GetBlock().Number if self.dpos_contract != nil { self.dpos_contract.EndBlockCall()